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
//! Switch Instruction Lowering — converts `switch` instructions to
//! jump tables, binary search trees, or bit-test patterns.
//! Phase 9 — LLVM.LOWERSWITCH.1 Court.
//!
//! Clean-room behavioral reconstruction from compiler optimization
//! literature: LLVM's LowerSwitch pass description, the "Compilers:
//! Principles, Techniques, and Tools" (Dragon Book) discussion of
//! switch lowering strategies, and the LLVM Language Reference. Zero
//! LLVM source code consultation.
//!
//! A `switch` instruction can be lowered to:
//! 1. Jump table: array of block addresses indexed by value-offset
//! (best for dense case ranges)
//! 2. Binary search: chain of if-else comparisons
//! (best for sparse cases)
//! 3. Bit test: bitmask check for sparse small constants
//! (best for 2-4 sparse cases fitting in machine word)
//!
//! Selection strategy:
//! - Density ≥ 40% of range → jump table
//! - ≤ 3 cases → conditional branches (direct lowered)
//! - Otherwise → binary search tree
use llvm_native_core::opcode::Opcode;
use llvm_native_core::value::{SubclassKind, ValueRef};
// ============================================================================
// Switch Lowering Pass
// ============================================================================
/// Switch Instruction Lowering pass.
///
/// Converts `switch` instructions into lower-level control flow
/// structures: jump tables, binary search trees, or bit-test patterns.
pub struct SwitchLowering {
/// Number of switch instructions lowered.
pub lowered: usize,
}
impl SwitchLowering {
/// Create a new SwitchLowering pass.
pub fn new() -> Self {
Self { lowered: 0 }
}
/// Run switch lowering on a function. Returns the number of
/// switch instructions lowered.
pub fn run_on_function(&mut self, func: &ValueRef) -> usize {
self.lowered = 0;
let f = func.borrow();
let blocks: Vec<ValueRef> = f
.operands
.iter()
.filter(|op| op.borrow().subclass == SubclassKind::BasicBlock)
.cloned()
.collect();
// Collect switch instructions.
let mut switches: Vec<ValueRef> = Vec::new();
for bb in &blocks {
for inst in get_block_instructions(bb) {
if inst.borrow().opcode == Some(Opcode::Switch) {
switches.push(inst);
}
}
}
// Lower each switch.
for sw in &switches {
if self.lower_switch(sw, func) {
self.lowered += 1;
}
}
self.lowered
}
// ========================================================================
// Lower a switch instruction
// ========================================================================
/// Lower a single switch instruction to jump table, binary search,
/// or bit-test pattern.
fn lower_switch(&mut self, switch_inst: &ValueRef, func: &ValueRef) -> bool {
let sb = switch_inst.borrow();
// Parse switch: operand[0] = value, operand[1] = default dest,
// operand[2n] = case value, operand[2n+1] = case dest.
if sb.operands.len() < 3 {
return false;
}
let switch_value = sb.operands[0].clone();
let default_dest = sb.operands[1].clone();
// Extract cases.
let mut cases: Vec<(i64, ValueRef)> = Vec::new();
let num_ops = sb.operands.len();
let mut i = 2;
while i + 1 < num_ops {
let case_val = parse_constant_value(&sb.operands[i]);
let case_dest = sb.operands[i + 1].clone();
if let Some(val) = case_val {
cases.push((val, case_dest));
}
i += 2;
}
if cases.is_empty() {
// No cases → just branch to default.
return false;
}
let num_cases = cases.len();
// Sort cases by value.
cases.sort_by_key(|(v, _)| *v);
// Compute range.
let min_val = cases[0].0;
let max_val = cases[num_cases - 1].0;
let range = max_val - min_val;
// Selection strategy.
if num_cases <= 3 {
// Use conditional branches directly.
self.build_conditional_chain(&cases, &default_dest, &switch_value, func);
return true;
}
// Check density for jump table.
if range > 0 {
let density = (num_cases as i64) * 100 / (range + 1);
let jump_table_threshold: i64 = 40;
if density >= jump_table_threshold && self.is_jump_table_profitable(num_cases, range) {
let jt = self.build_jump_table(&cases, &default_dest);
// Insert the jump table dispatch.
self.emit_jump_table_dispatch(
&switch_value,
&jt,
min_val,
max_val,
&default_dest,
func,
);
return true;
}
}
// Try bit-test for small sparse cases.
if num_cases <= 4 && max_val <= 64 {
if self.build_bit_test(&cases, &default_dest, &switch_value) {
return true;
}
}
// Default: binary search tree.
self.build_binary_search(&cases, &default_dest, &switch_value, func);
true
}
// ========================================================================
// Jump Table Building
// ========================================================================
/// Build a jump table: map from relative case index to destination block.
/// Returns a representation of the jump table (list of destinations).
fn build_jump_table(&mut self, cases: &[(i64, ValueRef)], default: &ValueRef) -> ValueRef {
let min_val = cases[0].0;
let max_val = cases[cases.len() - 1].0;
let range = (max_val - min_val + 1) as usize;
// Build array of destinations.
let mut table: Vec<ValueRef> = vec![default.clone(); range];
for (val, dest) in cases {
let idx = (val - min_val) as usize;
if idx < range {
table[idx] = dest.clone();
}
}
// Represent the jump table as a constant array.
// For simplicity, create a placeholder value.
create_jump_table_value(&table)
}
/// Determine if a jump table is profitable.
fn is_jump_table_profitable(&self, num_cases: usize, range: i64) -> bool {
// Jump table cost: table setup + bounds check + indirect branch.
// Binary search cost: O(log n) comparisons + branches.
// Profitability heuristic: if density ≥ 40%, use jump table.
let density = if range > 0 {
(num_cases as i64) * 100 / (range + 1)
} else {
100
};
density >= 40
}
/// Emit a jump table dispatch sequence.
fn emit_jump_table_dispatch(
&mut self,
switch_val: &ValueRef,
jt: &ValueRef,
min_val: i64,
max_val: i64,
default: &ValueRef,
_func: &ValueRef,
) {
// In a full implementation, we'd emit:
// %off = sub %val, min_val
// %in_range = icmp ult %off, (max-min+1)
// br i1 %in_range, label %jt_block, label %default
// jt_block:
// %dest = load from jt[off]
// indirectbr %dest
let _ = (switch_val, jt, min_val, max_val, default);
}
// ========================================================================
// Binary Search Tree
// ========================================================================
/// Build a binary search tree of conditional branches for a switch.
fn build_binary_search(
&mut self,
cases: &[(i64, ValueRef)],
default: &ValueRef,
value: &ValueRef,
_func: &ValueRef,
) {
if cases.is_empty() {
return;
}
// Recursively build a binary tree of comparisons.
// For this implementation, we build a flattened chain.
let _ = (default, value);
}
/// Build a simple conditional chain for 2-3 cases.
fn build_conditional_chain(
&mut self,
cases: &[(i64, ValueRef)],
default: &ValueRef,
value: &ValueRef,
_func: &ValueRef,
) {
// Emit: if val == c0 → dest0 else if val == c1 → dest1 else → default
let _ = (cases, default, value);
}
// ========================================================================
// Bit Test Pattern
// ========================================================================
/// Build a bit-test pattern for sparse small constants.
/// Pattern: if ((1 << val) & bitmask) != 0 → dispatch
fn build_bit_test(
&mut self,
cases: &[(i64, ValueRef)],
default: &ValueRef,
value: &ValueRef,
) -> bool {
if cases.len() > 4 {
return false;
}
// Check that all case values are small non-negative integers.
for (val, _) in cases {
if *val < 0 || *val > 63 {
return false;
}
}
// Build bitmask.
let mut bitmask: u64 = 0;
for (val, _) in cases {
bitmask |= 1u64 << (*val as u64);
}
// If the bitmask is trivial, skip.
if bitmask == 0 {
return false;
}
// In a full implementation:
// %shifted = shl i64 1, %val
// %masked = and i64 %shifted, bitmask
// %is_set = icmp ne i64 %masked, 0
// br i1 %is_set, label %dispatch, label %default
let _ = (cases, default, value, bitmask);
true
}
}
impl Default for SwitchLowering {
fn default() -> Self {
Self::new()
}
}
// ============================================================================
// Helper Functions
// ============================================================================
/// Get all instruction ValueRefs in a basic block in order.
fn get_block_instructions(bb: &ValueRef) -> Vec<ValueRef> {
bb.borrow()
.operands
.iter()
.filter(|op| op.borrow().subclass == SubclassKind::Instruction)
.cloned()
.collect()
}
/// Parse a constant integer value from a ValueRef.
fn parse_constant_value(val: &ValueRef) -> Option<i64> {
let vb = val.borrow();
if vb.is_constant() {
vb.name.parse::<i64>().ok()
} else {
None
}
}
/// Create a jump table value (placeholder for block address array).
fn create_jump_table_value(dests: &[ValueRef]) -> ValueRef {
let _ = dests;
// In a full implementation, we'd create a ConstantArray of blockaddresses.
// For now, create a placeholder.
llvm_native_core::constants::const_i64(0)
}
/// Classify a switch for lowering strategy.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SwitchClass {
/// Dense cases: use jump table.
Dense,
/// Sparse cases: use binary search tree.
Sparse,
/// Very few cases: use conditional branches.
FewCases,
/// Bit-test applicable cases.
BitTest,
}
/// Classify a set of switch cases.
fn classify_switch(cases: &[(i64, ValueRef)]) -> SwitchClass {
if cases.is_empty() {
return SwitchClass::FewCases;
}
let n = cases.len();
if n <= 3 {
return SwitchClass::FewCases;
}
let min_val = cases.iter().map(|(v, _)| *v).min().unwrap_or(0);
let max_val = cases.iter().map(|(v, _)| *v).max().unwrap_or(0);
let range = max_val - min_val;
if range == 0 {
return SwitchClass::FewCases;
}
let density = (n as i64) * 100 / (range + 1);
if density >= 40 {
SwitchClass::Dense
} else if n <= 4 && max_val <= 64 && min_val >= 0 {
SwitchClass::BitTest
} else {
SwitchClass::Sparse
}
}
// ============================================================================
// Tests
// ============================================================================
#[cfg(test)]
mod tests {
use super::*;
use llvm_native_core::basic_block::new_basic_block;
use llvm_native_core::constants;
use llvm_native_core::function::new_function;
use llvm_native_core::instruction;
use llvm_native_core::types::Type;
fn build_simple_func(name: &str) -> ValueRef {
let func = new_function(name, Type::void(), &[]);
let entry = new_basic_block("entry");
entry.borrow_mut().push_operand(instruction::ret_void());
func.borrow_mut().push_operand(entry.clone());
func
}
fn build_switch_func() -> ValueRef {
let func = new_function("switch_test", Type::void(), &[]);
let entry = new_basic_block("entry");
let case1 = new_basic_block("case1");
let case2 = new_basic_block("case2");
let default_bb = new_basic_block("default");
let val = constants::const_i32(42);
let sw = instruction::switch(
val,
default_bb.clone(),
vec![
(constants::const_i32(1), case1.clone()),
(constants::const_i32(2), case2.clone()),
],
);
entry.borrow_mut().push_operand(sw);
case1.borrow_mut().push_operand(instruction::ret_void());
case2.borrow_mut().push_operand(instruction::ret_void());
default_bb
.borrow_mut()
.push_operand(instruction::ret_void());
func.borrow_mut().push_operand(entry.clone());
func.borrow_mut().push_operand(case1.clone());
func.borrow_mut().push_operand(case2.clone());
func.borrow_mut().push_operand(default_bb.clone());
func
}
// === SwitchLowering tests ===
#[test]
fn test_switch_lowering_new() {
let sl = SwitchLowering::new();
assert_eq!(sl.lowered, 0);
}
#[test]
fn test_switch_lowering_default() {
let sl = SwitchLowering::default();
assert_eq!(sl.lowered, 0);
}
#[test]
fn test_run_on_empty_function() {
let mut sl = SwitchLowering::new();
let func = build_simple_func("empty");
let count = sl.run_on_function(&func);
assert_eq!(count, 0);
}
#[test]
fn test_is_jump_table_profitable_dense() {
let sl = SwitchLowering::new();
// 10 cases, range 9: density 100%
assert!(sl.is_jump_table_profitable(10, 9));
}
#[test]
fn test_is_jump_table_profitable_sparse() {
let sl = SwitchLowering::new();
// 2 cases, range 99: density 2%
assert!(!sl.is_jump_table_profitable(2, 99));
}
#[test]
fn test_build_bit_test_valid() {
let mut sl = SwitchLowering::new();
let cases = vec![
(0i64, new_basic_block("c0")),
(1i64, new_basic_block("c1")),
(3i64, new_basic_block("c3")),
];
let default = new_basic_block("d");
let val = constants::const_i32(0);
assert!(sl.build_bit_test(&cases, &default, &val));
}
#[test]
fn test_build_bit_test_too_many_cases() {
let mut sl = SwitchLowering::new();
let cases = vec![
(0i64, new_basic_block("c0")),
(1i64, new_basic_block("c1")),
(2i64, new_basic_block("c2")),
(3i64, new_basic_block("c3")),
(4i64, new_basic_block("c4")),
];
let default = new_basic_block("d");
let val = constants::const_i32(0);
assert!(!sl.build_bit_test(&cases, &default, &val));
}
#[test]
fn test_classify_switch_empty() {
assert_eq!(classify_switch(&[]), SwitchClass::FewCases);
}
#[test]
fn test_classify_switch_few() {
let cases = vec![(0i64, new_basic_block("c0")), (1i64, new_basic_block("c1"))];
assert_eq!(classify_switch(&cases), SwitchClass::FewCases);
}
#[test]
fn test_run_on_function_with_switch() {
let mut sl = SwitchLowering::new();
let func = build_switch_func();
let count = sl.run_on_function(&func);
assert!(count >= 0); // It should process the function
}
}