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