gen_mov_phi.rs 16.9 KB
Newer Older
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
1
// Copyright 2017 The Australian National University
2
//
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
3 4 5
// 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
6
//
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
7
//     http://www.apache.org/licenses/LICENSE-2.0
8
//
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
9 10 11 12 13 14
// 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 17 18 19 20 21 22 23
use ast::ir::*;
use ast::ptr::*;
use ast::inst::*;
use vm::VM;

use compiler::CompilerPass;
use std::any::Any;

pub struct GenMovPhi {
24
    name: &'static str
25 26 27 28
}

impl GenMovPhi {
    pub fn new() -> GenMovPhi {
29
        GenMovPhi {
30
            name: "Generate Phi Moves"
31
        }
32 33 34 35 36
    }
}

struct IntermediateBlockInfo {
    blk_id: MuID,
37
    blk_name: MuName,
38
    target: MuID,
39
    from_args: Vec<P<TreeNode>>
40 41 42 43 44 45 46 47 48 49 50 51 52 53
}

impl CompilerPass for GenMovPhi {
    fn name(&self) -> &'static str {
        self.name
    }

    fn as_any(&self) -> &Any {
        self
    }

    fn visit_function(&mut self, vm: &VM, func: &mut MuFunctionVersion) {
        let mut f_content = func.content.take().unwrap();

qinsoon's avatar
qinsoon committed
54 55 56
        // we do this with two steps.
        // first step collects information about intermediate blocks
        // and second step inserts intermediate blocks
57
        let mut new_blocks_to_insert: Vec<IntermediateBlockInfo> = vec![];
58

qinsoon's avatar
qinsoon committed
59
        // first step - collects info on intermediate blocks
60 61 62 63
        for (blk_id, mut block) in f_content.blocks.iter_mut() {
            trace!("block: {}", blk_id);

            // old block content
qinsoon's avatar
qinsoon committed
64
            let block_content = block.content.as_ref().unwrap().clone();
65 66 67 68 69 70 71

            let mut new_body = vec![];

            let mut i = 0;
            let i_last = block_content.body.len() - 1;
            for node in block_content.body.iter() {
                if i != i_last {
qinsoon's avatar
qinsoon committed
72
                    // if this is last instruction, we simply copy it
73 74
                    new_body.push(node.clone());
                } else {
qinsoon's avatar
qinsoon committed
75 76
                    // otherwise, we need to check if we need to insert intermediate block
                    // and rewrite the inst
77 78 79 80
                    trace!("last instruction is {}", node);
                    let last_inst = node.clone();
                    match last_inst.v {
                        TreeNode_::Instruction(inst) => {
81
                            let ref ops = inst.ops;
82
                            let inst_name = inst.name().clone();
83
                            match inst.v {
84 85 86 87
                                Instruction_::Branch2 {
                                    cond,
                                    true_dest,
                                    false_dest,
88
                                    true_prob
89
                                } => {
qinsoon's avatar
qinsoon committed
90
                                    // check and insert intermediate blocks for true/false dest
91 92 93 94 95 96
                                    let true_dest = process_dest(
                                        true_dest,
                                        &mut new_blocks_to_insert,
                                        &ops,
                                        vm,
                                        &inst_name,
97
                                        "true"
98 99 100 101 102 103 104
                                    );
                                    let false_dest = process_dest(
                                        false_dest,
                                        &mut new_blocks_to_insert,
                                        &ops,
                                        vm,
                                        &inst_name,
105
                                        "false"
106
                                    );
107

qinsoon's avatar
qinsoon committed
108
                                    // rewrite the instruction
109
                                    let new_inst = func.new_inst(Instruction {
110 111
                                        hdr: inst.hdr.clone(),
                                        value: inst.value.clone(),
112
                                        ops: ops.to_vec(),
113 114 115 116
                                        v: Instruction_::Branch2 {
                                            cond: cond,
                                            true_dest: true_dest,
                                            false_dest: false_dest,
117 118
                                            true_prob: true_prob
                                        }
119 120 121 122 123
                                    });

                                    trace!("rewrite to {}", new_inst);
                                    new_body.push(new_inst);
                                }
124 125 126 127 128 129 130
                                Instruction_::Call { data, resume } => {
                                    let norm_dest = process_dest(
                                        resume.normal_dest,
                                        &mut new_blocks_to_insert,
                                        &ops,
                                        vm,
                                        &inst_name,
131
                                        "norm"
132 133 134 135 136 137 138
                                    );
                                    let exn_dest = process_dest(
                                        resume.exn_dest,
                                        &mut new_blocks_to_insert,
                                        &ops,
                                        vm,
                                        &inst_name,
139
                                        "exc"
140 141 142
                                    );

                                    let new_inst = func.new_inst(Instruction {
143 144
                                        hdr: inst.hdr.clone(),
                                        value: inst.value.clone(),
145
                                        ops: ops.to_vec(),
146 147
                                        v: Instruction_::Call {
                                            data: data.clone(),
148
                                            resume: ResumptionData {
149
                                                normal_dest: norm_dest,
150 151 152
                                                exn_dest: exn_dest
                                            }
                                        }
153 154 155 156 157
                                    });

                                    trace!("rewrite to {}", new_inst);
                                    new_body.push(new_inst);
                                }
158 159 160 161 162 163 164
                                Instruction_::CCall { data, resume } => {
                                    let norm_dest = process_dest(
                                        resume.normal_dest,
                                        &mut new_blocks_to_insert,
                                        &ops,
                                        vm,
                                        &inst_name,
165
                                        "norm"
166 167 168 169 170 171 172
                                    );
                                    let exn_dest = process_dest(
                                        resume.exn_dest,
                                        &mut new_blocks_to_insert,
                                        &ops,
                                        vm,
                                        &inst_name,
173
                                        "exc"
174 175 176
                                    );

                                    let new_inst = func.new_inst(Instruction {
177 178
                                        hdr: inst.hdr.clone(),
                                        value: inst.value.clone(),
179
                                        ops: ops.to_vec(),
180 181
                                        v: Instruction_::Call {
                                            data: data.clone(),
182
                                            resume: ResumptionData {
183
                                                normal_dest: norm_dest,
184 185 186
                                                exn_dest: exn_dest
                                            }
                                        }
187 188 189 190
                                    });

                                    trace!("rewrite to {}", new_inst);
                                    new_body.push(new_inst);
191 192 193 194
                                }
                                Instruction_::Switch {
                                    cond,
                                    default,
195
                                    mut branches
196 197 198 199 200 201 202
                                } => {
                                    let default_dest = process_dest(
                                        default,
                                        &mut new_blocks_to_insert,
                                        &ops,
                                        vm,
                                        &inst_name,
203
                                        "default"
204 205 206 207 208 209 210 211 212 213 214
                                    );

                                    let new_branches = branches
                                        .drain(..)
                                        .map(|pair| {
                                            let dest = process_dest(
                                                pair.1,
                                                &mut new_blocks_to_insert,
                                                &ops,
                                                vm,
                                                &inst_name,
215
                                                format!("case_{}", pair.0).as_str()
216 217 218 219 220 221
                                            );
                                            (pair.0, dest)
                                        })
                                        .collect();

                                    let new_inst = func.new_inst(Instruction {
222 223
                                        hdr: inst.hdr.clone(),
                                        value: inst.value.clone(),
224
                                        ops: ops.to_vec(),
225 226 227
                                        v: Instruction_::Switch {
                                            cond: cond,
                                            default: default_dest,
228 229
                                            branches: new_branches
                                        }
230 231 232 233 234
                                    });

                                    trace!("rewrite to {}", new_inst);
                                    new_body.push(new_inst);
                                }
235 236
                                Instruction_::Watchpoint { .. } => unimplemented!(),
                                Instruction_::WPBranch { .. } => unimplemented!(),
237 238 239 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
                                Instruction_::SwapStackExc { stack, is_exception, args, resume } => {
                                    let norm_dest = process_dest(
                                        resume.normal_dest,
                                        &mut new_blocks_to_insert,
                                        &ops,
                                        vm,
                                        &inst_name,
                                        "norm"
                                    );
                                    let exn_dest = process_dest(
                                        resume.exn_dest,
                                        &mut new_blocks_to_insert,
                                        &ops,
                                        vm,
                                        &inst_name,
                                        "exc"
                                    );

                                    let new_inst = func.new_inst(Instruction {
                                        hdr: inst.hdr.clone(),
                                        value: inst.value.clone(),
                                        ops: ops.to_vec(),
                                        v: Instruction_::SwapStackExc {
                                            stack: stack,
                                            is_exception: is_exception,
                                            args: args,
                                            resume: ResumptionData {
                                                normal_dest: norm_dest,
                                                exn_dest: exn_dest
                                            }
                                        }
                                    });

                                    trace!("rewrite to {}", new_inst);
                                    new_body.push(new_inst);
                                },
273
                                Instruction_::ExnInstruction { .. } => unimplemented!(),
274 275 276 277 278 279
                                _ => {
                                    trace!("no rewrite");
                                    new_body.push(node.clone())
                                }
                            }
                        }
280
                        _ => panic!("expect a terminal instruction")
281 282 283 284 285 286
                    }
                }

                i += 1;
            }

287 288 289 290
            block.content = Some(BlockContent {
                args: block_content.args.to_vec(),
                exn_arg: block_content.exn_arg.clone(),
                body: new_body,
291
                keepalives: block_content.keepalives.clone()
292 293 294
            });
        }

qinsoon's avatar
qinsoon committed
295
        // second step - insert new blocks
296
        for block_info in new_blocks_to_insert {
qinsoon's avatar
qinsoon committed
297
            // create intermediate block
298 299
            let block = {
                let target_id = block_info.target;
300 301
                let mut ret = Block::new(MuEntityHeader::named(
                    block_info.blk_id,
302
                    block_info.blk_name.clone()
303
                ));
304
                vm.set_name(ret.as_entity());
305

306
                let mut target_block = f_content.get_block_mut(target_id);
307 308
                assert!(target_block.content.is_some());

309 310 311
                // if target_block is an exception block,
                // set its exn argument to None, and set this new block as an exception block
                let exn_arg = target_block.content.as_mut().unwrap().exn_arg.take();
312 313
                let ref target_args = target_block.content.as_ref().unwrap().args;

314
                ret.content = Some(BlockContent {
315
                    args: vec![],
316
                    exn_arg: exn_arg,
317 318 319 320 321 322
                    body: {
                        let mut vec = vec![];

                        // move every from_arg to target_arg
                        let mut i = 0;
                        for arg in block_info.from_args.iter() {
323
                            let m = func.new_inst(Instruction {
324 325
                                hdr: MuEntityHeader::unnamed(vm.next_id()),
                                value: Some(vec![target_args[i].clone()]),
326
                                ops: vec![arg.clone()],
327
                                v: Instruction_::Move(0)
328 329 330 331 332 333 334 335
                            });

                            vec.push(m);

                            i += 1;
                        }

                        // branch to target
336
                        let b = func.new_inst(Instruction {
337 338
                            hdr: MuEntityHeader::unnamed(vm.next_id()),
                            value: None,
339
                            ops: vec![],
340
                            v: Instruction_::Branch1(Destination {
341
                                target: target_id,
342 343
                                args: vec![]
                            })
344 345 346 347 348
                        });
                        vec.push(b);

                        vec
                    },
349
                    keepalives: None
350 351 352 353 354 355 356 357 358 359
                });

                trace!("inserting new intermediate block: {:?}", ret);

                ret
            };

            f_content.blocks.insert(block.id(), block);
        }

360
        func.content = Some(f_content);
361 362 363
    }
}

qinsoon's avatar
qinsoon committed
364 365 366 367 368
/// returns the destination.
/// if the instruction passes any argument to its destination,
/// we need an intermediate block to move the arguments, return
/// the intermediate block as destination. Otherwise, return
/// the original destination
369 370 371 372 373 374
fn process_dest(
    dest: Destination,
    blocks_to_insert: &mut Vec<IntermediateBlockInfo>,
    ops: &Vec<P<TreeNode>>,
    vm: &VM,
    inst: &MuName,
375
    label: &str
376
) -> Destination {
377 378 379 380 381 382 383 384 385
    if dest.args.is_empty() {
        dest
    } else {
        let target = dest.target;

        let mut from_args = vec![];
        for arg in dest.args.iter() {
            let from_arg = match arg {
                &DestArg::Normal(i) => ops[i].clone(),
386
                &DestArg::Freshbound(_) => unimplemented!()
387 388 389
            };

            from_args.push(from_arg);
390
        }
391 392 393 394 395

        let new_blk_id = vm.next_id();

        let dest = Destination {
            target: new_blk_id,
396
            args: vec![]
397 398 399 400
        };

        blocks_to_insert.push(IntermediateBlockInfo {
            blk_id: new_blk_id,
401
            blk_name: format!("{}:{}:#{}-#{}", inst, label, new_blk_id, target),
402
            target: target,
403
            from_args: from_args
404 405 406 407
        });

        dest
    }
408
}