liveness.rs 22.4 KB
Newer Older
1 2
extern crate hprof;

qinsoon's avatar
qinsoon committed
3
use compiler::machine_code::CompiledFunction;
4
use ast::ir::*;
qinsoon's avatar
qinsoon committed
5
use compiler::backend;
6
use utils::LinkedHashSet;
7

qinsoon's avatar
qinsoon committed
8 9
use std::collections::{HashMap, HashSet};

10 11 12
use compiler::backend::reg_alloc::graph_coloring::petgraph;
use compiler::backend::reg_alloc::graph_coloring::petgraph::Graph;
use compiler::backend::reg_alloc::graph_coloring::petgraph::graph::NodeIndex;
qinsoon's avatar
qinsoon committed
13

14 15 16
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct GraphNode {
    temp: MuID,
qinsoon's avatar
qinsoon committed
17
    color: Option<MuID>,
18 19
    group: backend::RegGroup,
    spill_cost: f32
qinsoon's avatar
qinsoon committed
20
}
21

qinsoon's avatar
qinsoon committed
22
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
23
pub struct Move{pub from: NodeIndex, pub to: NodeIndex}
24 25

pub struct InterferenceGraph {
26 27
    graph: Graph<GraphNode, (), petgraph::Undirected>,
    nodes: HashMap<MuID, NodeIndex>,
qinsoon's avatar
qinsoon committed
28
    moves: HashSet<Move>,
29 30 31 32
}

impl InterferenceGraph {
    fn new() -> InterferenceGraph {
qinsoon's avatar
qinsoon committed
33
        InterferenceGraph {
34
            graph: Graph::new_undirected(),
qinsoon's avatar
qinsoon committed
35 36 37 38 39
            nodes: HashMap::new(),
            moves: HashSet::new()
        }
    }
    
40
    fn new_node(&mut self, reg_id: MuID, context: &FunctionContext) -> NodeIndex {
qinsoon's avatar
qinsoon committed
41 42 43
        let entry = context.get_value(reg_id).unwrap();
        
        if !self.nodes.contains_key(&reg_id) {
44
            let node = GraphNode {
45
                temp: reg_id,
46 47
                color: None,
                group: backend::RegGroup::get(entry.ty()),
48
                spill_cost: 0.0f32
qinsoon's avatar
qinsoon committed
49
            };
50 51 52 53 54

            let index = self.graph.add_node(node);

            self.nodes.insert(reg_id, index);
        }
55
        
56 57
        let node_index = *self.nodes.get(&reg_id).unwrap();
        let node_mut = self.graph.node_weight_mut(node_index).unwrap();
58 59
        
        // increase node spill cost
60
        node_mut.spill_cost += 1.0f32;
61
        
62
        node_index
qinsoon's avatar
qinsoon committed
63 64
    }
    
65
    pub fn get_node(&self, reg: MuID) -> NodeIndex {
qinsoon's avatar
qinsoon committed
66
        match self.nodes.get(&reg) {
qinsoon's avatar
qinsoon committed
67
            Some(index) => *index,
qinsoon's avatar
qinsoon committed
68
            None => panic!("do not have a node for {}", reg)
qinsoon's avatar
qinsoon committed
69 70 71
        }
    }
    
72 73 74 75 76 77 78 79
    pub fn temps(&self) -> Vec<MuID>{
        let mut ret = vec![];
        for reg in self.nodes.keys() {
            ret.push(*reg);
        }
        ret
    }
    
80
    pub fn nodes(&self) -> Vec<NodeIndex> {
qinsoon's avatar
qinsoon committed
81
        let mut ret = vec![];
82 83
        for index in self.nodes.values() {
            ret.push(*index);
qinsoon's avatar
qinsoon committed
84 85 86 87 88 89 90 91 92 93 94 95
        }
        ret
    }
    
    pub fn moves(&self) -> &HashSet<Move> {
        &self.moves
    }
    
    pub fn n_nodes(&self) -> usize {
        self.nodes.len()
    }
    
96
    fn add_move(&mut self, src: NodeIndex, dst: NodeIndex) {
qinsoon's avatar
qinsoon committed
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
        let src = {
            let temp_src = self.get_temp_of(src);
            if temp_src < MACHINE_ID_END {
                let alias = backend::get_color_for_precolored(self.get_temp_of(src));
                self.get_node(alias)
            } else {
                src
            }
        };


        let dst = {
            let temp_dst = self.get_temp_of(dst);
            if temp_dst < MACHINE_ID_END {
                let alias = backend::get_color_for_precolored(self.get_temp_of(dst));
                self.get_node(alias)
            } else {
                dst
            }
        };

qinsoon's avatar
qinsoon committed
118
        self.moves.insert(Move{from: src, to: dst});
119 120
    }
    
121 122
    pub fn add_interference_edge(&mut self, from: NodeIndex, to: NodeIndex) {
        self.graph.update_edge(from, to, ());
qinsoon's avatar
qinsoon committed
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

        // if one of the node is machine register, we also add
        // interference edge to its alias
        // e.g. if we have %a, %edi interferenced,
        // we also add %a, %rdi interference

        let from_tmp = self.graph.node_weight(from).unwrap().temp;
        let to_tmp   = self.graph.node_weight(to).unwrap().temp;

        if from_tmp < MACHINE_ID_END || to_tmp < MACHINE_ID_END {
            let from_tmp = if from_tmp < MACHINE_ID_END {
                backend::get_color_for_precolored(from_tmp)
            } else {
                from_tmp
            };

            let to_tmp = if to_tmp < MACHINE_ID_END {
                backend::get_color_for_precolored(to_tmp)
            } else {
                to_tmp
            };

            let from_tmp_node = self.get_node(from_tmp);
            let to_tmp_node   = self.get_node(to_tmp);
            self.graph.update_edge(from_tmp_node, to_tmp_node, ());
        }
qinsoon's avatar
qinsoon committed
149 150
    }

151
    pub fn is_interferenced_with(&self, node1: NodeIndex, node2: NodeIndex) -> bool {
152 153 154
        let edge = self.graph.find_edge(node1, node2);

        edge.is_some()
qinsoon's avatar
qinsoon committed
155 156
    }
    
157 158
    pub fn color_node(&mut self, node: NodeIndex, color: MuID) {
        self.graph.node_weight_mut(node).unwrap().color = Some(color);
qinsoon's avatar
qinsoon committed
159 160
    }
    
161 162
    pub fn is_colored(&self, node: NodeIndex) -> bool {
        self.graph.node_weight(node).unwrap().color.is_some()
qinsoon's avatar
qinsoon committed
163 164
    }
    
165 166
    pub fn get_color_of(&self, node: NodeIndex) -> Option<MuID> {
        self.graph.node_weight(node).unwrap().color
167 168
    }
    
169 170
    pub fn get_group_of(&self, node: NodeIndex) -> backend::RegGroup {
        self.graph.node_weight(node).unwrap().group
qinsoon's avatar
qinsoon committed
171 172
    }
    
173 174
    pub fn get_temp_of(&self, node: NodeIndex) -> MuID {
        self.graph.node_weight(node).unwrap().temp
175 176
    }
    
177 178
    pub fn get_spill_cost(&self, node: NodeIndex) -> f32 {
        self.graph.node_weight(node).unwrap().spill_cost
179 180
    }
    
181
    fn is_same_node(&self, node1: NodeIndex, node2: NodeIndex) -> bool {
qinsoon's avatar
qinsoon committed
182
        node1 == node2
qinsoon's avatar
qinsoon committed
183
    }
184 185 186 187 188 189 190

    fn is_same_group(&self, node1: NodeIndex, node2: NodeIndex) -> bool {
        let node1 = self.graph.node_weight(node1).unwrap();
        let node2 = self.graph.node_weight(node2).unwrap();

        node1.group == node2.group
    }
qinsoon's avatar
qinsoon committed
191
    
192 193
    pub fn is_adj(&self, from: NodeIndex, to: NodeIndex) -> bool {
        self.is_interferenced_with(from, to)
qinsoon's avatar
qinsoon committed
194 195
    }
    
196 197
    pub fn outedges_of(&self, node: NodeIndex) -> Vec<NodeIndex> {
        self.graph.neighbors(node).collect()
198 199
    }
    
200 201
    pub fn outdegree_of(&self, node: NodeIndex) -> usize {
        self.outedges_of(node).len()
qinsoon's avatar
qinsoon committed
202 203
    }
    
204 205
    pub fn indegree_of(&self, node: NodeIndex) -> usize {
        self.outdegree_of(node)
qinsoon's avatar
qinsoon committed
206 207
    }
    
208
    pub fn degree_of(&self, node: NodeIndex) -> usize {
qinsoon's avatar
fix  
qinsoon committed
209
        self.outdegree_of(node)
qinsoon's avatar
qinsoon committed
210 211
    }
    
qinsoon's avatar
qinsoon committed
212
    pub fn print(&self, context: &FunctionContext) {
213 214 215
        use compiler::backend::reg_alloc::graph_coloring::petgraph::dot::Dot;
        use compiler::backend::reg_alloc::graph_coloring::petgraph::dot::Config;

qinsoon's avatar
qinsoon committed
216 217
        debug!("");
        debug!("Interference Graph");
218

qinsoon's avatar
qinsoon committed
219
        debug!("nodes:");
qinsoon's avatar
qinsoon committed
220
        for id in self.nodes.keys() {
qinsoon's avatar
qinsoon committed
221
            let val = context.get_value(*id).unwrap().value();
qinsoon's avatar
qinsoon committed
222
            debug!("Reg {} -> {:?}", val, self.nodes.get(&id).unwrap());
qinsoon's avatar
qinsoon committed
223 224
        }

qinsoon's avatar
qinsoon committed
225
        debug!("moves:");
226
        for mov in self.moves.iter() {
qinsoon's avatar
qinsoon committed
227
            debug!("Move {:?} -> {:?}", mov.from, mov.to);
228
        }
qinsoon's avatar
qinsoon committed
229

230
        debug!("graph:");
231
        debug!("\n\n{:?}\n", Dot::with_config(&self.graph, &[Config::EdgeNoLabel]));
qinsoon's avatar
qinsoon committed
232
        debug!("");
233
    }
qinsoon's avatar
qinsoon committed
234 235
}

236 237
const TRACE_BUILD_LIVE_SET : bool = false;

qinsoon's avatar
[wip]  
qinsoon committed
238 239
fn build_live_set (cf: &mut CompiledFunction, func: &MuFunctionVersion) {
    info!("---start building live set---");
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
    let cfg = local_liveness_analysis(cf, func);
    global_liveness_analysis(cfg, cf, func);

    info!("---finish building live set---");
}

#[derive(Clone, Debug)]
struct CFGBlockNode {
    block: String,

    pred: Vec<String>,
    succ: Vec<String>,

    uses:  Vec<MuID>,
    defs: Vec<MuID>
}

fn local_liveness_analysis (cf: &mut CompiledFunction, func: &MuFunctionVersion) -> HashMap<String, CFGBlockNode> {
    info!("---local liveness analysis---");
    let mc = cf.mc();

    let mut ret = hashmap!{};

    let all_blocks = mc.get_all_blocks();

    // create maps (start_inst -> name) and (end_inst -> name)
    let mut start_inst_map : HashMap<usize, &str> = hashmap!{};
    let mut end_inst_map   : HashMap<usize, &str> = hashmap!{};
    for block in all_blocks.iter() {
        let range = match mc.get_block_range(block) {
            Some(range) => range,
            None => panic!("cannot find range for block {}", block)
        };

        debug!("Block {}: start_inst={}, end_inst(inclusive)={}", block, range.start, range.end-1);
        start_inst_map.insert(range.start, block);
        end_inst_map.insert(range.end - 1, block);
    }

    // local liveness analysis
    for block in mc.get_all_blocks().iter() {
        trace!("---block {}---", block);
        let range = mc.get_block_range(block).unwrap();

        let start_inst = range.start;
        let end        = range.end;

        let mut livein = vec![];
        let mut all_defined : HashSet<MuID> = HashSet::new();

        for i in start_inst..end {
            let reg_uses = mc.get_inst_reg_uses(i);

            // if a reg is used but not defined before, it is a live-in
            for reg in reg_uses {
                if !all_defined.contains(&reg) {
                    livein.push(reg);
                }
            }

            let reg_defs = mc.get_inst_reg_defines(i);
            for reg in reg_defs {
                all_defined.insert(reg);
            }
        }

        let defs : Vec<MuID> = all_defined.into_iter().collect();

        let preds : Vec<String> = {
            let mut ret = vec![];

            // start_inst is the first instruction
            // start_inst-1 is the label for the block
            // FIXME: this is confusing! label should be an attribute to an instruction
            for pred in mc.get_preds(start_inst).into_iter() {
                match end_inst_map.get(pred) {
                    Some(str) => ret.push(String::from(*str)),
                    None => {}
                }
            }

            ret
        };

        let succs : Vec<String> = {
            let mut ret = vec![];

            for succ in mc.get_succs(end - 1).into_iter() {
                match start_inst_map.get(succ) {
                    Some(str) => ret.push(String::from(*str)),
                    None => {}
                }
            }

            ret
        };

        let node = CFGBlockNode {
            block: block.clone(),

            pred: preds,
            succ: succs,

            uses: livein,
            defs: defs
        };

        trace!("as CFGNode {:?}", node);

        ret.insert(block.clone(), node);
    }

    ret
}

//fn topological_sort_cfg(entry: String, cfg: HashMap<String, CFGBlockNode>) -> Vec<CFGBlockNode> {
//    let mut ret = vec![];
//    // for all nodes i
//    //   mark[i] <- false
//    let mut mark = {
//        let mut ret = hashmap!{};
//        for str in cfg.keys() {
//            ret.insert(str.clone(), false);
//        }
//
//        ret
//    };
//
//    // dfs(start-node)
//    dfs(entry, &cfg, &mut mark, &mut ret);
//
//    ret.reverse();
//
//    ret
//}
//
//fn dfs(node: String, cfg: &HashMap<String, CFGBlockNode>, mark: &mut HashMap<String, bool>, sorted: &mut Vec<CFGBlockNode>) {
//    // if mark[i] = false
//    if !mark.get(&node).unwrap() {
//        mark.insert(node.clone(), true);
//
//        let cfg_node = cfg.get(&node).unwrap().clone();
//        for succ in cfg_node.succ.iter() {
//            dfs(succ.clone(), cfg, mark, sorted);
//        }
//
//        sorted.push(cfg_node);
//    }
//}

fn global_liveness_analysis(blocks: HashMap<String, CFGBlockNode>, cf: &mut CompiledFunction, func: &MuFunctionVersion) {
    let n_nodes = blocks.len();

    // init live in and live out
    let mut livein  : HashMap<String, LinkedHashSet<MuID>> = {
        let mut ret = hashmap!{};
        for name in blocks.keys() {
            ret.insert(name.clone(), LinkedHashSet::new());
        }
        ret
    };
    let mut liveout  : HashMap<String, LinkedHashSet<MuID>> = {
        let mut ret = hashmap!{};
        for name in blocks.keys() {
            ret.insert(name.clone(), LinkedHashSet::new());
        }
        ret
    };

    let mut is_changed = true;
    let mut i = 0;

    while is_changed {
        trace!("---iteration {}---", i);
        i += 1;

        // reset
        is_changed = false;

        for node in blocks.keys() {
            let cfg_node = blocks.get(node).unwrap();

            let in_set_old  = livein.get(node).unwrap().clone();
            let out_set_old = liveout.get(node).unwrap().clone();

            // in <- use + (out - def)
            {
                let mut inset = livein.get_mut(node).unwrap();

                inset.clear();

                // (1) out - def
                inset.add_all(liveout.get(node).unwrap().clone());
                for def in cfg_node.defs.iter() {
                    inset.remove(def);
                }

                // (2) in + (out - def)
                for in_reg in cfg_node.uses.iter() {
                    inset.insert(*in_reg);
                }
            }

            // out[n] <- union(in[s] for every successor s of n)
            {
                let mut outset = liveout.get_mut(node).unwrap();
                outset.clear();

                for s in cfg_node.succ.iter() {
                    outset.add_all(livein.get(s).unwrap().clone());
                }
            }

            // is in/out changed in this iteration?
            let n_changed = !in_set_old.equals(livein.get(node).unwrap()) || !out_set_old.equals(liveout.get(node).unwrap());

            if TRACE_BUILD_LIVE_SET {
                trace!("block {}", node);
                trace!("in(old)  = {:?}", in_set_old);
                trace!("in(new)  = {:?}", livein.get(node).unwrap());
                trace!("out(old) = {:?}", out_set_old);
                trace!("out(new) = {:?}", liveout.get(node).unwrap());
            }

            is_changed = is_changed || n_changed;
        }
    }

    for block in blocks.keys() {
        let livein : Vec<MuID> = livein.get(block).unwrap().clone().iter().map(|x| *x).collect();
        {
            let display_array : Vec<String> =  livein.iter().map(|x| func.context.get_temp_display(*x)).collect();
            trace!("livein  for block {}: {:?}", block, display_array);
        }
        cf.mc_mut().set_ir_block_livein(block, livein);

        let liveout : Vec<MuID> = liveout.get(block).unwrap().clone().iter().map(|x| *x).collect();
        {
            let display_array : Vec<String> = liveout.iter().map(|x| func.context.get_temp_display(*x)).collect();
            trace!("liveout for block {}: {:?}", block, display_array);
        }
        cf.mc_mut().set_ir_block_liveout(block, liveout);
    }
}

#[allow(dead_code)]
fn naive_global_liveness_analysis(cf: &mut CompiledFunction, func: &MuFunctionVersion) {
qinsoon's avatar
qinsoon committed
488
    let n_insts = cf.mc().number_of_insts();
489 490 491 492

    let mut livein  : Vec<LinkedHashSet<MuID>> = vec![LinkedHashSet::new(); n_insts];
    let mut liveout : Vec<LinkedHashSet<MuID>> = vec![LinkedHashSet::new(); n_insts];

493
    let mut is_changed = true;
494

qinsoon's avatar
[wip]  
qinsoon committed
495
    let mut i = 0;
496
    while is_changed {
qinsoon's avatar
qinsoon committed
497
        trace!("---iteration {}---", i);
qinsoon's avatar
[wip]  
qinsoon committed
498 499
        i += 1;

500 501
        // reset
        is_changed = false;
502

503
        for n in 0..n_insts {
504 505 506 507 508 509 510 511 512
            let in_set_old = livein[n].clone();
            let out_set_old = liveout[n].clone();

            // in[n] <- use[n] + (out[n] - def[n]);
            {
                let ref mut inset = livein[n];

                inset.clear();

qinsoon's avatar
[wip]  
qinsoon committed
513
                // (1) out[n] - def[n]
514 515 516 517
                inset.add_all(liveout[n].clone());
                for def in cf.mc().get_inst_reg_defines(n) {
                    inset.remove(&def);
                }
qinsoon's avatar
[wip]  
qinsoon committed
518 519
                // (2) in[n] + (out[n] - def[n])
                inset.add_from_vec(cf.mc().get_inst_reg_uses(n));
520
            }
521

522
            // out[n] <- union(in[s] for every successor s of n)
523 524 525 526 527 528 529
            {
                let ref mut outset = liveout[n];
                outset.clear();

                for s in cf.mc().get_succs(n) {
                    outset.add_all(livein[*s].clone());
                }
530
            }
531 532 533 534

            // is in/out changed in this iteration?
            let n_changed = !in_set_old.equals(&livein[n]) || !out_set_old.equals(&liveout[n]);

535 536 537 538 539 540 541
            if TRACE_BUILD_LIVE_SET {
                trace!("inst {}", n);
                trace!("in(old)  = {:?}", in_set_old);
                trace!("in(new)  = {:?}", livein[n]);
                trace!("out(old) = {:?}", out_set_old);
                trace!("out(new) = {:?}", liveout[n]);
            }
qinsoon's avatar
[wip]  
qinsoon committed
542

543 544 545
            is_changed = is_changed || n_changed;
        }
    }
546 547
}

548
// from Tailoring Graph-coloring Register Allocation For Runtime Compilation, Figure 4
549
pub fn build_chaitin_briggs (cf: &mut CompiledFunction, func: &MuFunctionVersion) -> InterferenceGraph {
550
    let _p = hprof::enter("regalloc: build live set");
qinsoon's avatar
[wip]  
qinsoon committed
551
    build_live_set(cf, func);
552 553 554
    drop(_p);

    let _p = hprof::enter("regalloc: build interference graph");
qinsoon's avatar
[wip]  
qinsoon committed
555 556

    info!("---start building interference graph---");
557
    
558 559 560
    let mut ig = InterferenceGraph::new();
    
    // precolor machine register nodes
561
    for reg in backend::all_regs().values() {
562 563
        let reg_id = reg.extract_ssa_id().unwrap();
        let node = ig.new_node(reg_id, &func.context);
qinsoon's avatar
qinsoon committed
564

qinsoon's avatar
qinsoon committed
565
        let precolor = backend::get_color_for_precolored(reg_id);
qinsoon's avatar
qinsoon committed
566 567

        ig.color_node(node, precolor);
568 569 570
    }
    
    // Initialize and creates nodes for all the involved temps/regs
qinsoon's avatar
qinsoon committed
571 572
    for i in 0..cf.mc().number_of_insts() {
        for reg_id in cf.mc().get_inst_reg_defines(i) {
573 574 575
            ig.new_node(reg_id, &func.context);
        }
        
qinsoon's avatar
qinsoon committed
576
        for reg_id in cf.mc().get_inst_reg_uses(i) {
577 578 579 580
            ig.new_node(reg_id, &func.context);
        }
    }
    
qinsoon's avatar
qinsoon committed
581
    for block in cf.mc().get_all_blocks() {
582
        // Current_Live(B) = LiveOut(B)
qinsoon's avatar
qinsoon committed
583
        let mut current_live = LinkedHashSet::from_vec(match cf.mc().get_ir_block_liveout(&block) {
584 585 586
            Some(liveout) => liveout.to_vec(),
            None => panic!("cannot find liveout for block {}", block)
        });
qinsoon's avatar
qinsoon committed
587 588 589 590 591 592
        if cfg!(debug_assertions) {
            trace!("Block{}: live out", block);
            for ele in current_live.iter() {
                trace!("{}", func.context.get_temp_display(*ele));
            }
        }
593
        
qinsoon's avatar
qinsoon committed
594
        let range = cf.mc().get_block_range(&block);
595
        if range.is_none() {
qinsoon's avatar
qinsoon committed
596
            warn!("Block{}: has no range (no instructions?)", block);
597 598
            continue;
        }
qinsoon's avatar
qinsoon committed
599
        trace!("Block{}: range = {:?}", block, range.as_ref().unwrap());
600 601 602
        
        // for every inst I in reverse order
        for i in range.unwrap().rev() {
qinsoon's avatar
qinsoon committed
603
            if cfg!(debug_assertions) {
qinsoon's avatar
[wip]  
qinsoon committed
604 605 606
                trace!("Block{}: Inst{}", block, i);
                cf.mc().trace_inst(i);
                trace!("current live: ");
qinsoon's avatar
qinsoon committed
607 608 609 610 611
                for ele in current_live.iter() {
                    trace!("{}", func.context.get_temp_display(*ele));
                }
            }

612
            let src : Option<MuID> = {
qinsoon's avatar
qinsoon committed
613 614 615
                if cf.mc().is_move(i) {
                    let src = cf.mc().get_inst_reg_uses(i);
                    let dst = cf.mc().get_inst_reg_defines(i);
616
                    
qinsoon's avatar
qinsoon committed
617 618 619
                    // src:  reg/imm/mem
                    // dest: reg/mem
                    // we dont care if src/dest is mem
qinsoon's avatar
qinsoon committed
620
                    if cf.mc().is_using_mem_op(i) {
621
                        None
qinsoon's avatar
qinsoon committed
622 623 624 625
                    } else {
                        if src.len() == 1 {
                            let node1 = ig.get_node(src[0]);
                            let node2 = ig.get_node(dst[0]);
qinsoon's avatar
qinsoon committed
626 627 628
                            trace!("add move between {} and {}",
                                   func.context.get_temp_display(src[0]),
                                   func.context.get_temp_display(dst[0]));
qinsoon's avatar
qinsoon committed
629 630 631 632 633 634
                            ig.add_move(node1, node2);
                            
                            Some(src[0])
                        } else {
                            None
                        }
635 636 637 638 639
                    }
                } else {
                    None
                }
            };
qinsoon's avatar
qinsoon committed
640
            trace!("Block{}: Inst{}: src={:?}", block, i, src);
641 642
            
            // for every definition D in I
qinsoon's avatar
qinsoon committed
643
            for d in cf.mc().get_inst_reg_defines(i) {
qinsoon's avatar
qinsoon committed
644
                trace!("Block{}: Inst{}: for definition {}", block, i, func.context.get_temp_display(d));
645 646 647
                // add an interference from D to every element E in Current_Live - {D}
                // creating nodes if necessary
                for e in current_live.iter() {
qinsoon's avatar
qinsoon committed
648 649 650
                    trace!("Block{}: Inst{}: for each live {}",
                           block, i,
                           func.context.get_temp_display(*e));
651
                    if src.is_none() || (src.is_some() && *e != src.unwrap()) {
qinsoon's avatar
qinsoon committed
652
                        let from = ig.get_node(d);
653 654
                        let to = ig.get_node(*e);
                        
qinsoon's avatar
qinsoon committed
655
                        if !ig.is_same_node(from, to) &&ig.is_same_group(from, to) && !ig.is_adj(from, to) {
656
                            if !ig.is_colored(from) {
qinsoon's avatar
qinsoon committed
657 658 659 660
                                trace!("Block{}: Inst{}: add interference between {} and {}",
                                       block, i,
                                       func.context.get_temp_display(d),
                                       func.context.get_temp_display(*e));
661 662 663
                                ig.add_interference_edge(from, to);
                            }
                            if !ig.is_colored(to) {
qinsoon's avatar
qinsoon committed
664 665 666 667
                                trace!("Block{}: Inst{}: add interference between {} and {}",
                                       block, i,
                                       func.context.get_temp_display(*e),
                                       func.context.get_temp_display(d));
668 669 670 671 672 673 674 675
                                ig.add_interference_edge(to, from);
                            }
                        }
                    }
                }
            }
            
            // for every definition D in I
qinsoon's avatar
qinsoon committed
676
            for d in cf.mc().get_inst_reg_defines(i) {
qinsoon's avatar
qinsoon committed
677 678 679
                trace!("Block{}: Inst{}: remove define {} from current_live",
                       block, i,
                       func.context.get_temp_display(d));
680
                // remove D from Current_Live
qinsoon's avatar
qinsoon committed
681
                current_live.remove(&d);
682 683 684
            }
            
            // for every use U in I
qinsoon's avatar
qinsoon committed
685
            for u in cf.mc().get_inst_reg_uses(i) {
qinsoon's avatar
qinsoon committed
686 687 688
                trace!("Block{}: Inst{}: add use {} to current_live",
                       block, i,
                       func.context.get_temp_display(u));
689
                // add U to Current_live
qinsoon's avatar
qinsoon committed
690
                current_live.insert(u);
691
            }
qinsoon's avatar
qinsoon committed
692 693 694 695 696 697 698

            if cfg!(debug_assertions) {
                trace!("Block{}: Inst{}: done. current_live:", block, i);
                for ele in current_live.iter() {
                    trace!("{}", func.context.get_temp_display(*ele));
                }
            }
699 700
        }
    }
qinsoon's avatar
[wip]  
qinsoon committed
701

702
    drop(_p);
qinsoon's avatar
[wip]  
qinsoon committed
703
    info!("---finish building interference graph---");
704
    ig
705
}