73664028cad1766a6ec19a30b3b0beb3bbf20956
[oota-llvm.git] / tools / llvmc2 / CompilationGraph.cpp
1 //===--- CompilationGraph.cpp - The LLVM Compiler Driver --------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open
6 // Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  Compilation graph - implementation.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "CompilationGraph.h"
15
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/Support/CommandLine.h"
18 #include "llvm/Support/DOTGraphTraits.h"
19 #include "llvm/Support/GraphWriter.h"
20
21 #include <algorithm>
22 #include <iterator>
23 #include <limits>
24 #include <queue>
25 #include <stdexcept>
26
27 using namespace llvm;
28 using namespace llvmc;
29
30 extern cl::list<std::string> InputFilenames;
31 extern cl::opt<std::string> OutputFilename;
32 extern cl::list<std::string> Languages;
33
34 namespace {
35
36   // Return the edge with the maximum weight.
37   template <class C>
38   const Edge* ChooseEdge(const C& EdgesContainer,
39                          const InputLanguagesSet& InLangs,
40                          const std::string& NodeName = "root") {
41     const Edge* MaxEdge = 0;
42     unsigned MaxWeight = 0;
43     bool SingleMax = true;
44
45     for (typename C::const_iterator B = EdgesContainer.begin(),
46            E = EdgesContainer.end(); B != E; ++B) {
47       const Edge* E = B->getPtr();
48       unsigned EW = E->Weight(InLangs);
49       if (EW > MaxWeight) {
50         MaxEdge = E;
51         MaxWeight = EW;
52         SingleMax = true;
53       }
54       else if (EW == MaxWeight) {
55         SingleMax = false;
56       }
57     }
58
59     if (!SingleMax)
60       throw std::runtime_error("Node " + NodeName +
61                                ": multiple maximal outward edges found!"
62                                " Most probably a specification error.");
63     if (!MaxEdge)
64       throw std::runtime_error("Node " + NodeName +
65                                ": no maximal outward edge found!"
66                                " Most probably a specification error.");
67     return MaxEdge;
68   }
69
70 }
71
72 CompilationGraph::CompilationGraph() {
73   NodesMap["root"] = Node(this);
74 }
75
76 Node& CompilationGraph::getNode(const std::string& ToolName) {
77   nodes_map_type::iterator I = NodesMap.find(ToolName);
78   if (I == NodesMap.end())
79     throw std::runtime_error("Node " + ToolName + " is not in the graph");
80   return I->second;
81 }
82
83 const Node& CompilationGraph::getNode(const std::string& ToolName) const {
84   nodes_map_type::const_iterator I = NodesMap.find(ToolName);
85   if (I == NodesMap.end())
86     throw std::runtime_error("Node " + ToolName + " is not in the graph!");
87   return I->second;
88 }
89
90 // Find the language name corresponding to the given file.
91 const std::string& CompilationGraph::getLanguage(const sys::Path& File) const {
92   LanguageMap::const_iterator Lang = ExtsToLangs.find(File.getSuffix());
93   if (Lang == ExtsToLangs.end())
94     throw std::runtime_error("Unknown suffix: " + File.getSuffix() + '!');
95   return Lang->second;
96 }
97
98 // Find the tools list corresponding to the given language name.
99 const CompilationGraph::tools_vector_type&
100 CompilationGraph::getToolsVector(const std::string& LangName) const
101 {
102   tools_map_type::const_iterator I = ToolsMap.find(LangName);
103   if (I == ToolsMap.end())
104     throw std::runtime_error("No tool corresponding to the language "
105                              + LangName + "found!");
106   return I->second;
107 }
108
109 void CompilationGraph::insertNode(Tool* V) {
110   if (NodesMap.count(V->Name()) == 0) {
111     Node N;
112     N.OwningGraph = this;
113     N.ToolPtr = V;
114     NodesMap[V->Name()] = N;
115   }
116 }
117
118 void CompilationGraph::insertEdge(const std::string& A, Edge* E) {
119   Node& B = getNode(E->ToolName());
120   if (A == "root") {
121     const std::string& InputLanguage = B.ToolPtr->InputLanguage();
122     ToolsMap[InputLanguage].push_back(IntrusiveRefCntPtr<Edge>(E));
123     NodesMap["root"].AddEdge(E);
124   }
125   else {
126     Node& N = getNode(A);
127     N.AddEdge(E);
128   }
129   // Increase the inward edge counter.
130   B.IncrInEdges();
131 }
132
133 namespace {
134   sys::Path MakeTempFile(const sys::Path& TempDir, const std::string& BaseName,
135                          const std::string& Suffix) {
136     sys::Path Out = TempDir;
137     Out.appendComponent(BaseName);
138     Out.appendSuffix(Suffix);
139     Out.makeUnique(true, NULL);
140     return Out;
141   }
142 }
143
144 // Pass input file through the chain until we bump into a Join node or
145 // a node that says that it is the last.
146 void CompilationGraph::PassThroughGraph (const sys::Path& InFile,
147                                          const Node* StartNode,
148                                          const InputLanguagesSet& InLangs,
149                                          const sys::Path& TempDir) const {
150   bool Last = false;
151   sys::Path In = InFile;
152   const Node* CurNode = StartNode;
153
154   while(!Last) {
155     sys::Path Out;
156     Tool* CurTool = CurNode->ToolPtr.getPtr();
157
158     if (CurTool->IsJoin()) {
159       JoinTool& JT = dynamic_cast<JoinTool&>(*CurTool);
160       JT.AddToJoinList(In);
161       break;
162     }
163
164     // Since toolchains do not have to end with a Join node, we should
165     // check if this Node is the last.
166     if (!CurNode->HasChildren() || CurTool->IsLast()) {
167       if (!OutputFilename.empty()) {
168         Out.set(OutputFilename);
169       }
170       else {
171         Out.set(In.getBasename());
172         Out.appendSuffix(CurTool->OutputSuffix());
173       }
174       Last = true;
175     }
176     else {
177       Out = MakeTempFile(TempDir, In.getBasename(), CurTool->OutputSuffix());
178     }
179
180     if (CurTool->GenerateAction(In, Out).Execute() != 0)
181       throw std::runtime_error("Tool returned error code!");
182
183     if (Last)
184       return;
185
186     CurNode = &getNode(ChooseEdge(CurNode->OutEdges,
187                                   InLangs,
188                                   CurNode->Name())->ToolName());
189     In = Out; Out.clear();
190   }
191 }
192
193 // Find the head of the toolchain corresponding to the given file.
194 // Also, insert an input language into InLangs.
195 const Node* CompilationGraph::
196 FindToolChain(const sys::Path& In, const std::string* forceLanguage,
197               InputLanguagesSet& InLangs) const {
198
199   // Determine the input language.
200   const std::string& InLanguage =
201     forceLanguage ? *forceLanguage : getLanguage(In);
202
203   // Add the current input language to the input language set.
204   InLangs.insert(InLanguage);
205
206   // Find the toolchain for the input language.
207   const tools_vector_type& TV = getToolsVector(InLanguage);
208   if (TV.empty())
209     throw std::runtime_error("No toolchain corresponding to language"
210                              + InLanguage + " found!");
211   return &getNode(ChooseEdge(TV, InLangs)->ToolName());
212 }
213
214 // Helper function used by Build().
215 // Traverses initial portions of the toolchains (up to the first Join node).
216 // This function is also responsible for handling the -x option.
217 void CompilationGraph::BuildInitial (InputLanguagesSet& InLangs,
218                                      const sys::Path& TempDir) {
219   // This is related to -x option handling.
220   cl::list<std::string>::const_iterator xIter = Languages.begin(),
221     xBegin = xIter, xEnd = Languages.end();
222   bool xEmpty = true;
223   const std::string* xLanguage = 0;
224   unsigned xPos = 0, xPosNext = 0, filePos = 0;
225
226   if (xIter != xEnd) {
227     xEmpty = false;
228     xPos = Languages.getPosition(xIter - xBegin);
229     cl::list<std::string>::const_iterator xNext = llvm::next(xIter);
230     xPosNext = (xNext == xEnd) ? std::numeric_limits<unsigned>::max()
231       : Languages.getPosition(xNext - xBegin);
232     xLanguage = (*xIter == "none") ? 0 : &(*xIter);
233   }
234
235   // For each input file:
236   for (cl::list<std::string>::const_iterator B = InputFilenames.begin(),
237          CB = B, E = InputFilenames.end(); B != E; ++B) {
238     sys::Path In = sys::Path(*B);
239
240     // Code for handling the -x option.
241     // Output: std::string* xLanguage (can be NULL).
242     if (!xEmpty) {
243       filePos = InputFilenames.getPosition(B - CB);
244
245       if (xPos < filePos) {
246         if (filePos < xPosNext) {
247           xLanguage = (*xIter == "none") ? 0 : &(*xIter);
248         }
249         else { // filePos >= xPosNext
250           // Skip xIters while filePos > xPosNext
251           while (filePos > xPosNext) {
252             ++xIter;
253             xPos = xPosNext;
254
255             cl::list<std::string>::const_iterator xNext = llvm::next(xIter);
256             if (xNext == xEnd)
257               xPosNext = std::numeric_limits<unsigned>::max();
258             else
259               xPosNext = Languages.getPosition(xNext - xBegin);
260             xLanguage = (*xIter == "none") ? 0 : &(*xIter);
261           }
262         }
263       }
264     }
265
266     // Find the toolchain corresponding to this file.
267     const Node* N = FindToolChain(In, xLanguage, InLangs);
268     // Pass file through the chain starting at head.
269     PassThroughGraph(In, N, InLangs, TempDir);
270   }
271 }
272
273 // Sort the nodes in topological order.
274 void CompilationGraph::TopologicalSort(std::vector<const Node*>& Out) {
275   std::queue<const Node*> Q;
276   Q.push(&getNode("root"));
277
278   while (!Q.empty()) {
279     const Node* A = Q.front();
280     Q.pop();
281     Out.push_back(A);
282     for (Node::const_iterator EB = A->EdgesBegin(), EE = A->EdgesEnd();
283          EB != EE; ++EB) {
284       Node* B = &getNode((*EB)->ToolName());
285       B->DecrInEdges();
286       if (B->HasNoInEdges())
287         Q.push(B);
288     }
289   }
290 }
291
292 namespace {
293   bool NotJoinNode(const Node* N) {
294     return N->ToolPtr ? !N->ToolPtr->IsJoin() : true;
295   }
296 }
297
298 // Call TopologicalSort and filter the resulting list to include
299 // only Join nodes.
300 void CompilationGraph::
301 TopologicalSortFilterJoinNodes(std::vector<const Node*>& Out) {
302   std::vector<const Node*> TopSorted;
303   TopologicalSort(TopSorted);
304   std::remove_copy_if(TopSorted.begin(), TopSorted.end(),
305                       std::back_inserter(Out), NotJoinNode);
306 }
307
308 // Build the targets. Command-line options are accessed through global
309 // variables.
310 int CompilationGraph::Build (const sys::Path& TempDir) {
311
312   InputLanguagesSet InLangs;
313
314   // Traverse initial parts of the toolchains and fill in InLangs.
315   BuildInitial(InLangs, TempDir);
316
317   std::vector<const Node*> JTV;
318   TopologicalSortFilterJoinNodes(JTV);
319
320   // For all join nodes in topological order:
321   for (std::vector<const Node*>::iterator B = JTV.begin(), E = JTV.end();
322        B != E; ++B) {
323
324     sys::Path Out;
325     const Node* CurNode = *B;
326     JoinTool* JT = &dynamic_cast<JoinTool&>(*CurNode->ToolPtr.getPtr());
327     bool IsLast = false;
328
329     // Are there any files in the join list?
330     if (JT->JoinListEmpty())
331       continue;
332
333     // Is this the last tool in the toolchain?
334     // NOTE: we can process several toolchains in parallel.
335     if (!CurNode->HasChildren() || JT->IsLast()) {
336       if (OutputFilename.empty()) {
337         Out.set("a");
338         Out.appendSuffix(JT->OutputSuffix());
339       }
340       else
341         Out.set(OutputFilename);
342       IsLast = true;
343     }
344     else {
345       Out = MakeTempFile(TempDir, "tmp", JT->OutputSuffix());
346     }
347
348     if (JT->GenerateAction(Out).Execute() != 0)
349       throw std::runtime_error("Tool returned error code!");
350
351     if (!IsLast) {
352       const Node* NextNode =
353         &getNode(ChooseEdge(CurNode->OutEdges, InLangs,
354                             CurNode->Name())->ToolName());
355       PassThroughGraph(Out, NextNode, InLangs, TempDir);
356     }
357   }
358
359   return 0;
360 }
361
362 // Code related to graph visualization.
363
364 namespace llvm {
365   template <>
366   struct DOTGraphTraits<llvmc::CompilationGraph*>
367     : public DefaultDOTGraphTraits
368   {
369
370     template<typename GraphType>
371     static std::string getNodeLabel(const Node* N, const GraphType&)
372     {
373       if (N->ToolPtr)
374         if (N->ToolPtr->IsJoin())
375           return N->Name() + "\n (join" +
376             (N->HasChildren() ? ")"
377              : std::string(": ") + N->ToolPtr->OutputLanguage() + ')');
378         else
379           return N->Name();
380       else
381         return "root";
382     }
383
384     template<typename EdgeIter>
385     static std::string getEdgeSourceLabel(const Node* N, EdgeIter I) {
386       if (N->ToolPtr)
387         return N->ToolPtr->OutputLanguage();
388       else
389         return I->ToolPtr->InputLanguage();
390     }
391   };
392
393 }
394
395 void CompilationGraph::writeGraph() {
396   std::ofstream O("CompilationGraph.dot");
397
398   if (O.good()) {
399     llvm::WriteGraph(this, "compilation-graph");
400     O.close();
401   }
402   else {
403     throw std::runtime_error("");
404   }
405 }
406
407 void CompilationGraph::viewGraph() {
408   llvm::ViewGraph(this, "compilation-graph");
409 }