morok-ir 0.1.0-alpha.2

Intermediate representation for the Morok ML compiler
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
//! Range analysis (vmin/vmax) evaluation for UOp operations.
//!
//! This module computes minimum and maximum possible values for operations
//! based on their semantics and input ranges. The analysis is conservative -
//! when in doubt, it returns the full dtype bounds to avoid incorrect optimizations.

use crate::types::{BinaryOp, ConstValue, TernaryOp, UnaryOp};
use crate::{Op, UOp};
use morok_dtype::DType;
use std::cmp::Ordering;
use std::sync::Arc;

/// Sound range analysis — returns `None` for ops where range cannot be soundly computed.
///
/// Matches Tinygrad's `_min_max` (ops.py:734-772): ops without explicit rules fall through
/// to `(dtype.min, dtype.max)`, making `vmin != vmax` and preventing unsound constant collapse.
///
/// Returns `Some((vmin, vmax))` only when the bounds are provably correct.
/// Returns `None` for: LOAD, STORE, INDEX, REDUCE, Pow, Fdiv, BitCast, and any op
/// whose children have unknown bounds and the op's analysis depends on them.
pub fn compute_sound_vmin_vmax(uop: &Arc<UOp>) -> Option<(ConstValue, ConstValue)> {
    use crate::uop::cached_property::CachedProperty;
    use crate::uop::properties::SoundVminVmaxProperty;

    match &uop.op {
        Op::Const(c) => Some((c.0, c.0)),
        Op::VConst { values } => Some(sources_range_values(values, &uop.dtype)),
        Op::DefineVar { min_val, max_val, .. } => Some((ConstValue::Int(*min_val), ConstValue::Int(*max_val))),

        // [0, end-1] ranges: Range, Special (Tinygrad ops.py:763)
        Op::Range { end, .. } | Op::Special { end, .. } => Some(zero_to_end_minus_one(end, &uop.dtype)),

        // Propagate source soundness: Unroll, Gep, Bind
        Op::Unroll { src, .. } | Op::Bind { var: src, .. } | Op::Gep { vector: src, .. } => {
            *SoundVminVmaxProperty::get(src)
        }

        // Union of element ranges: Vectorize, Cat — sound only if all sources are sound
        Op::Vectorize { elements } => sound_sources_range(elements),
        Op::Cat { sources } => sound_sources_range(sources),

        // Unary: Tinygrad has no explicit unary rules — all fall through to dtype bounds.
        // Our analysis is more aggressive but some ops (Exp2, Log2, Reciprocal on floats)
        // can produce NaN/Inf that breaks monotonicity assumptions. Be conservative.
        Op::Unary(op, src) => {
            let (src_min, src_max) = (*SoundVminVmaxProperty::get(src))?;
            // Only Neg and Not are truly monotone/anti-monotone for all inputs
            match op {
                UnaryOp::Neg | UnaryOp::Not => Some(compute_unary_range(*op, src_min, src_max, &uop.dtype)),
                _ => None,
            }
        }

        // Binary: match Tinygrad's explicit rules
        Op::Binary(op, a, b) => {
            let (a_min, a_max) = (*SoundVminVmaxProperty::get(a))?;
            let (b_min, b_max) = (*SoundVminVmaxProperty::get(b))?;
            // Const-const fast path: any op on constants is sound
            if a_min == a_max && b_min == b_max {
                return Some(compute_binary_range(*op, a_min, a_max, b_min, b_max, &uop.dtype));
            }
            match op {
                // Tinygrad has explicit rules for these
                BinaryOp::Add
                | BinaryOp::Sub
                | BinaryOp::Mul
                | BinaryOp::Max
                | BinaryOp::Mod
                | BinaryOp::Idiv
                | BinaryOp::Shl
                | BinaryOp::Shr
                | BinaryOp::Lt
                | BinaryOp::Le
                | BinaryOp::Eq
                | BinaryOp::Ne
                | BinaryOp::Gt
                | BinaryOp::Ge => Some(compute_binary_range(*op, a_min, a_max, b_min, b_max, &uop.dtype)),
                // Bool AND/OR have rules in Tinygrad
                BinaryOp::And | BinaryOp::Or if uop.dtype == DType::Bool => {
                    Some(compute_binary_range(*op, a_min, a_max, b_min, b_max, &uop.dtype))
                }
                // AND with constant non-negative mask (Tinygrad ops.py:739-740)
                // Only sound when one operand is constant non-negative.
                BinaryOp::And
                    if uop.dtype.is_int() && b_min == b_max && matches!(b_min, ConstValue::Int(v) if v >= 0) =>
                {
                    Some(compute_binary_range(*op, a_min, a_max, b_min, b_max, &uop.dtype))
                }
                // Pow, Fdiv, XOR, OR/AND (non-bool non-int): unsound for variable ranges
                _ => None,
            }
        }

        // Ternary
        Op::Ternary(op, a, b, c) => {
            let (a_min, a_max) = (*SoundVminVmaxProperty::get(a))?;
            let (b_min, b_max) = (*SoundVminVmaxProperty::get(b))?;
            let (c_min, c_max) = (*SoundVminVmaxProperty::get(c))?;
            // Const-const-const fast path
            if a_min == a_max && b_min == b_max && c_min == c_max {
                return Some(compute_ternary_range(*op, a_min, a_max, b_min, b_max, c_min, c_max, &uop.dtype));
            }
            // WHERE for int only (Tinygrad ops.py:760)
            match op {
                TernaryOp::Where if uop.dtype.is_int() || uop.dtype == DType::Index => {
                    Some(compute_ternary_range(*op, a_min, a_max, b_min, b_max, c_min, c_max, &uop.dtype))
                }
                _ => None,
            }
        }

        // Cast: only for monotone targets (Tinygrad ops.py:770-771)
        Op::Cast { src, .. } => {
            let dt = &uop.dtype;
            if !(dt.is_float() || dt.is_signed() || *dt == DType::Index) {
                return None;
            }
            let (src_min, src_max) = (*SoundVminVmaxProperty::get(src))?;
            let has_special = matches!(src_min, ConstValue::Float(f) if f.is_nan() || f.is_infinite())
                || matches!(src_max, ConstValue::Float(f) if f.is_nan() || f.is_infinite());
            if has_special {
                return None;
            }
            let (target_min, target_max) = dtype_bounds(dt);
            let clamped_min = clamp_value(src_min, target_min, target_max);
            let clamped_max = clamp_value(src_max, target_min, target_max);
            Some((clamped_min.cast(dt).unwrap_or(target_min), clamped_max.cast(dt).unwrap_or(target_max)))
        }

        // Everything else: LOAD, STORE, INDEX, REDUCE, NOOP, etc.
        _ => None,
    }
}

/// Range [0, end-1] for Range and Special ops.
fn zero_to_end_minus_one(end: &Arc<UOp>, dtype: &DType) -> (ConstValue, ConstValue) {
    use crate::uop::cached_property::CachedProperty;
    use crate::uop::properties::VminVmaxProperty;
    let (_, end_max) = VminVmaxProperty::get(end);
    let max = match end_max {
        ConstValue::Int(v) => ConstValue::Int(v - 1),
        ConstValue::UInt(v) => ConstValue::UInt(v - 1),
        _ => dtype_bounds(dtype).1,
    };
    (ConstValue::Int(0), max)
}

/// Sound union of ranges — returns None if any source is unsound.
fn sound_sources_range(sources: &[Arc<UOp>]) -> Option<(ConstValue, ConstValue)> {
    use crate::uop::cached_property::CachedProperty;
    use crate::uop::properties::SoundVminVmaxProperty;
    if sources.is_empty() {
        return None;
    }
    let (first_min, first_max) = (*SoundVminVmaxProperty::get(&sources[0]))?;
    sources.iter().skip(1).try_fold((first_min, first_max), |(vmin, vmax), src| {
        let (s_min, s_max) = (*SoundVminVmaxProperty::get(src))?;
        Some((min_value(vmin, s_min), max_value(vmax, s_max)))
    })
}

/// Union of ranges across ConstValue slice (VConst).
fn sources_range_values(values: &[ConstValue], dtype: &DType) -> (ConstValue, ConstValue) {
    if values.is_empty() {
        return dtype_bounds(dtype);
    }
    values.iter().skip(1).fold((values[0], values[0]), |(vmin, vmax), &v| (min_value(vmin, v), max_value(vmax, v)))
}

// ============================================================================
// Unary Operations
// ============================================================================

/// Compute range for unary operations.
fn compute_unary_range(op: UnaryOp, vmin: ConstValue, vmax: ConstValue, dtype: &DType) -> (ConstValue, ConstValue) {
    use crate::uop::eval::eval_unary_op;

    match op {
        UnaryOp::Neg => {
            // Negation flips the range
            let new_min = eval_unary_op(UnaryOp::Neg, vmax).unwrap_or_else(|| dtype_bounds(dtype).0);
            let new_max = eval_unary_op(UnaryOp::Neg, vmin).unwrap_or_else(|| dtype_bounds(dtype).1);
            (new_min, new_max)
        }
        UnaryOp::Abs => {
            // Absolute value: if range crosses zero, min becomes 0
            // Otherwise, we need to take abs of both endpoints and find min/max
            let crosses_zero = match (vmin, vmax) {
                (ConstValue::Int(min), ConstValue::Int(max)) => min <= 0 && max >= 0,
                (ConstValue::Float(min), ConstValue::Float(max)) => min <= 0.0 && max >= 0.0,
                _ => false,
            };

            if crosses_zero {
                // Range includes zero, so min is 0
                let zero = match vmin {
                    ConstValue::Int(_) => ConstValue::Int(0),
                    ConstValue::UInt(_) => ConstValue::UInt(0),
                    ConstValue::Float(_) => ConstValue::Float(0.0),
                    _ => dtype_bounds(dtype).0,
                };

                let abs_min = eval_unary_op(UnaryOp::Abs, vmin);
                let abs_max = eval_unary_op(UnaryOp::Abs, vmax);
                let max_val = match (abs_min, abs_max) {
                    (Some(a), Some(b)) => {
                        if compare_const_values(&a, &b) == Ordering::Greater {
                            a
                        } else {
                            b
                        }
                    }
                    _ => dtype_bounds(dtype).1,
                };
                (zero, max_val)
            } else {
                // Range doesn't cross zero, evaluate at endpoints
                let val_min = eval_unary_op(op, vmin);
                let val_max = eval_unary_op(op, vmax);
                match (val_min, val_max) {
                    (Some(min), Some(max)) => {
                        if compare_const_values(&min, &max) == Ordering::Greater {
                            (max, min)
                        } else {
                            (min, max)
                        }
                    }
                    _ => dtype_bounds(dtype),
                }
            }
        }
        UnaryOp::Sin | UnaryOp::Cos => {
            // Sin and Cos are bounded in [-1, 1] for any input
            // TODO: Could be more precise for small ranges
            (ConstValue::Float(-1.0), ConstValue::Float(1.0))
        }
        UnaryOp::Tan => {
            // Tan is unbounded, so use dtype bounds
            // TODO: Could be more precise for small ranges avoiding discontinuities
            dtype_bounds(dtype)
        }
        UnaryOp::Erf => {
            // Erf is bounded in [-1, 1] for all inputs
            (ConstValue::Float(-1.0), ConstValue::Float(1.0))
        }
        UnaryOp::Sign => {
            // Sign returns -1, 0, or 1
            match vmin {
                ConstValue::Int(_) => (ConstValue::Int(-1), ConstValue::Int(1)),
                ConstValue::Float(_) => (ConstValue::Float(-1.0), ConstValue::Float(1.0)),
                ConstValue::UInt(_) => (ConstValue::UInt(0), ConstValue::UInt(1)),
                _ => dtype_bounds(dtype),
            }
        }
        UnaryOp::Square => {
            // Square: x² - similar to Abs, if range crosses zero, min becomes 0
            let crosses_zero = match (vmin, vmax) {
                (ConstValue::Int(min), ConstValue::Int(max)) => min <= 0 && max >= 0,
                (ConstValue::Float(min), ConstValue::Float(max)) => min <= 0.0 && max >= 0.0,
                _ => false,
            };

            if crosses_zero {
                // Range includes zero, so min is 0
                let zero = match vmin {
                    ConstValue::Int(_) => ConstValue::Int(0),
                    ConstValue::UInt(_) => ConstValue::UInt(0),
                    ConstValue::Float(_) => ConstValue::Float(0.0),
                    _ => dtype_bounds(dtype).0,
                };

                let sq_min = eval_unary_op(UnaryOp::Square, vmin);
                let sq_max = eval_unary_op(UnaryOp::Square, vmax);
                let max_val = match (sq_min, sq_max) {
                    (Some(a), Some(b)) => {
                        if compare_const_values(&a, &b) == Ordering::Greater {
                            a
                        } else {
                            b
                        }
                    }
                    _ => dtype_bounds(dtype).1,
                };
                (zero, max_val)
            } else {
                // Range doesn't cross zero, evaluate at endpoints
                let val_min = eval_unary_op(op, vmin);
                let val_max = eval_unary_op(op, vmax);
                match (val_min, val_max) {
                    (Some(min), Some(max)) => {
                        if compare_const_values(&min, &max) == Ordering::Greater {
                            (max, min)
                        } else {
                            (min, max)
                        }
                    }
                    _ => dtype_bounds(dtype),
                }
            }
        }
        UnaryOp::Not => {
            // Not flips bits/booleans - evaluate at endpoints and swap
            let new_min = eval_unary_op(UnaryOp::Not, vmax).unwrap_or_else(|| dtype_bounds(dtype).0);
            let new_max = eval_unary_op(UnaryOp::Not, vmin).unwrap_or_else(|| dtype_bounds(dtype).1);
            (new_min, new_max)
        }
        UnaryOp::Sqrt
        | UnaryOp::Rsqrt
        | UnaryOp::Exp
        | UnaryOp::Exp2
        | UnaryOp::Log
        | UnaryOp::Log2
        | UnaryOp::Reciprocal
        | UnaryOp::Trunc
        | UnaryOp::Floor
        | UnaryOp::Ceil
        | UnaryOp::Round => {
            // For monotonic or simple functions, evaluate at endpoints
            let val_min = eval_unary_op(op, vmin);
            let val_max = eval_unary_op(op, vmax);

            match (val_min, val_max) {
                (Some(min), Some(max)) => {
                    // Ensure min <= max (for non-monotonic functions)
                    if compare_const_values(&min, &max) == Ordering::Greater { (max, min) } else { (min, max) }
                }
                _ => dtype_bounds(dtype),
            }
        }
    }
}

// ============================================================================
// Binary Operations
// ============================================================================

/// Compute range for binary operations.
fn compute_binary_range(
    op: BinaryOp,
    a_min: ConstValue,
    a_max: ConstValue,
    b_min: ConstValue,
    b_max: ConstValue,
    dtype: &DType,
) -> (ConstValue, ConstValue) {
    use crate::uop::eval::eval_binary_op;

    // Fast path: if both operands are constants, evaluate exactly
    // (except for comparisons which always return full bool range for consistency)
    if a_min == a_max
        && b_min == b_max
        && !matches!(op, BinaryOp::Lt | BinaryOp::Le | BinaryOp::Eq | BinaryOp::Ne | BinaryOp::Gt | BinaryOp::Ge)
    {
        if let Some(val) = eval_binary_op(op, a_min, b_min) {
            return (val, val);
        }
        return dtype_bounds(dtype);
    }

    match op {
        // Arithmetic operations with overflow checking
        BinaryOp::Add => {
            match (a_min, a_max, b_min, b_max) {
                (ConstValue::Int(amin), ConstValue::Int(amax), ConstValue::Int(bmin), ConstValue::Int(bmax)) => {
                    match (amin.checked_add(bmin), amax.checked_add(bmax)) {
                        (Some(min), Some(max)) => (ConstValue::Int(min), ConstValue::Int(max)),
                        _ => dtype_bounds(dtype), // Overflow - return conservative bounds
                    }
                }
                (ConstValue::UInt(amin), ConstValue::UInt(amax), ConstValue::UInt(bmin), ConstValue::UInt(bmax)) => {
                    match (amin.checked_add(bmin), amax.checked_add(bmax)) {
                        (Some(min), Some(max)) => (ConstValue::UInt(min), ConstValue::UInt(max)),
                        _ => dtype_bounds(dtype), // Overflow - return conservative bounds
                    }
                }
                _ => {
                    // Float or fallback - use eval_binary_op (floats don't overflow to wrong values)
                    let min = eval_binary_op(BinaryOp::Add, a_min, b_min).unwrap_or_else(|| dtype_bounds(dtype).0);
                    let max = eval_binary_op(BinaryOp::Add, a_max, b_max).unwrap_or_else(|| dtype_bounds(dtype).1);
                    (min, max)
                }
            }
        }
        BinaryOp::Sub => {
            match (a_min, a_max, b_min, b_max) {
                (ConstValue::Int(amin), ConstValue::Int(amax), ConstValue::Int(bmin), ConstValue::Int(bmax)) => {
                    match (amin.checked_sub(bmax), amax.checked_sub(bmin)) {
                        (Some(min), Some(max)) => (ConstValue::Int(min), ConstValue::Int(max)),
                        _ => dtype_bounds(dtype), // Overflow - return conservative bounds
                    }
                }
                (ConstValue::UInt(amin), ConstValue::UInt(amax), ConstValue::UInt(bmin), ConstValue::UInt(bmax)) => {
                    match (amin.checked_sub(bmax), amax.checked_sub(bmin)) {
                        (Some(min), Some(max)) => (ConstValue::UInt(min), ConstValue::UInt(max)),
                        _ => dtype_bounds(dtype), // Overflow - return conservative bounds
                    }
                }
                _ => {
                    // Float or fallback
                    let min = eval_binary_op(BinaryOp::Sub, a_min, b_max).unwrap_or_else(|| dtype_bounds(dtype).0);
                    let max = eval_binary_op(BinaryOp::Sub, a_max, b_min).unwrap_or_else(|| dtype_bounds(dtype).1);
                    (min, max)
                }
            }
        }
        BinaryOp::Max => {
            let min = eval_binary_op(BinaryOp::Max, a_min, b_min).unwrap_or_else(|| dtype_bounds(dtype).0);
            let max = eval_binary_op(BinaryOp::Max, a_max, b_max).unwrap_or_else(|| dtype_bounds(dtype).1);
            (min, max)
        }

        // Operations requiring all four corners
        BinaryOp::Mul | BinaryOp::Pow => eval_four_corners(op, a_min, a_max, b_min, b_max, dtype),

        // Division operations
        BinaryOp::Idiv | BinaryOp::Fdiv => {
            if contains_zero(b_min, b_max) {
                dtype_bounds(dtype)
            } else {
                eval_four_corners(op, a_min, a_max, b_min, b_max, dtype)
            }
        }

        // Modulo operation — NOT monotonic, four-corner evaluation is unsound.
        // (Tinygrad: ops.py _min_max, Ops.MOD handler)
        BinaryOp::Mod => {
            match (a_min, a_max, b_min, b_max) {
                // Non-negative dividend, positive modulus: a % m ∈ [0, min(a_max, m_max - 1)]
                (ConstValue::Int(a_lo), ConstValue::Int(a_hi), ConstValue::Int(b_lo), ConstValue::Int(b_hi))
                    if a_lo >= 0 && b_lo > 0 =>
                {
                    (ConstValue::Int(0), ConstValue::Int(a_hi.min(b_hi - 1)))
                }
                // Non-positive dividend, positive modulus: result ∈ [-(m_max-1), 0]
                (ConstValue::Int(_a_lo), ConstValue::Int(a_hi), ConstValue::Int(b_lo), ConstValue::Int(b_hi))
                    if a_hi <= 0 && b_lo > 0 =>
                {
                    (ConstValue::Int(-(b_hi - 1)), ConstValue::Int(0))
                }
                // Mixed-sign dividend, positive modulus: result ∈ [-(m_max-1), m_max-1]
                (ConstValue::Int(_), ConstValue::Int(_), ConstValue::Int(b_lo), ConstValue::Int(b_hi)) if b_lo > 0 => {
                    (ConstValue::Int(-(b_hi - 1)), ConstValue::Int(b_hi - 1))
                }
                // Unsigned: always non-negative
                (ConstValue::UInt(_), ConstValue::UInt(a_hi), ConstValue::UInt(b_lo), ConstValue::UInt(b_hi))
                    if b_lo > 0 =>
                {
                    (ConstValue::UInt(0), ConstValue::UInt(a_hi.min(b_hi - 1)))
                }
                _ => dtype_bounds(dtype),
            }
        }

        // Comparison operations - use unified ComparisonAnalyzer
        BinaryOp::Lt | BinaryOp::Le | BinaryOp::Eq | BinaryOp::Ne | BinaryOp::Gt | BinaryOp::Ge => {
            use crate::uop::comparison_analysis::ComparisonAnalyzer;
            ComparisonAnalyzer::get_comparison_range(op, a_min, a_max, b_min, b_max)
        }

        // Bitwise operations
        BinaryOp::And | BinaryOp::Or | BinaryOp::Xor => compute_bitwise_range(op, a_min, a_max, b_min, b_max, dtype),

        // Shift operations
        BinaryOp::Shl | BinaryOp::Shr => compute_shift_range(op, a_min, a_max, b_min, b_max, dtype),

        // PRNG - unpredictable
        BinaryOp::Threefry => dtype_bounds(dtype),
    }
}

/// Compute range for bitwise operations.
fn compute_bitwise_range(
    op: BinaryOp,
    a_min: ConstValue,
    a_max: ConstValue,
    b_min: ConstValue,
    b_max: ConstValue,
    dtype: &DType,
) -> (ConstValue, ConstValue) {
    if dtype == &DType::Bool {
        // For bool, evaluate all combinations
        eval_four_corners(op, a_min, a_max, b_min, b_max, dtype)
    } else {
        match op {
            BinaryOp::And => {
                // Sound only with constant non-negative mask: 0 <= (x & mask) <= mask
                // (compute_sound_vmin_vmax ensures b_min == b_max >= 0)
                if let (ConstValue::Int(bmin), ConstValue::Int(bmax)) = (b_min, b_max)
                    && bmin == bmax
                    && bmin >= 0
                {
                    return (ConstValue::Int(0), ConstValue::Int(bmax));
                }
                dtype_bounds(dtype)
            }
            _ => dtype_bounds(dtype), // OR, XOR are harder to bound
        }
    }
}

/// Compute range for shift operations.
fn compute_shift_range(
    op: BinaryOp,
    a_min: ConstValue,
    a_max: ConstValue,
    b_min: ConstValue,
    b_max: ConstValue,
    dtype: &DType,
) -> (ConstValue, ConstValue) {
    // Get the bit width of the dtype
    let bit_width = if dtype == &DType::Int8 || dtype == &DType::UInt8 {
        8
    } else if dtype == &DType::Int16 || dtype == &DType::UInt16 {
        16
    } else if dtype == &DType::Int32 || dtype == &DType::UInt32 {
        32
    } else if dtype == &DType::Int64 || dtype == &DType::UInt64 {
        64
    } else {
        return dtype_bounds(dtype); // Unsupported type for shifts
    };

    // Check if shift amount is valid (0 to bit_width-1)
    match (b_min, b_max) {
        (ConstValue::Int(shift_min), ConstValue::Int(shift_max)) if shift_min >= 0 && shift_max < bit_width as i64 => {
            eval_four_corners(op, a_min, a_max, b_min, b_max, dtype)
        }
        (ConstValue::UInt(shift_min), ConstValue::UInt(shift_max))
            if shift_min == 0 && shift_max < bit_width as u64 =>
        {
            eval_four_corners(op, a_min, a_max, b_min, b_max, dtype)
        }
        _ => dtype_bounds(dtype), // Invalid shift amount or range crosses zero
    }
}

// ============================================================================
// Ternary Operations
// ============================================================================

/// Compute range for ternary operations.
#[allow(clippy::too_many_arguments)]
fn compute_ternary_range(
    op: TernaryOp,
    cond_min: ConstValue,
    cond_max: ConstValue,
    true_min: ConstValue,
    true_max: ConstValue,
    false_min: ConstValue,
    false_max: ConstValue,
    dtype: &DType,
) -> (ConstValue, ConstValue) {
    match op {
        TernaryOp::Where => {
            // WHERE: if cond then true_val else false_val
            match (cond_min, cond_max) {
                (ConstValue::Bool(true), ConstValue::Bool(true)) => (true_min, true_max),
                (ConstValue::Bool(false), ConstValue::Bool(false)) => (false_min, false_max),
                _ => {
                    // Could be either branch - take union of ranges
                    let candidates = [true_min, true_max, false_min, false_max];
                    range_union(&candidates)
                }
            }
        }
        TernaryOp::MulAcc => {
            // MulAcc: a * b + c
            // Conservative: evaluate all 8 corners
            use crate::uop::eval::eval_ternary_op;

            let corners = [
                (cond_min, true_min, false_min),
                (cond_min, true_min, false_max),
                (cond_min, true_max, false_min),
                (cond_min, true_max, false_max),
                (cond_max, true_min, false_min),
                (cond_max, true_min, false_max),
                (cond_max, true_max, false_min),
                (cond_max, true_max, false_max),
            ];

            let mut min = None;
            let mut max = None;

            for &(a, b, c) in &corners {
                if let Some(val) = eval_ternary_op(TernaryOp::MulAcc, a, b, c) {
                    min = Some(min.map_or(val, |m| min_value(m, val)));
                    max = Some(max.map_or(val, |m| max_value(m, val)));
                }
            }

            min.zip(max).unwrap_or_else(|| dtype_bounds(dtype))
        }
    }
}

// ============================================================================
// Helper Functions
// ============================================================================

/// Evaluate binary operation at all four corners of input ranges.
fn eval_four_corners(
    op: BinaryOp,
    a_min: ConstValue,
    a_max: ConstValue,
    b_min: ConstValue,
    b_max: ConstValue,
    dtype: &DType,
) -> (ConstValue, ConstValue) {
    use crate::uop::eval::eval_binary_op;

    let corners = [(a_min, b_min), (a_min, b_max), (a_max, b_min), (a_max, b_max)];

    let mut min = None;
    let mut max = None;

    for &(a, b) in &corners {
        if let Some(val) = eval_binary_op(op, a, b) {
            min = Some(min.map_or(val, |m| min_value(m, val)));
            max = Some(max.map_or(val, |m| max_value(m, val)));
        }
    }

    min.zip(max).unwrap_or_else(|| dtype_bounds(dtype))
}

/// Get the minimum and maximum values for a dtype.
pub fn dtype_bounds(dtype: &DType) -> (ConstValue, ConstValue) {
    let s = dtype.base();
    (ConstValue::min(s), ConstValue::max(s))
}

/// Compare two ConstValues and return the minimum.
fn min_value(a: ConstValue, b: ConstValue) -> ConstValue {
    if compare_const_values(&a, &b) == Ordering::Less { a } else { b }
}

/// Compare two ConstValues and return the maximum.
fn max_value(a: ConstValue, b: ConstValue) -> ConstValue {
    if compare_const_values(&a, &b) == Ordering::Greater { a } else { b }
}

/// Get the union of ranges (min of mins, max of maxes).
fn range_union(values: &[ConstValue]) -> (ConstValue, ConstValue) {
    let min = values.iter().copied().reduce(min_value).unwrap();
    let max = values.iter().copied().reduce(max_value).unwrap();
    (min, max)
}

/// Compare two ConstValues for ordering.
fn compare_const_values(a: &ConstValue, b: &ConstValue) -> Ordering {
    match (a, b) {
        (ConstValue::Int(x), ConstValue::Int(y)) => x.cmp(y),
        (ConstValue::UInt(x), ConstValue::UInt(y)) => x.cmp(y),
        (ConstValue::Float(x), ConstValue::Float(y)) => {
            // Handle NaN properly
            if x.is_nan() && y.is_nan() {
                Ordering::Equal
            } else if x.is_nan() {
                Ordering::Greater // NaN is "greater" for consistency
            } else if y.is_nan() {
                Ordering::Less
            } else {
                x.partial_cmp(y).unwrap_or(Ordering::Equal)
            }
        }
        (ConstValue::Bool(x), ConstValue::Bool(y)) => x.cmp(y),
        _ => Ordering::Equal, // Mixed types shouldn't happen
    }
}

/// Check if a range contains zero.
fn contains_zero(min: ConstValue, max: ConstValue) -> bool {
    match (min, max) {
        (ConstValue::Int(min_v), ConstValue::Int(max_v)) => min_v <= 0 && max_v >= 0,
        (ConstValue::UInt(min_v), _) => min_v == 0, // UInt range contains zero iff min is zero
        (ConstValue::Float(min_v), ConstValue::Float(max_v)) => min_v <= 0.0 && max_v >= 0.0,
        _ => false,
    }
}

/// Clamp a value to a range.
fn clamp_value(v: ConstValue, min: ConstValue, max: ConstValue) -> ConstValue {
    if compare_const_values(&v, &min) == Ordering::Less {
        min
    } else if compare_const_values(&v, &max) == Ordering::Greater {
        max
    } else {
        v
    }
}