aboutsummaryrefslogtreecommitdiffhomepage
path: root/third_party/checker_framework_dataflow/java/org/checkerframework/dataflow/cfg/CFGDOTVisualizer.java
blob: abd482122d8bfa5b5e4661603b1a90591a586c32 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
package org.checkerframework.dataflow.cfg;

/*>>>
import org.checkerframework.checker.nullness.qual.Nullable;
*/

import org.checkerframework.dataflow.analysis.AbstractValue;
import org.checkerframework.dataflow.analysis.Analysis;
import org.checkerframework.dataflow.analysis.Store;
import org.checkerframework.dataflow.analysis.TransferFunction;
import org.checkerframework.dataflow.analysis.TransferInput;
import org.checkerframework.dataflow.cfg.block.Block;
import org.checkerframework.dataflow.cfg.block.Block.BlockType;
import org.checkerframework.dataflow.cfg.block.ConditionalBlock;
import org.checkerframework.dataflow.cfg.block.ExceptionBlock;
import org.checkerframework.dataflow.cfg.block.RegularBlock;
import org.checkerframework.dataflow.cfg.block.SingleSuccessorBlock;
import org.checkerframework.dataflow.cfg.block.SpecialBlock;
import org.checkerframework.dataflow.cfg.node.Node;

import javax.lang.model.type.TypeMirror;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map.Entry;
import java.util.Queue;
import java.util.Set;

/**
 * Generate a graph description in the DOT language of a control graph.
 *
 * @author Stefan Heule
 *
 */
public class CFGDOTVisualizer {

    /**
     * Output a graph description in the DOT language, representing the control
     * flow graph starting at <code>entry</code>. Does not output verbose information
     * or stores at the beginning of basic blocks.
     *
     * @see #visualize(ControlFlowGraph, Block, Analysis, boolean)
     */
    public static String visualize(ControlFlowGraph cfg, Block entry) {
        return visualize(cfg, entry, null, false);
    }

    /**
     * Output a graph description in the DOT language, representing the control
     * flow graph starting at <code>entry</code>.
     *
     * @param entry
     *            The entry node of the control flow graph to be represented.
     * @param analysis
     *            An analysis containing information about the program
     *            represented by the CFG. The information includes {@link Store}
     *            s that are valid at the beginning of basic blocks reachable
     *            from <code>entry</code> and per-node information for value
     *            producing {@link Node}s. Can also be <code>null</code> to
     *            indicate that this information should not be output.
     * @param verbose
     *            Add more output to the CFG description.
     * @return String representation of the graph in the DOT language.
     */
    public static <A extends AbstractValue<A>, S extends Store<S>, T extends TransferFunction<A, S>> String visualize(
            ControlFlowGraph cfg,
            Block entry,
            /*@Nullable*/ Analysis<A, S, T> analysis,
            boolean verbose) {
        StringBuilder sb1 = new StringBuilder();
        StringBuilder sb2 = new StringBuilder();
        Set<Block> visited = new HashSet<>();
        Queue<Block> worklist = new LinkedList<>();
        Block cur = entry;
        visited.add(entry);

        // header
        sb1.append("digraph {\n");
        sb1.append("    node [shape=rectangle];\n\n");

        // traverse control flow graph and define all arrows
        while (true) {
            if (cur == null)
                break;

            if (cur.getType() == BlockType.CONDITIONAL_BLOCK) {
                ConditionalBlock ccur = ((ConditionalBlock) cur);
                Block thenSuccessor = ccur.getThenSuccessor();
                sb2.append("    " + ccur.getId() + " -> "
                        + thenSuccessor.getId());
                sb2.append(" [label=\"then\\n" + ccur.getThenFlowRule() + "\"];\n");
                if (!visited.contains(thenSuccessor)) {
                    visited.add(thenSuccessor);
                    worklist.add(thenSuccessor);
                }
                Block elseSuccessor = ccur.getElseSuccessor();
                sb2.append("    " + ccur.getId() + " -> "
                        + elseSuccessor.getId());
                sb2.append(" [label=\"else\\n" + ccur.getElseFlowRule() + "\"];\n");
                if (!visited.contains(elseSuccessor)) {
                    visited.add(elseSuccessor);
                    worklist.add(elseSuccessor);
                }
            } else {
                assert cur instanceof SingleSuccessorBlock;
                Block b = ((SingleSuccessorBlock) cur).getSuccessor();
                if (b != null) {
                    sb2.append("    " + cur.getId() + " -> " + b.getId());
                    sb2.append(" [label=\"" + ((SingleSuccessorBlock) cur).getFlowRule() + "\"];\n");
                    if (!visited.contains(b)) {
                        visited.add(b);
                        worklist.add(b);
                    }
                }
            }

            // exceptional edges
            if (cur.getType() == BlockType.EXCEPTION_BLOCK) {
                ExceptionBlock ecur = (ExceptionBlock) cur;
                for (Entry<TypeMirror, Set<Block>> e : ecur
                        .getExceptionalSuccessors().entrySet()) {
                    Set<Block> blocks = e.getValue();
                    TypeMirror cause = e.getKey();
                    String exception = cause.toString();
                    if (exception.startsWith("java.lang.")) {
                        exception = exception.replace("java.lang.", "");
                    }

                    for (Block b : blocks) {
                        sb2.append("    " + cur.getId() + " -> " + b.getId());
                        sb2.append(" [label=\"" + exception + "\"];\n");
                        if (!visited.contains(b)) {
                            visited.add(b);
                            worklist.add(b);
                        }
                    }
                }
            }

            cur = worklist.poll();
        }

        IdentityHashMap<Block, List<Integer>> processOrder = getProcessOrder(cfg);

        // definition of all nodes including their labels
        for (Block v : visited) {
            sb1.append("    " + v.getId() + " [");
            if (v.getType() == BlockType.CONDITIONAL_BLOCK) {
                sb1.append("shape=polygon sides=8 ");
            } else if (v.getType() == BlockType.SPECIAL_BLOCK) {
                sb1.append("shape=oval ");
            }
            sb1.append("label=\"");
            if (verbose) {
                sb1.append("Process order: " + processOrder.get(v).toString().replaceAll("[\\[\\]]", "") + "\\n");
            }
            sb1.append(visualizeContent(v, analysis, verbose).replace("\\n", "\\l")
                    + " \",];\n");
        }

        sb1.append("\n");
        sb1.append(sb2);

        // footer
        sb1.append("}\n");

        return sb1.toString();
    }

    private static IdentityHashMap<Block, List<Integer>> getProcessOrder(ControlFlowGraph cfg) {
        IdentityHashMap<Block, List<Integer>> depthFirstOrder = new IdentityHashMap<>();
        int count = 1;
        for (Block b : cfg.getDepthFirstOrderedBlocks()) {
            if (depthFirstOrder.get(b) == null) {
                depthFirstOrder.put(b, new ArrayList<Integer>());
            }
            depthFirstOrder.get(b).add(count++);
        }
        return depthFirstOrder;
    }

    /**
     * Produce a string representation of the contests of a basic block.
     *
     * @param bb
     *            Basic block to visualize.
     * @return String representation.
     */
    protected static <A extends AbstractValue<A>, S extends Store<S>, T extends TransferFunction<A, S>> String visualizeContent(
            Block bb,
            /*@Nullable*/ Analysis<A, S, T> analysis,
            boolean verbose) {

        StringBuilder sb = new StringBuilder();

        // loop over contents
        List<Node> contents = new LinkedList<>();
        switch (bb.getType()) {
        case REGULAR_BLOCK:
            contents.addAll(((RegularBlock) bb).getContents());
            break;
        case EXCEPTION_BLOCK:
            contents.add(((ExceptionBlock) bb).getNode());
            break;
        case CONDITIONAL_BLOCK:
            break;
        case SPECIAL_BLOCK:
            break;
        default:
            assert false : "All types of basic blocks covered";
        }
        boolean notFirst = false;
        for (Node t : contents) {
            if (notFirst) {
                sb.append("\\n");
            }
            notFirst = true;
            sb.append(prepareString(visualizeNode(t, analysis)));
        }

        // handle case where no contents are present
        boolean centered = false;
        if (sb.length() == 0) {
            centered = true;
            if (bb.getType() == BlockType.SPECIAL_BLOCK) {
                SpecialBlock sbb = (SpecialBlock) bb;
                switch (sbb.getSpecialType()) {
                case ENTRY:
                    sb.append("<entry>");
                    break;
                case EXIT:
                    sb.append("<exit>");
                    break;
                case EXCEPTIONAL_EXIT:
                    sb.append("<exceptional-exit>");
                    break;
                }
            } else if (bb.getType() == BlockType.CONDITIONAL_BLOCK) {
                return "";
            } else {
                return "?? empty ??";
            }
        }

        // visualize transfer input if necessary
        if (analysis != null) {
            TransferInput<A, S> input = analysis.getInput(bb);
            StringBuilder sb2 = new StringBuilder();

            // split input representation to two lines
            String s = input.toDOToutput().replace("}, else={", "}\\nelse={");
            sb2.append("Before:");
            sb2.append(s.subSequence(1, s.length() - 1));

            // separator
            sb2.append("\\n~~~~~~~~~\\n");
            sb2.append(sb);
            sb = sb2;

            if (verbose) {
                Node lastNode = null;
                switch (bb.getType()) {
                    case REGULAR_BLOCK:
                        List<Node> blockContents = ((RegularBlock) bb).getContents();
                        lastNode = contents.get(blockContents.size() - 1);
                        break;
                    case EXCEPTION_BLOCK:
                        lastNode = ((ExceptionBlock) bb).getNode();
                        break;
                }
                if (lastNode != null) {
                    sb2.append("\\n~~~~~~~~~\\n");
                    s = analysis.getResult().getStoreAfter(lastNode.getTree()).
                            toDOToutput().replace("}, else={", "}\\nelse={");
                    sb2.append("After:");
                    sb2.append(s);
                }
            }
        }

        return sb.toString() + (centered ? "" : "\\n");
    }

    protected static <A extends AbstractValue<A>, S extends Store<S>, T extends TransferFunction<A, S>>
    String visualizeNode(Node t, /*@Nullable*/ Analysis<A, S, T> analysis) {
        A value = analysis.getValue(t);
        String valueInfo = "";
        if (value != null) {
            valueInfo = "    > " + value.toString();
        }
        return t.toString() + "   [ " + visualizeType(t) + " ]" + valueInfo;
    }

    protected static String visualizeType(Node t) {
        String name = t.getClass().getSimpleName();
        return name.replace("Node", "");
    }

    protected static String prepareString(String s) {
        return s.replace("\"", "\\\"");
    }
}