control_flow.rs 8.51 KB
Newer Older
1 2
use ast::ir::*;
use ast::inst::Instruction_::*;
qinsoon's avatar
qinsoon committed
3
use common::vector_as_str;
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
use vm::context::VMContext;

use compiler::CompilerPass;

pub struct ControlFlowAnalysis {
    name: &'static str
}

impl ControlFlowAnalysis {
    pub fn new() -> ControlFlowAnalysis {
        ControlFlowAnalysis{name: "Control Flow Analysis"}
    }
}

fn check_edge_kind(target: MuTag, stack: &Vec<MuTag>) -> EdgeKind {
    if stack.contains(&target) {
        EdgeKind::Backward
    } else {
        EdgeKind::Forward
    }
}

qinsoon's avatar
qinsoon committed
26
fn new_edge(cur: MuTag, edge: BlockEdge, stack: &mut Vec<MuTag>, visited: &mut Vec<MuTag>, func: &mut MuFunction) {
27 28
    // add current block to target's predecessors
    {
qinsoon's avatar
qinsoon committed
29
        let target = func.content.as_mut().unwrap().get_block_mut(edge.target);
30 31 32
        target.control_flow.preds.push(cur);
    }
    
qinsoon's avatar
qinsoon committed
33 34
    // add target as current block's successors and start dfs
    let succ = edge.target;
35
    {
qinsoon's avatar
qinsoon committed
36
        let cur = func.content.as_mut().unwrap().get_block_mut(cur);
37 38
        cur.control_flow.succs.push(edge);
    }
qinsoon's avatar
qinsoon committed
39 40 41 42
    if !visited.contains(&succ) {
        dfs(succ, stack, visited, func);
    }
    
43 44 45 46 47 48 49 50
}

const WATCHPOINT_DISABLED_CHANCE : f32 = 0.9f32;

const NORMAL_RESUME_CHANCE       : f32 = 0.6f32;
const EXN_RESUME_CHANCE          : f32 = 1f32 - NORMAL_RESUME_CHANCE;

fn dfs(cur: MuTag, stack: &mut Vec<MuTag>, visited: &mut Vec<MuTag>, func: &mut MuFunction) {
qinsoon's avatar
qinsoon committed
51 52 53 54
    trace!("dfs visiting block {}", cur);
    trace!("current stack: {:?}", stack);
    trace!("current visited: {:?}", visited);
    
55 56 57 58 59
    stack.push(cur);
    visited.push(cur);
    
    // find all the successors for current block, and push them to the stack    
    let out_edges : Vec<BlockEdge> = {
qinsoon's avatar
qinsoon committed
60
        let cur = func.content.as_mut().unwrap().get_block_mut(cur); 
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
        let ref body = cur.content.as_ref().unwrap().body;
        let last_inst = body.last().unwrap();
        
        match last_inst.v {
            TreeNode_::Instruction(ref inst) => {
                match inst.v {
                    // unconditional branch, definitely branch to the target
                    Branch1(ref dest) => vec![BlockEdge{
                        target: dest.target,
                        kind: check_edge_kind(dest.target, stack),
                        is_exception: false,
                        probability: 1.0f32
                    }],
                    
                    // conditional branch
                    Branch2{ref true_dest, ref false_dest, true_prob, ..} => vec![
                        BlockEdge{
                            target: true_dest.target,
                            kind: check_edge_kind(true_dest.target, stack),
                            is_exception: false,
                            probability: true_prob
                        },
                        BlockEdge{
                            target: false_dest.target,
                            kind: check_edge_kind(false_dest.target, stack),
                            is_exception: false,
                            probability: 1.0f32 - true_prob
                        }
                    ],
                    
                    // watchpoints
                    Watchpoint{ref id, ref disable_dest, ref resume} => {
                        let ref normal = resume.normal_dest;
                        let ref exn    = resume.exn_dest;                        
                        
                        if id.is_none() {
                            // unconditional trap
                            vec![
                                BlockEdge{
                                    target: normal.target,
                                    kind: check_edge_kind(normal.target, stack),
                                    is_exception: false,
                                    probability: 1.0f32 * NORMAL_RESUME_CHANCE
                                },
                                BlockEdge{
                                    target: exn.target,
                                    kind: check_edge_kind(exn.target, stack),
                                    is_exception: true,
                                    probability: 1.0f32 * EXN_RESUME_CHANCE
                                }
                            ]
                        } else {
                            // watchpoint. jump to disable_dest when disabled. otherwise trap
                            vec![
                                BlockEdge{
                                    target: disable_dest.as_ref().unwrap().target,
                                    kind: check_edge_kind(disable_dest.as_ref().unwrap().target, stack),
                                    is_exception: false,
                                    probability: WATCHPOINT_DISABLED_CHANCE
                                },
                                BlockEdge{
                                    target: normal.target,
                                    kind: check_edge_kind(normal.target, stack),
                                    is_exception: false,
                                    probability: (1.0f32 - WATCHPOINT_DISABLED_CHANCE) * NORMAL_RESUME_CHANCE
                                },
                                BlockEdge{
                                    target: exn.target,
                                    kind: check_edge_kind(exn.target, stack),
                                    is_exception: true,
                                    probability: (1.0f32 - WATCHPOINT_DISABLED_CHANCE) * EXN_RESUME_CHANCE
                                }
                            ]
                        }
                    },
                    
                    // wpbranch
                    WPBranch{ref disable_dest, ref enable_dest, ..} => vec![
                        BlockEdge{
                            target: disable_dest.target,
                            kind: check_edge_kind(disable_dest.target, stack),
                            is_exception: false,
                            probability: WATCHPOINT_DISABLED_CHANCE
                        },
                        BlockEdge{
                            target: enable_dest.target,
                            kind: check_edge_kind(enable_dest.target, stack),
                            is_exception: false,
                            probability: 1.0f32 - WATCHPOINT_DISABLED_CHANCE
                        }
                    ],
                    
                    // call
                    Call{ref resume, ..} 
                    | SwapStack{ref resume, ..}
                    | ExnInstruction{ref resume, ..} => {
                        let ref normal = resume.normal_dest;
                        let ref exn    = resume.exn_dest;
                                                
                        vec![
                                BlockEdge{
                                    target: normal.target,
                                    kind: check_edge_kind(normal.target, stack),
                                    is_exception: false,
                                    probability: 1.0f32 * NORMAL_RESUME_CHANCE
                                },
                                BlockEdge{
                                    target: exn.target,
                                    kind: check_edge_kind(exn.target, stack),
                                    is_exception: true,
                                    probability: 1.0f32 * EXN_RESUME_CHANCE
                                }

                        ]
                    },
                    
                    _ => vec![]
                }
            },
            _ => panic!("expected an instruction")
        }
    };
    
qinsoon's avatar
qinsoon committed
184 185
    trace!("out edges for {}: {}", cur, vector_as_str(&out_edges));
    
186
    for edge in out_edges {
qinsoon's avatar
qinsoon committed
187
        new_edge(cur, edge, stack, visited, func);
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
    }
    
    stack.pop();
}

impl CompilerPass for ControlFlowAnalysis {
    fn name(&self) -> &'static str {
        self.name
    }
    
    #[allow(unused_variables)]
    fn visit_function(&mut self, vm_context: &VMContext, func: &mut MuFunction) {
        let mut stack   : Vec<MuTag> = vec![];
        let mut visited : Vec<MuTag> = vec![];
        
        dfs(func.content.as_ref().unwrap().entry, &mut stack, &mut visited, func);
    }
    
    #[allow(unused_variables)]
    fn finish_function(&mut self, vm_context: &VMContext, func: &mut MuFunction) {
        debug!("check control flow for {}", func.fn_name);
        
        for entry in func.content.as_ref().unwrap().blocks.iter() {
            debug!("block {}", entry.0);
            
            debug!("{}", entry.1.control_flow);
        }
    }
}