cubecl-opt 0.10.0

Compiler optimizations for CubeCL
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
use cubecl_ir::{
    Arithmetic, Bitwise, Comparison, ConstantValue, Instruction, Metadata, Operation, Operator,
    Type, Variable, VariableKind,
};

use crate::{AtomicCounter, Optimizer};

use super::OptimizerPass;

/// Simplifies certain expressions where one operand is constant.
/// For example: `out = x * 1` to `out = x`
pub struct ConstOperandSimplify;

impl OptimizerPass for ConstOperandSimplify {
    fn apply_post_ssa(&mut self, opt: &mut Optimizer, changes: AtomicCounter) {
        for node in opt.program.node_indices().collect::<Vec<_>>() {
            let ops = opt.program[node].ops.borrow().indices().collect::<Vec<_>>();

            for idx in ops {
                let op = &mut opt.program[node].ops.borrow_mut()[idx];
                match &mut op.operation {
                    Operation::Arithmetic(operator) => match operator {
                        // 0 * x == 0
                        Arithmetic::Mul(bin_op) if bin_op.lhs.is_constant(0) => {
                            op.operation = Operation::Copy(bin_op.lhs);
                            changes.inc();
                        }
                        // x * 0 == 0
                        Arithmetic::Mul(bin_op) if bin_op.rhs.is_constant(0) => {
                            op.operation = Operation::Copy(bin_op.rhs);
                            changes.inc();
                        }
                        // 1 * x == x
                        Arithmetic::Mul(bin_op) if bin_op.lhs.is_constant(1) => {
                            op.operation = Operation::Copy(bin_op.rhs);
                            changes.inc();
                        }
                        // x * 1 == x
                        Arithmetic::Mul(bin_op) if bin_op.rhs.is_constant(1) => {
                            op.operation = Operation::Copy(bin_op.lhs);
                            changes.inc();
                        }
                        // 0 + x = x
                        Arithmetic::Add(bin_op) if bin_op.lhs.is_constant(0) => {
                            op.operation = Operation::Copy(bin_op.rhs);
                            changes.inc();
                        }
                        // x + 0 = x
                        Arithmetic::Add(bin_op) if bin_op.rhs.is_constant(0) => {
                            op.operation = Operation::Copy(bin_op.lhs);
                            changes.inc();
                        }
                        // x - 0 == x
                        Arithmetic::Sub(bin_op) if bin_op.rhs.is_constant(0) => {
                            op.operation = Operation::Copy(bin_op.lhs);
                            changes.inc();
                        }
                        // x / 1 == x, 0 / x == 0
                        Arithmetic::Div(bin_op)
                            if bin_op.lhs.is_constant(0) || bin_op.rhs.is_constant(1) =>
                        {
                            op.operation = Operation::Copy(bin_op.lhs);
                            changes.inc();
                        }
                        // x % 1 == 0, 0 % x == 0
                        Arithmetic::Modulo(bin_op)
                            if bin_op.rhs.is_constant(1) || bin_op.lhs.is_constant(0) =>
                        {
                            op.operation = Operation::Copy(op.ty().constant(ConstantValue::Int(0)));
                            changes.inc();
                        }
                        _ => {}
                    },

                    Operation::Operator(operator) => match operator {
                        // true || x == true, x || true == true
                        Operator::Or(bin_op) if bin_op.lhs.is_true() || bin_op.rhs.is_true() => {
                            op.operation = Operation::Copy(true.into());
                            changes.inc();
                        }
                        // false || x == x, x || false == x
                        Operator::Or(bin_op) if bin_op.lhs.is_false() => {
                            op.operation = Operation::Copy(bin_op.rhs);
                            changes.inc();
                        }
                        // x || false == x
                        Operator::Or(bin_op) if bin_op.rhs.is_false() => {
                            op.operation = Operation::Copy(bin_op.lhs);
                            changes.inc();
                        }
                        // false && x == false, x && false == false
                        Operator::And(bin_op) if bin_op.lhs.is_false() || bin_op.rhs.is_false() => {
                            op.operation = Operation::Copy(false.into());
                            changes.inc();
                        }
                        // true && x == x
                        Operator::And(bin_op) if bin_op.lhs.is_true() => {
                            op.operation = Operation::Copy(bin_op.rhs);
                            changes.inc();
                        }
                        // x && true == x
                        Operator::And(bin_op) if bin_op.rhs.is_true() => {
                            op.operation = Operation::Copy(bin_op.lhs);
                            changes.inc();
                        }
                        // select(true, a, b) == a
                        Operator::Select(select) if select.cond.is_true() => {
                            op.operation = Operation::Copy(select.then);
                            changes.inc();
                        }
                        // select(false, a, b) == b
                        Operator::Select(select) if select.cond.is_false() => {
                            op.operation = Operation::Copy(select.or_else);
                            changes.inc();
                        }
                        _ => {}
                    },

                    // Constant length to const value
                    Operation::Metadata(Metadata::Length { var }) => match var.kind {
                        VariableKind::ConstantArray { length, .. }
                        | VariableKind::SharedArray { length, .. }
                        | VariableKind::LocalArray { length, .. } => {
                            op.operation = Operation::Copy(length.into());
                            changes.inc();
                        }
                        _ => {}
                    },
                    _ => {}
                }
            }
        }
    }
}

/// Evaluates expressions where both operands are constant and replaces them with simple constant
/// assignments. This can often be applied as a result of assignment merging or constant operand
/// simplification.
pub struct ConstEval;

impl OptimizerPass for ConstEval {
    fn apply_post_ssa(&mut self, opt: &mut Optimizer, changes: AtomicCounter) {
        for node in opt.node_ids() {
            let ops = opt.program[node].ops.clone();
            for op in ops.borrow_mut().values_mut() {
                if let Some(const_eval) = try_const_eval(op) {
                    let input = Variable::constant(const_eval, op.out().ty);
                    op.operation = Operation::Copy(input);
                    changes.inc();
                }
            }
        }
    }
}

macro_rules! const_eval {
    ($op:tt $lhs:expr, $rhs:expr) => {{
        use ConstantValue::*;

        let ty = $lhs.ty;
        let lhs = $lhs.as_const();
        let rhs = $rhs.as_const();
        if let (Some(lhs), Some(rhs)) = (lhs, rhs) {
            let rhs = rhs.cast_to(ty);
            Some(match (lhs, rhs) {
                (Int(lhs), Int(rhs)) => ConstantValue::Int(lhs $op rhs),
                (Float(lhs), Float(rhs)) => ConstantValue::Float(lhs $op rhs),
                (UInt(lhs), UInt(rhs)) => ConstantValue::UInt(lhs $op rhs),
                _ => unreachable!(),
            })
        } else {
            None
        }
    }};
    ($lhs:expr, $rhs:expr; $op:path) => {{
        use ConstantScalarValue::*;

        let lhs = $lhs.as_const();
        let rhs = $rhs.as_const();
        if let (Some(lhs), Some(rhs)) = (lhs, rhs) {
            let rhs = rhs.cast_to(lhs.storage_type());
            Some(match (lhs, rhs) {
                (Int(lhs, kind), Int(rhs, _)) => ConstantScalarValue::Int($op(lhs, rhs), kind),
                (Float(lhs, kind), Float(rhs, _)) => ConstantScalarValue::Float($op(lhs, rhs), kind),
                (UInt(lhs), UInt(rhs)) => ConstantScalarValue::UInt($op(lhs, rhs)),
                _ => unreachable!(),
            })
        } else {
            None
        }
    }};
}

macro_rules! const_eval_int {
    ($op:tt $lhs:expr, $rhs:expr) => {{
        use ConstantValue::*;

        let ty = $lhs.ty;
        let lhs = $lhs.as_const();
        let rhs = $rhs.as_const();
        if let (Some(lhs), Some(rhs)) = (lhs, rhs) {
            let rhs = rhs.cast_to(ty);
            Some(match (lhs, rhs) {
                (Int(lhs), Int(rhs)) => ConstantValue::Int(lhs $op rhs),
                (UInt(lhs), UInt(rhs)) => ConstantValue::UInt(lhs $op rhs),
                _ => unreachable!(),
            })
        } else {
            None
        }
    }};
}

macro_rules! const_eval_float {
    ($lhs:expr, $rhs:expr; $fn:path) => {{
        use ConstantValue::*;

        let ty = $lhs.ty;
        let lhs = $lhs.as_const();
        let rhs = $rhs.as_const();
        if let (Some(lhs), Some(rhs)) = (lhs, rhs) {
            let rhs = rhs.cast_to(ty);
            Some(match (lhs, rhs) {
                (Float(lhs), Float(rhs)) => ConstantValue::Float($fn(lhs, rhs)),
                _ => unreachable!(),
            })
        } else {
            None
        }
    }};
    ($input:expr; $fn:path) => {{
        use ConstantValue::*;

        if let Some(input) = $input.as_const() {
            Some(match input {
                Float(input) => ConstantValue::Float($fn(input)),
                _ => unreachable!(),
            })
        } else {
            None
        }
    }};
}

macro_rules! const_eval_cmp {
    ($op:tt $lhs:expr, $rhs:expr) => {{
        use ConstantValue::*;

        let lhs = $lhs.as_const();
        let rhs = $rhs.as_const();
        if let (Some(lhs), Some(rhs)) = (lhs, rhs) {
            Some(match (lhs, rhs) {
                (Int(lhs), Int(rhs)) => ConstantValue::Bool(lhs $op rhs),
                (Float(lhs), Float(rhs)) => ConstantValue::Bool(lhs $op rhs),
                (UInt(lhs), UInt(rhs)) => ConstantValue::Bool(lhs $op rhs),
                _ => unreachable!(),
            })
        } else {
            None
        }
    }};
}

macro_rules! const_eval_bool {
    ($op:tt $lhs:expr, $rhs:expr) => {{
        use ConstantValue::*;

        let lhs = $lhs.as_const();
        let rhs = $rhs.as_const();
        if let (Some(lhs), Some(rhs)) = (lhs, rhs) {
            Some(match (lhs, rhs) {
                (Bool(lhs), Bool(rhs)) => ConstantValue::Bool(lhs $op rhs),
                _ => unreachable!(),
            })
        } else {
            None
        }
    }};
}

fn try_const_eval(inst: &mut Instruction) -> Option<ConstantValue> {
    match &mut inst.operation {
        Operation::Arithmetic(op) => try_const_eval_arithmetic(op),
        Operation::Comparison(op) => try_const_eval_cmp(op),
        Operation::Bitwise(op) => try_const_eval_bitwise(op),
        Operation::Operator(op) => try_const_eval_operator(op, inst.out.map(|it| it.ty)),
        _ => None,
    }
}

fn try_const_eval_arithmetic(op: &mut Arithmetic) -> Option<ConstantValue> {
    match op {
        Arithmetic::Add(op) => const_eval!(+ op.lhs, op.rhs),
        Arithmetic::Sub(op) => const_eval!(-op.lhs, op.rhs),
        Arithmetic::Mul(op) => const_eval!(*op.lhs, op.rhs),
        Arithmetic::Div(op) => const_eval!(/ op.lhs, op.rhs),
        Arithmetic::SaturatingAdd(op) => {
            use ConstantValue::*;

            let ty = op.lhs.ty;
            let lhs = op.lhs.as_const();
            let rhs = op.rhs.as_const();
            if let (Some(lhs), Some(rhs)) = (lhs, rhs) {
                let rhs = rhs.cast_to(ty);
                // Saturating ops only support 32-bit
                // NOTE: Change this if that's ever not the case!
                Some(match (lhs, rhs) {
                    (Int(lhs), Int(rhs)) => Int((lhs as i32).saturating_add(rhs as i32) as i64),
                    (UInt(lhs), UInt(rhs)) => UInt((lhs as u32).saturating_add(rhs as u32) as u64),
                    _ => unreachable!(),
                })
            } else {
                None
            }
        }
        Arithmetic::SaturatingSub(op) => {
            use ConstantValue::*;

            let ty = op.lhs.ty;
            let lhs = op.lhs.as_const();
            let rhs = op.rhs.as_const();
            if let (Some(lhs), Some(rhs)) = (lhs, rhs) {
                let rhs = rhs.cast_to(ty);
                // Saturating ops only support 32-bit
                // NOTE: Change this if that's ever not the case!
                Some(match (lhs, rhs) {
                    (Int(lhs), Int(rhs)) => Int((lhs as i32).saturating_sub(rhs as i32) as i64),
                    (UInt(lhs), UInt(rhs)) => UInt((lhs as u32).saturating_sub(rhs as u32) as u64),
                    _ => unreachable!(),
                })
            } else {
                None
            }
        }
        Arithmetic::Powf(op) => const_eval_float!(op.lhs, op.rhs; num::Float::powf),
        // powf is fast enough for const eval
        Arithmetic::Powi(op) => {
            const_eval_float!(op.lhs, op.rhs; num::Float::powf)
        }
        Arithmetic::Modulo(op) => const_eval!(% op.lhs, op.rhs),
        Arithmetic::Remainder(op) => const_eval!(% op.lhs, op.rhs),
        Arithmetic::MulHi(op) => {
            use ConstantValue::*;
            let ty = op.lhs.ty;
            if let (Some(lhs), Some(rhs)) = (op.lhs.as_const(), op.rhs.as_const()) {
                let rhs = rhs.cast_to(ty);
                Some(match (lhs, rhs) {
                    (Int(lhs), Int(rhs)) => {
                        let mul = (lhs * rhs) >> 32;
                        ConstantValue::Int(mul as i32 as i64)
                    }
                    (UInt(lhs), UInt(rhs)) => {
                        let mul = (lhs * rhs) >> 32;
                        ConstantValue::UInt(mul as u32 as u64)
                    }
                    _ => unreachable!(),
                })
            } else {
                None
            }
        }
        Arithmetic::Max(op) => {
            use ConstantValue::*;
            let ty = op.lhs.ty;
            if let (Some(lhs), Some(rhs)) = (op.lhs.as_const(), op.rhs.as_const()) {
                let rhs = rhs.cast_to(ty);
                Some(match (lhs, rhs) {
                    (Int(lhs), Int(rhs)) => ConstantValue::Int(lhs.max(rhs)),
                    (Float(lhs), Float(rhs)) => ConstantValue::Float(lhs.max(rhs)),
                    (UInt(lhs), UInt(rhs)) => ConstantValue::UInt(lhs.max(rhs)),
                    _ => unreachable!(),
                })
            } else {
                None
            }
        }
        Arithmetic::Min(op) => {
            use ConstantValue::*;
            let ty = op.lhs.ty;
            if let (Some(lhs), Some(rhs)) = (op.lhs.as_const(), op.rhs.as_const()) {
                let rhs = rhs.cast_to(ty);
                Some(match (lhs, rhs) {
                    (Int(lhs), Int(rhs)) => ConstantValue::Int(lhs.min(rhs)),
                    (Float(lhs), Float(rhs)) => ConstantValue::Float(lhs.min(rhs)),
                    (UInt(lhs), UInt(rhs)) => ConstantValue::UInt(lhs.min(rhs)),
                    _ => unreachable!(),
                })
            } else {
                None
            }
        }
        Arithmetic::Dot(op) => const_eval!(*op.lhs, op.rhs),

        Arithmetic::Abs(op) => {
            use ConstantValue::*;
            op.input.as_const().map(|input| match input {
                Int(input) => ConstantValue::Int(input.abs()),
                Float(input) => ConstantValue::Float(input.abs()),
                _ => unreachable!(),
            })
        }
        Arithmetic::Exp(op) => const_eval_float!(op.input; num::Float::exp),
        Arithmetic::Log(op) => const_eval_float!(op.input; num::Float::ln),
        Arithmetic::Log1p(op) => const_eval_float!(op.input; num::Float::ln_1p),
        Arithmetic::Cos(op) => const_eval_float!(op.input; num::Float::cos),
        Arithmetic::Sin(op) => const_eval_float!(op.input; num::Float::sin),
        Arithmetic::Tan(op) => const_eval_float!(op.input; num::Float::tan),
        Arithmetic::Tanh(op) => const_eval_float!(op.input; num::Float::tanh),
        Arithmetic::Sinh(op) => const_eval_float!(op.input; num::Float::sinh),
        Arithmetic::Cosh(op) => const_eval_float!(op.input; num::Float::cosh),
        Arithmetic::ArcCos(op) => const_eval_float!(op.input; num::Float::acos),
        Arithmetic::ArcSin(op) => const_eval_float!(op.input; num::Float::asin),
        Arithmetic::ArcTan(op) => const_eval_float!(op.input; num::Float::atan),
        Arithmetic::ArcSinh(op) => const_eval_float!(op.input; num::Float::asinh),
        Arithmetic::ArcCosh(op) => const_eval_float!(op.input; num::Float::acosh),
        Arithmetic::ArcTanh(op) => const_eval_float!(op.input; num::Float::atanh),
        Arithmetic::Degrees(op) => const_eval_float!(op.input; num::Float::to_degrees),
        Arithmetic::Radians(op) => const_eval_float!(op.input; num::Float::to_radians),
        Arithmetic::ArcTan2(op) => {
            use ConstantValue::*;
            let ty = op.lhs.ty;
            if let (Some(lhs), Some(rhs)) = (op.lhs.as_const(), op.rhs.as_const()) {
                let rhs = rhs.cast_to(ty);
                Some(match (lhs, rhs) {
                    (Float(lhs), Float(rhs)) => ConstantValue::Float(lhs.atan2(rhs)),
                    _ => unreachable!(),
                })
            } else {
                None
            }
        }
        Arithmetic::Sqrt(op) => const_eval_float!(op.input; num::Float::sqrt),
        Arithmetic::InverseSqrt(op) => {
            let sqrt = const_eval_float!(op.input; num::Float::sqrt)?;
            let ConstantValue::Float(val) = sqrt else {
                unreachable!()
            };
            Some(ConstantValue::Float(1.0 / val))
        }
        Arithmetic::Round(op) => const_eval_float!(op.input; num::Float::round),
        Arithmetic::Floor(op) => const_eval_float!(op.input; num::Float::floor),
        Arithmetic::Ceil(op) => const_eval_float!(op.input; num::Float::ceil),
        Arithmetic::Trunc(op) => const_eval_float!(op.input; num::Float::trunc),
        Arithmetic::Recip(op) => const_eval_float!(op.input; num::Float::recip),
        Arithmetic::Neg(op) => {
            use ConstantValue::*;
            op.input.as_const().map(|input| match input {
                Int(input) => ConstantValue::Int(-input),
                Float(input) => ConstantValue::Float(-input),
                _ => unreachable!(),
            })
        }

        Arithmetic::Fma(op) => {
            use ConstantValue::*;
            let ty = op.a.ty;
            let a = op.a.as_const();
            let b = op.b.as_const();
            let c = op.c.as_const();

            a.zip(b).zip(c).map(|((a, b), c)| {
                let b = b.cast_to(ty);
                let c = c.cast_to(ty);
                match (a, b, c) {
                    (Float(a), Float(b), Float(c)) => ConstantValue::Float(a * b + c),
                    _ => unreachable!(),
                }
            })
        }
        Arithmetic::Clamp(op) => {
            use ConstantValue::*;
            let ty = op.input.ty;
            let a = op.input.as_const();
            let b = op.min_value.as_const();
            let c = op.max_value.as_const();

            a.zip(b).zip(c).map(|((a, b), c)| {
                let b = b.cast_to(ty);
                let c = c.cast_to(ty);
                match (a, b, c) {
                    (Int(a), Int(b), Int(c)) => ConstantValue::Int(a.clamp(b, c)),
                    (Float(a), Float(b), Float(c)) => ConstantValue::Float(a.clamp(b, c)),
                    (UInt(a), UInt(b), UInt(c)) => ConstantValue::UInt(a.clamp(b, c)),
                    _ => unreachable!(),
                }
            })
        }
        Arithmetic::Erf(_)
        | Arithmetic::Hypot(_)
        | Arithmetic::Rhypot(_)
        | Arithmetic::Magnitude(_)
        | Arithmetic::Normalize(_)
        | Arithmetic::VectorSum(_) => None,
    }
}

fn try_const_eval_cmp(op: &mut Comparison) -> Option<ConstantValue> {
    match op {
        Comparison::Equal(op) => const_eval_cmp!(== op.lhs, op.rhs),
        Comparison::NotEqual(op) => const_eval_cmp!(!= op.lhs, op.rhs),
        Comparison::Lower(op) => const_eval_cmp!(< op.lhs, op.rhs),
        Comparison::Greater(op) => const_eval_cmp!(> op.lhs, op.rhs),
        Comparison::LowerEqual(op) => const_eval_cmp!(<= op.lhs, op.rhs),
        Comparison::GreaterEqual(op) => const_eval_cmp!(>= op.lhs, op.rhs),
        Comparison::IsNan(op) => {
            use ConstantValue::*;
            op.input.as_const().map(|input| match input {
                Float(val) => Bool(val.is_nan()),
                // Integers, bools, uints can't be NaN, so always false
                Int(_) | UInt(_) | Bool(_) => Bool(false),
            })
        }
        Comparison::IsInf(op) => {
            use ConstantValue::*;
            op.input.as_const().map(|input| match input {
                Float(val) => Bool(val.is_infinite()),
                // Integers, bools, uints can't be infinite, so always false
                Int(_) | UInt(_) | Bool(_) => Bool(false),
            })
        }
    }
}

fn try_const_eval_bitwise(op: &mut Bitwise) -> Option<ConstantValue> {
    match op {
        Bitwise::BitwiseAnd(op) => const_eval_int!(&op.lhs, op.rhs),
        Bitwise::BitwiseOr(op) => const_eval_int!(| op.lhs, op.rhs),
        Bitwise::BitwiseXor(op) => const_eval_int!(^ op.lhs, op.rhs),
        Bitwise::ShiftLeft(op) => const_eval_int!(<< op.lhs, op.rhs),
        Bitwise::ShiftRight(op) => const_eval_int!(>> op.lhs, op.rhs),
        Bitwise::BitwiseNot(op) => {
            use ConstantValue::*;
            op.input.as_const().map(|input| match input {
                Int(input) => ConstantValue::Int(!input),
                UInt(input) => ConstantValue::UInt(!input),
                _ => unreachable!(),
            })
        }
        Bitwise::CountOnes(op) => {
            use ConstantValue::*;
            op.input.as_const().map(|input| match input {
                Int(input) => ConstantValue::Int(input.count_ones() as i64),
                UInt(input) => ConstantValue::UInt(input.count_ones() as u64),
                _ => unreachable!(),
            })
        }
        Bitwise::ReverseBits(op) => {
            use ConstantValue::*;
            op.input.as_const().map(|input| match input {
                Int(input) => ConstantValue::Int(input.reverse_bits()),
                UInt(input) => ConstantValue::UInt(input.reverse_bits()),
                _ => unreachable!(),
            })
        }
        Bitwise::LeadingZeros(_) | Bitwise::TrailingZeros(_) | Bitwise::FindFirstSet(_) => {
            // Depends too much on type width and Rust semantics, leave this one out of const eval
            None
        }
    }
}

fn try_const_eval_operator(op: &mut Operator, out_ty: Option<Type>) -> Option<ConstantValue> {
    match op {
        Operator::And(op) => const_eval_bool!(&&op.lhs, op.rhs),
        Operator::Or(op) => const_eval_bool!(|| op.lhs, op.rhs),
        Operator::Not(op) => {
            use ConstantValue::*;
            op.input.as_const().map(|input| match input {
                Bool(input) => ConstantValue::Bool(!input),
                _ => unreachable!(),
            })
        }
        Operator::Cast(op) => op.input.as_const().map(|val| val.cast_to(out_ty.unwrap())),
        Operator::Index(_)
        | Operator::CopyMemory(_)
        | Operator::CopyMemoryBulk(_)
        | Operator::UncheckedIndex(_)
        | Operator::IndexAssign(_)
        | Operator::InitVector(_)
        | Operator::UncheckedIndexAssign(_)
        | Operator::Reinterpret(_)
        | Operator::Select(_) => None,
    }
}