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
use super::HashMap;
use crate::frontend::FunctionBuilder;
use alloc::vec::Vec;
use core::convert::TryFrom;
use cranelift_codegen::ir::condcodes::IntCC;
use cranelift_codegen::ir::*;

type EntryIndex = u128;

/// Unlike with `br_table`, `Switch` cases may be sparse or non-0-based.
/// They emit efficient code using branches, jump tables, or a combination of both.
///
/// # Example
///
/// ```rust
/// # use cranelift_codegen::ir::types::*;
/// # use cranelift_codegen::ir::{UserFuncName, Function, Signature, InstBuilder};
/// # use cranelift_codegen::isa::CallConv;
/// # use cranelift_frontend::{FunctionBuilder, FunctionBuilderContext, Switch};
/// #
/// # let mut sig = Signature::new(CallConv::SystemV);
/// # let mut fn_builder_ctx = FunctionBuilderContext::new();
/// # let mut func = Function::with_name_signature(UserFuncName::user(0, 0), sig);
/// # let mut builder = FunctionBuilder::new(&mut func, &mut fn_builder_ctx);
/// #
/// # let entry = builder.create_block();
/// # builder.switch_to_block(entry);
/// #
/// let block0 = builder.create_block();
/// let block1 = builder.create_block();
/// let block2 = builder.create_block();
/// let fallback = builder.create_block();
///
/// let val = builder.ins().iconst(I32, 1);
///
/// let mut switch = Switch::new();
/// switch.set_entry(0, block0);
/// switch.set_entry(1, block1);
/// switch.set_entry(7, block2);
/// switch.emit(&mut builder, val, fallback);
/// ```
#[derive(Debug, Default)]
pub struct Switch {
    cases: HashMap<EntryIndex, Block>,
}

impl Switch {
    /// Create a new empty switch
    pub fn new() -> Self {
        Self {
            cases: HashMap::new(),
        }
    }

    /// Set a switch entry
    pub fn set_entry(&mut self, index: EntryIndex, block: Block) {
        let prev = self.cases.insert(index, block);
        assert!(
            prev.is_none(),
            "Tried to set the same entry {} twice",
            index
        );
    }

    /// Get a reference to all existing entries
    pub fn entries(&self) -> &HashMap<EntryIndex, Block> {
        &self.cases
    }

    /// Turn the `cases` `HashMap` into a list of `ContiguousCaseRange`s.
    ///
    /// # Postconditions
    ///
    /// * Every entry will be represented.
    /// * The `ContiguousCaseRange`s will not overlap.
    /// * Between two `ContiguousCaseRange`s there will be at least one entry index.
    /// * No `ContiguousCaseRange`s will be empty.
    fn collect_contiguous_case_ranges(self) -> Vec<ContiguousCaseRange> {
        log::trace!("build_contiguous_case_ranges before: {:#?}", self.cases);
        let mut cases = self.cases.into_iter().collect::<Vec<(_, _)>>();
        cases.sort_by_key(|&(index, _)| index);

        let mut contiguous_case_ranges: Vec<ContiguousCaseRange> = vec![];
        let mut last_index = None;
        for (index, block) in cases {
            match last_index {
                None => contiguous_case_ranges.push(ContiguousCaseRange::new(index)),
                Some(last_index) => {
                    if index > last_index + 1 {
                        contiguous_case_ranges.push(ContiguousCaseRange::new(index));
                    }
                }
            }
            contiguous_case_ranges
                .last_mut()
                .unwrap()
                .blocks
                .push(block);
            last_index = Some(index);
        }

        log::trace!(
            "build_contiguous_case_ranges after: {:#?}",
            contiguous_case_ranges
        );

        contiguous_case_ranges
    }

    /// Binary search for the right `ContiguousCaseRange`.
    fn build_search_tree<'a>(
        bx: &mut FunctionBuilder,
        val: Value,
        otherwise: Block,
        contiguous_case_ranges: &'a [ContiguousCaseRange],
    ) {
        // If no switch cases were added to begin with, we can just emit `jump otherwise`.
        if contiguous_case_ranges.is_empty() {
            bx.ins().jump(otherwise, &[]);
            return;
        }

        // Avoid allocation in the common case
        if contiguous_case_ranges.len() <= 3 {
            Self::build_search_branches(bx, val, otherwise, contiguous_case_ranges);
            return;
        }

        let mut stack = Vec::new();
        stack.push((None, contiguous_case_ranges));

        while let Some((block, contiguous_case_ranges)) = stack.pop() {
            if let Some(block) = block {
                bx.switch_to_block(block);
            }

            if contiguous_case_ranges.len() <= 3 {
                Self::build_search_branches(bx, val, otherwise, contiguous_case_ranges);
            } else {
                let split_point = contiguous_case_ranges.len() / 2;
                let (left, right) = contiguous_case_ranges.split_at(split_point);

                let left_block = bx.create_block();
                let right_block = bx.create_block();

                let first_index = right[0].first_index;
                let should_take_right_side =
                    icmp_imm_u128(bx, IntCC::UnsignedGreaterThanOrEqual, val, first_index);
                bx.ins()
                    .brif(should_take_right_side, right_block, &[], left_block, &[]);

                bx.seal_block(left_block);
                bx.seal_block(right_block);

                stack.push((Some(left_block), left));
                stack.push((Some(right_block), right));
            }
        }
    }

    /// Linear search for the right `ContiguousCaseRange`.
    fn build_search_branches<'a>(
        bx: &mut FunctionBuilder,
        val: Value,
        otherwise: Block,
        contiguous_case_ranges: &'a [ContiguousCaseRange],
    ) {
        for (ix, range) in contiguous_case_ranges.iter().enumerate().rev() {
            let alternate = if ix == 0 {
                otherwise
            } else {
                bx.create_block()
            };

            if range.first_index == 0 {
                assert_eq!(alternate, otherwise);

                if let Some(block) = range.single_block() {
                    bx.ins().brif(val, otherwise, &[], block, &[]);
                } else {
                    Self::build_jump_table(bx, val, otherwise, 0, &range.blocks);
                }
            } else {
                if let Some(block) = range.single_block() {
                    let is_good_val = icmp_imm_u128(bx, IntCC::Equal, val, range.first_index);
                    bx.ins().brif(is_good_val, block, &[], alternate, &[]);
                } else {
                    let is_good_val = icmp_imm_u128(
                        bx,
                        IntCC::UnsignedGreaterThanOrEqual,
                        val,
                        range.first_index,
                    );
                    let jt_block = bx.create_block();
                    bx.ins().brif(is_good_val, jt_block, &[], alternate, &[]);
                    bx.seal_block(jt_block);
                    bx.switch_to_block(jt_block);
                    Self::build_jump_table(bx, val, otherwise, range.first_index, &range.blocks);
                }
            }

            if alternate != otherwise {
                bx.seal_block(alternate);
                bx.switch_to_block(alternate);
            }
        }
    }

    fn build_jump_table(
        bx: &mut FunctionBuilder,
        val: Value,
        otherwise: Block,
        first_index: EntryIndex,
        blocks: &[Block],
    ) {
        // There are currently no 128bit systems supported by rustc, but once we do ensure that
        // we don't silently ignore a part of the jump table for 128bit integers on 128bit systems.
        assert!(
            u32::try_from(blocks.len()).is_ok(),
            "Jump tables bigger than 2^32-1 are not yet supported"
        );

        let jt_data = JumpTableData::new(
            bx.func.dfg.block_call(otherwise, &[]),
            &blocks
                .iter()
                .map(|block| bx.func.dfg.block_call(*block, &[]))
                .collect::<Vec<_>>(),
        );
        let jump_table = bx.create_jump_table(jt_data);

        let discr = if first_index == 0 {
            val
        } else {
            if let Ok(first_index) = u64::try_from(first_index) {
                bx.ins().iadd_imm(val, (first_index as i64).wrapping_neg())
            } else {
                let (lsb, msb) = (first_index as u64, (first_index >> 64) as u64);
                let lsb = bx.ins().iconst(types::I64, lsb as i64);
                let msb = bx.ins().iconst(types::I64, msb as i64);
                let index = bx.ins().iconcat(lsb, msb);
                bx.ins().isub(val, index)
            }
        };

        let discr = match bx.func.dfg.value_type(discr).bits() {
            bits if bits > 32 => {
                // Check for overflow of cast to u32. This is the max supported jump table entries.
                let new_block = bx.create_block();
                let bigger_than_u32 =
                    bx.ins()
                        .icmp_imm(IntCC::UnsignedGreaterThan, discr, u32::MAX as i64);
                bx.ins()
                    .brif(bigger_than_u32, otherwise, &[], new_block, &[]);
                bx.seal_block(new_block);
                bx.switch_to_block(new_block);

                // Cast to i32, as br_table is not implemented for i64/i128
                bx.ins().ireduce(types::I32, discr)
            }
            bits if bits < 32 => bx.ins().uextend(types::I32, discr),
            _ => discr,
        };

        bx.ins().br_table(discr, jump_table);
    }

    /// Build the switch
    ///
    /// # Arguments
    ///
    /// * The function builder to emit to
    /// * The value to switch on
    /// * The default block
    pub fn emit(self, bx: &mut FunctionBuilder, val: Value, otherwise: Block) {
        // Validate that the type of `val` is sufficiently wide to address all cases.
        let max = self.cases.keys().max().copied().unwrap_or(0);
        let val_ty = bx.func.dfg.value_type(val);
        let val_ty_max = val_ty.bounds(false).1;
        if max > val_ty_max {
            panic!(
                "The index type {} does not fit the maximum switch entry of {}",
                val_ty, max
            );
        }

        let contiguous_case_ranges = self.collect_contiguous_case_ranges();
        Self::build_search_tree(bx, val, otherwise, &contiguous_case_ranges);
    }
}

fn icmp_imm_u128(bx: &mut FunctionBuilder, cond: IntCC, x: Value, y: u128) -> Value {
    if let Ok(index) = u64::try_from(y) {
        bx.ins().icmp_imm(cond, x, index as i64)
    } else {
        let (lsb, msb) = (y as u64, (y >> 64) as u64);
        let lsb = bx.ins().iconst(types::I64, lsb as i64);
        let msb = bx.ins().iconst(types::I64, msb as i64);
        let index = bx.ins().iconcat(lsb, msb);
        bx.ins().icmp(cond, x, index)
    }
}

/// This represents a contiguous range of cases to switch on.
///
/// For example 10 => block1, 11 => block2, 12 => block7 will be represented as:
///
/// ```plain
/// ContiguousCaseRange {
///     first_index: 10,
///     blocks: vec![Block::from_u32(1), Block::from_u32(2), Block::from_u32(7)]
/// }
/// ```
#[derive(Debug)]
struct ContiguousCaseRange {
    /// The entry index of the first case. Eg. 10 when the entry indexes are 10, 11, 12 and 13.
    first_index: EntryIndex,

    /// The blocks to jump to sorted in ascending order of entry index.
    blocks: Vec<Block>,
}

impl ContiguousCaseRange {
    fn new(first_index: EntryIndex) -> Self {
        Self {
            first_index,
            blocks: Vec::new(),
        }
    }

    /// Returns `Some` block when there is only a single block in this range.
    fn single_block(&self) -> Option<Block> {
        if self.blocks.len() == 1 {
            Some(self.blocks[0])
        } else {
            None
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::frontend::FunctionBuilderContext;
    use alloc::string::ToString;
    use cranelift_codegen::ir::Function;

    macro_rules! setup {
        ($default:expr, [$($index:expr,)*]) => {{
            let mut func = Function::new();
            let mut func_ctx = FunctionBuilderContext::new();
            {
                let mut bx = FunctionBuilder::new(&mut func, &mut func_ctx);
                let block = bx.create_block();
                bx.switch_to_block(block);
                let val = bx.ins().iconst(types::I8, 0);
                #[allow(unused_mut)]
                let mut switch = Switch::new();
                $(
                    let block = bx.create_block();
                    switch.set_entry($index, block);
                )*
                switch.emit(&mut bx, val, Block::with_number($default).unwrap());
            }
            func
                .to_string()
                .trim_start_matches("function u0:0() fast {\n")
                .trim_end_matches("\n}\n")
                .to_string()
        }};
    }

    macro_rules! assert_eq_output {
        ($actual:ident, $expected:literal) => {
            assert_eq!(
                $actual,
                $expected,
                "\n{}",
                similar::TextDiff::from_lines($expected, &$actual)
                    .unified_diff()
                    .header("expected", "actual")
            )
        };
    }

    #[test]
    fn switch_empty() {
        let func = setup!(42, []);
        assert_eq_output!(
            func,
            "block0:
    v0 = iconst.i8 0
    jump block42"
        );
    }

    #[test]
    fn switch_zero() {
        let func = setup!(0, [0,]);
        assert_eq_output!(
            func,
            "block0:
    v0 = iconst.i8 0
    brif v0, block0, block1  ; v0 = 0"
        );
    }

    #[test]
    fn switch_single() {
        let func = setup!(0, [1,]);
        assert_eq_output!(
            func,
            "block0:
    v0 = iconst.i8 0
    v1 = icmp_imm eq v0, 1  ; v0 = 0
    brif v1, block1, block0"
        );
    }

    #[test]
    fn switch_bool() {
        let func = setup!(0, [0, 1,]);
        assert_eq_output!(
            func,
            "block0:
    v0 = iconst.i8 0
    v1 = uextend.i32 v0  ; v0 = 0
    br_table v1, block0, [block1, block2]"
        );
    }

    #[test]
    fn switch_two_gap() {
        let func = setup!(0, [0, 2,]);
        assert_eq_output!(
            func,
            "block0:
    v0 = iconst.i8 0
    v1 = icmp_imm eq v0, 2  ; v0 = 0
    brif v1, block2, block3

block3:
    brif.i8 v0, block0, block1  ; v0 = 0"
        );
    }

    #[test]
    fn switch_many() {
        let func = setup!(0, [0, 1, 5, 7, 10, 11, 12,]);
        assert_eq_output!(
            func,
            "block0:
    v0 = iconst.i8 0
    v1 = icmp_imm uge v0, 7  ; v0 = 0
    brif v1, block9, block8

block9:
    v2 = icmp_imm.i8 uge v0, 10  ; v0 = 0
    brif v2, block11, block10

block11:
    v3 = iadd_imm.i8 v0, -10  ; v0 = 0
    v4 = uextend.i32 v3
    br_table v4, block0, [block5, block6, block7]

block10:
    v5 = icmp_imm.i8 eq v0, 7  ; v0 = 0
    brif v5, block4, block0

block8:
    v6 = icmp_imm.i8 eq v0, 5  ; v0 = 0
    brif v6, block3, block12

block12:
    v7 = uextend.i32 v0  ; v0 = 0
    br_table v7, block0, [block1, block2]"
        );
    }

    #[test]
    fn switch_min_index_value() {
        let func = setup!(0, [i8::MIN as u8 as u128, 1,]);
        assert_eq_output!(
            func,
            "block0:
    v0 = iconst.i8 0
    v1 = icmp_imm eq v0, 128  ; v0 = 0
    brif v1, block1, block3

block3:
    v2 = icmp_imm.i8 eq v0, 1  ; v0 = 0
    brif v2, block2, block0"
        );
    }

    #[test]
    fn switch_max_index_value() {
        let func = setup!(0, [i8::MAX as u8 as u128, 1,]);
        assert_eq_output!(
            func,
            "block0:
    v0 = iconst.i8 0
    v1 = icmp_imm eq v0, 127  ; v0 = 0
    brif v1, block1, block3

block3:
    v2 = icmp_imm.i8 eq v0, 1  ; v0 = 0
    brif v2, block2, block0"
        )
    }

    #[test]
    fn switch_optimal_codegen() {
        let func = setup!(0, [-1i8 as u8 as u128, 0, 1,]);
        assert_eq_output!(
            func,
            "block0:
    v0 = iconst.i8 0
    v1 = icmp_imm eq v0, 255  ; v0 = 0
    brif v1, block1, block4

block4:
    v2 = uextend.i32 v0  ; v0 = 0
    br_table v2, block0, [block2, block3]"
        );
    }

    #[test]
    #[should_panic(
        expected = "The index type i8 does not fit the maximum switch entry of 4683743612477887600"
    )]
    fn switch_rejects_small_inputs() {
        // This is a regression test for a bug that we found where we would emit a cmp
        // with a type that was not able to fully represent a large index.
        //
        // See: https://github.com/bytecodealliance/wasmtime/pull/4502#issuecomment-1191961677
        setup!(1, [0x4100_0000_00bf_d470,]);
    }

    #[test]
    fn switch_seal_generated_blocks() {
        let cases = &[vec![0, 1, 2], vec![0, 1, 2, 10, 11, 12, 20, 30, 40, 50]];

        for case in cases {
            for typ in &[types::I8, types::I16, types::I32, types::I64, types::I128] {
                eprintln!("Testing {:?} with keys: {:?}", typ, case);
                do_case(case, *typ);
            }
        }

        fn do_case(keys: &[u128], typ: Type) {
            let mut func = Function::new();
            let mut builder_ctx = FunctionBuilderContext::new();
            let mut builder = FunctionBuilder::new(&mut func, &mut builder_ctx);

            let root_block = builder.create_block();
            let default_block = builder.create_block();
            let mut switch = Switch::new();

            let case_blocks = keys
                .iter()
                .map(|key| {
                    let block = builder.create_block();
                    switch.set_entry(*key, block);
                    block
                })
                .collect::<Vec<_>>();

            builder.seal_block(root_block);
            builder.switch_to_block(root_block);

            let val = builder.ins().iconst(typ, 1);
            switch.emit(&mut builder, val, default_block);

            for &block in case_blocks.iter().chain(std::iter::once(&default_block)) {
                builder.seal_block(block);
                builder.switch_to_block(block);
                builder.ins().return_(&[]);
            }

            builder.finalize(); // Will panic if some blocks are not sealed
        }
    }

    #[test]
    fn switch_64bit() {
        let mut func = Function::new();
        let mut func_ctx = FunctionBuilderContext::new();
        {
            let mut bx = FunctionBuilder::new(&mut func, &mut func_ctx);
            let block0 = bx.create_block();
            bx.switch_to_block(block0);
            let val = bx.ins().iconst(types::I64, 0);
            let mut switch = Switch::new();
            let block1 = bx.create_block();
            switch.set_entry(1, block1);
            let block2 = bx.create_block();
            switch.set_entry(0, block2);
            let block3 = bx.create_block();
            switch.emit(&mut bx, val, block3);
        }
        let func = func
            .to_string()
            .trim_start_matches("function u0:0() fast {\n")
            .trim_end_matches("\n}\n")
            .to_string();
        assert_eq_output!(
            func,
            "block0:
    v0 = iconst.i64 0
    v1 = icmp_imm ugt v0, 0xffff_ffff  ; v0 = 0
    brif v1, block3, block4

block4:
    v2 = ireduce.i32 v0  ; v0 = 0
    br_table v2, block3, [block2, block1]"
        );
    }

    #[test]
    fn switch_128bit() {
        let mut func = Function::new();
        let mut func_ctx = FunctionBuilderContext::new();
        {
            let mut bx = FunctionBuilder::new(&mut func, &mut func_ctx);
            let block0 = bx.create_block();
            bx.switch_to_block(block0);
            let val = bx.ins().iconst(types::I64, 0);
            let val = bx.ins().uextend(types::I128, val);
            let mut switch = Switch::new();
            let block1 = bx.create_block();
            switch.set_entry(1, block1);
            let block2 = bx.create_block();
            switch.set_entry(0, block2);
            let block3 = bx.create_block();
            switch.emit(&mut bx, val, block3);
        }
        let func = func
            .to_string()
            .trim_start_matches("function u0:0() fast {\n")
            .trim_end_matches("\n}\n")
            .to_string();
        assert_eq_output!(
            func,
            "block0:
    v0 = iconst.i64 0
    v1 = uextend.i128 v0  ; v0 = 0
    v2 = icmp_imm ugt v1, 0xffff_ffff
    brif v2, block3, block4

block4:
    v3 = ireduce.i32 v1
    br_table v3, block3, [block2, block1]"
        );
    }
}