logicaffeine_forge/vectorize.rs
1//! Element-wise map vectorization — the general, sound SIMD lever.
2//!
3//! Recognizes a region that is a PURE ELEMENT-WISE MAP — a loop `for i in 1..=n`
4//! (1-based, the Logos array convention) whose body reads one or more arrays at
5//! index `i`, computes a straight-line float expression, and writes the result
6//! to an array at index `i`, with the
7//! induction variable `i` as the ONLY loop-carried value. Such a loop is
8//! bit-exactly vectorizable: lane `i` computes exactly `f(a[i], b[i], ...)`
9//! whether scalar or packed, so 2-wide (or wider) SIMD changes nothing about the
10//! per-element result — unlike a REDUCTION (`sum += a[i]`), whose 2-lane form
11//! reassociates the float adds and is therefore NOT bit-identical (and is
12//! rejected here).
13//!
14//! This is the recognizer half (a pure analysis). The codegen half lowers each
15//! body op to its packed form (`AddF`->`addpd`, …) over 2 lanes with a scalar
16//! tail; the packed primitives live in [`crate::x64asm`].
17
18use crate::jit::{Cmp, MicroOp, Slot};
19use std::collections::HashSet;
20
21/// A recognized element-wise map loop. The straight-line load/compute/store body
22/// is `ops[body_start..body_end]`; the guard, increment, and back-edge surround it.
23#[derive(Debug, Clone, PartialEq, Eq)]
24pub struct MapPlan {
25 /// The induction variable slot `i` (a 1-based array index).
26 pub induction: Slot,
27 /// The loop-limit slot `n` (the guard `Branch` right operand).
28 pub limit: Slot,
29 /// The guard comparison: `Lt` (`i < n`) or `LtEq` (`i <= n`). Decides how many
30 /// elements a full SIMD pair needs and where the scalar tail begins.
31 pub cmp: Cmp,
32 /// The straight-line load/compute/store body is `ops[body_start..body_end]`.
33 pub body_start: usize,
34 pub body_end: usize,
35}
36
37/// Returns `Some(MapPlan)` iff `ops` is a pure element-wise map region in the
38/// top-tested `while` shape that `adapt_region` produces:
39///
40/// ```text
41/// [0] Branch { cmp(Lt|LtEq), lhs:i, rhs:n, .. } // loop guard (exit when cmp FALSE)
42/// [1..j-2] body: ArrLoad{idx==i,checked:false} / float arith / ArrStore{idx==i,checked:false}
43/// [j-2] LoadConst { dst:step, value:1 }
44/// [j-1] Add { dst:i, lhs:i, rhs:step } // increment
45/// [j] Jump { target:0 } // back-edge to head
46/// [j+1..] exit (Return)
47/// ```
48///
49/// Any reduction (loop-carried operand), cross-index access, bounds-checked
50/// access, non-unit stride, call, or other op makes it `None` — the
51/// conservative, sound side.
52pub fn recognize_elementwise_map(ops: &[MicroOp]) -> Option<MapPlan> {
53 // guard + >=1 body op + step LoadConst + increment + back-Jump.
54 if ops.len() < 5 {
55 return None;
56 }
57
58 // [0]: the loop guard — `Branch` jumps to its target when the comparison is
59 // FALSE, i.e. it falls through (continues) while `i </<= n`.
60 let (induction, limit, cmp) = match &ops[0] {
61 MicroOp::Branch {
62 cmp: c @ (Cmp::Lt | Cmp::LtEq),
63 lhs,
64 rhs,
65 ..
66 } => (*lhs, *rhs, *c),
67 _ => return None,
68 };
69
70 // The back-edge `Jump { target: 0 }`.
71 let j = ops
72 .iter()
73 .position(|o| matches!(o, MicroOp::Jump { target: 0 }))?;
74 if j < 4 {
75 return None; // need [0]guard [1..]body [j-2]LoadConst [j-1]increment
76 }
77
78 // [j-1]: the induction increment `i = i + step`.
79 let step = match &ops[j - 1] {
80 MicroOp::Add { dst, lhs, rhs } if *dst == induction && *lhs == induction => *rhs,
81 _ => return None,
82 };
83 // [j-2]: the stride-1 constant feeding it. The kernel processes EVERY index,
84 // so a non-unit / unknown stride (a loop over a subset) must be rejected.
85 match &ops[j - 2] {
86 MicroOp::LoadConst { dst, value } if *dst == step && *value == 1 => {}
87 _ => return None,
88 }
89
90 // The straight-line body is everything between the guard and the increment
91 // machinery: `ops[1..j-2]` (load/compute/store only — no LoadConst/Add here).
92 let (body_start, body_end) = (1usize, j - 2);
93 let body = &ops[body_start..body_end];
94 if body.is_empty() {
95 return None;
96 }
97
98 // The body must be straight-line: every slot an op reads is either the
99 // induction variable, a constant, or a value DEFINED EARLIER IN THE BODY.
100 // A read of a slot not yet defined in the body is a loop-carried value
101 // (e.g. a reduction accumulator) — NOT bit-exactly vectorizable -> reject.
102 let mut defined: HashSet<Slot> = HashSet::new();
103 defined.insert(induction);
104 let mut wrote_an_array = false;
105
106 let known = |s: &Slot, defined: &HashSet<Slot>| defined.contains(s);
107
108 for op in body {
109 match op {
110 MicroOp::LoadConst { dst, .. } => {
111 defined.insert(*dst);
112 }
113 MicroOp::ArrLoad {
114 dst, idx, checked, ..
115 } => {
116 if *idx != induction || *checked {
117 // cross-index read, OR a bounds-checked access whose length the
118 // kernel can't prove >= n (the kernel elides per-element checks,
119 // so it is sound ONLY when the Oracle already proved in-bounds,
120 // i.e. `checked == false`).
121 return None;
122 }
123 defined.insert(*dst);
124 }
125 MicroOp::AddF { dst, lhs, rhs }
126 | MicroOp::SubF { dst, lhs, rhs }
127 | MicroOp::MulF { dst, lhs, rhs }
128 | MicroOp::DivF { dst, lhs, rhs } => {
129 if !known(lhs, &defined) || !known(rhs, &defined) {
130 return None; // loop-carried operand (reduction) — unsound
131 }
132 defined.insert(*dst);
133 }
134 MicroOp::SqrtF { dst, src } => {
135 if !known(src, &defined) {
136 return None;
137 }
138 defined.insert(*dst);
139 }
140 MicroOp::ArrStore {
141 src, idx, checked, ..
142 } => {
143 if *idx != induction || *checked || !known(src, &defined) {
144 return None;
145 }
146 wrote_an_array = true;
147 }
148 // Any other op (Call, Move, integer arithmetic, comparisons,
149 // list/map/byte ops, a second induction) means this is not a pure
150 // element-wise float map — reject conservatively.
151 _ => return None,
152 }
153 }
154
155 // A map must actually STORE a result; a body that only loads is not a map.
156 if !wrote_an_array {
157 return None;
158 }
159
160 Some(MapPlan {
161 induction,
162 limit,
163 cmp,
164 body_start,
165 body_end,
166 })
167}
168
169/// Lower one straight-line float-arithmetic body op to its 2-wide PACKED form,
170/// computing `dst = lhs OP rhs` over both lanes. `xmm(slot)` maps a body slot to
171/// its assigned lane register; `scratch` is a free XMM for the awkward
172/// `dst == rhs` non-commutative case. SSE packed ops are 2-operand (`x OP= y`),
173/// so this materializes the 3-operand `dst = lhs OP rhs` form, never clobbering
174/// an operand it still needs. Loads/stores/LoadConst are handled by the loop
175/// driver, not here.
176#[cfg(target_arch = "x86_64")]
177pub fn emit_packed_arith(
178 asm: &mut crate::x64asm::Asm,
179 op: &MicroOp,
180 xmm: impl Fn(Slot) -> crate::x64asm::Xmm,
181 scratch: crate::x64asm::Xmm,
182) {
183 use crate::x64asm::Asm;
184 match op {
185 MicroOp::AddF { dst, lhs, rhs } => emit_bin(
186 asm,
187 xmm(*dst),
188 xmm(*lhs),
189 xmm(*rhs),
190 scratch,
191 Asm::addpd_rr,
192 true,
193 ),
194 MicroOp::MulF { dst, lhs, rhs } => emit_bin(
195 asm,
196 xmm(*dst),
197 xmm(*lhs),
198 xmm(*rhs),
199 scratch,
200 Asm::mulpd_rr,
201 true,
202 ),
203 MicroOp::SubF { dst, lhs, rhs } => emit_bin(
204 asm,
205 xmm(*dst),
206 xmm(*lhs),
207 xmm(*rhs),
208 scratch,
209 Asm::subpd_rr,
210 false,
211 ),
212 MicroOp::DivF { dst, lhs, rhs } => emit_bin(
213 asm,
214 xmm(*dst),
215 xmm(*lhs),
216 xmm(*rhs),
217 scratch,
218 Asm::divpd_rr,
219 false,
220 ),
221 MicroOp::SqrtF { dst, src } => asm.sqrtpd_rr(xmm(*dst), xmm(*src)),
222 _ => {}
223 }
224}
225
226/// Materialize `d = l OP r` from a 2-operand packed `op(x, y): x OP= y`, without
227/// destroying an operand before it is consumed.
228#[cfg(target_arch = "x86_64")]
229fn emit_bin(
230 asm: &mut crate::x64asm::Asm,
231 d: crate::x64asm::Xmm,
232 l: crate::x64asm::Xmm,
233 r: crate::x64asm::Xmm,
234 scratch: crate::x64asm::Xmm,
235 op: fn(&mut crate::x64asm::Asm, crate::x64asm::Xmm, crate::x64asm::Xmm),
236 commutative: bool,
237) {
238 if d == l {
239 op(asm, d, r); // d already holds l
240 } else if d == r {
241 if commutative {
242 op(asm, d, l); // d = r OP l == l OP r
243 } else {
244 asm.movupd_rr(scratch, l);
245 op(asm, scratch, r); // scratch = l OP r (r untouched until read)
246 asm.movupd_rr(d, scratch);
247 }
248 } else {
249 asm.movupd_rr(d, l);
250 op(asm, d, r);
251 }
252}
253
254/// Emit a complete vectorized loop kernel for a recognized element-wise map,
255/// frame-ABI `extern "C" fn(*mut i64) -> i64`: it reads the induction `i`, limit
256/// `n`, and each array base pointer from their frame slots (`[rdi + slot*8]`),
257/// runs a 2-wide packed loop (`i += 2`) over full pairs, then a single-element
258/// scalar tail that REUSES the packed body (load one element with `movsd` so lane
259/// 1 is zero, run the same packed ops, store lane 0 with `movsd` — the junk lane
260/// is never stored and masked SSE faults are harmless), writes `i = n` back, and
261/// returns 0. Returns `None` (caller falls back to the scalar region) if the body
262/// needs more than 4 distinct arrays or 14 lane temps, or uses an op the kernel
263/// does not lower (e.g. `LoadConst`).
264///
265/// Register plan (all SysV caller-saved, no callee-save needed): rdi=frame,
266/// rsi=i, rdx=n, rcx=i*8 offset, rax=address scratch, r8..r11=array bases,
267/// xmm0..xmm13=lane temps, xmm15=arith scratch.
268#[cfg(target_arch = "x86_64")]
269pub fn emit_map_kernel(body: &[MicroOp], plan: &MapPlan) -> Option<Vec<u8>> {
270 use crate::x64asm::{Asm, Cond, Reg, Xmm};
271 const ARRAY_REGS: [Reg; 4] = [Reg::R8, Reg::R9, Reg::R10, Reg::R11];
272 const LANES: [Xmm; 14] = [
273 Xmm::Xmm0,
274 Xmm::Xmm1,
275 Xmm::Xmm2,
276 Xmm::Xmm3,
277 Xmm::Xmm4,
278 Xmm::Xmm5,
279 Xmm::Xmm6,
280 Xmm::Xmm7,
281 Xmm::Xmm8,
282 Xmm::Xmm9,
283 Xmm::Xmm10,
284 Xmm::Xmm11,
285 Xmm::Xmm12,
286 Xmm::Xmm13,
287 ];
288 let scratch = Xmm::Xmm15;
289
290 // Assign each distinct array pointer slot a GP base register.
291 let mut arr_reg: Vec<(Slot, Reg)> = Vec::new();
292 for op in body {
293 let ptr = match op {
294 MicroOp::ArrLoad { ptr_slot, .. } | MicroOp::ArrStore { ptr_slot, .. } => {
295 Some(*ptr_slot)
296 }
297 _ => None,
298 };
299 if let Some(p) = ptr {
300 if !arr_reg.iter().any(|(s, _)| *s == p) {
301 if arr_reg.len() >= ARRAY_REGS.len() {
302 return None;
303 }
304 arr_reg.push((p, ARRAY_REGS[arr_reg.len()]));
305 }
306 }
307 }
308 let reg_of = |slot: Slot| arr_reg.iter().find(|(s, _)| *s == slot).map(|(_, r)| *r);
309
310 // Assign each load/arith destination slot a lane XMM register.
311 let mut lane: Vec<(Slot, Xmm)> = Vec::new();
312 let add_lane = |slot: Slot, lane: &mut Vec<(Slot, Xmm)>| -> Option<()> {
313 if !lane.iter().any(|(s, _)| *s == slot) {
314 if lane.len() >= LANES.len() {
315 return None;
316 }
317 lane.push((slot, LANES[lane.len()]));
318 }
319 Some(())
320 };
321 for op in body {
322 match op {
323 MicroOp::ArrLoad { dst, .. }
324 | MicroOp::AddF { dst, .. }
325 | MicroOp::SubF { dst, .. }
326 | MicroOp::MulF { dst, .. }
327 | MicroOp::DivF { dst, .. }
328 | MicroOp::SqrtF { dst, .. } => add_lane(*dst, &mut lane)?,
329 MicroOp::ArrStore { .. } => {}
330 _ => return None, // unsupported op (e.g. LoadConst) — bail to scalar
331 }
332 }
333 let xmm_of = |slot: Slot| lane.iter().find(|(s, _)| *s == slot).map(|(_, x)| *x);
334
335 let off = |slot: Slot| (slot as i32) * 8;
336 let mut a = Asm::new();
337 // Prologue: load `i`, `n`, and point each array register at `&buffer[i-1]`
338 // (the 1-based element `i`). The inner loop then advances these pointers
339 // instead of recomputing `base + (i-1)*8` every iteration.
340 a.mov_rm(Reg::Rsi, Reg::Rdi, off(plan.induction)); // i
341 a.mov_rm(Reg::Rdx, Reg::Rdi, off(plan.limit)); // n
342 a.mov_rr(Reg::Rcx, Reg::Rsi);
343 a.sub_ri(Reg::Rcx, 1);
344 a.shl_ri(Reg::Rcx, 3); // off0 = (i-1)*8
345 for (slot, reg) in &arr_reg {
346 a.mov_rm(*reg, Reg::Rdi, off(*slot)); // base
347 a.add_rr(*reg, Reg::Rcx); // base + off0 = &buffer[i-1]
348 }
349
350 // Emit the load/arith/store body at a given element width (`packed`). The
351 // array pointers already hold `&buffer[i-1]`, so each access is a direct
352 // `movupd [ptr]` / `movsd [ptr]` — no per-iteration address arithmetic.
353 let emit_body = |a: &mut Asm, packed: bool| {
354 for op in body {
355 match op {
356 MicroOp::ArrLoad { dst, ptr_slot, .. } => {
357 let p = reg_of(*ptr_slot).unwrap();
358 let x = xmm_of(*dst).unwrap();
359 if packed {
360 a.movupd_rm(x, p, 0);
361 } else {
362 a.movsd_rm(x, p, 0);
363 }
364 }
365 MicroOp::ArrStore { src, ptr_slot, .. } => {
366 let p = reg_of(*ptr_slot).unwrap();
367 let x = xmm_of(*src).unwrap();
368 if packed {
369 a.movupd_mr(p, 0, x);
370 } else {
371 a.movsd_mr(p, 0, x);
372 }
373 }
374 _ => emit_packed_arith(a, op, |s| xmm_of(s).unwrap(), scratch),
375 }
376 }
377 };
378
379 // Exit the loop when the (1-based) index exceeds the valid range: for
380 // `i <= n` (LtEq) that is `index > n`; for `i < n` (Lt) it is `index >= n`.
381 let exit_cond = if plan.cmp == Cmp::LtEq {
382 Cond::Gt
383 } else {
384 Cond::Ge
385 };
386
387 // Pair loop: process elements i and i+1 while BOTH are in range (i+1 valid).
388 let pair_top = a.new_label();
389 let tail = a.new_label();
390 let done = a.new_label();
391 a.bind(pair_top);
392 a.mov_rr(Reg::Rax, Reg::Rsi);
393 a.add_ri(Reg::Rax, 1); // i+1
394 a.cmp_rr(Reg::Rax, Reg::Rdx);
395 a.jcc(exit_cond, tail); // i+1 out of range -> no full pair left
396 emit_body(&mut a, true);
397 for (_, reg) in &arr_reg {
398 a.add_ri(*reg, 16); // advance each pointer by 2 f64 elements
399 }
400 a.add_ri(Reg::Rsi, 2);
401 a.jmp(pair_top);
402
403 // Scalar tail: at most one element (i still in range, i+1 not).
404 a.bind(tail);
405 a.cmp_rr(Reg::Rsi, Reg::Rdx);
406 a.jcc(exit_cond, done);
407 emit_body(&mut a, false);
408
409 a.bind(done);
410 // Leave the induction at its scalar terminal value: n+1 for `i <= n`, n for
411 // `i < n` (the first value that fails the loop test), so post-loop bytecode
412 // that reads `i` sees exactly what the scalar loop would have left.
413 a.mov_rr(Reg::Rax, Reg::Rdx);
414 if plan.cmp == Cmp::LtEq {
415 a.add_ri(Reg::Rax, 1);
416 }
417 a.mov_mr(Reg::Rdi, off(plan.induction), Reg::Rax);
418 a.xor_rr(Reg::Rax, Reg::Rax);
419 a.ret();
420 Some(a.resolve())
421}
422
423#[cfg(test)]
424#[path = "../../logicaffeine_tests/unit/logicaffeine_forge/vectorize/tests.rs"]
425mod tests;