|
| 1 | +package com.compilerprogramming.ezlang.compiler; |
| 2 | + |
| 3 | +import com.compilerprogramming.ezlang.compiler.codegen.CodeGen; |
| 4 | +import com.compilerprogramming.ezlang.compiler.node.Node; |
| 5 | +import com.compilerprogramming.ezlang.compiler.node.StopNode; |
| 6 | + |
| 7 | +import java.util.ArrayList; |
| 8 | +import java.util.BitSet; |
| 9 | +import java.util.List; |
| 10 | +import java.util.function.Consumer; |
| 11 | + |
| 12 | +public class IterPeeps2 { |
| 13 | + |
| 14 | + static void dfs(Node root, Consumer<Node> consumer, BitSet visited) { |
| 15 | + visited.set(root._nid); |
| 16 | + /* For each successor node */ |
| 17 | + for (int i = 0; i < root.nOuts(); i++) { |
| 18 | + Node S = root.out(i); |
| 19 | + if (S == null) |
| 20 | + continue; |
| 21 | + if (!visited.get(S._nid)) |
| 22 | + dfs(S, consumer, visited); |
| 23 | + } |
| 24 | + consumer.accept(root); |
| 25 | + } |
| 26 | + |
| 27 | + public static List<Node> rpo(Node root) { |
| 28 | + List<Node> nodes = new ArrayList<>(); |
| 29 | + // note add below prepends |
| 30 | + dfs(root, (n)->nodes.add(0,n), new BitSet()); |
| 31 | + return nodes; |
| 32 | + } |
| 33 | + |
| 34 | + public void iterate(CodeGen code) { |
| 35 | + final Node startNode = code._start; // We need the start node to get to the full graph |
| 36 | + int iter = 1; |
| 37 | + int count = 0; // Count of nodes we peepholed |
| 38 | + for (;;iter++) { |
| 39 | + List<Node> rpos = rpo(startNode); |
| 40 | + count += rpos.size(); |
| 41 | + boolean progress = false; |
| 42 | + for (int i = 0; i < rpos.size(); i++) { |
| 43 | + Node n = rpos.get(i); |
| 44 | + if (n.isDead()) continue; |
| 45 | + Node x = n.peepholeOpt(); |
| 46 | + if (x != null) { |
| 47 | + progress = true; |
| 48 | + if (x.isDead()) continue; |
| 49 | + // peepholeOpt can return brand-new nodes, needing an initial type set |
| 50 | + if( x._type==null ) x.setType(x.compute()); |
| 51 | + if (x != n) n.subsume(x); |
| 52 | + } |
| 53 | + if( n.isUnused() && !(n instanceof StopNode) ) |
| 54 | + n.kill(); // Just plain dead |
| 55 | + } |
| 56 | + if (!progress) break; |
| 57 | + } |
| 58 | + System.out.println("Completed in " + iter + " iterations; peepholed " + count + " nodes"); |
| 59 | +// if( show ) |
| 60 | +// System.out.println(new GraphVisualizer().generateDotOutput(stopNode,null,null)); |
| 61 | + } |
| 62 | +} |
0 commit comments