Enhance the GraphWriter support for edge destinations, and teach the
[oota-llvm.git] / lib / CodeGen / SelectionDAG / SelectionDAGPrinter.cpp
1 //===-- SelectionDAGPrinter.cpp - Implement SelectionDAG::viewGraph() -----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This implements the SelectionDAG::viewGraph method.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Constants.h"
15 #include "llvm/Function.h"
16 #include "llvm/Assembly/Writer.h"
17 #include "llvm/CodeGen/SelectionDAG.h"
18 #include "llvm/CodeGen/ScheduleDAG.h"
19 #include "llvm/CodeGen/MachineConstantPool.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineModuleInfo.h"
22 #include "llvm/CodeGen/PseudoSourceValue.h"
23 #include "llvm/Target/TargetRegisterInfo.h"
24 #include "llvm/Target/TargetMachine.h"
25 #include "llvm/Support/GraphWriter.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/Config/config.h"
28 #include <fstream>
29 #include <sstream>
30 using namespace llvm;
31
32 namespace llvm {
33   template<>
34   struct DOTGraphTraits<SelectionDAG*> : public DefaultDOTGraphTraits {
35     static bool hasEdgeDestLabels() {
36       return true;
37     }
38
39     static unsigned numEdgeDestLabels(const void *Node) {
40       return ((const SDNode *) Node)->getNumValues();
41     }
42
43     static std::string getEdgeDestLabel(const void *Node, unsigned i) {
44       return ((const SDNode *) Node)->getValueType(i).getMVTString();
45     }
46
47     /// edgeTargetsEdgeSource - This method returns true if this outgoing edge
48     /// should actually target another edge source, not a node.  If this method is
49     /// implemented, getEdgeTarget should be implemented.
50     template<typename EdgeIter>
51     static bool edgeTargetsEdgeSource(const void *Node, EdgeIter I) {
52       return true;
53     }
54
55     /// getEdgeTarget - If edgeTargetsEdgeSource returns true, this method is
56     /// called to determine which outgoing edge of Node is the target of this
57     /// edge.
58     template<typename EdgeIter>
59     static EdgeIter getEdgeTarget(const void *Node, EdgeIter I) {
60       SDNode *TargetNode = *I;
61       SDNodeIterator NI = SDNodeIterator::begin(TargetNode);
62       std::advance(NI, I.getNode()->getOperand(I.getOperand()).ResNo);
63       return NI;
64     }
65
66     static std::string getGraphName(const SelectionDAG *G) {
67       return G->getMachineFunction().getFunction()->getName();
68     }
69
70     static bool renderGraphFromBottomUp() {
71       return true;
72     }
73     
74     static bool hasNodeAddressLabel(const SDNode *Node,
75                                     const SelectionDAG *Graph) {
76       return true;
77     }
78     
79     /// If you want to override the dot attributes printed for a particular
80     /// edge, override this method.
81     template<typename EdgeIter>
82     static std::string getEdgeAttributes(const void *Node, EdgeIter EI) {
83       SDOperand Op = EI.getNode()->getOperand(EI.getOperand());
84       MVT VT = Op.getValueType();
85       if (VT == MVT::Flag)
86         return "color=red,style=bold";
87       else if (VT == MVT::Other)
88         return "color=blue,style=dashed";
89       return "";
90     }
91     
92
93     static std::string getNodeLabel(const SDNode *Node,
94                                     const SelectionDAG *Graph);
95     static std::string getNodeAttributes(const SDNode *N,
96                                          const SelectionDAG *Graph) {
97 #ifndef NDEBUG
98       const std::string &Attrs = Graph->getGraphAttrs(N);
99       if (!Attrs.empty()) {
100         if (Attrs.find("shape=") == std::string::npos)
101           return std::string("shape=Mrecord,") + Attrs;
102         else
103           return Attrs;
104       }
105 #endif
106       return "shape=Mrecord";
107     }
108
109     static void addCustomGraphFeatures(SelectionDAG *G,
110                                        GraphWriter<SelectionDAG*> &GW) {
111       GW.emitSimpleNode(0, "plaintext=circle", "GraphRoot");
112       if (G->getRoot().Val)
113         GW.emitEdge(0, -1, G->getRoot().Val, -1, "");
114     }
115   };
116 }
117
118 std::string DOTGraphTraits<SelectionDAG*>::getNodeLabel(const SDNode *Node,
119                                                         const SelectionDAG *G) {
120   std::string Op = Node->getOperationName(G);
121
122   if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(Node)) {
123     Op += ": " + utostr(CSDN->getValue());
124   } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(Node)) {
125     Op += ": " + ftostr(CSDN->getValueAPF());
126   } else if (const GlobalAddressSDNode *GADN =
127              dyn_cast<GlobalAddressSDNode>(Node)) {
128     int offset = GADN->getOffset();
129     Op += ": " + GADN->getGlobal()->getName();
130     if (offset > 0)
131       Op += "+" + itostr(offset);
132     else
133       Op += itostr(offset);
134   } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(Node)) {
135     Op += " " + itostr(FIDN->getIndex());
136   } else if (const JumpTableSDNode *JTDN = dyn_cast<JumpTableSDNode>(Node)) {
137     Op += " " + itostr(JTDN->getIndex());
138   } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Node)){
139     if (CP->isMachineConstantPoolEntry()) {
140       std::ostringstream SS;
141       CP->getMachineCPVal()->print(SS);
142       Op += "<" + SS.str() + ">";
143     } else {
144       if (ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
145         Op += "<" + ftostr(CFP->getValueAPF()) + ">";
146       else if (ConstantInt *CI = dyn_cast<ConstantInt>(CP->getConstVal()))
147         Op += "<" + utostr(CI->getZExtValue()) + ">";
148       else {
149         std::ostringstream SS;
150         WriteAsOperand(SS, CP->getConstVal(), false);
151         Op += "<" + SS.str() + ">";
152       }
153     }
154   } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(Node)) {
155     Op = "BB: ";
156     const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
157     if (LBB)
158       Op += LBB->getName();
159     //Op += " " + (const void*)BBDN->getBasicBlock();
160   } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(Node)) {
161     if (G && R->getReg() != 0 &&
162         TargetRegisterInfo::isPhysicalRegister(R->getReg())) {
163       Op = Op + " " +
164         G->getTarget().getRegisterInfo()->getName(R->getReg());
165     } else {
166       Op += " #" + utostr(R->getReg());
167     }
168   } else if (const DbgStopPointSDNode *D = dyn_cast<DbgStopPointSDNode>(Node)) {
169     Op += ": " + D->getCompileUnit()->getFileName();
170     Op += ":" + utostr(D->getLine());
171     if (D->getColumn() != 0)
172       Op += ":" + utostr(D->getColumn());
173   } else if (const LabelSDNode *L = dyn_cast<LabelSDNode>(Node)) {
174     Op += ": LabelID=" + utostr(L->getLabelID());
175   } else if (const ExternalSymbolSDNode *ES =
176              dyn_cast<ExternalSymbolSDNode>(Node)) {
177     Op += "'" + std::string(ES->getSymbol()) + "'";
178   } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(Node)) {
179     if (M->getValue())
180       Op += "<" + M->getValue()->getName() + ">";
181     else
182       Op += "<null>";
183   } else if (const MemOperandSDNode *M = dyn_cast<MemOperandSDNode>(Node)) {
184     const Value *V = M->MO.getValue();
185     Op += '<';
186     if (!V) {
187       Op += "(unknown)";
188     } else if (isa<PseudoSourceValue>(V)) {
189       // PseudoSourceValues don't have names, so use their print method.
190       std::ostringstream SS;
191       M->MO.getValue()->print(SS);
192       Op += SS.str();
193     } else {
194       Op += V->getName();
195     }
196     Op += '+' + itostr(M->MO.getOffset()) + '>';
197   } else if (const ARG_FLAGSSDNode *N = dyn_cast<ARG_FLAGSSDNode>(Node)) {
198     Op = Op + " AF=" + N->getArgFlags().getArgFlagsString();
199   } else if (const VTSDNode *N = dyn_cast<VTSDNode>(Node)) {
200     Op = Op + " VT=" + N->getVT().getMVTString();
201   } else if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(Node)) {
202     bool doExt = true;
203     switch (LD->getExtensionType()) {
204     default: doExt = false; break;
205     case ISD::EXTLOAD:
206       Op = Op + "<anyext ";
207       break;
208     case ISD::SEXTLOAD:
209       Op = Op + " <sext ";
210       break;
211     case ISD::ZEXTLOAD:
212       Op = Op + " <zext ";
213       break;
214     }
215     if (doExt)
216       Op += LD->getMemoryVT().getMVTString() + ">";
217     if (LD->isVolatile())
218       Op += "<V>";
219     Op += LD->getIndexedModeName(LD->getAddressingMode());
220     if (LD->getAlignment() > 1)
221       Op += " A=" + utostr(LD->getAlignment());
222   } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(Node)) {
223     if (ST->isTruncatingStore())
224       Op += "<trunc " + ST->getMemoryVT().getMVTString() + ">";
225     if (ST->isVolatile())
226       Op += "<V>";
227     Op += ST->getIndexedModeName(ST->getAddressingMode());
228     if (ST->getAlignment() > 1)
229       Op += " A=" + utostr(ST->getAlignment());
230   }
231
232 #if 0
233   Op += " Id=" + itostr(Node->getNodeId());
234 #endif
235   
236   return Op;
237 }
238
239
240 /// viewGraph - Pop up a ghostview window with the reachable parts of the DAG
241 /// rendered using 'dot'.
242 ///
243 void SelectionDAG::viewGraph(const std::string &Title) {
244 // This code is only for debugging!
245 #ifndef NDEBUG
246   ViewGraph(this, "dag." + getMachineFunction().getFunction()->getName(),
247             Title);
248 #else
249   cerr << "SelectionDAG::viewGraph is only available in debug builds on "
250        << "systems with Graphviz or gv!\n";
251 #endif  // NDEBUG
252 }
253
254
255 /// clearGraphAttrs - Clear all previously defined node graph attributes.
256 /// Intended to be used from a debugging tool (eg. gdb).
257 void SelectionDAG::clearGraphAttrs() {
258 #ifndef NDEBUG
259   NodeGraphAttrs.clear();
260 #else
261   cerr << "SelectionDAG::clearGraphAttrs is only available in debug builds"
262        << " on systems with Graphviz or gv!\n";
263 #endif
264 }
265
266
267 /// setGraphAttrs - Set graph attributes for a node. (eg. "color=red".)
268 ///
269 void SelectionDAG::setGraphAttrs(const SDNode *N, const char *Attrs) {
270 #ifndef NDEBUG
271   NodeGraphAttrs[N] = Attrs;
272 #else
273   cerr << "SelectionDAG::setGraphAttrs is only available in debug builds"
274        << " on systems with Graphviz or gv!\n";
275 #endif
276 }
277
278
279 /// getGraphAttrs - Get graph attributes for a node. (eg. "color=red".)
280 /// Used from getNodeAttributes.
281 const std::string SelectionDAG::getGraphAttrs(const SDNode *N) const {
282 #ifndef NDEBUG
283   std::map<const SDNode *, std::string>::const_iterator I =
284     NodeGraphAttrs.find(N);
285     
286   if (I != NodeGraphAttrs.end())
287     return I->second;
288   else
289     return "";
290 #else
291   cerr << "SelectionDAG::getGraphAttrs is only available in debug builds"
292        << " on systems with Graphviz or gv!\n";
293   return std::string("");
294 #endif
295 }
296
297 /// setGraphColor - Convenience for setting node color attribute.
298 ///
299 void SelectionDAG::setGraphColor(const SDNode *N, const char *Color) {
300 #ifndef NDEBUG
301   NodeGraphAttrs[N] = std::string("color=") + Color;
302 #else
303   cerr << "SelectionDAG::setGraphColor is only available in debug builds"
304        << " on systems with Graphviz or gv!\n";
305 #endif
306 }
307
308 namespace llvm {
309   template<>
310   struct DOTGraphTraits<ScheduleDAG*> : public DefaultDOTGraphTraits {
311     static std::string getGraphName(const ScheduleDAG *G) {
312       return DOTGraphTraits<SelectionDAG*>::getGraphName(&G->DAG);
313     }
314
315     static bool renderGraphFromBottomUp() {
316       return true;
317     }
318     
319     static bool hasNodeAddressLabel(const SUnit *Node,
320                                     const ScheduleDAG *Graph) {
321       return true;
322     }
323     
324     /// If you want to override the dot attributes printed for a particular
325     /// edge, override this method.
326     template<typename EdgeIter>
327     static std::string getEdgeAttributes(const void *Node, EdgeIter EI) {
328       if (EI.isSpecialDep())
329         return "color=cyan,style=dashed";
330       if (EI.isCtrlDep())
331         return "color=blue,style=dashed";
332       return "";
333     }
334     
335
336     static std::string getNodeLabel(const SUnit *Node,
337                                     const ScheduleDAG *Graph);
338     static std::string getNodeAttributes(const SUnit *N,
339                                          const ScheduleDAG *Graph) {
340       return "shape=Mrecord";
341     }
342
343     static void addCustomGraphFeatures(ScheduleDAG *G,
344                                        GraphWriter<ScheduleDAG*> &GW) {
345       GW.emitSimpleNode(0, "plaintext=circle", "GraphRoot");
346       const SDNode *N = G->DAG.getRoot().Val;
347       if (N && N->getNodeId() != -1)
348         GW.emitEdge(0, -1, &G->SUnits[N->getNodeId()], -1, "");
349     }
350   };
351 }
352
353 std::string DOTGraphTraits<ScheduleDAG*>::getNodeLabel(const SUnit *SU,
354                                                        const ScheduleDAG *G) {
355   std::string Op;
356
357   for (unsigned i = 0; i < SU->FlaggedNodes.size(); ++i) {
358     Op += DOTGraphTraits<SelectionDAG*>::getNodeLabel(SU->FlaggedNodes[i],
359                                                       &G->DAG) + "\n";
360   }
361
362   if (SU->Node)
363     Op += DOTGraphTraits<SelectionDAG*>::getNodeLabel(SU->Node, &G->DAG);
364   else
365     Op += "<CROSS RC COPY>";
366
367   return Op;
368 }
369
370
371 /// viewGraph - Pop up a ghostview window with the reachable parts of the DAG
372 /// rendered using 'dot'.
373 ///
374 void ScheduleDAG::viewGraph() {
375 // This code is only for debugging!
376 #ifndef NDEBUG
377   ViewGraph(this, "dag." + MF->getFunction()->getName(),
378             "Scheduling-Units Graph for " + MF->getFunction()->getName() + ':' +
379             BB->getBasicBlock()->getName());
380 #else
381   cerr << "ScheduleDAG::viewGraph is only available in debug builds on "
382        << "systems with Graphviz or gv!\n";
383 #endif  // NDEBUG
384 }