chipi-core 0.9.1

Core library for chipi: parser, IR, and code generation backends for instruction decoder generation
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
//! Decision tree construction for optimal instruction dispatch.
//!
//! Builds a compact decision tree that efficiently dispatches on bit patterns
//! to select the correct instruction. The tree minimizes the maximum partition
//! size and balances splits to create an efficient decoder.

use std::collections::BTreeMap;

use crate::types::*;

/// A node in the dispatch/decision tree.
#[derive(Debug, Clone)]
pub enum DecodeNode {
    /// Branch on a range of bits, with arms for each value
    Branch {
        range: BitRange,
        arms: BTreeMap<u64, DecodeNode>,
        default: Box<DecodeNode>,
    },
    /// Leaf: matched this instruction
    Leaf { instruction_index: usize },
    /// Multiple candidates to try in priority order (most specific to least specific)
    /// Used when patterns overlap and can't be distinguished by bit splits alone
    PriorityLeaves { candidates: Vec<usize> },
    /// No instruction matches
    Fail,
}

/// Build an optimal dispatch tree from validated instructions.
///
/// The tree is constructed recursively, choosing bit ranges that best
/// partition the instruction candidates at each level.
pub fn build_tree(def: &ValidatedDef) -> DecodeNode {
    let candidates: Vec<usize> = (0..def.instructions.len()).collect();
    build_node(&def.instructions, &candidates, def.config.width)
}

fn build_node(
    instructions: &[ValidatedInstruction],
    candidates: &[usize],
    width: u32,
) -> DecodeNode {
    match candidates.len() {
        0 => DecodeNode::Fail,
        1 => DecodeNode::Leaf {
            instruction_index: candidates[0],
        },
        _ => {
            // Find the best bit range to split on
            let groups = find_useful_bit_groups(instructions, candidates, width);

            if groups.is_empty() {
                // No bits can distinguish candidates.
                // Separate specific patterns from wildcards and preserve both.
                let (specifics, wildcards) =
                    separate_specific_and_wildcards(instructions, candidates, width);

                if !specifics.is_empty() && !wildcards.is_empty() {
                    // Both specific and wildcard patterns exist
                    // Return a PriorityLeaves node with specifics first, then wildcards
                    let mut priority_order = specifics;
                    priority_order.extend(wildcards);
                    return DecodeNode::PriorityLeaves {
                        candidates: priority_order,
                    };
                } else if !specifics.is_empty() {
                    // Only specific patterns
                    if specifics.len() == 1 {
                        return DecodeNode::Leaf {
                            instruction_index: specifics[0],
                        };
                    } else {
                        return DecodeNode::PriorityLeaves {
                            candidates: specifics,
                        };
                    }
                } else {
                    // Only wildcards
                    if wildcards.len() == 1 {
                        return DecodeNode::Leaf {
                            instruction_index: wildcards[0],
                        };
                    } else {
                        return DecodeNode::PriorityLeaves {
                            candidates: wildcards,
                        };
                    }
                }
            }

            // Try all candidate ranges and pick the best
            let mut best_range: Option<BitRange> = None;
            let mut best_score: Option<(usize, usize, u32)> = None;

            for group in &groups {
                let ranges_to_try = generate_sub_ranges(group);
                for range in ranges_to_try {
                    let partitions = partition_by_range(instructions, candidates, range);

                    // Count effective partitions (values that actually split)
                    let num_values = partitions.len();
                    if num_values <= 1 {
                        continue;
                    }

                    let max_part = partitions.values().map(|v| v.len()).max().unwrap_or(0);

                    // If this split doesn't actually reduce any partition, skip
                    if max_part >= candidates.len() {
                        continue;
                    }

                    // Score: (max_partition, inv_num_partitions, inv_width) - lower is better
                    let score = (max_part, usize::MAX - num_values, u32::MAX - range.width());

                    let is_better = match &best_score {
                        None => true,
                        Some(prev) => score < *prev,
                    };

                    if is_better {
                        best_score = Some(score);
                        best_range = Some(range);
                    }
                }
            }

            let range = match best_range {
                Some(r) => r,
                None => {
                    // Can't split further, separate specifics from wildcards
                    let (specifics, wildcards) =
                        separate_specific_and_wildcards(instructions, candidates, width);

                    if !specifics.is_empty() && !wildcards.is_empty() {
                        let mut priority_order = specifics;
                        priority_order.extend(wildcards);
                        return DecodeNode::PriorityLeaves {
                            candidates: priority_order,
                        };
                    } else if !specifics.is_empty() {
                        if specifics.len() == 1 {
                            return DecodeNode::Leaf {
                                instruction_index: specifics[0],
                            };
                        } else {
                            return DecodeNode::PriorityLeaves {
                                candidates: specifics,
                            };
                        }
                    } else {
                        if wildcards.len() == 1 {
                            return DecodeNode::Leaf {
                                instruction_index: wildcards[0],
                            };
                        } else {
                            return DecodeNode::PriorityLeaves {
                                candidates: wildcards,
                            };
                        }
                    }
                }
            };

            let partitions = partition_by_range(instructions, candidates, range);

            // Collect wildcards: candidates that don't have all fixed bits in range
            let wildcards: Vec<usize> = candidates
                .iter()
                .copied()
                .filter(|&idx| !has_all_fixed_at(&instructions[idx], range))
                .collect();

            let mut arms = BTreeMap::new();
            for (value, sub_candidates) in partitions {
                // Guard: if partition didn't reduce candidate count, avoid infinite recursion
                if sub_candidates.len() >= candidates.len() {
                    // No progress, separate specifics from wildcards
                    let (specifics, wildcards) =
                        separate_specific_and_wildcards(instructions, &sub_candidates, width);

                    if !specifics.is_empty() && !wildcards.is_empty() {
                        let mut priority_order = specifics;
                        priority_order.extend(wildcards);
                        arms.insert(
                            value,
                            DecodeNode::PriorityLeaves {
                                candidates: priority_order,
                            },
                        );
                    } else if !specifics.is_empty() {
                        if specifics.len() == 1 {
                            arms.insert(
                                value,
                                DecodeNode::Leaf {
                                    instruction_index: specifics[0],
                                },
                            );
                        } else {
                            arms.insert(
                                value,
                                DecodeNode::PriorityLeaves {
                                    candidates: specifics,
                                },
                            );
                        }
                    } else {
                        if wildcards.len() == 1 {
                            arms.insert(
                                value,
                                DecodeNode::Leaf {
                                    instruction_index: wildcards[0],
                                },
                            );
                        } else {
                            arms.insert(
                                value,
                                DecodeNode::PriorityLeaves {
                                    candidates: wildcards,
                                },
                            );
                        }
                    }
                } else {
                    let child = build_node(instructions, &sub_candidates, width);
                    arms.insert(value, child);
                }
            }

            // Default arm for values not explicitly matched
            let default = if wildcards.is_empty() {
                Box::new(DecodeNode::Fail)
            } else {
                Box::new(build_node(instructions, &wildcards, width))
            };

            DecodeNode::Branch {
                range,
                arms,
                default,
            }
        }
    }
}

/// Check if an instruction has fixed bits at ALL positions in a range.
fn has_all_fixed_at(instr: &ValidatedInstruction, range: BitRange) -> bool {
    range.bits().all(|bit| instr.fixed_bit_at(bit).is_some())
}

/// Find contiguous bit groups useful for splitting.
/// A bit position is useful if at least 2 candidates have variation at that position.
fn find_useful_bit_groups(
    instructions: &[ValidatedInstruction],
    candidates: &[usize],
    width: u32,
) -> Vec<BitRange> {
    let mut useful = vec![false; width as usize];

    for bit in 0..width {
        // Collect fixed values at this bit (skip candidates without fixed bits here)
        let fixed_values: Vec<Bit> = candidates
            .iter()
            .filter_map(|&idx| instructions[idx].fixed_bit_at(bit))
            .collect();

        // Need at least 2 fixed values with variation
        if fixed_values.len() >= 2 {
            let has_variation = fixed_values.iter().any(|&v| v != fixed_values[0]);
            useful[bit as usize] = has_variation;
        }
    }

    // Group contiguous useful bits into ranges
    let mut groups = Vec::new();
    let mut i = 0u32;
    while i < width {
        if useful[i as usize] {
            let start = i;
            while i < width && useful[i as usize] {
                i += 1;
            }
            let end = i - 1;
            // BitRange: start is MSB, end is LSB. Iteration goes from LSB to MSB.
            groups.push(BitRange::new(end, start));
        } else {
            i += 1;
        }
    }

    groups
}

/// Generate sub-ranges from a full range for finer-grained splitting.
fn generate_sub_ranges(range: &BitRange) -> Vec<BitRange> {
    let mut ranges = vec![*range];

    let w = range.width();
    if w > 1 {
        if w <= 10 {
            for sub_width in (1..w).rev() {
                for start_offset in 0..=(w - sub_width) {
                    let sub_start = range.start.saturating_sub(start_offset);
                    let sub_end_needed = sub_start + 1 - sub_width;
                    if sub_end_needed >= range.end && sub_start >= sub_end_needed {
                        let sub = BitRange::new(sub_start, sub_end_needed);
                        if sub != *range && !ranges.contains(&sub) {
                            ranges.push(sub);
                        }
                    }
                }
            }
        } else {
            let mid = range.end + w / 2;
            ranges.push(BitRange::new(range.start, mid));
            if mid > range.end {
                ranges.push(BitRange::new(mid - 1, range.end));
            }

            for chunk_size in [4u32, 6, 8] {
                if chunk_size < w {
                    if range.start >= chunk_size - 1 {
                        let sub = BitRange::new(range.start, range.start - chunk_size + 1);
                        if !ranges.contains(&sub) {
                            ranges.push(sub);
                        }
                    }
                    let sub = BitRange::new(range.end + chunk_size - 1, range.end);
                    if !ranges.contains(&sub) {
                        ranges.push(sub);
                    }
                }
            }
        }
    }

    ranges
}

/// Partition candidates by fixed bit values at a given range.
/// Instructions with all fixed bits at the range go in their specific bucket.
/// Instructions with any non-fixed bits (wildcards) go in every bucket.
fn partition_by_range(
    instructions: &[ValidatedInstruction],
    candidates: &[usize],
    range: BitRange,
) -> BTreeMap<u64, Vec<usize>> {
    let mut fixed_map: BTreeMap<u64, Vec<usize>> = BTreeMap::new();
    let mut wildcards: Vec<usize> = Vec::new();

    for &idx in candidates {
        if has_all_fixed_at(&instructions[idx], range) {
            let value = extract_fixed_value(&instructions[idx], range);
            fixed_map.entry(value).or_default().push(idx);
        } else {
            wildcards.push(idx);
        }
    }

    // Add wildcards to every partition
    if !wildcards.is_empty() {
        for bucket in fixed_map.values_mut() {
            bucket.extend_from_slice(&wildcards);
        }
    }

    fixed_map
}

/// Extract the fixed bit value of an instruction at a given range.
fn extract_fixed_value(instr: &ValidatedInstruction, range: BitRange) -> u64 {
    let mut value: u64 = 0;
    for bit_pos in range.bits() {
        value <<= 1;
        if let Some(Bit::One) = instr.fixed_bit_at(bit_pos) {
            value |= 1;
        }
    }
    value
}

/// Separate candidates into specific (all bits fixed in unit 0) vs wildcards (some don't-care bits).
/// Returns (specific_candidates, wildcard_candidates).
/// Specific candidates are ordered by number of fixed bits (most specific first).
fn separate_specific_and_wildcards(
    instructions: &[ValidatedInstruction],
    candidates: &[usize],
    width: u32,
) -> (Vec<usize>, Vec<usize>) {
    let mut specifics = Vec::new();
    let mut wildcards = Vec::new();

    for &idx in candidates {
        // Check if this instruction has a fixed bit at EVERY position in unit 0
        let all_fixed = (0..width).all(|bit| instructions[idx].fixed_bit_at(bit).is_some());

        if all_fixed {
            specifics.push(idx);
        } else {
            wildcards.push(idx);
        }
    }

    // Sort specifics by number of fixed bits across ALL units (most to least)
    specifics.sort_by_key(|&idx| std::cmp::Reverse(instructions[idx].fixed_bits().len()));

    // Sort wildcards by number of fixed bits too (for consistent prioritization)
    wildcards.sort_by_key(|&idx| std::cmp::Reverse(instructions[idx].fixed_bits().len()));

    (specifics, wildcards)
}