Fix printing of PseudoSourceValues in SDNode graphs.
[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/ScheduleDAGSDNodes.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/Debug.h"
26 #include "llvm/Support/GraphWriter.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/ADT/DenseSet.h"
29 #include "llvm/ADT/StringExtras.h"
30 #include "llvm/Config/config.h"
31 #include <fstream>
32 using namespace llvm;
33
34 namespace llvm {
35   template<>
36   struct DOTGraphTraits<SelectionDAG*> : public DefaultDOTGraphTraits {
37     static bool hasEdgeDestLabels() {
38       return true;
39     }
40
41     static unsigned numEdgeDestLabels(const void *Node) {
42       return ((const SDNode *) Node)->getNumValues();
43     }
44
45     static std::string getEdgeDestLabel(const void *Node, unsigned i) {
46       return ((const SDNode *) Node)->getValueType(i).getMVTString();
47     }
48
49     /// edgeTargetsEdgeSource - This method returns true if this outgoing edge
50     /// should actually target another edge source, not a node.  If this method is
51     /// implemented, getEdgeTarget should be implemented.
52     template<typename EdgeIter>
53     static bool edgeTargetsEdgeSource(const void *Node, EdgeIter I) {
54       return true;
55     }
56
57     /// getEdgeTarget - If edgeTargetsEdgeSource returns true, this method is
58     /// called to determine which outgoing edge of Node is the target of this
59     /// edge.
60     template<typename EdgeIter>
61     static EdgeIter getEdgeTarget(const void *Node, EdgeIter I) {
62       SDNode *TargetNode = *I;
63       SDNodeIterator NI = SDNodeIterator::begin(TargetNode);
64       std::advance(NI, I.getNode()->getOperand(I.getOperand()).getResNo());
65       return NI;
66     }
67
68     static std::string getGraphName(const SelectionDAG *G) {
69       return G->getMachineFunction().getFunction()->getName();
70     }
71
72     static bool renderGraphFromBottomUp() {
73       return true;
74     }
75     
76     static bool hasNodeAddressLabel(const SDNode *Node,
77                                     const SelectionDAG *Graph) {
78       return true;
79     }
80     
81     /// If you want to override the dot attributes printed for a particular
82     /// edge, override this method.
83     template<typename EdgeIter>
84     static std::string getEdgeAttributes(const void *Node, EdgeIter EI) {
85       SDValue Op = EI.getNode()->getOperand(EI.getOperand());
86       MVT VT = Op.getValueType();
87       if (VT == MVT::Flag)
88         return "color=red,style=bold";
89       else if (VT == MVT::Other)
90         return "color=blue,style=dashed";
91       return "";
92     }
93     
94
95     static std::string getNodeLabel(const SDNode *Node,
96                                     const SelectionDAG *Graph);
97     static std::string getNodeAttributes(const SDNode *N,
98                                          const SelectionDAG *Graph) {
99 #ifndef NDEBUG
100       const std::string &Attrs = Graph->getGraphAttrs(N);
101       if (!Attrs.empty()) {
102         if (Attrs.find("shape=") == std::string::npos)
103           return std::string("shape=Mrecord,") + Attrs;
104         else
105           return Attrs;
106       }
107 #endif
108       return "shape=Mrecord";
109     }
110
111     static void addCustomGraphFeatures(SelectionDAG *G,
112                                        GraphWriter<SelectionDAG*> &GW) {
113       GW.emitSimpleNode(0, "plaintext=circle", "GraphRoot");
114       if (G->getRoot().getNode())
115         GW.emitEdge(0, -1, G->getRoot().getNode(), G->getRoot().getResNo(),
116                     "color=blue,style=dashed");
117     }
118   };
119 }
120
121 std::string DOTGraphTraits<SelectionDAG*>::getNodeLabel(const SDNode *Node,
122                                                         const SelectionDAG *G) {
123   std::string Op = Node->getOperationName(G);
124
125   if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(Node)) {
126     Op += ": " + utostr(CSDN->getZExtValue());
127   } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(Node)) {
128     Op += ": " + ftostr(CSDN->getValueAPF());
129   } else if (const GlobalAddressSDNode *GADN =
130              dyn_cast<GlobalAddressSDNode>(Node)) {
131     Op += ": " + GADN->getGlobal()->getName();
132     if (int64_t Offset = GADN->getOffset()) {
133       if (Offset > 0)
134         Op += "+" + itostr(Offset);
135       else
136         Op += itostr(Offset);
137     }
138   } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(Node)) {
139     Op += " " + itostr(FIDN->getIndex());
140   } else if (const JumpTableSDNode *JTDN = dyn_cast<JumpTableSDNode>(Node)) {
141     Op += " " + itostr(JTDN->getIndex());
142   } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Node)){
143     if (CP->isMachineConstantPoolEntry()) {
144       Op += '<';
145       {
146         raw_string_ostream OSS(Op);
147         OSS << *CP->getMachineCPVal();
148       }
149       Op += '>';
150     } else {
151       if (ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
152         Op += "<" + ftostr(CFP->getValueAPF()) + ">";
153       else if (ConstantInt *CI = dyn_cast<ConstantInt>(CP->getConstVal()))
154         Op += "<" + utostr(CI->getZExtValue()) + ">";
155       else {
156         Op += '<';
157         {
158           raw_string_ostream OSS(Op);
159           WriteAsOperand(OSS, CP->getConstVal(), false);
160         }
161         Op += '>';
162       }
163     }
164     Op += " A=" + itostr(1 << CP->getAlignment());
165   } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(Node)) {
166     Op = "BB: ";
167     const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
168     if (LBB)
169       Op += LBB->getName();
170     //Op += " " + (const void*)BBDN->getBasicBlock();
171   } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(Node)) {
172     if (G && R->getReg() != 0 &&
173         TargetRegisterInfo::isPhysicalRegister(R->getReg())) {
174       Op = Op + " " +
175         G->getTarget().getRegisterInfo()->getName(R->getReg());
176     } else {
177       Op += " #" + utostr(R->getReg());
178     }
179   } else if (const DbgStopPointSDNode *D = dyn_cast<DbgStopPointSDNode>(Node)) {
180     Op += ": " + D->getCompileUnit()->getFileName();
181     Op += ":" + utostr(D->getLine());
182     if (D->getColumn() != 0)
183       Op += ":" + utostr(D->getColumn());
184   } else if (const LabelSDNode *L = dyn_cast<LabelSDNode>(Node)) {
185     Op += ": LabelID=" + utostr(L->getLabelID());
186   } else if (const CallSDNode *C = dyn_cast<CallSDNode>(Node)) {
187     Op += ": CallingConv=" + utostr(C->getCallingConv());
188     if (C->isVarArg())
189       Op += ", isVarArg";
190     if (C->isTailCall())
191       Op += ", isTailCall";
192   } else if (const ExternalSymbolSDNode *ES =
193              dyn_cast<ExternalSymbolSDNode>(Node)) {
194     Op += "'" + std::string(ES->getSymbol()) + "'";
195   } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(Node)) {
196     if (M->getValue())
197       Op += "<" + M->getValue()->getName() + ">";
198     else
199       Op += "<null>";
200   } else if (const MemOperandSDNode *M = dyn_cast<MemOperandSDNode>(Node)) {
201     const Value *V = M->MO.getValue();
202     Op += '<';
203     if (!V) {
204       Op += "(unknown)";
205     } else if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V)) {
206       // PseudoSourceValues don't have names, so use their print method.
207       raw_string_ostream OSS(Op);
208       PSV->print(OSS);
209     } else {
210       Op += V->getName();
211     }
212     Op += '+' + itostr(M->MO.getOffset()) + '>';
213   } else if (const ARG_FLAGSSDNode *N = dyn_cast<ARG_FLAGSSDNode>(Node)) {
214     Op = Op + " AF=" + N->getArgFlags().getArgFlagsString();
215   } else if (const VTSDNode *N = dyn_cast<VTSDNode>(Node)) {
216     Op = Op + " VT=" + N->getVT().getMVTString();
217   } else if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(Node)) {
218     bool doExt = true;
219     switch (LD->getExtensionType()) {
220     default: doExt = false; break;
221     case ISD::EXTLOAD:
222       Op = Op + "<anyext ";
223       break;
224     case ISD::SEXTLOAD:
225       Op = Op + " <sext ";
226       break;
227     case ISD::ZEXTLOAD:
228       Op = Op + " <zext ";
229       break;
230     }
231     if (doExt)
232       Op += LD->getMemoryVT().getMVTString() + ">";
233     if (LD->isVolatile())
234       Op += "<V>";
235     Op += LD->getIndexedModeName(LD->getAddressingMode());
236     if (LD->getAlignment() > 1)
237       Op += " A=" + utostr(LD->getAlignment());
238   } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(Node)) {
239     if (ST->isTruncatingStore())
240       Op += "<trunc " + ST->getMemoryVT().getMVTString() + ">";
241     if (ST->isVolatile())
242       Op += "<V>";
243     Op += ST->getIndexedModeName(ST->getAddressingMode());
244     if (ST->getAlignment() > 1)
245       Op += " A=" + utostr(ST->getAlignment());
246   }
247
248 #if 0
249   Op += " Id=" + itostr(Node->getNodeId());
250 #endif
251   
252   return Op;
253 }
254
255
256 /// viewGraph - Pop up a ghostview window with the reachable parts of the DAG
257 /// rendered using 'dot'.
258 ///
259 void SelectionDAG::viewGraph(const std::string &Title) {
260 // This code is only for debugging!
261 #ifndef NDEBUG
262   ViewGraph(this, "dag." + getMachineFunction().getFunction()->getName(),
263             Title);
264 #else
265   cerr << "SelectionDAG::viewGraph is only available in debug builds on "
266        << "systems with Graphviz or gv!\n";
267 #endif  // NDEBUG
268 }
269
270 // This overload is defined out-of-line here instead of just using a
271 // default parameter because this is easiest for gdb to call.
272 void SelectionDAG::viewGraph() {
273   viewGraph("");
274 }
275
276 /// clearGraphAttrs - Clear all previously defined node graph attributes.
277 /// Intended to be used from a debugging tool (eg. gdb).
278 void SelectionDAG::clearGraphAttrs() {
279 #ifndef NDEBUG
280   NodeGraphAttrs.clear();
281 #else
282   cerr << "SelectionDAG::clearGraphAttrs is only available in debug builds"
283        << " on systems with Graphviz or gv!\n";
284 #endif
285 }
286
287
288 /// setGraphAttrs - Set graph attributes for a node. (eg. "color=red".)
289 ///
290 void SelectionDAG::setGraphAttrs(const SDNode *N, const char *Attrs) {
291 #ifndef NDEBUG
292   NodeGraphAttrs[N] = Attrs;
293 #else
294   cerr << "SelectionDAG::setGraphAttrs is only available in debug builds"
295        << " on systems with Graphviz or gv!\n";
296 #endif
297 }
298
299
300 /// getGraphAttrs - Get graph attributes for a node. (eg. "color=red".)
301 /// Used from getNodeAttributes.
302 const std::string SelectionDAG::getGraphAttrs(const SDNode *N) const {
303 #ifndef NDEBUG
304   std::map<const SDNode *, std::string>::const_iterator I =
305     NodeGraphAttrs.find(N);
306     
307   if (I != NodeGraphAttrs.end())
308     return I->second;
309   else
310     return "";
311 #else
312   cerr << "SelectionDAG::getGraphAttrs is only available in debug builds"
313        << " on systems with Graphviz or gv!\n";
314   return std::string("");
315 #endif
316 }
317
318 /// setGraphColor - Convenience for setting node color attribute.
319 ///
320 void SelectionDAG::setGraphColor(const SDNode *N, const char *Color) {
321 #ifndef NDEBUG
322   NodeGraphAttrs[N] = std::string("color=") + Color;
323 #else
324   cerr << "SelectionDAG::setGraphColor is only available in debug builds"
325        << " on systems with Graphviz or gv!\n";
326 #endif
327 }
328
329 /// setSubgraphColorHelper - Implement setSubgraphColor.  Return
330 /// whether we truncated the search.
331 ///
332 bool SelectionDAG::setSubgraphColorHelper(SDNode *N, const char *Color, DenseSet<SDNode *> &visited,
333                                           int level, bool &printed) {
334   bool hit_limit = false;
335
336 #ifndef NDEBUG
337   if (level >= 20) {
338     if (!printed) {
339       printed = true;
340       DOUT << "setSubgraphColor hit max level\n";
341     }
342     return true;
343   }
344
345   unsigned oldSize = visited.size();
346   visited.insert(N);
347   if (visited.size() != oldSize) {
348     setGraphColor(N, Color);
349     for(SDNodeIterator i = SDNodeIterator::begin(N), iend = SDNodeIterator::end(N);
350         i != iend;
351         ++i) {
352       hit_limit = setSubgraphColorHelper(*i, Color, visited, level+1, printed) || hit_limit;
353     }
354   }
355 #else
356   cerr << "SelectionDAG::setSubgraphColor is only available in debug builds"
357        << " on systems with Graphviz or gv!\n";
358 #endif
359   return hit_limit;
360 }
361
362 /// setSubgraphColor - Convenience for setting subgraph color attribute.
363 ///
364 void SelectionDAG::setSubgraphColor(SDNode *N, const char *Color) {
365 #ifndef NDEBUG
366   DenseSet<SDNode *> visited;
367   bool printed = false;
368   if (setSubgraphColorHelper(N, Color, visited, 0, printed)) {
369     // Visually mark that we hit the limit
370     if (strcmp(Color, "red") == 0) {
371       setSubgraphColorHelper(N, "blue", visited, 0, printed);
372     }
373     else if (strcmp(Color, "yellow") == 0) {
374       setSubgraphColorHelper(N, "green", visited, 0, printed);
375     }
376   }
377
378 #else
379   cerr << "SelectionDAG::setSubgraphColor is only available in debug builds"
380        << " on systems with Graphviz or gv!\n";
381 #endif
382 }
383
384 std::string ScheduleDAGSDNodes::getGraphNodeLabel(const SUnit *SU) const {
385   std::string s;
386   raw_string_ostream O(s);
387   O << "SU(" << SU->NodeNum << "): ";
388   if (SU->getNode()) {
389     SmallVector<SDNode *, 4> FlaggedNodes;
390     for (SDNode *N = SU->getNode(); N; N = N->getFlaggedNode())
391       FlaggedNodes.push_back(N);
392     while (!FlaggedNodes.empty()) {
393       O << DOTGraphTraits<SelectionDAG*>::getNodeLabel(FlaggedNodes.back(), DAG);
394       FlaggedNodes.pop_back();
395       if (!FlaggedNodes.empty())
396         O << "\n    ";
397     }
398   } else {
399     O << "CROSS RC COPY";
400   }
401   return O.str();
402 }
403
404 void ScheduleDAGSDNodes::getCustomGraphFeatures(GraphWriter<ScheduleDAG*> &GW) const {
405   if (DAG) {
406     // Draw a special "GraphRoot" node to indicate the root of the graph.
407     GW.emitSimpleNode(0, "plaintext=circle", "GraphRoot");
408     const SDNode *N = DAG->getRoot().getNode();
409     if (N && N->getNodeId() != -1)
410       GW.emitEdge(0, -1, &SUnits[N->getNodeId()], -1,
411                   "color=blue,style=dashed");
412   }
413 }