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