blob: 35bff565a1f0129be14ab1ad8b8f16d7075beaf7 [file] [log] [blame]
Chris Lattnerac859db2002-10-07 18:38:01 +00001//===- GraphPrinters.cpp - DOT printers for various graph types -----------===//
2//
3// This file defines several printers for various different types of graphs used
4// by the LLVM infrastructure. It uses the generic graph interface to convert
5// the graph into a .dot graph. These graphs can then be processed with the
6// "dot" tool to convert them to postscript or some other suitable format.
7//
8//===----------------------------------------------------------------------===//
9
10#include "Support/GraphWriter.h"
11#include "llvm/Pass.h"
12#include "llvm/iTerminators.h"
13#include "llvm/Support/CFG.h"
14#include <sstream>
15#include <fstream>
16
17template<>
18struct DOTGraphTraits<Function*> : public DefaultDOTGraphTraits {
19 static std::string getGraphName(Function *F) {
20 return "CFG for '" + F->getName() + "' function";
21 }
22
23 static std::string getNodeLabel(BasicBlock *Node, Function *Graph) {
24 std::ostringstream Out;
25 Out << Node;
26 std::string OutStr = Out.str();
27 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
28
29 // Process string output to make it nicer...
30 for (unsigned i = 0; i != OutStr.length(); ++i)
31 if (OutStr[i] == '\n') { // Left justify
32 OutStr[i] = '\\';
33 OutStr.insert(OutStr.begin()+i+1, 'l');
34 } else if (OutStr[i] == ';') { // Delete comments!
35 unsigned Idx = OutStr.find('\n', i+1); // Find end of line
36 OutStr.erase(OutStr.begin()+i, OutStr.begin()+Idx);
37 --i;
38 }
39
40 return OutStr;
41 }
42
43 static std::string getNodeAttributes(BasicBlock *N) {
44 return "fontname=Courier";
45 }
46
47 static std::string getEdgeSourceLabel(BasicBlock *Node, succ_iterator I) {
48 // Label source of conditional branches with "T" or "F"
49 if (BranchInst *BI = dyn_cast<BranchInst>(Node->getTerminator()))
50 if (BI->isConditional())
51 return (I == succ_begin(Node)) ? "T" : "F";
52 return "";
53 }
54};
55
56template<typename GraphType>
57static void WriteGraphToFile(std::ostream &O, const std::string &GraphName,
58 const GraphType &GT) {
59 std::string Filename = GraphName + ".dot";
60 O << "Writing '" << Filename << "'...";
61 std::ofstream F(Filename.c_str());
62
63 if (F.good())
64 WriteGraph(F, GT);
65 else
66 O << " error opening file for writing!";
67 O << "\n";
68}
69
70
71namespace {
72 struct CFGPrinter : public FunctionPass {
73 Function *F;
74 virtual bool runOnFunction(Function &Func) {
75 WriteGraphToFile(std::cerr, "cfg."+Func.getName(), &Func);
76 return false;
77 }
78
79 void print(std::ostream &OS) const {}
80
81 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
82 AU.setPreservesAll();
83 }
84 };
85
86 RegisterAnalysis<CFGPrinter> P1("print-cfg",
87 "Print CFG of function to 'dot' file");
88};