Skip to main content

ruxla_codegen/
opt.rs

1//! Optimizations of the IR before code generation: inlining of calls,
2//! constant folding and algebraic simplification, common subexpression
3//! elimination, dead code elimination, and the conversion of selects on a
4//! scalar predicate into conditionals (so that only the chosen side is
5//! computed).
6//!
7//! Every pass keeps the values of the function (they are checked against
8//! the interpreter in the tests), except the simplifications of
9//! [`Options::fast_math`].
10
11use std::cmp::Reverse;
12use std::collections::{BinaryHeap, HashMap, HashSet};
13use std::sync::Arc;
14
15use ruxla_interp::Interp;
16use ruxla_ir::{AVal, Atom, DType, DTypeKind, Eqn, Function, HostArray, Literal, Params, Var};
17
18/// The options of the optimizations.
19#[derive(Clone, Copy, Debug)]
20pub struct Options {
21    /// Simplifications that hold for finite floats but not for NaN,
22    /// infinities, or the sign of zero: `x * 0 = 0`, `x + 0 = x`, `x - 0 =
23    /// x`.
24    pub fast_math: bool,
25    /// The largest constant (in elements) that folding creates.
26    pub max_constant: usize,
27    /// Passes to skip, to measure what each contributes (all enabled by
28    /// default).
29    pub skip: Skip,
30}
31
32impl Default for Options {
33    fn default() -> Self {
34        Self {
35            fast_math: false,
36            max_constant: 1 << 16,
37            skip: Skip::default(),
38        }
39    }
40}
41
42/// Passes of [`optimize`] that can be skipped (ablation). Skipping a pass
43/// keeps the values of the function; only the generated code changes.
44#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
45pub struct Skip {
46    /// The conversion of selects on a scalar predicate into conditionals.
47    pub select_branches: bool,
48    /// The rewriting of scatter chains into masked selects.
49    pub masked_scatters: bool,
50    /// The splitting of small arrays into scalars.
51    pub scalarize: bool,
52    /// The hoisting of outputs that every branch passes through unchanged.
53    pub passthrough: bool,
54    /// The emitter's fusion of elementwise operations into their consumers
55    /// (every elementwise result is then built as an array).
56    pub fusion: bool,
57    /// The emitter's views: data movement read from its sources instead of
58    /// built, and windows that are references instead of copies.
59    pub views: bool,
60    /// The emitter's in-place updates: arrays updated in place when nothing
61    /// reads them afterwards, and outputs computed directly into the state
62    /// (every update then copies its array).
63    pub in_place: bool,
64}
65
66impl Skip {
67    /// Parses a comma-separated list of `selects`, `scatters`, `scalars`,
68    /// `passthrough`, `all` (these four passes), `fusion`, `views` and
69    /// `inplace` (unknown names are ignored).
70    ///
71    /// # Examples
72    ///
73    /// ```
74    /// use ruxla_codegen::opt::Skip;
75    ///
76    /// let s = Skip::parse("selects, scalars");
77    /// assert!(s.select_branches && s.scalarize && !s.masked_scatters);
78    /// ```
79    pub fn parse(list: &str) -> Self {
80        let mut s = Self::default();
81        for name in list.split(',').map(str::trim) {
82            let all = name == "all";
83            s.select_branches |= all || name == "selects";
84            s.masked_scatters |= all || name == "scatters";
85            s.scalarize |= all || name == "scalars";
86            s.passthrough |= all || name == "passthrough";
87            s.fusion |= name == "fusion";
88            s.views |= name == "views";
89            s.in_place |= name == "inplace";
90        }
91        s
92    }
93}
94
95/// Optimizes `f` for code generation.
96///
97/// # Examples
98///
99/// ```
100/// use ruxla_ir::{AVal, Atom, DType, Eqn, Function, HostArray, Literal, Params, Var};
101///
102/// // `x + (2 * 3)`: the product is folded.
103/// let x = Var::new(AVal::scalar(DType::I32));
104/// let (t, y) = (Var::new(AVal::scalar(DType::I32)), Var::new(AVal::scalar(DType::I32)));
105/// let lit = |v: i32| Atom::Lit(Literal::new(HostArray::scalar(v)));
106/// let eqn = |p, inputs, out: &Var| Eqn {
107///     prim: p,
108///     inputs,
109///     params: Params::None,
110///     outputs: vec![out.clone()],
111///     loc: None,
112/// };
113/// let f = Function {
114///     invars: vec![x.clone()],
115///     eqns: vec![
116///         eqn(ruxla_prims::MUL, vec![lit(2), lit(3)], &t),
117///         eqn(ruxla_prims::ADD, vec![x.into(), t.into()], &y),
118///     ],
119///     outvars: vec![y.into()],
120///     ..Function::default()
121/// };
122/// let g = ruxla_codegen::opt::optimize(&f, &Default::default());
123/// assert_eq!(g.eqns.len(), 1);
124/// ```
125pub fn optimize(f: &Function, options: &Options) -> Function {
126    let f = inline_calls(f);
127    optimize_inlined(&f, options)
128}
129
130/// [`optimize`] of a function without calls to inline.
131fn optimize_inlined(f: &Function, options: &Options) -> Function {
132    let skip = options.skip;
133    let f = simplify(f, options);
134    let f = simplify(&sink_broadcasts(&f), options);
135    let f = if skip.scalarize {
136        f
137    } else {
138        simplify(&scalarize(&f), options)
139    };
140    let f = simplify(&collapse_nested_selects(&f), options);
141    let f = if skip.masked_scatters {
142        f
143    } else {
144        simplify(&mask_scatters(&f), options)
145    };
146    let f = if skip.select_branches {
147        f
148    } else {
149        sink_selects(&f, options)
150    };
151    let f = if skip.passthrough {
152        f
153    } else {
154        hoist_passthrough(&f)
155    };
156    // Selects turned into conditionals may leave dead code and constant
157    // operands of branches.
158    simplify(&f, options)
159}
160
161/// Folding, CSE, and DCE until the function no longer shrinks.
162fn simplify(f: &Function, options: &Options) -> Function {
163    let mut f = f.clone();
164    for _ in 0..8 {
165        let n = count_eqns(&f);
166        f = dce(&cse(&fold(&f, options)));
167        if count_eqns(&f) == n {
168            break;
169        }
170    }
171    f
172}
173
174fn count_eqns(f: &Function) -> usize {
175    f.eqns
176        .iter()
177        .map(|e| {
178            1 + e
179                .params
180                .functions()
181                .iter()
182                .map(|g| count_eqns(g))
183                .sum::<usize>()
184        })
185        .sum()
186}
187
188/// Substitutions of variables.
189#[derive(Default)]
190struct Subst(HashMap<u64, Atom>);
191
192impl Subst {
193    fn atom(&self, a: &Atom) -> Atom {
194        match a {
195            Atom::Var(v) => self.0.get(&v.id()).cloned().unwrap_or_else(|| a.clone()),
196            Atom::Lit(_) => a.clone(),
197        }
198    }
199
200    fn set(&mut self, v: &Var, a: Atom) {
201        self.0.insert(v.id(), a);
202    }
203}
204
205/// `params` with its functions replaced by `g` of them.
206fn map_functions(params: &Params, g: &dyn Fn(&Function) -> Function) -> Params {
207    let m = |f: &Arc<Function>| Arc::new(g(f));
208    match params {
209        Params::Cond { branches } => Params::Cond {
210            branches: branches.iter().map(m).collect(),
211        },
212        Params::While {
213            cond,
214            body,
215            cond_nconsts,
216            body_nconsts,
217        } => Params::While {
218            cond: m(cond),
219            body: m(body),
220            cond_nconsts: *cond_nconsts,
221            body_nconsts: *body_nconsts,
222        },
223        Params::Scan {
224            body,
225            length,
226            reverse,
227            num_consts,
228            num_carry,
229        } => Params::Scan {
230            body: m(body),
231            length: *length,
232            reverse: *reverse,
233            num_consts: *num_consts,
234            num_carry: *num_carry,
235        },
236        p => p.clone(),
237    }
238}
239
240/// The function that a call equation (`jit`, `checkpoint`, `custom_jvp_call`,
241/// `custom_vjp_call`) computes from its inputs.
242fn call_body(p: &Params) -> Option<&Function> {
243    match p {
244        Params::Jit { body, .. } | Params::Checkpoint { body } => Some(body),
245        Params::CustomJvp { call, .. } | Params::CustomVjp { call, .. } => Some(call),
246        _ => None,
247    }
248}
249
250/// Appends the equations of `body` applied to `inputs` to `out` (with fresh
251/// variables, and its constants added to `consts`), and returns its outputs.
252fn inline_function(
253    body: &Function,
254    inputs: &[Atom],
255    out: &mut Vec<Eqn>,
256    consts: &mut Vec<(Var, HostArray)>,
257) -> Vec<Atom> {
258    let mut s = Subst::default();
259    for (v, a) in body.invars.iter().zip(inputs) {
260        s.set(v, a.clone());
261    }
262    for (v, c) in &body.constvars {
263        let nv = Var::new(v.aval().clone());
264        consts.push((nv.clone(), c.clone()));
265        s.set(v, nv.into());
266    }
267    inline_into(&body.eqns, &mut s, out, consts);
268    body.outvars.iter().map(|a| s.atom(a)).collect()
269}
270
271/// Copies `eqns` to `out` with fresh output variables, inlining calls.
272fn inline_into(
273    eqns: &[Eqn],
274    s: &mut Subst,
275    out: &mut Vec<Eqn>,
276    consts: &mut Vec<(Var, HostArray)>,
277) {
278    for e in eqns {
279        let inputs: Vec<Atom> = e.inputs.iter().map(|a| s.atom(a)).collect();
280        if let Some(body) = call_body(&e.params) {
281            let results = inline_function(body, &inputs, out, consts);
282            for (o, a) in e.outputs.iter().zip(results) {
283                s.set(o, a);
284            }
285            continue;
286        }
287        let outputs = e
288            .outputs
289            .iter()
290            .map(|o| {
291                let n = Var::new(o.aval().clone());
292                s.set(o, n.clone().into());
293                n
294            })
295            .collect();
296        out.push(Eqn {
297            prim: e.prim,
298            inputs,
299            params: map_functions(&e.params, &inline_calls),
300            outputs,
301            loc: e.loc,
302        });
303    }
304}
305
306/// Inlines the calls of `f` (and of its nested functions).
307pub(crate) fn inline_calls(f: &Function) -> Function {
308    let mut s = Subst::default();
309    let mut eqns = Vec::new();
310    let mut consts = f.constvars.clone();
311    inline_into(&f.eqns, &mut s, &mut eqns, &mut consts);
312    Function {
313        constvars: consts,
314        invars: f.invars.clone(),
315        eqns,
316        outvars: f.outvars.iter().map(|a| s.atom(a)).collect(),
317    }
318}
319
320fn lit(x: HostArray) -> Atom {
321    Atom::Lit(Literal::new(x))
322}
323
324fn is_scalar(aval: &AVal) -> bool {
325    aval.shape.rank() == 0
326}
327
328/// Whether every element of `x` has the value `v` (compared as `f64`; for
329/// integers and booleans exactly).
330fn all_equal(x: &HostArray, v: f64) -> bool {
331    (0..x.size()).all(|i| match x.get(i) {
332        ruxla_ir::Value::Bool(b) => f64::from(u8::from(b)) == v,
333        ruxla_ir::Value::Int(n) => n as f64 == v,
334        ruxla_ir::Value::UInt(n) => n as f64 == v,
335        ruxla_ir::Value::Float(f) => f == v && (v != 0.0 || f.is_sign_positive()),
336        ruxla_ir::Value::Complex(..) => false,
337    })
338}
339
340/// The value of `a` if it is constant.
341fn value_of(a: &Atom, known: &HashMap<u64, HostArray>) -> Option<HostArray> {
342    match a {
343        Atom::Lit(l) => Some(l.value().clone()),
344        Atom::Var(v) => known.get(&v.id()).cloned(),
345    }
346}
347
348/// Whether equations of this primitive may be evaluated at compile time.
349fn foldable(e: &Eqn) -> bool {
350    !matches!(
351        e.prim.name(),
352        "extern_call" | "while" | "scan" | "cond" | "custom_lin"
353    )
354}
355
356/// Constant folding and algebraic simplification.
357fn fold(f: &Function, options: &Options) -> Function {
358    fold_with(f, options, Subst::default(), HashMap::new())
359}
360
361fn fold_with(
362    f: &Function,
363    options: &Options,
364    mut s: Subst,
365    mut known: HashMap<u64, HostArray>,
366) -> Function {
367    for (v, c) in &f.constvars {
368        if is_scalar(v.aval()) {
369            s.set(v, lit(c.clone()));
370        } else {
371            known.insert(v.id(), c.clone());
372        }
373    }
374    let mut eqns: Vec<Eqn> = Vec::new();
375    let mut new_consts: Vec<(Var, HostArray)> = Vec::new();
376    for e in &f.eqns {
377        let inputs: Vec<Atom> = e.inputs.iter().map(|a| s.atom(a)).collect();
378        let values: Vec<Option<HostArray>> = inputs.iter().map(|a| value_of(a, &known)).collect();
379        // Every input constant: evaluate.
380        if foldable(e)
381            && values.iter().all(Option::is_some)
382            && e.outputs
383                .iter()
384                .map(|o| o.aval().shape.size())
385                .sum::<usize>()
386                <= options.max_constant
387        {
388            let vals: Vec<HostArray> = values.iter().flatten().cloned().collect();
389            if let Ok(outs) = e.prim.eval(&Interp, &vals, &e.params) {
390                for (o, x) in e.outputs.iter().zip(outs) {
391                    if is_scalar(o.aval()) {
392                        s.set(o, lit(x));
393                    } else {
394                        known.insert(o.id(), x);
395                    }
396                }
397                continue;
398            }
399        }
400        if let Some(a) = simplify_eqn(e, &inputs, &values, options) {
401            s.set(&e.outputs[0], a);
402            continue;
403        }
404        // A conditional on a constant index: inline the branch.
405        if let (Params::Cond { branches }, Some(Some(index))) = (&e.params, values.first()) {
406            let i = match index.get(0) {
407                ruxla_ir::Value::Int(i) => i,
408                ruxla_ir::Value::UInt(i) => i as i64,
409                ruxla_ir::Value::Bool(b) => i64::from(b),
410                _ => 0,
411            };
412            let branch = &branches[i.clamp(0, branches.len() as i64 - 1) as usize];
413            let results = inline_function(branch, &inputs[1..], &mut eqns, &mut new_consts);
414            for (o, a) in e.outputs.iter().zip(results) {
415                s.set(o, a);
416            }
417            continue;
418        }
419        // Scalar constants become literals.
420        let inputs: Vec<Atom> = inputs
421            .into_iter()
422            .zip(&values)
423            .map(|(a, v)| match (v, &a) {
424                (Some(x), Atom::Var(var)) if is_scalar(var.aval()) => lit(x.clone()),
425                _ => a,
426            })
427            .collect();
428        let (inputs, params) = match &e.params {
429            Params::Cond { branches } => fold_cond_operands(inputs, branches, &known, options),
430            Params::Scan {
431                body,
432                length,
433                reverse,
434                num_consts,
435                num_carry,
436            } => {
437                // Constant operands of the body become its constants (which the
438                // code generator emits as `static` arrays the compiler knows,
439                // also in a body that is a function of its own).
440                let moved = if count_eqns(body) >= crate::emit::OUTLINE_EQNS {
441                    constant_positions(&inputs[..*num_consts], &known)
442                } else {
443                    Vec::new()
444                };
445                let inputs = drop_positions(inputs, &moved, 0);
446                let body = with_const_inputs(body, &moved, options);
447                let params = Params::Scan {
448                    body: Arc::new(body),
449                    length: *length,
450                    reverse: *reverse,
451                    num_consts: num_consts - moved.len(),
452                    num_carry: *num_carry,
453                };
454                (inputs, params)
455            }
456            Params::While {
457                cond,
458                body,
459                cond_nconsts,
460                body_nconsts,
461            } => {
462                let (cn, bn) = (*cond_nconsts, *body_nconsts);
463                // Only for a body that is a function of its own: an inline body
464                // reads the parent's constants anyway (and a loop of known
465                // values in place may be evaluated by LLVM at length).
466                let outlined = count_eqns(body) >= crate::emit::OUTLINE_EQNS;
467                let moved_c = if outlined {
468                    constant_positions(&inputs[..cn], &known)
469                } else {
470                    Vec::new()
471                };
472                let moved_b = if outlined {
473                    constant_positions(&inputs[cn..cn + bn], &known)
474                } else {
475                    Vec::new()
476                };
477                let inputs = drop_positions(inputs, &moved_b, cn);
478                let inputs = drop_positions(inputs, &moved_c, 0);
479                let params = Params::While {
480                    cond: Arc::new(with_const_inputs(cond, &moved_c, options)),
481                    body: Arc::new(with_const_inputs(body, &moved_b, options)),
482                    cond_nconsts: cn - moved_c.len(),
483                    body_nconsts: bn - moved_b.len(),
484                };
485                (inputs, params)
486            }
487            p => (inputs, map_functions(p, &|g: &Function| fold(g, options))),
488        };
489        eqns.push(Eqn {
490            prim: e.prim,
491            inputs,
492            params,
493            outputs: e.outputs.clone(),
494            loc: e.loc,
495        });
496    }
497    let outvars: Vec<Atom> = f.outvars.iter().map(|a| s.atom(a)).collect();
498    // The constants that remain in use.
499    let mut used = HashSet::new();
500    for e in &eqns {
501        for a in &e.inputs {
502            if let Atom::Var(v) = a {
503                used.insert(v.id());
504            }
505        }
506    }
507    for a in &outvars {
508        if let Atom::Var(v) = a {
509            used.insert(v.id());
510        }
511    }
512    let invar_ids: HashSet<u64> = f.invars.iter().map(Var::id).collect();
513    let mut constvars: Vec<(Var, HostArray)> = Vec::new();
514    let mut seen = HashSet::new();
515    let mut add = |v: &Var, x: &HostArray| {
516        if used.contains(&v.id()) && !invar_ids.contains(&v.id()) && seen.insert(v.id()) {
517            constvars.push((v.clone(), x.clone()));
518        }
519    };
520    for (v, x) in f.constvars.iter().chain(&new_consts) {
521        if !is_scalar(v.aval()) {
522            add(v, x);
523        }
524    }
525    for e in &f.eqns {
526        for o in &e.outputs {
527            if let Some(x) = known.get(&o.id()) {
528                add(o, x);
529            }
530        }
531    }
532    Function {
533        constvars,
534        invars: f.invars.clone(),
535        eqns,
536        outvars,
537    }
538}
539
540/// The positions of the constant operands among `inputs`, with their values.
541fn constant_positions(inputs: &[Atom], known: &HashMap<u64, HostArray>) -> Vec<(usize, HostArray)> {
542    inputs
543        .iter()
544        .enumerate()
545        .filter_map(|(k, a)| value_of(a, known).map(|x| (k, x)))
546        .collect()
547}
548
549/// `inputs` without those at `offset` plus the positions of `moved`.
550fn drop_positions(inputs: Vec<Atom>, moved: &[(usize, HostArray)], offset: usize) -> Vec<Atom> {
551    let drop: HashSet<usize> = moved.iter().map(|(k, _)| offset + k).collect();
552    inputs
553        .into_iter()
554        .enumerate()
555        .filter(|(k, _)| !drop.contains(k))
556        .map(|(_, a)| a)
557        .collect()
558}
559
560/// `f` with its inputs at the positions of `moved` made constants (scalars
561/// as literals), folded.
562fn with_const_inputs(f: &Function, moved: &[(usize, HostArray)], options: &Options) -> Function {
563    let mut s = Subst::default();
564    let drop: HashSet<usize> = moved.iter().map(|(k, _)| *k).collect();
565    let mut g = Function {
566        constvars: f.constvars.clone(),
567        invars: f
568            .invars
569            .iter()
570            .enumerate()
571            .filter(|(k, _)| !drop.contains(k))
572            .map(|(_, v)| v.clone())
573            .collect(),
574        eqns: f.eqns.clone(),
575        outvars: f.outvars.clone(),
576    };
577    for (k, x) in moved {
578        let v = &f.invars[*k];
579        if is_scalar(v.aval()) {
580            s.set(v, lit(x.clone()));
581        } else {
582            g.constvars.push((v.clone(), x.clone()));
583        }
584    }
585    fold_with(&g, options, s, HashMap::new())
586}
587
588/// Moves the constant operands of a conditional into its branches, and
589/// folds the branches.
590fn fold_cond_operands(
591    inputs: Vec<Atom>,
592    branches: &[Arc<Function>],
593    known: &HashMap<u64, HostArray>,
594    options: &Options,
595) -> (Vec<Atom>, Params) {
596    let mut kept = vec![inputs[0].clone()];
597    let mut moved: Vec<(usize, HostArray)> = Vec::new();
598    for (k, a) in inputs[1..].iter().enumerate() {
599        match value_of(a, known) {
600            Some(x) => moved.push((k, x)),
601            None => kept.push(a.clone()),
602        }
603    }
604    let branches = branches
605        .iter()
606        .map(|b| {
607            let mut s = Subst::default();
608            let mut consts = HashMap::new();
609            let moved_ids: HashSet<usize> = moved.iter().map(|(k, _)| *k).collect();
610            for (k, x) in &moved {
611                let v = &b.invars[*k];
612                if is_scalar(v.aval()) {
613                    s.set(v, lit(x.clone()));
614                } else {
615                    consts.insert(v.id(), x.clone());
616                }
617            }
618            let g = Function {
619                constvars: b.constvars.clone(),
620                invars: b
621                    .invars
622                    .iter()
623                    .enumerate()
624                    .filter(|(k, _)| !moved_ids.contains(k))
625                    .map(|(_, v)| v.clone())
626                    .collect(),
627                eqns: b.eqns.clone(),
628                outvars: b.outvars.clone(),
629            };
630            // The moved non-scalar operands become constants of the branch.
631            let mut g = g;
632            for (k, x) in &moved {
633                let v = &b.invars[*k];
634                if !is_scalar(v.aval()) {
635                    g.constvars.push((v.clone(), x.clone()));
636                }
637            }
638            Arc::new(fold_with(&g, options, s, HashMap::new()))
639        })
640        .collect();
641    (kept, Params::Cond { branches })
642}
643
644/// Algebraic simplifications that replace the output of `e` by an atom.
645fn simplify_eqn(
646    e: &Eqn,
647    inputs: &[Atom],
648    values: &[Option<HostArray>],
649    options: &Options,
650) -> Option<Atom> {
651    if e.outputs.len() != 1 {
652        return None;
653    }
654    let out = e.outputs[0].aval();
655    let same = |a: &Atom| a.aval() == *out;
656    let is = |k: usize, v: f64| values[k].as_ref().is_some_and(|x| all_equal(x, v));
657    let float = matches!(out.dtype.kind(), DTypeKind::Float);
658    match e.prim.name() {
659        "select_n" => {
660            // A constant predicate: the chosen case (for every element; an
661            // empty predicate chooses nothing to simplify).
662            if let Some(p) = values[0].as_ref().filter(|p| p.size() > 0) {
663                let first = p.get(0);
664                let uniform = (0..p.size()).all(|i| p.get(i) == first);
665                if uniform {
666                    let i = match first {
667                        ruxla_ir::Value::Bool(b) => usize::from(b),
668                        ruxla_ir::Value::Int(i) => i as usize,
669                        ruxla_ir::Value::UInt(i) => i as usize,
670                        _ => return None,
671                    };
672                    let a = &inputs[1 + i.min(inputs.len() - 2)];
673                    return same(a).then(|| a.clone());
674                }
675            }
676            // Every case the same.
677            if inputs[1..].iter().all(|a| *a == inputs[1]) && same(&inputs[1]) {
678                return Some(inputs[1].clone());
679            }
680            None
681        }
682        "and" if out.dtype == DType::Bool => {
683            for (k, other) in [(0, 1), (1, 0)] {
684                if is(k, 1.0) && same(&inputs[other]) {
685                    return Some(inputs[other].clone());
686                }
687                if is(k, 0.0) && same(&inputs[k]) {
688                    return Some(inputs[k].clone());
689                }
690            }
691            None
692        }
693        "or" if out.dtype == DType::Bool => {
694            for (k, other) in [(0, 1), (1, 0)] {
695                if is(k, 0.0) && same(&inputs[other]) {
696                    return Some(inputs[other].clone());
697                }
698                if is(k, 1.0) && same(&inputs[k]) {
699                    return Some(inputs[k].clone());
700                }
701            }
702            None
703        }
704        "add" if !float || options.fast_math => {
705            for (k, other) in [(0, 1), (1, 0)] {
706                if is(k, 0.0) && same(&inputs[other]) {
707                    return Some(inputs[other].clone());
708                }
709            }
710            None
711        }
712        "sub" if (!float || options.fast_math) && is(1, 0.0) && same(&inputs[0]) => {
713            Some(inputs[0].clone())
714        }
715        "mul" => {
716            for (k, other) in [(0, 1), (1, 0)] {
717                if is(k, 1.0) && same(&inputs[other]) {
718                    return Some(inputs[other].clone());
719                }
720                if (!float || options.fast_math) && is(k, 0.0) && same(&inputs[k]) {
721                    return Some(inputs[k].clone());
722                }
723            }
724            None
725        }
726        "convert_element_type" | "reshape" if same(&inputs[0]) => Some(inputs[0].clone()),
727        "broadcast_in_dim" if same(&inputs[0]) => Some(inputs[0].clone()),
728        _ => None,
729    }
730}
731
732/// The largest array that [`scalarize`] splits into its elements.
733const SCALARIZE_MAX: usize = 8;
734
735/// The primitives that [`scalarize`] computes element by element.
736fn elementwise_prim(name: &str) -> bool {
737    ruxla_kernels::UnaryOp::ALL.iter().any(|o| o.name() == name)
738        || ruxla_kernels::BinaryOp::ALL
739            .iter()
740            .any(|o| o.name() == name)
741        || ruxla_kernels::CompareOp::ALL
742            .iter()
743            .any(|o| o.name() == name)
744        || matches!(
745            name,
746            "convert_element_type"
747                | "select_n"
748                | "clamp"
749                | "integer_pow"
750                | "round"
751                | "threefry2x32"
752        )
753}
754
755/// The primitives that [`scalarize`] follows element by element (data
756/// movement with static positions).
757fn movement_prim(name: &str) -> bool {
758    matches!(
759        name,
760        "broadcast_in_dim"
761            | "reshape"
762            | "slice"
763            | "concatenate"
764            | "transpose"
765            | "rev"
766            | "squeeze"
767            | "expand_dims"
768    )
769}
770
771/// A variable that broadcasts `src` (`broadcast_in_dim` with these
772/// dimensions) to its shape.
773#[derive(Clone)]
774struct Broadcast {
775    src: Atom,
776    dims: Vec<usize>,
777}
778
779/// Moves `broadcast_in_dim` after the operations that commute with it, so
780/// that they compute on the smaller operand: elementwise operations whose
781/// array operands broadcast the same shape in the same way (and scalars),
782/// slices, and reshapes that only insert or remove dimensions of size one.
783/// Waymax's pairwise overlaps broadcast the boxes of 1408 objects to their
784/// 180,224 pairs and then computed the corners of every pair's boxes. The
785/// results are bit for bit the same (the same operations on the same
786/// values).
787fn sink_broadcasts(f: &Function) -> Function {
788    let mut bcast: HashMap<u64, Broadcast> = HashMap::new();
789    // Broadcasts of one value: the value.
790    let mut uniform: HashMap<u64, Atom> = HashMap::new();
791    let mut eqns: Vec<Eqn> = Vec::new();
792    let new_eqn = |prim, inputs: Vec<Atom>, params: Params, outputs: Vec<Var>| Eqn {
793        prim,
794        inputs,
795        params,
796        outputs,
797        loc: None,
798    };
799    let broadcast_to = |src: Atom, dims: Vec<usize>, out: Var, eqns: &mut Vec<Eqn>| {
800        eqns.push(new_eqn(
801            ruxla_prims::BROADCAST_IN_DIM,
802            vec![src],
803            Params::BroadcastInDim {
804                shape: out.aval().shape.clone(),
805                broadcast_dimensions: dims,
806            },
807            vec![out],
808        ));
809    };
810    for e in &f.eqns {
811        let inputs = e.inputs.clone();
812        let params = map_functions(&e.params, &sink_broadcasts);
813        let name = e.prim.name();
814        let of = |a: &Atom| match a {
815            Atom::Var(v) => bcast.get(&v.id()).cloned(),
816            Atom::Lit(_) => None,
817        };
818        let mut done = false;
819        let mut composed = false;
820        if e.outputs.len() == 1 {
821            let out = &e.outputs[0];
822            let oshape = out.aval().shape.dims().to_vec();
823            match (name, &params) {
824                (
825                    "slice",
826                    Params::Slice {
827                        start_indices,
828                        limit_indices,
829                        strides,
830                    },
831                ) => {
832                    if let Some(b) = of(&inputs[0]) {
833                        // The source sliced along the dimensions it keeps.
834                        let sdims = b.src.aval().shape.dims().to_vec();
835                        let mut starts = vec![0; sdims.len()];
836                        let mut limits = sdims.clone();
837                        let mut steps = vec![1; sdims.len()];
838                        for (sd, &d) in b.dims.iter().enumerate() {
839                            if sdims[sd] != 1 {
840                                starts[sd] = start_indices[d];
841                                limits[sd] = limit_indices[d];
842                                steps[sd] = strides.get(d).copied().unwrap_or(1);
843                            }
844                        }
845                        let src = if starts.iter().all(|&x| x == 0)
846                            && limits == sdims
847                            && steps.iter().all(|&x| x == 1)
848                        {
849                            b.src.clone()
850                        } else {
851                            let shape: Vec<usize> = (0..sdims.len())
852                                .map(|k| (limits[k] - starts[k]).div_ceil(steps[k]))
853                                .collect();
854                            let v = Var::new(AVal::new(shape, b.src.aval().dtype));
855                            eqns.push(new_eqn(
856                                ruxla_prims::SLICE,
857                                vec![b.src.clone()],
858                                Params::Slice {
859                                    start_indices: starts,
860                                    limit_indices: limits,
861                                    strides: steps,
862                                },
863                                vec![v.clone()],
864                            ));
865                            v.into()
866                        };
867                        broadcast_to(src.clone(), b.dims.clone(), out.clone(), &mut eqns);
868                        bcast.insert(out.id(), Broadcast { src, dims: b.dims });
869                        done = true;
870                    }
871                }
872                ("concatenate", Params::Concatenate { dimension }) => {
873                    // Broadcasts of the same shape the same way, concatenated along a
874                    // dimension that each source has (not broadcast): the sources
875                    // concatenated, broadcast.
876                    let mut bs: Option<Vec<Broadcast>> = inputs.iter().map(of).collect();
877                    // A concatenation along a dimension of size one in every operand
878                    // that the sources do not have: the sources with that dimension.
879                    if let Some(list) = &bs
880                        && list.iter().all(|b| !b.dims.contains(dimension))
881                        && inputs
882                            .iter()
883                            .all(|a| a.aval().shape.dims()[*dimension] == 1)
884                    {
885                        let mut expanded = Vec::new();
886                        for b in list {
887                            let at = b.dims.iter().filter(|&&d| d < *dimension).count();
888                            let mut shape = b.src.aval().shape.dims().to_vec();
889                            shape.insert(at, 1);
890                            let v = Var::new(AVal::new(shape.clone(), b.src.aval().dtype));
891                            eqns.push(new_eqn(
892                                ruxla_prims::RESHAPE,
893                                vec![b.src.clone()],
894                                Params::Reshape {
895                                    new_sizes: ruxla_ir::Shape::from(shape),
896                                },
897                                vec![v.clone()],
898                            ));
899                            let mut dims = b.dims.clone();
900                            dims.insert(at, *dimension);
901                            expanded.push(Broadcast {
902                                src: v.into(),
903                                dims,
904                            });
905                        }
906                        bs = Some(expanded);
907                    }
908                    let same = bs.as_ref().and_then(|bs| {
909                        let first = bs.first()?;
910                        let sd = first.dims.iter().position(|&d| d == *dimension)?;
911                        let ok = bs.iter().zip(&inputs).all(|(b, a)| {
912                            let (sdims, fdims) = (
913                                b.src.aval().shape.dims().to_vec(),
914                                first.src.aval().shape.dims().to_vec(),
915                            );
916                            b.dims == first.dims
917                                && sdims.len() == fdims.len()
918                                && (0..sdims.len()).all(|k| k == sd || sdims[k] == fdims[k])
919                                && sdims[sd] == a.aval().shape.dims()[*dimension]
920                        });
921                        ok.then_some(sd)
922                    });
923                    if let (Some(bs), Some(sd)) = (bs, same) {
924                        let mut shape = bs[0].src.aval().shape.dims().to_vec();
925                        shape[sd] = bs.iter().map(|b| b.src.aval().shape.dims()[sd]).sum();
926                        let v = Var::new(AVal::new(shape, out.aval().dtype));
927                        eqns.push(new_eqn(
928                            ruxla_prims::CONCATENATE,
929                            bs.iter().map(|b| b.src.clone()).collect(),
930                            Params::Concatenate { dimension: sd },
931                            vec![v.clone()],
932                        ));
933                        let dims = bs[0].dims.clone();
934                        broadcast_to(v.clone().into(), dims.clone(), out.clone(), &mut eqns);
935                        bcast.insert(
936                            out.id(),
937                            Broadcast {
938                                src: v.into(),
939                                dims,
940                            },
941                        );
942                        done = true;
943                    }
944                }
945                ("reshape", _) => {
946                    let ishape = inputs[0].aval().shape.dims().to_vec();
947                    let nonone =
948                        |x: &[usize]| x.iter().copied().filter(|&n| n != 1).collect::<Vec<_>>();
949                    if let Some(b) = of(&inputs[0])
950                        && nonone(&ishape) == nonone(&oshape)
951                    {
952                        // Each operand dimension (not of size one) to its result dimension.
953                        let mut to = HashMap::new();
954                        let mut j = 0;
955                        for (i, &n) in ishape.iter().enumerate() {
956                            if n == 1 {
957                                continue;
958                            }
959                            while oshape[j] == 1 {
960                                j += 1;
961                            }
962                            to.insert(i, j);
963                            j += 1;
964                        }
965                        let sdims = b.src.aval().shape.dims().to_vec();
966                        let kept: Vec<usize> = (0..sdims.len())
967                            .filter(|&sd| ishape[b.dims[sd]] != 1)
968                            .collect();
969                        let src = if kept.len() == sdims.len() {
970                            b.src.clone()
971                        } else {
972                            let shape: Vec<usize> = kept.iter().map(|&sd| sdims[sd]).collect();
973                            let v = Var::new(AVal::new(shape.clone(), b.src.aval().dtype));
974                            eqns.push(new_eqn(
975                                ruxla_prims::RESHAPE,
976                                vec![b.src.clone()],
977                                Params::Reshape {
978                                    new_sizes: ruxla_ir::Shape::from(shape),
979                                },
980                                vec![v.clone()],
981                            ));
982                            v.into()
983                        };
984                        let dims: Vec<usize> = kept.iter().map(|&sd| to[&b.dims[sd]]).collect();
985                        broadcast_to(src.clone(), dims.clone(), out.clone(), &mut eqns);
986                        bcast.insert(out.id(), Broadcast { src, dims });
987                        done = true;
988                    }
989                }
990                _ if elementwise_prim(name)
991                    && name != "threefry2x32"
992                    && oshape.iter().product::<usize>() > 1 =>
993                {
994                    // The array operands broadcast one shape the same way; the others are scalars.
995                    let mut common: Option<Broadcast> = None;
996                    let mut ok = true;
997                    let scalar = |a: &Atom| -> Option<Atom> {
998                        if a.aval().shape.rank() == 0 {
999                            return Some(a.clone());
1000                        }
1001                        match a {
1002                            Atom::Var(v) => uniform.get(&v.id()).cloned(),
1003                            Atom::Lit(_) => None,
1004                        }
1005                    };
1006                    for a in &inputs {
1007                        if scalar(a).is_some() {
1008                            continue;
1009                        }
1010                        match of(a) {
1011                            Some(b) if a.aval().shape.dims() == oshape.as_slice() => {
1012                                match &common {
1013                                    None => common = Some(b),
1014                                    Some(c)
1015                                        if c.dims == b.dims
1016                                            && c.src.aval().shape == b.src.aval().shape => {}
1017                                    _ => ok = false,
1018                                }
1019                            }
1020                            _ => ok = false,
1021                        }
1022                    }
1023                    if ok
1024                        && let Some(c) = common
1025                        && c.src.aval().shape.size() < out.aval().shape.size()
1026                    {
1027                        let srcs: Vec<Atom> = inputs
1028                            .iter()
1029                            .map(|a| scalar(a).unwrap_or_else(|| of(a).expect("a broadcast").src))
1030                            .collect();
1031                        let t = Var::new(AVal::new(
1032                            c.src.aval().shape.dims().to_vec(),
1033                            out.aval().dtype,
1034                        ));
1035                        eqns.push(new_eqn(e.prim, srcs, params.clone(), vec![t.clone()]));
1036                        broadcast_to(t.clone().into(), c.dims.clone(), out.clone(), &mut eqns);
1037                        bcast.insert(
1038                            out.id(),
1039                            Broadcast {
1040                                src: t.into(),
1041                                dims: c.dims,
1042                            },
1043                        );
1044                        done = true;
1045                    }
1046                }
1047                (
1048                    "broadcast_in_dim",
1049                    Params::BroadcastInDim {
1050                        broadcast_dimensions,
1051                        ..
1052                    },
1053                ) => {
1054                    if inputs[0].aval().shape.rank() == 0 {
1055                        uniform.insert(out.id(), inputs[0].clone());
1056                    }
1057                    // A broadcast of a broadcast: one broadcast of the inner source.
1058                    if let Some(inner) = of(&inputs[0]) {
1059                        let dims = inner
1060                            .dims
1061                            .iter()
1062                            .map(|&d| broadcast_dimensions[d])
1063                            .collect();
1064                        bcast.insert(
1065                            out.id(),
1066                            Broadcast {
1067                                src: inner.src,
1068                                dims,
1069                            },
1070                        );
1071                        composed = true;
1072                    }
1073                    if !composed {
1074                        bcast.insert(
1075                            out.id(),
1076                            Broadcast {
1077                                src: inputs[0].clone(),
1078                                dims: broadcast_dimensions.clone(),
1079                            },
1080                        );
1081                    }
1082                }
1083                _ => {}
1084            }
1085        }
1086        if !done {
1087            eqns.push(new_eqn(e.prim, inputs, params, e.outputs.clone()));
1088        }
1089    }
1090    Function {
1091        constvars: f.constvars.clone(),
1092        invars: f.invars.clone(),
1093        eqns,
1094        outvars: f.outvars.clone(),
1095    }
1096}
1097
1098/// The element `k` of `x` as a literal.
1099fn element_lit(x: &HostArray, k: usize) -> Atom {
1100    let all = x.clone().reshape([x.size()]);
1101    let r = ruxla_prims::SLICE
1102        .eval(
1103            &Interp,
1104            &[all],
1105            &Params::Slice {
1106                start_indices: vec![k],
1107                limit_indices: vec![k + 1],
1108                strides: vec![1],
1109            },
1110        )
1111        .expect("a slice of a constant");
1112    lit(r[0].clone().reshape(ruxla_ir::Shape::scalar()))
1113}
1114
1115/// Splits operations on small arrays (of at most [`SCALARIZE_MAX`]
1116/// elements) into operations on their elements, and forwards elements
1117/// through data movement, so that the elements are separate scalars: a
1118/// key split computes two keys with one `threefry2x32` of two lanes, and
1119/// once split, each key's lane is computed only where that key is used.
1120/// The arrays are still built (from the elements) for the operations that
1121/// need them; dead code elimination removes them otherwise.
1122fn scalarize(f: &Function) -> Function {
1123    let mut elems: HashMap<u64, Vec<Atom>> = HashMap::new();
1124    let consts: HashMap<u64, HostArray> = f
1125        .constvars
1126        .iter()
1127        .map(|(v, x)| (v.id(), x.clone()))
1128        .collect();
1129    let mut s = Subst::default();
1130    let mut eqns: Vec<Eqn> = Vec::new();
1131    let new_eqn = |prim, inputs: Vec<Atom>, params: Params, outputs: Vec<Var>| Eqn {
1132        prim,
1133        inputs,
1134        params,
1135        outputs,
1136        loc: None,
1137    };
1138    // The elements of an atom (rank-0 atoms), extracting them if needed.
1139    let elements =
1140        |a: &Atom, eqns: &mut Vec<Eqn>, elems: &mut HashMap<u64, Vec<Atom>>| -> Option<Vec<Atom>> {
1141            let aval = a.aval();
1142            let n = aval.shape.size();
1143            if is_scalar(&aval) {
1144                return Some(vec![a.clone()]);
1145            }
1146            let Atom::Var(v) = a else {
1147                return None;
1148            };
1149            if let Some(es) = elems.get(&v.id()) {
1150                return Some(es.clone());
1151            }
1152            if let Some(x) = consts.get(&v.id()) {
1153                if n > SCALARIZE_MAX {
1154                    return None;
1155                }
1156                let es: Vec<Atom> = (0..n).map(|k| element_lit(x, k)).collect();
1157                elems.insert(v.id(), es.clone());
1158                return Some(es);
1159            }
1160            if n > SCALARIZE_MAX {
1161                return None;
1162            }
1163            // Slices of the flattened array, reshaped to scalars.
1164            let flat = if aval.shape.rank() == 1 {
1165                a.clone()
1166            } else {
1167                let fv = Var::new(AVal::new([n], aval.dtype));
1168                eqns.push(new_eqn(
1169                    ruxla_prims::RESHAPE,
1170                    vec![a.clone()],
1171                    Params::Reshape {
1172                        new_sizes: ruxla_ir::Shape::from(vec![n]),
1173                    },
1174                    vec![fv.clone()],
1175                ));
1176                fv.into()
1177            };
1178            let mut es = Vec::new();
1179            for k in 0..n {
1180                let sv = Var::new(AVal::new([1], aval.dtype));
1181                eqns.push(new_eqn(
1182                    ruxla_prims::SLICE,
1183                    vec![flat.clone()],
1184                    Params::Slice {
1185                        start_indices: vec![k],
1186                        limit_indices: vec![k + 1],
1187                        strides: vec![1],
1188                    },
1189                    vec![sv.clone()],
1190                ));
1191                let ev = Var::new(AVal::scalar(aval.dtype));
1192                eqns.push(new_eqn(
1193                    ruxla_prims::RESHAPE,
1194                    vec![sv.into()],
1195                    Params::Reshape {
1196                        new_sizes: ruxla_ir::Shape::scalar(),
1197                    },
1198                    vec![ev.clone()],
1199                ));
1200                es.push(ev.into());
1201            }
1202            elems.insert(v.id(), es.clone());
1203            Some(es)
1204        };
1205    // Builds `out` from its elements.
1206    let rebuild = |out: &Var, es: &[Atom], eqns: &mut Vec<Eqn>| {
1207        let aval = out.aval();
1208        let n = es.len();
1209        let pieces: Vec<Atom> = es
1210            .iter()
1211            .map(|e| {
1212                let b = Var::new(AVal::new([1], aval.dtype));
1213                eqns.push(new_eqn(
1214                    ruxla_prims::BROADCAST_IN_DIM,
1215                    vec![e.clone()],
1216                    Params::BroadcastInDim {
1217                        shape: ruxla_ir::Shape::from(vec![1]),
1218                        broadcast_dimensions: vec![],
1219                    },
1220                    vec![b.clone()],
1221                ));
1222                b.into()
1223            })
1224            .collect();
1225        if aval.shape.rank() == 1 {
1226            eqns.push(new_eqn(
1227                ruxla_prims::CONCATENATE,
1228                pieces,
1229                Params::Concatenate { dimension: 0 },
1230                vec![out.clone()],
1231            ));
1232        } else {
1233            let c = Var::new(AVal::new([n], aval.dtype));
1234            eqns.push(new_eqn(
1235                ruxla_prims::CONCATENATE,
1236                pieces,
1237                Params::Concatenate { dimension: 0 },
1238                vec![c.clone()],
1239            ));
1240            eqns.push(new_eqn(
1241                ruxla_prims::RESHAPE,
1242                vec![c.into()],
1243                Params::Reshape {
1244                    new_sizes: aval.shape.clone(),
1245                },
1246                vec![out.clone()],
1247            ));
1248        }
1249    };
1250    for e in &f.eqns {
1251        let inputs: Vec<Atom> = e.inputs.iter().map(|a| s.atom(a)).collect();
1252        let name = e.prim.name();
1253        let out_size = e.outputs.first().map_or(0, |o| o.aval().shape.size());
1254        let small_inputs = inputs
1255            .iter()
1256            .all(|a| a.aval().shape.size() <= 4 * SCALARIZE_MAX);
1257        // Empty arrays stay arrays (there are no elements to rebuild them
1258        // from).
1259        let candidate = (1..=SCALARIZE_MAX).contains(&out_size)
1260            && small_inputs
1261            && e.outputs.iter().all(|o| o.aval().shape.size() == out_size)
1262            && (elementwise_prim(name) || movement_prim(name))
1263            && e.params.functions().is_empty();
1264        if !candidate {
1265            eqns.push(Eqn {
1266                inputs,
1267                params: map_functions(&e.params, &scalarize),
1268                ..e.clone()
1269            });
1270            continue;
1271        }
1272        if movement_prim(name) {
1273            // The positions, with a probe: input `k`'s element `i` is coded
1274            // `(k + 1) << 32 | i`.
1275            let mut srcs: Vec<Vec<Atom>> = Vec::new();
1276            let mut ok = true;
1277            for a in &inputs {
1278                match elements(a, &mut eqns, &mut elems) {
1279                    Some(es) => srcs.push(es),
1280                    None => {
1281                        ok = false;
1282                        break;
1283                    }
1284                }
1285            }
1286            let probes: Vec<HostArray> = inputs
1287                .iter()
1288                .enumerate()
1289                .map(|(k, a)| {
1290                    let n = a.aval().shape.size();
1291                    HostArray::from_vec(
1292                        (0..n)
1293                            .map(|i| (((k + 1) as i64) << 32) | i as i64)
1294                            .collect::<Vec<i64>>(),
1295                        a.aval().shape.clone(),
1296                    )
1297                })
1298                .collect();
1299            let map = ok
1300                .then(|| e.prim.eval(&Interp, &probes, &e.params).ok())
1301                .flatten()
1302                .and_then(|r| r[0].to_vec::<i64>().ok());
1303            let Some(map) = map else {
1304                eqns.push(Eqn {
1305                    inputs,
1306                    ..e.clone()
1307                });
1308                continue;
1309            };
1310            let es: Vec<Atom> = map
1311                .iter()
1312                .map(|&m| srcs[((m >> 32) - 1) as usize][(m & 0xffff_ffff) as usize].clone())
1313                .collect();
1314            let out = &e.outputs[0];
1315            if is_scalar(out.aval()) {
1316                s.set(out, es[0].clone());
1317            } else {
1318                elems.insert(out.id(), es.clone());
1319                rebuild(out, &es, &mut eqns);
1320            }
1321            continue;
1322        }
1323        // Elementwise: one equation per element.
1324        if out_size <= 1 {
1325            eqns.push(Eqn {
1326                inputs,
1327                ..e.clone()
1328            });
1329            continue;
1330        }
1331        let mut srcs: Vec<Vec<Atom>> = Vec::new();
1332        let mut ok = true;
1333        for a in &inputs {
1334            match elements(a, &mut eqns, &mut elems) {
1335                Some(es) => srcs.push(es),
1336                None => {
1337                    ok = false;
1338                    break;
1339                }
1340            }
1341        }
1342        if !ok {
1343            eqns.push(Eqn {
1344                inputs,
1345                ..e.clone()
1346            });
1347            continue;
1348        }
1349        let mut outs: Vec<Vec<Atom>> = vec![Vec::new(); e.outputs.len()];
1350        for k in 0..out_size {
1351            let ins: Vec<Atom> = srcs
1352                .iter()
1353                .map(|es| {
1354                    if es.len() == 1 {
1355                        es[0].clone()
1356                    } else {
1357                        es[k].clone()
1358                    }
1359                })
1360                .collect();
1361            let os: Vec<Var> = e
1362                .outputs
1363                .iter()
1364                .map(|o| Var::new(AVal::scalar(o.aval().dtype)))
1365                .collect();
1366            for (j, o) in os.iter().enumerate() {
1367                outs[j].push(o.clone().into());
1368            }
1369            eqns.push(Eqn {
1370                prim: e.prim,
1371                inputs: ins,
1372                params: e.params.clone(),
1373                outputs: os,
1374                loc: e.loc,
1375            });
1376        }
1377        for (o, es) in e.outputs.iter().zip(outs) {
1378            elems.insert(o.id(), es.clone());
1379            rebuild(o, &es, &mut eqns);
1380        }
1381    }
1382    Function {
1383        constvars: f.constvars.clone(),
1384        invars: f.invars.clone(),
1385        eqns,
1386        outvars: f.outvars.iter().map(|a| s.atom(a)).collect(),
1387    }
1388}
1389
1390/// Common subexpression elimination.
1391fn cse(f: &Function) -> Function {
1392    let mut s = Subst::default();
1393    let mut seen: HashMap<String, Vec<Var>> = HashMap::new();
1394    let mut eqns = Vec::new();
1395    for e in &f.eqns {
1396        let inputs: Vec<Atom> = e.inputs.iter().map(|a| s.atom(a)).collect();
1397        let params = map_functions(&e.params, &cse);
1398        let has_functions = !params.functions().is_empty();
1399        if !has_functions {
1400            let key = format!("{}|{:?}|{:?}", e.prim.name(), inputs, params);
1401            if let Some(outs) = seen.get(&key) {
1402                for (o, p) in e.outputs.iter().zip(outs) {
1403                    s.set(o, p.clone().into());
1404                }
1405                continue;
1406            }
1407            seen.insert(key, e.outputs.clone());
1408        }
1409        eqns.push(Eqn {
1410            prim: e.prim,
1411            inputs,
1412            params,
1413            outputs: e.outputs.clone(),
1414            loc: e.loc,
1415        });
1416    }
1417    Function {
1418        constvars: f.constvars.clone(),
1419        invars: f.invars.clone(),
1420        eqns,
1421        outvars: f.outvars.iter().map(|a| s.atom(a)).collect(),
1422    }
1423}
1424
1425fn mark(a: &Atom, live: &mut HashSet<u64>) {
1426    if let Atom::Var(v) = a {
1427        live.insert(v.id());
1428    }
1429}
1430
1431/// The variables that `f` reads from outside (its free variables, not
1432/// counting its inputs), and those it reads at all.
1433fn used_vars(f: &Function) -> HashSet<u64> {
1434    let mut used = HashSet::new();
1435    for e in &f.eqns {
1436        for a in &e.inputs {
1437            mark(a, &mut used);
1438        }
1439    }
1440    for a in &f.outvars {
1441        mark(a, &mut used);
1442    }
1443    used
1444}
1445
1446/// Dead code elimination (also of the unused outputs and operands of
1447/// conditionals).
1448fn dce(f: &Function) -> Function {
1449    let mut live = HashSet::new();
1450    for a in &f.outvars {
1451        mark(a, &mut live);
1452    }
1453    let mut eqns: Vec<Eqn> = Vec::new();
1454    for e in f.eqns.iter().rev() {
1455        let used: Vec<bool> = e.outputs.iter().map(|o| live.contains(&o.id())).collect();
1456        if !used.iter().any(|&u| u) {
1457            continue;
1458        }
1459        let e = match &e.params {
1460            Params::Cond { branches } => prune_cond(e, branches, &used),
1461            p => Eqn {
1462                params: map_functions(p, &dce),
1463                ..e.clone()
1464            },
1465        };
1466        for a in &e.inputs {
1467            mark(a, &mut live);
1468        }
1469        eqns.push(e);
1470    }
1471    eqns.reverse();
1472    Function {
1473        constvars: f
1474            .constvars
1475            .iter()
1476            .filter(|(v, _)| live.contains(&v.id()))
1477            .cloned()
1478            .collect(),
1479        invars: f.invars.clone(),
1480        eqns,
1481        outvars: f.outvars.clone(),
1482    }
1483}
1484
1485/// A conditional without the outputs that are not `used`, and without the
1486/// operands that no branch reads.
1487fn prune_cond(e: &Eqn, branches: &[Arc<Function>], used: &[bool]) -> Eqn {
1488    let branches: Vec<Function> = branches
1489        .iter()
1490        .map(|b| {
1491            dce(&Function {
1492                outvars: b
1493                    .outvars
1494                    .iter()
1495                    .zip(used)
1496                    .filter(|(_, u)| **u)
1497                    .map(|(a, _)| a.clone())
1498                    .collect(),
1499                ..(**b).clone()
1500            })
1501        })
1502        .collect();
1503    let n = e.inputs.len() - 1;
1504    let reads: Vec<HashSet<u64>> = branches.iter().map(used_vars).collect();
1505    let read: Vec<bool> = (0..n)
1506        .map(|k| {
1507            branches
1508                .iter()
1509                .zip(&reads)
1510                .any(|(b, r)| r.contains(&b.invars[k].id()))
1511        })
1512        .collect();
1513    let branches = branches
1514        .into_iter()
1515        .map(|b| {
1516            Arc::new(Function {
1517                invars: b
1518                    .invars
1519                    .iter()
1520                    .zip(&read)
1521                    .filter(|(_, r)| **r)
1522                    .map(|(v, _)| v.clone())
1523                    .collect(),
1524                ..b
1525            })
1526        })
1527        .collect();
1528    let mut inputs = vec![e.inputs[0].clone()];
1529    inputs.extend(
1530        e.inputs[1..]
1531            .iter()
1532            .zip(&read)
1533            .filter(|(_, r)| **r)
1534            .map(|(a, _)| a.clone()),
1535    );
1536    Eqn {
1537        prim: e.prim,
1538        inputs,
1539        params: Params::Cond { branches },
1540        outputs: e
1541            .outputs
1542            .iter()
1543            .zip(used)
1544            .filter(|(_, u)| **u)
1545            .map(|(o, _)| o.clone())
1546            .collect(),
1547        loc: e.loc,
1548    }
1549}
1550
1551/// The scalar boolean predicate of a two-way `select_n` (also when the
1552/// predicate is a scalar broadcast to the shape of the cases).
1553fn scalar_predicate(e: &Eqn, defs: &HashMap<u64, usize>, eqns: &[Eqn]) -> Option<Var> {
1554    if e.prim.name() != "select_n" || e.inputs.len() != 3 {
1555        return None;
1556    }
1557    let Atom::Var(p) = &e.inputs[0] else {
1558        return None;
1559    };
1560    if p.aval().dtype != DType::Bool {
1561        return None;
1562    }
1563    if p.aval().shape.size() == 1 && p.aval().shape.rank() == 0 {
1564        return Some(p.clone());
1565    }
1566    let d = &eqns[*defs.get(&p.id())?];
1567    if d.prim.name() == "broadcast_in_dim"
1568        && let Atom::Var(q) = &d.inputs[0]
1569        && is_scalar(q.aval())
1570    {
1571        return Some(q.clone());
1572    }
1573    None
1574}
1575
1576/// Replaces a case of a select that is itself a select on the same scalar
1577/// predicate by that select's case: `select_n(p, select_n(p, a, b), c)` is
1578/// `select_n(p, a, c)`, and likewise for the other case, at this level and
1579/// in nested functions. Otherwise the outer select depends on the inner
1580/// one, cannot join the group of selects on `p` that becomes a conditional,
1581/// and keeps what its other case computes out of the conditional (Pgx's
1582/// legal action mask, all true where the episode ended, then selected
1583/// against the reset's).
1584fn collapse_nested_selects(f: &Function) -> Function {
1585    let mut eqns: Vec<Eqn> = Vec::with_capacity(f.eqns.len());
1586    let mut defs: HashMap<u64, usize> = HashMap::new();
1587    for e in &f.eqns {
1588        let mut e = Eqn {
1589            params: map_functions(&e.params, &collapse_nested_selects),
1590            ..e.clone()
1591        };
1592        if e.inputs.len() == 3
1593            && let Some(p) = scalar_predicate(&e, &defs, &eqns)
1594        {
1595            for k in 1..3 {
1596                if let Atom::Var(v) = &e.inputs[k]
1597                    && let Some(&d) = defs.get(&v.id())
1598                    && eqns[d].inputs.len() == 3
1599                    && scalar_predicate(&eqns[d], &defs, &eqns).is_some_and(|q| q.id() == p.id())
1600                {
1601                    e.inputs[k] = eqns[d].inputs[k].clone();
1602                }
1603            }
1604        }
1605        for o in &e.outputs {
1606            defs.insert(o.id(), eqns.len());
1607        }
1608        eqns.push(e);
1609    }
1610    Function { eqns, ..f.clone() }
1611}
1612
1613/// Replaces a select between an array and scatters into it by the scatters
1614/// with selected updates, at this level and in nested functions:
1615/// `select_n(p, scatter(x, i, u), x)` is `scatter(x, i, select_n(p[i], u,
1616/// x[i]))` (the positions that the scatter writes, read with a `gather` of
1617/// the same dimension numbers; a chain of scatters into `x` likewise). JAX's
1618/// batching of `cond` (Jumanji's robots, each updating its observation in a
1619/// `scan` under `vmap`) gives such selects with an array predicate, which
1620/// otherwise copy the array, write the copy, and select every element.
1621fn mask_scatters(f: &Function) -> Function {
1622    let mut uses: HashMap<u64, usize> = HashMap::new();
1623    for e in &f.eqns {
1624        for a in &e.inputs {
1625            if let Atom::Var(v) = a {
1626                *uses.entry(v.id()).or_default() += 1;
1627            }
1628        }
1629    }
1630    for a in &f.outvars {
1631        if let Atom::Var(v) = a {
1632            *uses.entry(v.id()).or_default() += 1;
1633        }
1634    }
1635    let defs: HashMap<u64, usize> = f
1636        .eqns
1637        .iter()
1638        .enumerate()
1639        .flat_map(|(k, e)| e.outputs.iter().map(move |o| (o.id(), k)))
1640        .collect();
1641    let mut eqns = Vec::with_capacity(f.eqns.len());
1642    for e in &f.eqns {
1643        let e = Eqn {
1644            params: map_functions(&e.params, &mask_scatters),
1645            ..e.clone()
1646        };
1647        match masked_scatter(&e, &f.eqns, &defs, &uses) {
1648            Some(new) => eqns.extend(new),
1649            None => eqns.push(e),
1650        }
1651    }
1652    Function { eqns, ..f.clone() }
1653}
1654
1655/// The equations of [`mask_scatters`] that replace the select `e`, if it is
1656/// one between `x` and a chain of `scatter`s into `x` used only by it.
1657fn masked_scatter(
1658    e: &Eqn,
1659    eqns: &[Eqn],
1660    defs: &HashMap<u64, usize>,
1661    uses: &HashMap<u64, usize>,
1662) -> Option<Vec<Eqn>> {
1663    if e.prim.name() != "select_n" || e.inputs.len() != 3 {
1664        return None;
1665    }
1666    let out = &e.outputs[0];
1667    let Atom::Var(p) = &e.inputs[0] else {
1668        return None;
1669    };
1670    // A boolean predicate, or an integer one (the index of a batched `cond`).
1671    if matches!(p.aval().dtype.kind(), DTypeKind::Float | DTypeKind::Complex)
1672        || p.aval().shape != out.aval().shape
1673    {
1674        return None;
1675    }
1676    for k in 0..2 {
1677        let (Atom::Var(chain), Atom::Var(x)) = (&e.inputs[1 + k], &e.inputs[2 - k]) else {
1678            continue;
1679        };
1680        // The scatters from the select back to `x` (outermost first).
1681        let mut scatters: Vec<&Eqn> = Vec::new();
1682        let mut cur = chain.clone();
1683        let found = loop {
1684            if cur.id() == x.id() {
1685                break !scatters.is_empty();
1686            }
1687            let Some(&d) = defs.get(&cur.id()) else {
1688                break false;
1689            };
1690            let s = &eqns[d];
1691            if s.prim.name() != "scatter"
1692                || uses.get(&cur.id()).copied() != Some(1)
1693                || scatters.len() >= 16
1694            {
1695                break false;
1696            }
1697            let Atom::Var(operand) = &s.inputs[0] else {
1698                break false;
1699            };
1700            scatters.push(s);
1701            cur = operand.clone();
1702        };
1703        if !found {
1704            continue;
1705        }
1706        let mut new = Vec::new();
1707        let mut operand = Atom::Var(x.clone());
1708        for (j, s) in scatters.iter().rev().enumerate() {
1709            let Params::Scatter {
1710                dimension_numbers: d,
1711                mode,
1712                indices_are_sorted,
1713                unique_indices,
1714            } = &s.params
1715            else {
1716                return None;
1717            };
1718            let (idx, u) = (&s.inputs[1], &s.inputs[2]);
1719            let rank = out.aval().shape.rank();
1720            let mut slice_sizes = vec![1usize; rank];
1721            let window: Vec<usize> = (0..rank)
1722                .filter(|i| {
1723                    !d.inserted_window_dims.contains(i) && !d.operand_batching_dims.contains(i)
1724                })
1725                .collect();
1726            if window.len() != d.update_window_dims.len() {
1727                return None;
1728            }
1729            for (&o, &w) in window.iter().zip(&d.update_window_dims) {
1730                slice_sizes[o] = u.aval().shape.dims()[w];
1731            }
1732            let gather = Params::Gather {
1733                dimension_numbers: ruxla_ir::GatherDims {
1734                    offset_dims: d.update_window_dims.clone(),
1735                    collapsed_slice_dims: d.inserted_window_dims.clone(),
1736                    start_index_map: d.scatter_dims_to_operand_dims.clone(),
1737                    operand_batching_dims: d.operand_batching_dims.clone(),
1738                    start_indices_batching_dims: d.scatter_indices_batching_dims.clone(),
1739                },
1740                slice_sizes,
1741                mode: *mode,
1742                indices_are_sorted: *indices_are_sorted,
1743                unique_indices: *unique_indices,
1744            };
1745            let eqn = |prim, inputs, params: Params, out: &Var| Eqn {
1746                prim,
1747                inputs,
1748                params,
1749                outputs: vec![out.clone()],
1750                loc: e.loc,
1751            };
1752            let gp = Var::new(AVal::new(u.aval().shape.clone(), p.aval().dtype));
1753            new.push(eqn(
1754                ruxla_prims::GATHER,
1755                vec![Atom::Var(p.clone()), idx.clone()],
1756                gather.clone(),
1757                &gp,
1758            ));
1759            let gx = Var::new(u.aval());
1760            new.push(eqn(
1761                ruxla_prims::GATHER,
1762                vec![operand.clone(), idx.clone()],
1763                gather,
1764                &gx,
1765            ));
1766            let selected = Var::new(u.aval());
1767            let cases = if k == 0 {
1768                vec![Atom::Var(gp), u.clone(), Atom::Var(gx)]
1769            } else {
1770                vec![Atom::Var(gp), Atom::Var(gx), u.clone()]
1771            };
1772            new.push(eqn(ruxla_prims::SELECT_N, cases, Params::None, &selected));
1773            let result = if j + 1 == scatters.len() {
1774                out.clone()
1775            } else {
1776                Var::new(s.outputs[0].aval().clone())
1777            };
1778            new.push(eqn(
1779                ruxla_prims::SCATTER,
1780                vec![operand, idx.clone(), Atom::Var(selected)],
1781                s.params.clone(),
1782                &result,
1783            ));
1784            operand = Atom::Var(result);
1785        }
1786        return Some(new);
1787    }
1788    None
1789}
1790
1791/// Turns groups of selects on the same scalar predicate into conditionals
1792/// whose branches compute what only that side of the selects uses, at this
1793/// level and in nested functions.
1794fn sink_selects(f: &Function, options: &Options) -> Function {
1795    let mut f = f.clone();
1796    while let Some(g) = sink_one_group(&f) {
1797        f = g;
1798    }
1799    // Nested functions (the new branches among them).
1800    let eqns = f
1801        .eqns
1802        .iter()
1803        .map(|e| Eqn {
1804            params: map_functions(&e.params, &|g: &Function| {
1805                let g = simplify(g, options);
1806                sink_selects(&g, options)
1807            }),
1808            ..e.clone()
1809        })
1810        .collect();
1811    Function { eqns, ..f }
1812}
1813
1814/// Takes the outputs of two-way conditionals that every branch gives
1815/// without computing them (an operand, a literal, or a constant) out of
1816/// the conditional as selects, which code generation turns into a write
1817/// only where the value changes (an unchanged state, for example, is not
1818/// copied through the conditional).
1819fn hoist_passthrough(f: &Function) -> Function {
1820    let mut defs: HashMap<u64, &Eqn> = HashMap::new();
1821    for e in &f.eqns {
1822        for o in &e.outputs {
1823            defs.insert(o.id(), e);
1824        }
1825    }
1826    let mut constvars = f.constvars.clone();
1827    let mut eqns = Vec::new();
1828    for e in &f.eqns {
1829        let params = map_functions(&e.params, &hoist_passthrough);
1830        let e = Eqn {
1831            params,
1832            ..e.clone()
1833        };
1834        let Params::Cond { branches } = &e.params else {
1835            eqns.push(e);
1836            continue;
1837        };
1838        // The boolean predicate of the index.
1839        let pred = match &e.inputs[0] {
1840            Atom::Var(i) => defs.get(&i.id()).and_then(|d| {
1841                (d.prim.name() == "convert_element_type"
1842                    && d.inputs[0].aval().dtype == DType::Bool
1843                    && is_scalar(&d.inputs[0].aval()))
1844                .then(|| d.inputs[0].clone())
1845            }),
1846            Atom::Lit(_) => None,
1847        };
1848        let (Some(pred), 2) = (pred, branches.len()) else {
1849            eqns.push(e);
1850            continue;
1851        };
1852        // The atom outside that a branch output is, if any.
1853        let outside =
1854            |b: &Function, a: &Atom, consts: &mut Vec<(Var, HostArray)>| -> Option<Atom> {
1855                match a {
1856                    Atom::Lit(_) => Some(a.clone()),
1857                    Atom::Var(v) => {
1858                        if let Some(k) = b.invars.iter().position(|x| x.id() == v.id()) {
1859                            return Some(e.inputs[1 + k].clone());
1860                        }
1861                        let (cv, cx) = b.constvars.iter().find(|(c, _)| c.id() == v.id())?;
1862                        if !consts.iter().any(|(c, _)| c.id() == cv.id()) {
1863                            consts.push((cv.clone(), cx.clone()));
1864                        }
1865                        Some(Atom::Var(cv.clone()))
1866                    }
1867                }
1868            };
1869        let mut hoisted: Vec<(usize, Atom, Atom)> = Vec::new();
1870        let mut new_consts = Vec::new();
1871        for k in 0..e.outputs.len() {
1872            let mut tmp = Vec::new();
1873            let a0 = outside(&branches[0], &branches[0].outvars[k], &mut tmp);
1874            let a1 = outside(&branches[1], &branches[1].outvars[k], &mut tmp);
1875            if let (Some(a0), Some(a1)) = (a0, a1) {
1876                new_consts.extend(tmp);
1877                hoisted.push((k, a0, a1));
1878            }
1879        }
1880        if hoisted.is_empty() {
1881            eqns.push(e);
1882            continue;
1883        }
1884        for c in new_consts {
1885            if !constvars.iter().any(|(v, _)| v.id() == c.0.id()) {
1886                constvars.push(c);
1887            }
1888        }
1889        let keep: Vec<bool> = (0..e.outputs.len())
1890            .map(|k| !hoisted.iter().any(|(h, _, _)| *h == k))
1891            .collect();
1892        let branches: Vec<Arc<Function>> = branches
1893            .iter()
1894            .map(|b| {
1895                Arc::new(Function {
1896                    outvars: b
1897                        .outvars
1898                        .iter()
1899                        .zip(&keep)
1900                        .filter(|(_, k)| **k)
1901                        .map(|(a, _)| a.clone())
1902                        .collect(),
1903                    ..(**b).clone()
1904                })
1905            })
1906            .collect();
1907        let outputs: Vec<Var> = e
1908            .outputs
1909            .iter()
1910            .zip(&keep)
1911            .filter(|(_, k)| **k)
1912            .map(|(o, _)| o.clone())
1913            .collect();
1914        if !outputs.is_empty() {
1915            eqns.push(Eqn {
1916                prim: e.prim,
1917                inputs: e.inputs.clone(),
1918                params: Params::Cond { branches },
1919                outputs,
1920                loc: e.loc,
1921            });
1922        }
1923        for (k, a0, a1) in hoisted {
1924            eqns.push(Eqn {
1925                prim: ruxla_prims::SELECT_N,
1926                inputs: vec![pred.clone(), a0, a1],
1927                params: Params::None,
1928                outputs: vec![e.outputs[k].clone()],
1929                loc: e.loc,
1930            });
1931        }
1932    }
1933    Function {
1934        constvars,
1935        eqns,
1936        ..f.clone()
1937    }
1938}
1939
1940const OUTVAR: usize = usize::MAX;
1941
1942/// Sinks the first group of selects that has code to sink.
1943fn sink_one_group(f: &Function) -> Option<Function> {
1944    let eqns = &f.eqns;
1945    let mut defs: HashMap<u64, usize> = HashMap::new();
1946    for (i, e) in eqns.iter().enumerate() {
1947        for o in &e.outputs {
1948            defs.insert(o.id(), i);
1949        }
1950    }
1951    let mut groups: Vec<(Var, Vec<usize>)> = Vec::new();
1952    for (i, e) in eqns.iter().enumerate() {
1953        if let Some(p) = scalar_predicate(e, &defs, eqns) {
1954            match groups.iter_mut().find(|(q, _)| q.id() == p.id()) {
1955                Some((_, sel)) => sel.push(i),
1956                None => groups.push((p, vec![i])),
1957            }
1958        }
1959    }
1960    let mut uses: HashMap<u64, Vec<(usize, usize)>> = HashMap::new();
1961    for (i, e) in eqns.iter().enumerate() {
1962        for (k, a) in e.inputs.iter().enumerate() {
1963            if let Atom::Var(v) = a {
1964                uses.entry(v.id()).or_default().push((i, k));
1965            }
1966        }
1967    }
1968    for a in &f.outvars {
1969        if let Atom::Var(v) = a {
1970            uses.entry(v.id()).or_default().push((OUTVAR, 0));
1971        }
1972    }
1973    groups.iter().find_map(|(p, sel)| {
1974        let sel = independent_selects(eqns, &defs, sel);
1975        sink_group(f, p, &sel, &uses)
1976    })
1977}
1978
1979/// The selects of a group, in order, without those that depend on an
1980/// earlier one (one conditional cannot compute both).
1981fn independent_selects(eqns: &[Eqn], defs: &HashMap<u64, usize>, sel: &[usize]) -> Vec<usize> {
1982    let mut chosen: Vec<usize> = Vec::new();
1983    for &j in sel {
1984        // The equations that select `j` depends on.
1985        let mut seen = HashSet::new();
1986        let mut stack = vec![j];
1987        let mut depends = false;
1988        while let Some(i) = stack.pop() {
1989            if i != j && chosen.contains(&i) {
1990                depends = true;
1991                break;
1992            }
1993            for a in &eqns[i].inputs {
1994                if let Atom::Var(v) = a
1995                    && let Some(&d) = defs.get(&v.id())
1996                    && seen.insert(d)
1997                {
1998                    stack.push(d);
1999                }
2000            }
2001        }
2002        if !depends {
2003            chosen.push(j);
2004        }
2005    }
2006    chosen
2007}
2008
2009/// A rough cost of computing an equation: the elements it writes, weighted
2010/// for expensive operations.
2011fn cost(e: &Eqn) -> usize {
2012    let out: usize = e.outputs.iter().map(|o| o.aval().shape.size()).sum();
2013    let weight = match e.prim.name() {
2014        "reshape" => 0,
2015        "threefry2x32" => 30,
2016        "exp" | "log" | "log1p" | "expm1" | "sin" | "cos" | "tan" | "tanh" | "logistic"
2017        | "erf_inv" | "erf" | "erfc" | "pow" | "atan2" | "sqrt" | "rsqrt" | "cbrt" | "lgamma"
2018        | "digamma" => 10,
2019        _ => 1,
2020    };
2021    out * weight
2022        + e.params
2023            .functions()
2024            .iter()
2025            .map(|g| g.eqns.iter().map(cost).sum::<usize>())
2026            .sum::<usize>()
2027}
2028
2029/// The least cost of the code that a conditional moves out of the way.
2030const MIN_SINK_COST: usize = 12;
2031
2032fn sink_group(
2033    f: &Function,
2034    p: &Var,
2035    sel: &[usize],
2036    uses: &HashMap<u64, Vec<(usize, usize)>>,
2037) -> Option<Function> {
2038    let eqns = &f.eqns;
2039    let n = eqns.len();
2040    let selset: HashSet<usize> = sel.iter().copied().collect();
2041    // The equations that only one side of the selects uses (directly or
2042    // through other such equations), found from the last equation back.
2043    let mut excl = [vec![false; n], vec![false; n]];
2044    for (side, ex) in excl.iter_mut().enumerate() {
2045        for i in (0..n).rev() {
2046            if selset.contains(&i) {
2047                continue;
2048            }
2049            // Every use of the outputs is on this side (outputs without uses
2050            // do not count, but one output must be used).
2051            let mut used = false;
2052            ex[i] = eqns[i].outputs.iter().all(|o| {
2053                let us = uses.get(&o.id()).map_or(&[][..], Vec::as_slice);
2054                used |= !us.is_empty();
2055                us.iter()
2056                    .all(|&(j, k)| j != OUTVAR && (ex[j] || (selset.contains(&j) && k == 1 + side)))
2057            }) && used;
2058        }
2059    }
2060    let moved: usize = (0..n)
2061        .filter(|&i| excl[0][i] || excl[1][i])
2062        .map(|i| cost(&eqns[i]))
2063        .sum();
2064    if sel.is_empty() || moved < MIN_SINK_COST {
2065        return None;
2066    }
2067    // The branches.
2068    let mut operands: Vec<Var> = Vec::new();
2069    let mut operand_ids = HashSet::new();
2070    let mut bodies: Vec<(Vec<Eqn>, Vec<Atom>)> = Vec::new();
2071    for ex in &excl {
2072        let body: Vec<Eqn> = (0..n).filter(|&i| ex[i]).map(|i| eqns[i].clone()).collect();
2073        let outvars: Vec<Atom> = sel
2074            .iter()
2075            .map(|&j| eqns[j].inputs[1 + bodies.len()].clone())
2076            .collect();
2077        let defined: HashSet<u64> = body
2078            .iter()
2079            .flat_map(|e| e.outputs.iter().map(Var::id))
2080            .collect();
2081        let reads = body
2082            .iter()
2083            .flat_map(|e| e.inputs.iter())
2084            .chain(outvars.iter());
2085        for a in reads {
2086            if let Atom::Var(v) = a
2087                && !defined.contains(&v.id())
2088                && operand_ids.insert(v.id())
2089            {
2090                operands.push(v.clone());
2091            }
2092        }
2093        bodies.push((body, outvars));
2094    }
2095    let branches: Vec<Arc<Function>> = bodies
2096        .into_iter()
2097        .map(|(eqns, outvars)| {
2098            Arc::new(Function {
2099                constvars: Vec::new(),
2100                invars: operands.clone(),
2101                eqns,
2102                outvars,
2103            })
2104        })
2105        .collect();
2106    let index = Var::new(AVal::scalar(DType::I32));
2107    let convert = Eqn {
2108        prim: ruxla_prims::CONVERT_ELEMENT_TYPE,
2109        inputs: vec![p.clone().into()],
2110        params: Params::Convert {
2111            new_dtype: DType::I32,
2112        },
2113        outputs: vec![index.clone()],
2114        loc: None,
2115    };
2116    let mut cond_inputs: Vec<Atom> = vec![index.into()];
2117    cond_inputs.extend(operands.iter().cloned().map(Atom::Var));
2118    let cond = Eqn {
2119        prim: ruxla_prims::COND,
2120        inputs: cond_inputs,
2121        params: Params::Cond { branches },
2122        outputs: sel.iter().map(|&j| eqns[j].outputs[0].clone()).collect(),
2123        loc: eqns[sel[0]].loc,
2124    };
2125    // Schedules the remaining equations and the conditional (as one node)
2126    // in dependency order, keeping the original order where possible.
2127    let mut nodes: Vec<(usize, Vec<Eqn>)> = Vec::new();
2128    for (i, e) in eqns.iter().enumerate() {
2129        if !selset.contains(&i) && !excl[0][i] && !excl[1][i] {
2130            nodes.push((i, vec![e.clone()]));
2131        }
2132    }
2133    nodes.push((sel[0], vec![convert, cond]));
2134    schedule(f, nodes)
2135}
2136
2137/// Orders nodes of equations so that every variable is defined before it
2138/// is used, preferring the nodes' priorities; `None` if they depend on each
2139/// other in a cycle.
2140fn schedule(f: &Function, mut nodes: Vec<(usize, Vec<Eqn>)>) -> Option<Function> {
2141    nodes.sort_by_key(|(p, _)| *p);
2142    let mut producer: HashMap<u64, usize> = HashMap::new();
2143    for (k, (_, es)) in nodes.iter().enumerate() {
2144        for e in es {
2145            for o in &e.outputs {
2146                producer.insert(o.id(), k);
2147            }
2148        }
2149    }
2150    let mut deps: Vec<HashSet<usize>> = vec![HashSet::new(); nodes.len()];
2151    let mut users: Vec<Vec<usize>> = vec![Vec::new(); nodes.len()];
2152    for (k, (_, es)) in nodes.iter().enumerate() {
2153        let inner: HashSet<u64> = es
2154            .iter()
2155            .flat_map(|e| e.outputs.iter().map(Var::id))
2156            .collect();
2157        for e in es {
2158            for a in &e.inputs {
2159                if let Atom::Var(v) = a
2160                    && !inner.contains(&v.id())
2161                    && let Some(&q) = producer.get(&v.id())
2162                    && deps[k].insert(q)
2163                {
2164                    users[q].push(k);
2165                }
2166            }
2167        }
2168    }
2169    let mut indegree: Vec<usize> = deps.iter().map(HashSet::len).collect();
2170    let mut ready: BinaryHeap<Reverse<(usize, usize)>> = BinaryHeap::new();
2171    for (k, (p, _)) in nodes.iter().enumerate() {
2172        if indegree[k] == 0 {
2173            ready.push(Reverse((*p, k)));
2174        }
2175    }
2176    let mut order = Vec::new();
2177    while let Some(Reverse((_, k))) = ready.pop() {
2178        order.push(k);
2179        for &u in &users[k] {
2180            indegree[u] -= 1;
2181            if indegree[u] == 0 {
2182                ready.push(Reverse((nodes[u].0, u)));
2183            }
2184        }
2185    }
2186    if order.len() != nodes.len() {
2187        return None;
2188    }
2189    let eqns = order
2190        .into_iter()
2191        .flat_map(|k| std::mem::take(&mut nodes[k].1))
2192        .collect();
2193    Some(Function {
2194        constvars: f.constvars.clone(),
2195        invars: f.invars.clone(),
2196        eqns,
2197        outvars: f.outvars.clone(),
2198    })
2199}
2200
2201#[cfg(test)]
2202mod tests {
2203    use ruxla_ir::{
2204        AVal, Atom, DType, Eqn, Function, GatherScatterMode, HostArray, Params, ScatterDims, Var,
2205    };
2206
2207    /// A small generator of test inputs.
2208    struct Lcg(u64);
2209
2210    impl Lcg {
2211        fn next(&mut self, n: i64) -> i64 {
2212            self.0 = self
2213                .0
2214                .wrapping_mul(6364136223846793005)
2215                .wrapping_add(1442695041);
2216            ((self.0 >> 33) as i64).rem_euclid(n)
2217        }
2218    }
2219
2220    fn eqn(prim: ruxla_ir::Prim, inputs: Vec<Atom>, params: Params, out: &Var) -> Eqn {
2221        Eqn {
2222            prim,
2223            inputs,
2224            params,
2225            outputs: vec![out.clone()],
2226            loc: None,
2227        }
2228    }
2229
2230    /// `select_n(p, x, scatter(scatter(x, i, u), j, w))` (or one scatter)
2231    /// over an operand of shape `shape`, updated by windows of `window`
2232    /// elements along the last dimension (1: elements) at row-major
2233    /// positions given by one index per update.
2234    fn masked(
2235        shape: &[usize],
2236        window: usize,
2237        updates: usize,
2238        chain: usize,
2239        mode: GatherScatterMode,
2240        pred: DType,
2241        on_true: bool,
2242    ) -> Function {
2243        let rank = shape.len();
2244        let x = Var::new(AVal::new(shape.to_vec(), DType::I32));
2245        let p = Var::new(AVal::new(shape.to_vec(), pred));
2246        // The index vectors give every dimension; the last one is a window
2247        // of `window` elements (an inserted dimension when it is 1).
2248        let ia = AVal::new(vec![updates, rank], DType::I32);
2249        let mut ushape = vec![updates];
2250        if window > 1 {
2251            ushape.push(window);
2252        }
2253        let ua = AVal::new(ushape, DType::I32);
2254        let dims = ScatterDims {
2255            update_window_dims: if window > 1 { vec![1] } else { vec![] },
2256            inserted_window_dims: if window > 1 {
2257                (0..rank - 1).collect()
2258            } else {
2259                (0..rank).collect()
2260            },
2261            scatter_dims_to_operand_dims: (0..rank).collect(),
2262            operand_batching_dims: vec![],
2263            scatter_indices_batching_dims: vec![],
2264        };
2265        let params = Params::Scatter {
2266            dimension_numbers: dims,
2267            mode,
2268            indices_are_sorted: false,
2269            unique_indices: false,
2270        };
2271        let mut invars = vec![x.clone(), p.clone()];
2272        let mut eqns = Vec::new();
2273        let mut cur = x.clone();
2274        for _ in 0..chain {
2275            let (i, u) = (Var::new(ia.clone()), Var::new(ua.clone()));
2276            invars.push(i.clone());
2277            invars.push(u.clone());
2278            let s = Var::new(x.aval().clone());
2279            eqns.push(eqn(
2280                ruxla_prims::SCATTER,
2281                vec![cur.into(), i.into(), u.into()],
2282                params.clone(),
2283                &s,
2284            ));
2285            cur = s;
2286        }
2287        let y = Var::new(x.aval().clone());
2288        let cases = if on_true {
2289            vec![p.into(), x.into(), cur.into()]
2290        } else {
2291            vec![p.into(), cur.into(), x.into()]
2292        };
2293        eqns.push(eqn(ruxla_prims::SELECT_N, cases, Params::None, &y));
2294        Function {
2295            constvars: vec![],
2296            invars,
2297            eqns,
2298            outvars: vec![y.into()],
2299        }
2300    }
2301
2302    fn inputs(f: &Function, rng: &mut Lcg, shape: &[usize]) -> Vec<HostArray> {
2303        f.invars
2304            .iter()
2305            .enumerate()
2306            .map(|(k, v)| {
2307                let a = v.aval();
2308                let n: usize = a.shape.dims().iter().product();
2309                match (k, a.dtype) {
2310                    (1, DType::Bool) => HostArray::from_vec(
2311                        (0..n).map(|_| rng.next(2) == 1).collect::<Vec<_>>(),
2312                        a.shape.clone(),
2313                    ),
2314                    (1, _) => HostArray::from_vec(
2315                        (0..n).map(|_| rng.next(2) as i32).collect::<Vec<_>>(),
2316                        a.shape.clone(),
2317                    ),
2318                    // Indices: in bounds, repeated, negative and past the end.
2319                    (k, _) if k >= 2 && k % 2 == 0 => {
2320                        let rank = a.shape.dims()[1];
2321                        let data: Vec<i32> = (0..n)
2322                            .map(|e| {
2323                                let d = shape[e % rank] as i64;
2324                                (rng.next(d + 4) - 2) as i32
2325                            })
2326                            .collect();
2327                        HostArray::from_vec(data, a.shape.clone())
2328                    }
2329                    _ => HostArray::from_vec(
2330                        (0..n).map(|_| rng.next(100) as i32 + 1).collect::<Vec<_>>(),
2331                        a.shape.clone(),
2332                    ),
2333                }
2334            })
2335            .collect()
2336    }
2337
2338    /// The masked-scatter rewrite keeps the values of the function for
2339    /// out-of-bounds indices in both modes, windows partly out of bounds,
2340    /// repeated indices, integer predicates, either side of the select, and
2341    /// chains of scatters.
2342    #[test]
2343    fn masked_scatters_keep_values() {
2344        let mut rng = Lcg(7);
2345        let mut rewritten = 0;
2346        for shape in [vec![6], vec![4, 5]] {
2347            for window in [1, 2, 3] {
2348                for mode in [GatherScatterMode::FillOrDrop, GatherScatterMode::Clip] {
2349                    for pred in [DType::Bool, DType::I32] {
2350                        for chain in [1, 2] {
2351                            for on_true in [true, false] {
2352                                let f = masked(&shape, window, 5, chain, mode, pred, on_true);
2353                                let g = super::mask_scatters(&f);
2354                                if g.eqns.iter().any(|e| e.prim.name() == "gather") {
2355                                    rewritten += 1;
2356                                }
2357                                for _ in 0..20 {
2358                                    let args = inputs(&f, &mut rng, &shape);
2359                                    let a = ruxla_interp::eval(&f, &args).unwrap();
2360                                    let b = ruxla_interp::eval(&g, &args).unwrap();
2361                                    assert_eq!(
2362                                        a[0].to_bytes(),
2363                                        b[0].to_bytes(),
2364                                        "shape {shape:?}, window {window}, {mode:?}, {pred:?}, chain {chain}, on_true {on_true}"
2365                                    );
2366                                }
2367                            }
2368                        }
2369                    }
2370                }
2371            }
2372        }
2373        // Every case is rewritten (the test exercises the rewrite).
2374        assert_eq!(rewritten, 2 * 3 * 2 * 2 * 2 * 2);
2375    }
2376}