Skip to main content

zu_vector/kernels/
cmp.rs

1//! Comparison kernels: the (op x type x encoding-pair) matrix.
2//!
3//! Output is a positional bitmap over the vector, bit set when the
4//! predicate holds and both sides are valid, so NULL compares false and
5//! null propagation costs one word-wise AND at the end. With a selection
6//! present only the selected rows are evaluated; the rest stay zero.
7//!
8//! The dict x constant arm is the compressed-domain path from perf/07
9//! section 3: the constant translates through the sorted dictionary once,
10//! then every row is one integer compare against a code. The dictionary
11//! order matches the value order, so range predicates translate too, via
12//! the insertion point when the constant itself is absent.
13
14use zu_common::{Result, ZuError};
15
16use crate::bitmap::Bitmap;
17use crate::sel::SelVector;
18use crate::str::{NO_BUFFERS, StrView};
19use crate::vector::{PhysType, ValueVector, VecEncoding};
20
21#[derive(Clone, Copy, PartialEq, Eq, Debug)]
22pub enum CmpOp {
23    Eq,
24    Ne,
25    Lt,
26    Le,
27    Gt,
28    Ge,
29}
30
31impl CmpOp {
32    /// The op with its operands swapped: a < b is b > a.
33    fn flip(self) -> Self {
34        match self {
35            CmpOp::Eq => CmpOp::Eq,
36            CmpOp::Ne => CmpOp::Ne,
37            CmpOp::Lt => CmpOp::Gt,
38            CmpOp::Le => CmpOp::Ge,
39            CmpOp::Gt => CmpOp::Lt,
40            CmpOp::Ge => CmpOp::Le,
41        }
42    }
43
44    /// Whether the op holds between two values. This is the whole
45    /// definition of the op, which is why it is public: a caller that
46    /// rewrites a predicate before compiling it can check the rewrite
47    /// against the kernel's own rule rather than against a copy of it.
48    #[inline(always)]
49    pub fn holds<T: PartialOrd>(self, a: T, b: T) -> bool {
50        match self {
51            CmpOp::Eq => a == b,
52            CmpOp::Ne => a != b,
53            CmpOp::Lt => a < b,
54            CmpOp::Le => a <= b,
55            CmpOp::Gt => a > b,
56            CmpOp::Ge => a >= b,
57        }
58    }
59}
60
61/// Pack eight bool bytes (0 or 1 each) into eight bits. Byte i of the
62/// input lands on bit i. The multiply spreads each byte's bit onto its
63/// own position in the top byte; the cross terms provably never reach
64/// bits 56 and up.
65#[inline(always)]
66fn pack8(bool_bytes: u64) -> u64 {
67    bool_bytes.wrapping_mul(0x0102_0408_1020_4080) >> 56
68}
69
70/// Turn a byte-per-row predicate staging area into bitmap words.
71#[inline(always)]
72fn pack_stage(stage: &[u8], out: &mut Bitmap) {
73    let words = out.words_mut();
74    for (wi, group) in stage.chunks(64).enumerate() {
75        let mut w = 0u64;
76        // Eights as arrays rather than as slices, so the octet is the
77        // type `from_le_bytes` wants and the fallible conversion that
78        // could never fail goes away with it.
79        let (octets, tail) = group.as_chunks::<8>();
80        for (k, bytes) in octets.iter().enumerate() {
81            w |= pack8(u64::from_le_bytes(*bytes)) << (8 * k);
82        }
83        let base = group.len() / 8 * 8;
84        for (b, &s) in tail.iter().enumerate() {
85            w |= u64::from(s) << (base + b);
86        }
87        words[wi] = w;
88    }
89}
90
91/// Predicate over a full vector in two passes: compare into one bool
92/// byte per row, which every backend turns into packed compares with
93/// narrowing stores, then pack the bytes into mask words with one
94/// multiply per eight rows. The staging array lives on the stack. The
95/// op dispatch happens here, outside the loop, so each arm's inner
96/// closure is branch-free and the vectorizer sees a single compare.
97#[inline(always)]
98fn fill_const<T: Copy + PartialOrd>(op: CmpOp, vals: &[T], c: T, out: &mut Bitmap) {
99    match op {
100        CmpOp::Eq => fill_const_with(vals, out, |x| x == c),
101        CmpOp::Ne => fill_const_with(vals, out, |x| x != c),
102        CmpOp::Lt => fill_const_with(vals, out, |x| x < c),
103        CmpOp::Le => fill_const_with(vals, out, |x| x <= c),
104        CmpOp::Gt => fill_const_with(vals, out, |x| x > c),
105        CmpOp::Ge => fill_const_with(vals, out, |x| x >= c),
106    }
107}
108
109#[inline(always)]
110fn fill_const_with<T: Copy, F: Fn(T) -> bool>(vals: &[T], out: &mut Bitmap, f: F) {
111    debug_assert!(vals.len() <= crate::VECTOR_SIZE);
112    // Uninit staging: zeroing 2 KiB per call would cost more than the
113    // whole compare pass for narrow types. Only bytes written below are
114    // read back.
115    let mut stage = [std::mem::MaybeUninit::<u8>::uninit(); crate::VECTOR_SIZE];
116    for (s, &x) in stage.iter_mut().zip(vals) {
117        s.write(u8::from(f(x)));
118    }
119    let stage: &[u8] = unsafe { std::slice::from_raw_parts(stage.as_ptr().cast(), vals.len()) };
120    pack_stage(stage, out);
121}
122
123#[inline(always)]
124fn fill_pair<T: Copy + PartialOrd>(op: CmpOp, l: &[T], r: &[T], out: &mut Bitmap) {
125    match op {
126        CmpOp::Eq => fill_pair_with(l, r, out, |x, y| x == y),
127        CmpOp::Ne => fill_pair_with(l, r, out, |x, y| x != y),
128        CmpOp::Lt => fill_pair_with(l, r, out, |x, y| x < y),
129        CmpOp::Le => fill_pair_with(l, r, out, |x, y| x <= y),
130        CmpOp::Gt => fill_pair_with(l, r, out, |x, y| x > y),
131        CmpOp::Ge => fill_pair_with(l, r, out, |x, y| x >= y),
132    }
133}
134
135#[inline(always)]
136fn fill_pair_with<T: Copy, F: Fn(T, T) -> bool>(l: &[T], r: &[T], out: &mut Bitmap, f: F) {
137    debug_assert!(l.len() <= crate::VECTOR_SIZE);
138    let mut stage = [std::mem::MaybeUninit::<u8>::uninit(); crate::VECTOR_SIZE];
139    for ((s, &x), &y) in stage.iter_mut().zip(l).zip(r) {
140        s.write(u8::from(f(x, y)));
141    }
142    let n = l.len().min(r.len());
143    let stage: &[u8] = unsafe { std::slice::from_raw_parts(stage.as_ptr().cast(), n) };
144    pack_stage(stage, out);
145}
146
147#[inline(always)]
148fn fill_sel_const<T: Copy, F: Fn(T) -> bool>(vals: &[T], sel: &SelVector, out: &mut Bitmap, f: F) {
149    for &row in sel.as_slice() {
150        if f(vals[row as usize]) {
151            out.set(row as usize);
152        }
153    }
154}
155
156#[inline(always)]
157fn fill_sel_pair<T: Copy, F: Fn(T, T) -> bool>(
158    l: &[T],
159    r: &[T],
160    sel: &SelVector,
161    out: &mut Bitmap,
162    f: F,
163) {
164    for &row in sel.as_slice() {
165        if f(l[row as usize], r[row as usize]) {
166            out.set(row as usize);
167        }
168    }
169}
170
171/// The typed arms share this shape; the macro stamps one per physical
172/// representation so each loop monomorphizes on its element type.
173macro_rules! cmp_typed {
174    ($op:expr, $l:expr, $r:expr, $sel:expr, $out:expr, $ty:ty) => {{
175        let op = $op;
176        match ($l.encoding, $r.encoding) {
177            (VecEncoding::Flat, VecEncoding::Constant) => {
178                let c = $r.constant_value::<$ty>();
179                match $sel {
180                    None => fill_const(op, $l.values::<$ty>(), c, $out),
181                    Some(s) => fill_sel_const($l.values::<$ty>(), s, $out, |x| op.holds(x, c)),
182                }
183            }
184            (VecEncoding::Constant, VecEncoding::Flat) => {
185                let op = op.flip();
186                let c = $l.constant_value::<$ty>();
187                match $sel {
188                    None => fill_const(op, $r.values::<$ty>(), c, $out),
189                    Some(s) => fill_sel_const($r.values::<$ty>(), s, $out, |x| op.holds(x, c)),
190                }
191            }
192            (VecEncoding::Flat, VecEncoding::Flat) => match $sel {
193                None => fill_pair(op, $l.values::<$ty>(), $r.values::<$ty>(), $out),
194                Some(s) => {
195                    fill_sel_pair($l.values::<$ty>(), $r.values::<$ty>(), s, $out, |x, y| {
196                        op.holds(x, y)
197                    })
198                }
199            },
200            (VecEncoding::Constant, VecEncoding::Constant) => {
201                if op.holds($l.constant_value::<$ty>(), $r.constant_value::<$ty>()) {
202                    set_all($sel, $out);
203                }
204            }
205            _ => return unsupported($l, $r),
206        }
207    }};
208}
209
210fn set_all(sel: Option<&SelVector>, out: &mut Bitmap) {
211    match sel {
212        None => {
213            out.words_mut().fill(!0u64);
214            out.mask_tail();
215        }
216        Some(s) => {
217            for &row in s.as_slice() {
218                out.set(row as usize);
219            }
220        }
221    }
222}
223
224fn unsupported(l: &ValueVector, r: &ValueVector) -> Result<()> {
225    Err(ZuError::InvalidArgument(format!(
226        "no compare kernel for {:?} {:?} vs {:?} {:?}",
227        l.phys, l.encoding, r.phys, r.encoding
228    )))
229}
230
231/// Compare two vectors of the same physical type into `out`, which must
232/// be sized to the vector length and cleared (or freshly allocated).
233pub fn compare(
234    op: CmpOp,
235    l: &ValueVector,
236    r: &ValueVector,
237    sel: Option<&SelVector>,
238    out: &mut Bitmap,
239) -> Result<()> {
240    debug_assert_eq!(l.len, r.len);
241    debug_assert_eq!(out.len(), l.len as usize);
242    if l.phys != r.phys {
243        return unsupported(l, r);
244    }
245    match l.phys {
246        PhysType::Int64 | PhysType::Date | PhysType::Timestamp | PhysType::Interval => {
247            cmp_typed!(op, l, r, sel, out, i64)
248        }
249        PhysType::Float64 => cmp_typed!(op, l, r, sel, out, f64),
250        PhysType::NodeRef | PhysType::RelRef => cmp_typed!(op, l, r, sel, out, u64),
251        PhysType::Str => cmp_str(op, l, r, sel, out)?,
252        PhysType::Bool | PhysType::List => return unsupported(l, r),
253    }
254    if let Some(v) = &l.validity {
255        out.and_with(v);
256    }
257    if let Some(v) = &r.validity {
258        out.and_with(v);
259    }
260    out.mask_tail();
261    Ok(())
262}
263
264fn cmp_str(
265    op: CmpOp,
266    l: &ValueVector,
267    r: &ValueVector,
268    sel: Option<&SelVector>,
269    out: &mut Bitmap,
270) -> Result<()> {
271    match (l.encoding, r.encoding) {
272        // The compressed-domain arm: constant through the dictionary
273        // once, then a u16 compare per row.
274        (VecEncoding::Dict { codes_width: 2 }, VecEncoding::Constant) => {
275            let dict = l.dictionary();
276            let needle = const_str_bytes(r);
277            let codes = l.codes_u16();
278            // Translate the predicate into the code domain. The
279            // dictionary is sorted, so when the needle is absent the
280            // insertion point carries the range semantics.
281            let (op, threshold) = match (op, dict.code_of(needle)) {
282                (CmpOp::Eq, Ok(c)) => (CmpOp::Eq, c),
283                (CmpOp::Eq, Err(_)) => return Ok(()),
284                (CmpOp::Ne, Ok(c)) => (CmpOp::Ne, c),
285                (CmpOp::Ne, Err(_)) => {
286                    set_all(sel, out);
287                    return Ok(());
288                }
289                (CmpOp::Lt, Ok(c)) | (CmpOp::Lt | CmpOp::Le, Err(c)) => (CmpOp::Lt, c),
290                (CmpOp::Le, Ok(c)) => (CmpOp::Le, c),
291                (CmpOp::Gt, Ok(c)) => (CmpOp::Gt, c),
292                (CmpOp::Ge, Ok(c)) | (CmpOp::Gt | CmpOp::Ge, Err(c)) => (CmpOp::Ge, c),
293            };
294            let t = threshold as u16;
295            match sel {
296                None => fill_const(op, codes, t, out),
297                Some(s) => fill_sel_const(codes, s, out, |c| op.holds(c, t)),
298            }
299            Ok(())
300        }
301        (VecEncoding::Constant, VecEncoding::Dict { .. }) => cmp_str(op.flip(), r, l, sel, out),
302        // Two vectors over the same dictionary compare as codes.
303        (VecEncoding::Dict { codes_width: 2 }, VecEncoding::Dict { codes_width: 2 })
304            if std::ptr::eq(l.dictionary(), r.dictionary()) =>
305        {
306            let (a, b) = (l.codes_u16(), r.codes_u16());
307            match sel {
308                None => fill_pair(op, a, b, out),
309                Some(s) => fill_sel_pair(a, b, s, out, |x, y| op.holds(x, y)),
310            }
311            Ok(())
312        }
313        (VecEncoding::Flat, VecEncoding::Constant) => {
314            let needle = const_str_bytes(r);
315            let bufs = l.str_buffers();
316            let views = l.values::<StrView>();
317            // A vector without buffers holds only inline views.
318            let eval = |i: usize| -> bool {
319                let bytes = match bufs {
320                    Some(b) => views[i].bytes(b),
321                    None => views[i].inline_bytes(),
322                };
323                op.holds(bytes, needle)
324            };
325            match sel {
326                None => {
327                    for i in 0..views.len() {
328                        if eval(i) {
329                            out.set(i);
330                        }
331                    }
332                }
333                Some(s) => {
334                    for &row in s.as_slice() {
335                        if eval(row as usize) {
336                            out.set(row as usize);
337                        }
338                    }
339                }
340            }
341            Ok(())
342        }
343        (VecEncoding::Constant, VecEncoding::Flat) => cmp_str(op.flip(), r, l, sel, out),
344        // Two columns of strings, row against row. Neither side is one
345        // value the other can be translated against, so this is the arm
346        // with no trick in it: the views are compared where they lie.
347        // Equality still avoids most of the payloads, `eq_with`
348        // rejecting a pair on its length and its four byte prefix
349        // before either side is resolved, and an ordering has to look
350        // at the bytes.
351        (VecEncoding::Flat, VecEncoding::Flat) => {
352            let (lb, rb) = (
353                l.str_buffers().unwrap_or(&NO_BUFFERS),
354                r.str_buffers().unwrap_or(&NO_BUFFERS),
355            );
356            let (lv, rv) = (l.values::<StrView>(), r.values::<StrView>());
357            let eval = |i: usize| -> bool {
358                match op {
359                    CmpOp::Eq => lv[i].eq_with(lb, &rv[i], rb),
360                    CmpOp::Ne => !lv[i].eq_with(lb, &rv[i], rb),
361                    _ => op.holds(lv[i].bytes(lb), rv[i].bytes(rb)),
362                }
363            };
364            match sel {
365                None => {
366                    for i in 0..lv.len().min(rv.len()) {
367                        if eval(i) {
368                            out.set(i);
369                        }
370                    }
371                }
372                Some(s) => {
373                    for &row in s.as_slice() {
374                        if eval(row as usize) {
375                            out.set(row as usize);
376                        }
377                    }
378                }
379            }
380            Ok(())
381        }
382        _ => unsupported(l, r),
383    }
384}
385
386/// Bytes of a constant string vector. Inline constants read from the
387/// view, which lives in the vector's data buffer; long ones resolve
388/// through the vector's own buffers.
389fn const_str_bytes(v: &ValueVector) -> &[u8] {
390    debug_assert_eq!(v.encoding, VecEncoding::Constant);
391    let view: &StrView = &v.data.as_slice::<StrView>()[0];
392    if view.is_inline() {
393        view.inline_bytes()
394    } else {
395        let bufs = v.str_buffers().expect("long constant needs buffers");
396        view.bytes(bufs)
397    }
398}