liveness.rs 22.6 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
use utils::LinkedHashMap;
qinsoon's avatar
qinsoon committed
8

9 10 11
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
12

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

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

pub struct InterferenceGraph {
25
    graph: Graph<GraphNode, (), petgraph::Undirected>,
26 27
    nodes: LinkedHashMap<MuID, NodeIndex>,
    moves: LinkedHashSet<Move>,
28 29 30 31
}

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

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

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

        // 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
148 149
    }

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

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

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

215 216
        trace!("");
        trace!("Interference Graph");
217

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

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

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

235 236
const TRACE_BUILD_LIVE_SET : bool = false;

qinsoon's avatar
[wip]  
qinsoon committed
237 238
fn build_live_set (cf: &mut CompiledFunction, func: &MuFunctionVersion) {
    info!("---start building live set---");
239

240
    let cfg = local_liveness_analysis(cf);
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
    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>
}

257
fn local_liveness_analysis (cf: &mut CompiledFunction) -> LinkedHashMap<String, CFGBlockNode> {
258 259 260
    info!("---local liveness analysis---");
    let mc = cf.mc();

261
    let mut ret = LinkedHashMap::new();
262 263 264 265

    let all_blocks = mc.get_all_blocks();

    // create maps (start_inst -> name) and (end_inst -> name)
266 267
    let mut start_inst_map : LinkedHashMap<usize, &str> = LinkedHashMap::new();
    let mut end_inst_map   : LinkedHashMap<usize, &str> = LinkedHashMap::new();
268 269 270 271 272 273
    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)
        };

274
        trace!("Block {}: start_inst={}, end_inst(inclusive)={}", block, range.start, range.end-1);
275 276 277 278 279 280 281 282 283 284 285 286 287
        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![];
288
        let mut all_defined : LinkedHashSet<MuID> = LinkedHashSet::new();
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305

        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);
            }
        }

306
        let defs : Vec<MuID> = all_defined.iter().map(|x| *x).collect();
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

        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
}

355
//fn topological_sort_cfg(entry: String, cfg: LinkedHashMap<String, CFGBlockNode>) -> Vec<CFGBlockNode> {
356 357 358 359
//    let mut ret = vec![];
//    // for all nodes i
//    //   mark[i] <- false
//    let mut mark = {
360
//        let mut ret = LinkedHashMap::new();
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
//        for str in cfg.keys() {
//            ret.insert(str.clone(), false);
//        }
//
//        ret
//    };
//
//    // dfs(start-node)
//    dfs(entry, &cfg, &mut mark, &mut ret);
//
//    ret.reverse();
//
//    ret
//}
//
376
//fn dfs(node: String, cfg: &LinkedHashMap<String, CFGBlockNode>, mark: &mut LinkedHashMap<String, bool>, sorted: &mut Vec<CFGBlockNode>) {
377 378 379 380 381 382 383 384 385 386 387 388 389
//    // 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);
//    }
//}

390
fn global_liveness_analysis(blocks: LinkedHashMap<String, CFGBlockNode>, cf: &mut CompiledFunction, func: &MuFunctionVersion) {
391 392
    info!("---global liveness analysis---");
    info!("{} blocks", blocks.len());
393 394

    // init live in and live out
395 396
    let mut livein  : LinkedHashMap<String, LinkedHashSet<MuID>> = {
        let mut ret = LinkedHashMap::new();
397 398 399 400 401
        for name in blocks.keys() {
            ret.insert(name.clone(), LinkedHashSet::new());
        }
        ret
    };
402 403
    let mut liveout  : LinkedHashMap<String, LinkedHashSet<MuID>> = {
        let mut ret = LinkedHashMap::new();
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
        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;
        }
    }

469 470
    info!("finished in {} iterations", i);

471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
    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)]
489
fn naive_global_liveness_analysis(cf: &mut CompiledFunction) {
qinsoon's avatar
qinsoon committed
490
    let n_insts = cf.mc().number_of_insts();
491 492 493 494

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

495
    let mut is_changed = true;
496

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

502 503
        // reset
        is_changed = false;
504

505
        for n in 0..n_insts {
506 507 508 509 510 511 512 513 514
            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
515
                // (1) out[n] - def[n]
516 517 518 519
                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
520 521
                // (2) in[n] + (out[n] - def[n])
                inset.add_from_vec(cf.mc().get_inst_reg_uses(n));
522
            }
523

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

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

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

537 538 539 540 541 542 543
            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
544

545 546 547
            is_changed = is_changed || n_changed;
        }
    }
548 549
}

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

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

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

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

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

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

            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));
                }
            }
701 702
        }
    }
qinsoon's avatar
[wip]  
qinsoon committed
703

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