Skip to content

Commit

Permalink
add MergeBlock in SimplifyCFG
Browse files Browse the repository at this point in the history
  • Loading branch information
1024th committed Feb 5, 2023
1 parent 8d79716 commit 3a90099
Showing 1 changed file with 51 additions and 0 deletions.
51 changes: 51 additions & 0 deletions src/middleend/SimplifyCFG.java
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
package middleend;

import java.util.HashMap;
import java.util.HashSet;

import ir.BasicBlock;

/**
* <ul>
* <li>Merges a basic block into its predecessor if there is only one and the
* predecessor only has one successor.
* <li>Removes basic blocks with no predecessors.
* <li>Eliminates PHI nodes for basic blocks with a single predecessor.
*/
Expand All @@ -16,6 +19,10 @@ void runOnModule(ir.Module module) {

void runOnFunc(ir.Function func) {
boolean changed = true;
while (changed) {
new CFGBuilder().runOnFunc(func);
changed = mergeBlock(func);
}
while (changed) {
new CFGBuilder().runOnFunc(func);
changed = removeDeadBlock(func);
Expand Down Expand Up @@ -68,4 +75,48 @@ public void removePhiBranchIn(BasicBlock block, BasicBlock removed) {
}
}
}

boolean mergeBlock(ir.Function func) {
blockMoveMap.clear();
for (var pred : func.blocks) {
pred = getAlias(pred);
if (pred.nexts.size() != 1)
continue;
var succ = pred.nexts.get(0);
if (succ.prevs.size() != 1)
continue;
if (func.exitBlock == succ)
func.exitBlock = pred;
pred.insts.remove(pred.insts.size() - 1);
assert succ.phiInsts.isEmpty();
for (var sucInst : succ.insts) {
sucInst.parent = pred;
pred.insts.add(sucInst);
}
pred.nexts.clear();
pred.nexts.addAll(succ.nexts);
for (var suc : succ.nexts) {
suc.redirectPred(succ, pred);
}
blockMoveMap.put(succ, pred);
}
var iter = func.blocks.iterator();
while (iter.hasNext()) {
var block = iter.next();
if (blockMoveMap.containsKey(block))
iter.remove();
}
return blockMoveMap.size() != 0;
}

HashMap<BasicBlock, BasicBlock> blockMoveMap = new HashMap<>();

BasicBlock getAlias(BasicBlock block) {
var a = blockMoveMap.get(block);
if (a == null)
return block;
a = getAlias(a);
blockMoveMap.put(block, a);
return a;
}
}

0 comments on commit 3a90099

Please sign in to comment.