liveness.rs 23.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// Copyright 2017 The Australian National University
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
//     http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

15 16
extern crate hprof;

qinsoon's avatar
qinsoon committed
17
use compiler::machine_code::CompiledFunction;
18
use ast::ir::*;
19
use compiler::backend;
20
use utils::LinkedHashSet;
21
use utils::LinkedHashMap;
qinsoon's avatar
qinsoon committed
22

23 24 25
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
26

27 28 29
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct GraphNode {
    temp: MuID,
30
    color: Option<MuID>,
31 32
    group: backend::RegGroup,
    spill_cost: f32
33
}
34

35
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
36
pub struct Move{pub from: NodeIndex, pub to: NodeIndex}
37 38

pub struct InterferenceGraph {
39
    graph: Graph<GraphNode, (), petgraph::Undirected>,
40 41
    nodes: LinkedHashMap<MuID, NodeIndex>,
    moves: LinkedHashSet<Move>,
42 43 44 45
}

impl InterferenceGraph {
    fn new() -> InterferenceGraph {
qinsoon's avatar
qinsoon committed
46
        InterferenceGraph {
47
            graph: Graph::new_undirected(),
48 49
            nodes: LinkedHashMap::new(),
            moves: LinkedHashSet::new()
qinsoon's avatar
qinsoon committed
50 51 52
        }
    }
    
53
    fn new_node(&mut self, reg_id: MuID, context: &FunctionContext) -> NodeIndex {
54 55 56
        let entry = context.get_value(reg_id).unwrap();
        
        if !self.nodes.contains_key(&reg_id) {
57
            let node = GraphNode {
58
                temp: reg_id,
59
                color: None,
60
                group: backend::RegGroup::get_from_ty(entry.ty()),
61
                spill_cost: 0.0f32
62
            };
63 64 65 66 67

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

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

131
        self.moves.insert(Move{from: src, to: dst});
132 133
    }
    
134 135
    pub fn add_interference_edge(&mut self, from: NodeIndex, to: NodeIndex) {
        self.graph.update_edge(from, to, ());
qinsoon's avatar
qinsoon committed
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

        // 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
162 163
    }

164
    pub fn is_interferenced_with(&self, node1: NodeIndex, node2: NodeIndex) -> bool {
165 166 167
        let edge = self.graph.find_edge(node1, node2);

        edge.is_some()
qinsoon's avatar
qinsoon committed
168 169
    }
    
170 171
    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
172 173
    }
    
174 175
    pub fn is_colored(&self, node: NodeIndex) -> bool {
        self.graph.node_weight(node).unwrap().color.is_some()
176 177
    }
    
178 179
    pub fn get_color_of(&self, node: NodeIndex) -> Option<MuID> {
        self.graph.node_weight(node).unwrap().color
180 181
    }
    
182 183
    pub fn get_group_of(&self, node: NodeIndex) -> backend::RegGroup {
        self.graph.node_weight(node).unwrap().group
qinsoon's avatar
qinsoon committed
184 185
    }
    
186 187
    pub fn get_temp_of(&self, node: NodeIndex) -> MuID {
        self.graph.node_weight(node).unwrap().temp
188 189
    }
    
190 191
    pub fn get_spill_cost(&self, node: NodeIndex) -> f32 {
        self.graph.node_weight(node).unwrap().spill_cost
192 193
    }
    
194
    fn is_same_node(&self, node1: NodeIndex, node2: NodeIndex) -> bool {
qinsoon's avatar
qinsoon committed
195
        node1 == node2
qinsoon's avatar
qinsoon committed
196
    }
197 198 199 200 201 202 203

    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
204
    
205 206
    pub fn is_adj(&self, from: NodeIndex, to: NodeIndex) -> bool {
        self.is_interferenced_with(from, to)
qinsoon's avatar
qinsoon committed
207 208
    }
    
209 210
    pub fn outedges_of(&self, node: NodeIndex) -> Vec<NodeIndex> {
        self.graph.neighbors(node).collect()
211 212
    }
    
213 214
    pub fn outdegree_of(&self, node: NodeIndex) -> usize {
        self.outedges_of(node).len()
215 216
    }
    
217 218
    pub fn indegree_of(&self, node: NodeIndex) -> usize {
        self.outdegree_of(node)
219 220
    }
    
221
    pub fn degree_of(&self, node: NodeIndex) -> usize {
qinsoon's avatar
qinsoon committed
222
        self.outdegree_of(node)
223 224
    }
    
qinsoon's avatar
qinsoon committed
225
    pub fn print(&self, context: &FunctionContext) {
226 227 228
        use compiler::backend::reg_alloc::graph_coloring::petgraph::dot::Dot;
        use compiler::backend::reg_alloc::graph_coloring::petgraph::dot::Config;

229 230
        trace!("");
        trace!("Interference Graph");
231

232
        trace!("nodes:");
233
        for id in self.nodes.keys() {
qinsoon's avatar
qinsoon committed
234
            let val = context.get_value(*id).unwrap().value();
235
            trace!("Reg {} -> {:?}", val, self.nodes.get(&id).unwrap());
236 237
        }

238
        trace!("moves:");
239
        for mov in self.moves.iter() {
240
            trace!("Move {:?} -> {:?}", mov.from, mov.to);
241
        }
qinsoon's avatar
qinsoon committed
242

243 244 245
        trace!("graph:");
        trace!("\n\n{:?}\n", Dot::with_config(&self.graph, &[Config::EdgeNoLabel]));
        trace!("");
246
    }
qinsoon's avatar
qinsoon committed
247 248
}

249 250
const TRACE_BUILD_LIVE_SET : bool = false;

qinsoon's avatar
qinsoon committed
251 252
fn build_live_set (cf: &mut CompiledFunction, func: &MuFunctionVersion) {
    info!("---start building live set---");
253

254
    let cfg = local_liveness_analysis(cf);
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
    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>
}

271
fn local_liveness_analysis (cf: &mut CompiledFunction) -> LinkedHashMap<String, CFGBlockNode> {
272 273 274
    info!("---local liveness analysis---");
    let mc = cf.mc();

275
    let mut ret = LinkedHashMap::new();
276 277 278 279

    let all_blocks = mc.get_all_blocks();

    // create maps (start_inst -> name) and (end_inst -> name)
280 281
    let mut start_inst_map : LinkedHashMap<usize, &str> = LinkedHashMap::new();
    let mut end_inst_map   : LinkedHashMap<usize, &str> = LinkedHashMap::new();
282 283 284 285 286 287
    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)
        };

288 289 290 291 292 293 294 295 296
        let first_inst = range.start;
        let last_inst = match mc.get_last_inst(range.end) {
            Some(last) => last,
            None => panic!("cannot find last instruction in block {}, this block contains no instruction?", block)
        };
        trace!("Block {}: start_inst={}, end_inst(inclusive)={}", block, first_inst, last_inst);

        start_inst_map.insert(first_inst, block);
        end_inst_map.insert(last_inst, block);
297 298 299 300 301 302 303 304 305 306 307
    }

    // 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![];
308
        let mut all_defined : LinkedHashSet<MuID> = LinkedHashSet::new();
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325

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

326
        let defs : Vec<MuID> = all_defined.iter().map(|x| *x).collect();
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346

        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![];

347
            for succ in mc.get_succs(mc.get_last_inst(end).unwrap()).into_iter() {
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
                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
}

375
//fn topological_sort_cfg(entry: String, cfg: LinkedHashMap<String, CFGBlockNode>) -> Vec<CFGBlockNode> {
376 377 378 379
//    let mut ret = vec![];
//    // for all nodes i
//    //   mark[i] <- false
//    let mut mark = {
380
//        let mut ret = LinkedHashMap::new();
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
//        for str in cfg.keys() {
//            ret.insert(str.clone(), false);
//        }
//
//        ret
//    };
//
//    // dfs(start-node)
//    dfs(entry, &cfg, &mut mark, &mut ret);
//
//    ret.reverse();
//
//    ret
//}
//
396
//fn dfs(node: String, cfg: &LinkedHashMap<String, CFGBlockNode>, mark: &mut LinkedHashMap<String, bool>, sorted: &mut Vec<CFGBlockNode>) {
397 398 399 400 401 402 403 404 405 406 407 408 409
//    // 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);
//    }
//}

410
fn global_liveness_analysis(blocks: LinkedHashMap<String, CFGBlockNode>, cf: &mut CompiledFunction, func: &MuFunctionVersion) {
411 412
    info!("---global liveness analysis---");
    info!("{} blocks", blocks.len());
413 414

    // init live in and live out
415 416
    let mut livein  : LinkedHashMap<String, LinkedHashSet<MuID>> = {
        let mut ret = LinkedHashMap::new();
417 418 419 420 421
        for name in blocks.keys() {
            ret.insert(name.clone(), LinkedHashSet::new());
        }
        ret
    };
422 423
    let mut liveout  : LinkedHashMap<String, LinkedHashSet<MuID>> = {
        let mut ret = LinkedHashMap::new();
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 488
        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;
        }
    }

489 490
    info!("finished in {} iterations", i);

491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508
    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)]
509
fn naive_global_liveness_analysis(cf: &mut CompiledFunction) {
qinsoon's avatar
qinsoon committed
510
    let n_insts = cf.mc().number_of_insts();
511 512 513 514

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

515
    let mut is_changed = true;
516

qinsoon's avatar
qinsoon committed
517
    let mut i = 0;
518
    while is_changed {
qinsoon's avatar
qinsoon committed
519
        trace!("---iteration {}---", i);
qinsoon's avatar
qinsoon committed
520 521
        i += 1;

522 523
        // reset
        is_changed = false;
524

525
        for n in 0..n_insts {
526 527 528 529 530 531 532 533 534
            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
qinsoon committed
535
                // (1) out[n] - def[n]
536 537 538 539
                inset.add_all(liveout[n].clone());
                for def in cf.mc().get_inst_reg_defines(n) {
                    inset.remove(&def);
                }
qinsoon's avatar
qinsoon committed
540 541
                // (2) in[n] + (out[n] - def[n])
                inset.add_from_vec(cf.mc().get_inst_reg_uses(n));
542
            }
543

544
            // out[n] <- union(in[s] for every successor s of n)
545 546 547 548 549 550 551
            {
                let ref mut outset = liveout[n];
                outset.clear();

                for s in cf.mc().get_succs(n) {
                    outset.add_all(livein[*s].clone());
                }
552
            }
553 554 555 556

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

557 558 559 560 561 562 563
            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
qinsoon committed
564

565 566 567
            is_changed = is_changed || n_changed;
        }
    }
568 569
}

570
// from Tailoring Graph-coloring Register Allocation For Runtime Compilation, Figure 4
571
pub fn build_chaitin_briggs (cf: &mut CompiledFunction, func: &MuFunctionVersion) -> InterferenceGraph {
572
    let _p = hprof::enter("regalloc: build live set");
qinsoon's avatar
qinsoon committed
573
    build_live_set(cf, func);
574 575 576
    drop(_p);

    let _p = hprof::enter("regalloc: build interference graph");
qinsoon's avatar
qinsoon committed
577 578

    info!("---start building interference graph---");
579
    
580 581 582
    let mut ig = InterferenceGraph::new();
    
    // precolor machine register nodes
583
    for reg in backend::all_regs().values() {
584 585
        let reg_id = reg.extract_ssa_id().unwrap();
        let node = ig.new_node(reg_id, &func.context);
586

qinsoon's avatar
qinsoon committed
587
        let precolor = backend::get_color_for_precolored(reg_id);
588 589

        ig.color_node(node, precolor);
590 591 592
    }
    
    // Initialize and creates nodes for all the involved temps/regs
qinsoon's avatar
qinsoon committed
593 594
    for i in 0..cf.mc().number_of_insts() {
        for reg_id in cf.mc().get_inst_reg_defines(i) {
595 596 597
            ig.new_node(reg_id, &func.context);
        }
        
qinsoon's avatar
qinsoon committed
598
        for reg_id in cf.mc().get_inst_reg_uses(i) {
599 600 601 602
            ig.new_node(reg_id, &func.context);
        }
    }
    
qinsoon's avatar
qinsoon committed
603
    for block in cf.mc().get_all_blocks() {
604
        // Current_Live(B) = LiveOut(B)
qinsoon's avatar
qinsoon committed
605
        let mut current_live = LinkedHashSet::from_vec(match cf.mc().get_ir_block_liveout(&block) {
606 607 608
            Some(liveout) => liveout.to_vec(),
            None => panic!("cannot find liveout for block {}", block)
        });
qinsoon's avatar
qinsoon committed
609 610 611 612 613 614
        if cfg!(debug_assertions) {
            trace!("Block{}: live out", block);
            for ele in current_live.iter() {
                trace!("{}", func.context.get_temp_display(*ele));
            }
        }
615
        
qinsoon's avatar
qinsoon committed
616
        let range = cf.mc().get_block_range(&block);
617
        if range.is_none() {
qinsoon's avatar
qinsoon committed
618
            warn!("Block{}: has no range (no instructions?)", block);
619 620
            continue;
        }
qinsoon's avatar
qinsoon committed
621
        trace!("Block{}: range = {:?}", block, range.as_ref().unwrap());
622 623 624
        
        // for every inst I in reverse order
        for i in range.unwrap().rev() {
qinsoon's avatar
qinsoon committed
625
            if cfg!(debug_assertions) {
qinsoon's avatar
qinsoon committed
626 627 628
                trace!("Block{}: Inst{}", block, i);
                cf.mc().trace_inst(i);
                trace!("current live: ");
qinsoon's avatar
qinsoon committed
629 630 631 632 633
                for ele in current_live.iter() {
                    trace!("{}", func.context.get_temp_display(*ele));
                }
            }

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

            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));
                }
            }
721 722
        }
    }
qinsoon's avatar
qinsoon committed
723

724
    drop(_p);
qinsoon's avatar
qinsoon committed
725
    info!("---finish building interference graph---");
726
    ig
727
}