Skip to main content

kasl_ir/function/
block_sort.rs

1//
2//  Copyright 2025-2026 Shuntaro Kasatani
3//
4//  Licensed under the Apache License, Version 2.0 (the "License");
5//  you may not use this file except in compliance with the License.
6//  You may obtain a copy of the License at
7//
8//      http://www.apache.org/licenses/LICENSE-2.0
9//
10//  Unless required by applicable law or agreed to in writing, software
11//  distributed under the License is distributed on an "AS IS" BASIS,
12//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13//  See the License for the specific language governing permissions and
14//  limitations under the License.
15//
16
17use crate::{Block, Function};
18use std::collections::HashSet;
19
20impl Function {
21    pub fn sorted_blocks(&self) -> Vec<Block> {
22        let mut visited: HashSet<Block> = HashSet::new();
23        let mut post_order: Vec<Block> = Vec::new();
24
25        // Sort the blocks using depth first search
26        if let Some(entry) = self.entry_block() {
27            self.dfs(entry, &mut visited, &mut post_order);
28        }
29
30        post_order.into_iter().rev().collect()
31    }
32
33    fn dfs(&self, block: Block, visited: &mut HashSet<Block>, post_order: &mut Vec<Block>) {
34        visited.insert(block);
35
36        if let Some(block_data) = self.get_block(&block) {
37            // Get the next block from the last instruction
38            for next_block in block_data.get_successors() {
39                if !visited.contains(&next_block) {
40                    self.dfs(next_block, visited, post_order);
41                }
42            }
43        }
44
45        post_order.push(block);
46    }
47}