1 //===--- CompilationGraph.cpp - The LLVM Compiler Driver --------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open
6 // Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Compilation graph - implementation.
12 //===----------------------------------------------------------------------===//
15 #include "CompilationGraph.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/Support/CommandLine.h"
19 #include "llvm/Support/DOTGraphTraits.h"
20 #include "llvm/Support/GraphWriter.h"
29 using namespace llvmc;
31 extern cl::list<std::string> InputFilenames;
32 extern cl::opt<std::string> OutputFilename;
33 extern cl::list<std::string> Languages;
36 /// ExtsToLangs - Map from file extensions to language names.
37 LanguageMap GlobalLanguageMap;
39 /// GetLanguage - Find the language name corresponding to the given file.
40 const std::string& GetLanguage(const sys::Path& File) {
41 LanguageMap::const_iterator Lang = GlobalLanguageMap.find(File.getSuffix());
42 if (Lang == GlobalLanguageMap.end())
43 throw std::runtime_error("Unknown suffix: " + File.getSuffix());
50 /// ChooseEdge - Return the edge with the maximum weight.
52 const Edge* ChooseEdge(const C& EdgesContainer,
53 const InputLanguagesSet& InLangs,
54 const std::string& NodeName = "root") {
55 const Edge* MaxEdge = 0;
56 unsigned MaxWeight = 0;
57 bool SingleMax = true;
59 for (typename C::const_iterator B = EdgesContainer.begin(),
60 E = EdgesContainer.end(); B != E; ++B) {
61 const Edge* E = B->getPtr();
62 unsigned EW = E->Weight(InLangs);
67 } else if (EW == MaxWeight) {
73 throw std::runtime_error("Node " + NodeName +
74 ": multiple maximal outward edges found!"
75 " Most probably a specification error.");
77 throw std::runtime_error("Node " + NodeName +
78 ": no maximal outward edge found!"
79 " Most probably a specification error.");
85 CompilationGraph::CompilationGraph() {
86 NodesMap["root"] = Node(this);
89 Node& CompilationGraph::getNode(const std::string& ToolName) {
90 nodes_map_type::iterator I = NodesMap.find(ToolName);
91 if (I == NodesMap.end())
92 throw std::runtime_error("Node " + ToolName + " is not in the graph");
96 const Node& CompilationGraph::getNode(const std::string& ToolName) const {
97 nodes_map_type::const_iterator I = NodesMap.find(ToolName);
98 if (I == NodesMap.end())
99 throw std::runtime_error("Node " + ToolName + " is not in the graph!");
103 // Find the tools list corresponding to the given language name.
104 const CompilationGraph::tools_vector_type&
105 CompilationGraph::getToolsVector(const std::string& LangName) const
107 tools_map_type::const_iterator I = ToolsMap.find(LangName);
108 if (I == ToolsMap.end())
109 throw std::runtime_error("No tool corresponding to the language "
110 + LangName + " found");
114 void CompilationGraph::insertNode(Tool* V) {
115 if (NodesMap.count(V->Name()) == 0) {
117 N.OwningGraph = this;
119 NodesMap[V->Name()] = N;
123 void CompilationGraph::insertEdge(const std::string& A, Edge* Edg) {
124 Node& B = getNode(Edg->ToolName());
126 const char** InLangs = B.ToolPtr->InputLanguages();
127 for (;*InLangs; ++InLangs)
128 ToolsMap[*InLangs].push_back(IntrusiveRefCntPtr<Edge>(Edg));
129 NodesMap["root"].AddEdge(Edg);
132 Node& N = getNode(A);
135 // Increase the inward edge counter.
140 sys::Path MakeTempFile(const sys::Path& TempDir, const std::string& BaseName,
141 const std::string& Suffix) {
142 sys::Path Out = TempDir;
143 Out.appendComponent(BaseName);
144 Out.appendSuffix(Suffix);
145 Out.makeUnique(true, NULL);
150 // Pass input file through the chain until we bump into a Join node or
151 // a node that says that it is the last.
152 void CompilationGraph::PassThroughGraph (const sys::Path& InFile,
153 const Node* StartNode,
154 const InputLanguagesSet& InLangs,
155 const sys::Path& TempDir) const {
157 sys::Path In = InFile;
158 const Node* CurNode = StartNode;
162 Tool* CurTool = CurNode->ToolPtr.getPtr();
164 if (CurTool->IsJoin()) {
165 JoinTool& JT = dynamic_cast<JoinTool&>(*CurTool);
166 JT.AddToJoinList(In);
170 // Since toolchains do not have to end with a Join node, we should
171 // check if this Node is the last.
172 if (!CurNode->HasChildren() || CurTool->IsLast()) {
173 if (!OutputFilename.empty()) {
174 Out.set(OutputFilename);
177 Out.set(In.getBasename());
178 Out.appendSuffix(CurTool->OutputSuffix());
183 Out = MakeTempFile(TempDir, In.getBasename(), CurTool->OutputSuffix());
186 if (int ret = CurTool->GenerateAction(In, Out, InLangs).Execute())
187 throw error_code(ret);
192 CurNode = &getNode(ChooseEdge(CurNode->OutEdges,
194 CurNode->Name())->ToolName());
195 In = Out; Out.clear();
199 // Find the head of the toolchain corresponding to the given file.
200 // Also, insert an input language into InLangs.
201 const Node* CompilationGraph::
202 FindToolChain(const sys::Path& In, const std::string* forceLanguage,
203 InputLanguagesSet& InLangs) const {
205 // Determine the input language.
206 const std::string& InLanguage =
207 forceLanguage ? *forceLanguage : GetLanguage(In);
209 // Add the current input language to the input language set.
210 InLangs.insert(InLanguage);
212 // Find the toolchain for the input language.
213 const tools_vector_type& TV = getToolsVector(InLanguage);
215 throw std::runtime_error("No toolchain corresponding to language "
216 + InLanguage + " found");
217 return &getNode(ChooseEdge(TV, InLangs)->ToolName());
220 // Helper function used by Build().
221 // Traverses initial portions of the toolchains (up to the first Join node).
222 // This function is also responsible for handling the -x option.
223 void CompilationGraph::BuildInitial (InputLanguagesSet& InLangs,
224 const sys::Path& TempDir) {
225 // This is related to -x option handling.
226 cl::list<std::string>::const_iterator xIter = Languages.begin(),
227 xBegin = xIter, xEnd = Languages.end();
229 const std::string* xLanguage = 0;
230 unsigned xPos = 0, xPosNext = 0, filePos = 0;
234 xPos = Languages.getPosition(xIter - xBegin);
235 cl::list<std::string>::const_iterator xNext = llvm::next(xIter);
236 xPosNext = (xNext == xEnd) ? std::numeric_limits<unsigned>::max()
237 : Languages.getPosition(xNext - xBegin);
238 xLanguage = (*xIter == "none") ? 0 : &(*xIter);
241 // For each input file:
242 for (cl::list<std::string>::const_iterator B = InputFilenames.begin(),
243 CB = B, E = InputFilenames.end(); B != E; ++B) {
244 sys::Path In = sys::Path(*B);
246 // Code for handling the -x option.
247 // Output: std::string* xLanguage (can be NULL).
249 filePos = InputFilenames.getPosition(B - CB);
251 if (xPos < filePos) {
252 if (filePos < xPosNext) {
253 xLanguage = (*xIter == "none") ? 0 : &(*xIter);
255 else { // filePos >= xPosNext
256 // Skip xIters while filePos > xPosNext
257 while (filePos > xPosNext) {
261 cl::list<std::string>::const_iterator xNext = llvm::next(xIter);
263 xPosNext = std::numeric_limits<unsigned>::max();
265 xPosNext = Languages.getPosition(xNext - xBegin);
266 xLanguage = (*xIter == "none") ? 0 : &(*xIter);
272 // Find the toolchain corresponding to this file.
273 const Node* N = FindToolChain(In, xLanguage, InLangs);
274 // Pass file through the chain starting at head.
275 PassThroughGraph(In, N, InLangs, TempDir);
279 // Sort the nodes in topological order.
280 void CompilationGraph::TopologicalSort(std::vector<const Node*>& Out) {
281 std::queue<const Node*> Q;
282 Q.push(&getNode("root"));
285 const Node* A = Q.front();
288 for (Node::const_iterator EB = A->EdgesBegin(), EE = A->EdgesEnd();
290 Node* B = &getNode((*EB)->ToolName());
292 if (B->HasNoInEdges())
299 bool NotJoinNode(const Node* N) {
300 return N->ToolPtr ? !N->ToolPtr->IsJoin() : true;
304 // Call TopologicalSort and filter the resulting list to include
306 void CompilationGraph::
307 TopologicalSortFilterJoinNodes(std::vector<const Node*>& Out) {
308 std::vector<const Node*> TopSorted;
309 TopologicalSort(TopSorted);
310 std::remove_copy_if(TopSorted.begin(), TopSorted.end(),
311 std::back_inserter(Out), NotJoinNode);
314 int CompilationGraph::Build (const sys::Path& TempDir) {
316 InputLanguagesSet InLangs;
318 // Traverse initial parts of the toolchains and fill in InLangs.
319 BuildInitial(InLangs, TempDir);
321 std::vector<const Node*> JTV;
322 TopologicalSortFilterJoinNodes(JTV);
324 // For all join nodes in topological order:
325 for (std::vector<const Node*>::iterator B = JTV.begin(), E = JTV.end();
329 const Node* CurNode = *B;
330 JoinTool* JT = &dynamic_cast<JoinTool&>(*CurNode->ToolPtr.getPtr());
333 // Are there any files in the join list?
334 if (JT->JoinListEmpty())
337 // Is this the last tool in the toolchain?
338 // NOTE: we can process several toolchains in parallel.
339 if (!CurNode->HasChildren() || JT->IsLast()) {
340 if (OutputFilename.empty()) {
342 Out.appendSuffix(JT->OutputSuffix());
345 Out.set(OutputFilename);
349 Out = MakeTempFile(TempDir, "tmp", JT->OutputSuffix());
352 if (int ret = JT->GenerateAction(Out, InLangs).Execute())
353 throw error_code(ret);
356 const Node* NextNode =
357 &getNode(ChooseEdge(CurNode->OutEdges, InLangs,
358 CurNode->Name())->ToolName());
359 PassThroughGraph(Out, NextNode, InLangs, TempDir);
366 // Code related to graph visualization.
370 struct DOTGraphTraits<llvmc::CompilationGraph*>
371 : public DefaultDOTGraphTraits
374 template<typename GraphType>
375 static std::string getNodeLabel(const Node* N, const GraphType&)
378 if (N->ToolPtr->IsJoin())
379 return N->Name() + "\n (join" +
380 (N->HasChildren() ? ")"
381 : std::string(": ") + N->ToolPtr->OutputLanguage() + ')');
388 template<typename EdgeIter>
389 static std::string getEdgeSourceLabel(const Node* N, EdgeIter I) {
391 return N->ToolPtr->OutputLanguage();
394 const char** InLangs = I->ToolPtr->InputLanguages();
397 for (; *InLangs; ++InLangs) {
398 if (*(InLangs + 1)) {
414 void CompilationGraph::writeGraph() {
415 std::ofstream O("compilation-graph.dot");
418 llvm::WriteGraph(this, "compilation-graph");
422 throw std::runtime_error("Error opening file 'compilation-graph.dot'"
427 void CompilationGraph::viewGraph() {
428 llvm::ViewGraph(this, "compilation-graph");