SelectionDAGPrinter.cpp revision 694caf56f15bec971d493069a1613a8f992f510a
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>
30using namespace llvm;
31
32namespace 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, G->getRoot().ResNo,
114                    "color=blue,style=dashed");
115    }
116  };
117}
118
119std::string DOTGraphTraits<SelectionDAG*>::getNodeLabel(const SDNode *Node,
120                                                        const SelectionDAG *G) {
121  std::string Op = Node->getOperationName(G);
122
123  if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(Node)) {
124    Op += ": " + utostr(CSDN->getValue());
125  } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(Node)) {
126    Op += ": " + ftostr(CSDN->getValueAPF());
127  } else if (const GlobalAddressSDNode *GADN =
128             dyn_cast<GlobalAddressSDNode>(Node)) {
129    int offset = GADN->getOffset();
130    Op += ": " + GADN->getGlobal()->getName();
131    if (offset > 0)
132      Op += "+" + itostr(offset);
133    else
134      Op += itostr(offset);
135  } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(Node)) {
136    Op += " " + itostr(FIDN->getIndex());
137  } else if (const JumpTableSDNode *JTDN = dyn_cast<JumpTableSDNode>(Node)) {
138    Op += " " + itostr(JTDN->getIndex());
139  } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Node)){
140    if (CP->isMachineConstantPoolEntry()) {
141      std::ostringstream SS;
142      CP->getMachineCPVal()->print(SS);
143      Op += "<" + SS.str() + ">";
144    } else {
145      if (ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
146        Op += "<" + ftostr(CFP->getValueAPF()) + ">";
147      else if (ConstantInt *CI = dyn_cast<ConstantInt>(CP->getConstVal()))
148        Op += "<" + utostr(CI->getZExtValue()) + ">";
149      else {
150        std::ostringstream SS;
151        WriteAsOperand(SS, CP->getConstVal(), false);
152        Op += "<" + SS.str() + ">";
153      }
154    }
155  } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(Node)) {
156    Op = "BB: ";
157    const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
158    if (LBB)
159      Op += LBB->getName();
160    //Op += " " + (const void*)BBDN->getBasicBlock();
161  } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(Node)) {
162    if (G && R->getReg() != 0 &&
163        TargetRegisterInfo::isPhysicalRegister(R->getReg())) {
164      Op = Op + " " +
165        G->getTarget().getRegisterInfo()->getName(R->getReg());
166    } else {
167      Op += " #" + utostr(R->getReg());
168    }
169  } else if (const DbgStopPointSDNode *D = dyn_cast<DbgStopPointSDNode>(Node)) {
170    Op += ": " + D->getCompileUnit()->getFileName();
171    Op += ":" + utostr(D->getLine());
172    if (D->getColumn() != 0)
173      Op += ":" + utostr(D->getColumn());
174  } else if (const LabelSDNode *L = dyn_cast<LabelSDNode>(Node)) {
175    Op += ": LabelID=" + utostr(L->getLabelID());
176  } else if (const ExternalSymbolSDNode *ES =
177             dyn_cast<ExternalSymbolSDNode>(Node)) {
178    Op += "'" + std::string(ES->getSymbol()) + "'";
179  } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(Node)) {
180    if (M->getValue())
181      Op += "<" + M->getValue()->getName() + ">";
182    else
183      Op += "<null>";
184  } else if (const MemOperandSDNode *M = dyn_cast<MemOperandSDNode>(Node)) {
185    const Value *V = M->MO.getValue();
186    Op += '<';
187    if (!V) {
188      Op += "(unknown)";
189    } else if (isa<PseudoSourceValue>(V)) {
190      // PseudoSourceValues don't have names, so use their print method.
191      std::ostringstream SS;
192      M->MO.getValue()->print(SS);
193      Op += SS.str();
194    } else {
195      Op += V->getName();
196    }
197    Op += '+' + itostr(M->MO.getOffset()) + '>';
198  } else if (const ARG_FLAGSSDNode *N = dyn_cast<ARG_FLAGSSDNode>(Node)) {
199    Op = Op + " AF=" + N->getArgFlags().getArgFlagsString();
200  } else if (const VTSDNode *N = dyn_cast<VTSDNode>(Node)) {
201    Op = Op + " VT=" + N->getVT().getMVTString();
202  } else if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(Node)) {
203    bool doExt = true;
204    switch (LD->getExtensionType()) {
205    default: doExt = false; break;
206    case ISD::EXTLOAD:
207      Op = Op + "<anyext ";
208      break;
209    case ISD::SEXTLOAD:
210      Op = Op + " <sext ";
211      break;
212    case ISD::ZEXTLOAD:
213      Op = Op + " <zext ";
214      break;
215    }
216    if (doExt)
217      Op += LD->getMemoryVT().getMVTString() + ">";
218    if (LD->isVolatile())
219      Op += "<V>";
220    Op += LD->getIndexedModeName(LD->getAddressingMode());
221    if (LD->getAlignment() > 1)
222      Op += " A=" + utostr(LD->getAlignment());
223  } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(Node)) {
224    if (ST->isTruncatingStore())
225      Op += "<trunc " + ST->getMemoryVT().getMVTString() + ">";
226    if (ST->isVolatile())
227      Op += "<V>";
228    Op += ST->getIndexedModeName(ST->getAddressingMode());
229    if (ST->getAlignment() > 1)
230      Op += " A=" + utostr(ST->getAlignment());
231  }
232
233#if 0
234  Op += " Id=" + itostr(Node->getNodeId());
235#endif
236
237  return Op;
238}
239
240
241/// viewGraph - Pop up a ghostview window with the reachable parts of the DAG
242/// rendered using 'dot'.
243///
244void SelectionDAG::viewGraph(const std::string &Title) {
245// This code is only for debugging!
246#ifndef NDEBUG
247  ViewGraph(this, "dag." + getMachineFunction().getFunction()->getName(),
248            Title);
249#else
250  cerr << "SelectionDAG::viewGraph is only available in debug builds on "
251       << "systems with Graphviz or gv!\n";
252#endif  // NDEBUG
253}
254
255
256/// clearGraphAttrs - Clear all previously defined node graph attributes.
257/// Intended to be used from a debugging tool (eg. gdb).
258void SelectionDAG::clearGraphAttrs() {
259#ifndef NDEBUG
260  NodeGraphAttrs.clear();
261#else
262  cerr << "SelectionDAG::clearGraphAttrs is only available in debug builds"
263       << " on systems with Graphviz or gv!\n";
264#endif
265}
266
267
268/// setGraphAttrs - Set graph attributes for a node. (eg. "color=red".)
269///
270void SelectionDAG::setGraphAttrs(const SDNode *N, const char *Attrs) {
271#ifndef NDEBUG
272  NodeGraphAttrs[N] = Attrs;
273#else
274  cerr << "SelectionDAG::setGraphAttrs is only available in debug builds"
275       << " on systems with Graphviz or gv!\n";
276#endif
277}
278
279
280/// getGraphAttrs - Get graph attributes for a node. (eg. "color=red".)
281/// Used from getNodeAttributes.
282const std::string SelectionDAG::getGraphAttrs(const SDNode *N) const {
283#ifndef NDEBUG
284  std::map<const SDNode *, std::string>::const_iterator I =
285    NodeGraphAttrs.find(N);
286
287  if (I != NodeGraphAttrs.end())
288    return I->second;
289  else
290    return "";
291#else
292  cerr << "SelectionDAG::getGraphAttrs is only available in debug builds"
293       << " on systems with Graphviz or gv!\n";
294  return std::string("");
295#endif
296}
297
298/// setGraphColor - Convenience for setting node color attribute.
299///
300void SelectionDAG::setGraphColor(const SDNode *N, const char *Color) {
301#ifndef NDEBUG
302  NodeGraphAttrs[N] = std::string("color=") + Color;
303#else
304  cerr << "SelectionDAG::setGraphColor is only available in debug builds"
305       << " on systems with Graphviz or gv!\n";
306#endif
307}
308
309namespace llvm {
310  template<>
311  struct DOTGraphTraits<ScheduleDAG*> : public DefaultDOTGraphTraits {
312    static std::string getGraphName(const ScheduleDAG *G) {
313      return DOTGraphTraits<SelectionDAG*>::getGraphName(&G->DAG);
314    }
315
316    static bool renderGraphFromBottomUp() {
317      return true;
318    }
319
320    static bool hasNodeAddressLabel(const SUnit *Node,
321                                    const ScheduleDAG *Graph) {
322      return true;
323    }
324
325    /// If you want to override the dot attributes printed for a particular
326    /// edge, override this method.
327    template<typename EdgeIter>
328    static std::string getEdgeAttributes(const void *Node, EdgeIter EI) {
329      if (EI.isSpecialDep())
330        return "color=cyan,style=dashed";
331      if (EI.isCtrlDep())
332        return "color=blue,style=dashed";
333      return "";
334    }
335
336
337    static std::string getNodeLabel(const SUnit *Node,
338                                    const ScheduleDAG *Graph);
339    static std::string getNodeAttributes(const SUnit *N,
340                                         const ScheduleDAG *Graph) {
341      return "shape=Mrecord";
342    }
343
344    static void addCustomGraphFeatures(ScheduleDAG *G,
345                                       GraphWriter<ScheduleDAG*> &GW) {
346      GW.emitSimpleNode(0, "plaintext=circle", "GraphRoot");
347      const SDNode *N = G->DAG.getRoot().Val;
348      if (N && N->getNodeId() != -1)
349        GW.emitEdge(0, -1, &G->SUnits[N->getNodeId()], -1, "");
350    }
351  };
352}
353
354std::string DOTGraphTraits<ScheduleDAG*>::getNodeLabel(const SUnit *SU,
355                                                       const ScheduleDAG *G) {
356  std::string Op;
357
358  for (unsigned i = 0; i < SU->FlaggedNodes.size(); ++i) {
359    Op += DOTGraphTraits<SelectionDAG*>::getNodeLabel(SU->FlaggedNodes[i],
360                                                      &G->DAG) + "\n";
361  }
362
363  if (SU->Node)
364    Op += DOTGraphTraits<SelectionDAG*>::getNodeLabel(SU->Node, &G->DAG);
365  else
366    Op += "<CROSS RC COPY>";
367
368  return Op;
369}
370
371
372/// viewGraph - Pop up a ghostview window with the reachable parts of the DAG
373/// rendered using 'dot'.
374///
375void ScheduleDAG::viewGraph() {
376// This code is only for debugging!
377#ifndef NDEBUG
378  ViewGraph(this, "dag." + MF->getFunction()->getName(),
379            "Scheduling-Units Graph for " + MF->getFunction()->getName() + ':' +
380            BB->getBasicBlock()->getName());
381#else
382  cerr << "ScheduleDAG::viewGraph is only available in debug builds on "
383       << "systems with Graphviz or gv!\n";
384#endif  // NDEBUG
385}
386