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) {
144 // Make sure we don't end up with path names like '/file.o' if the
146 if (TempDir.empty()) {
151 Out.appendComponent(BaseName);
153 Out.appendSuffix(Suffix);
154 // NOTE: makeUnique always *creates* a unique temporary file,
155 // which is good, since there will be no races. However, some
156 // tools do not like it when the output file already exists, so
157 // they have to be placated with -f or something like that.
158 Out.makeUnique(true, NULL);
163 // Pass input file through the chain until we bump into a Join node or
164 // a node that says that it is the last.
165 void CompilationGraph::PassThroughGraph (const sys::Path& InFile,
166 const Node* StartNode,
167 const InputLanguagesSet& InLangs,
168 const sys::Path& TempDir) const {
170 sys::Path In = InFile;
171 const Node* CurNode = StartNode;
175 Tool* CurTool = CurNode->ToolPtr.getPtr();
177 if (CurTool->IsJoin()) {
178 JoinTool& JT = dynamic_cast<JoinTool&>(*CurTool);
179 JT.AddToJoinList(In);
183 // Since toolchains do not have to end with a Join node, we should
184 // check if this Node is the last.
185 if (!CurNode->HasChildren() || CurTool->IsLast()) {
186 if (!OutputFilename.empty()) {
187 Out.set(OutputFilename);
190 Out.set(In.getBasename());
191 Out.appendSuffix(CurTool->OutputSuffix());
196 Out = MakeTempFile(TempDir, In.getBasename(), CurTool->OutputSuffix());
199 if (int ret = CurTool->GenerateAction(In, Out, InLangs).Execute())
200 throw error_code(ret);
205 CurNode = &getNode(ChooseEdge(CurNode->OutEdges,
207 CurNode->Name())->ToolName());
208 In = Out; Out.clear();
212 // Find the head of the toolchain corresponding to the given file.
213 // Also, insert an input language into InLangs.
214 const Node* CompilationGraph::
215 FindToolChain(const sys::Path& In, const std::string* forceLanguage,
216 InputLanguagesSet& InLangs) const {
218 // Determine the input language.
219 const std::string& InLanguage =
220 forceLanguage ? *forceLanguage : GetLanguage(In);
222 // Add the current input language to the input language set.
223 InLangs.insert(InLanguage);
225 // Find the toolchain for the input language.
226 const tools_vector_type& TV = getToolsVector(InLanguage);
228 throw std::runtime_error("No toolchain corresponding to language "
229 + InLanguage + " found");
230 return &getNode(ChooseEdge(TV, InLangs)->ToolName());
233 // Helper function used by Build().
234 // Traverses initial portions of the toolchains (up to the first Join node).
235 // This function is also responsible for handling the -x option.
236 void CompilationGraph::BuildInitial (InputLanguagesSet& InLangs,
237 const sys::Path& TempDir) {
238 // This is related to -x option handling.
239 cl::list<std::string>::const_iterator xIter = Languages.begin(),
240 xBegin = xIter, xEnd = Languages.end();
242 const std::string* xLanguage = 0;
243 unsigned xPos = 0, xPosNext = 0, filePos = 0;
247 xPos = Languages.getPosition(xIter - xBegin);
248 cl::list<std::string>::const_iterator xNext = llvm::next(xIter);
249 xPosNext = (xNext == xEnd) ? std::numeric_limits<unsigned>::max()
250 : Languages.getPosition(xNext - xBegin);
251 xLanguage = (*xIter == "none") ? 0 : &(*xIter);
254 // For each input file:
255 for (cl::list<std::string>::const_iterator B = InputFilenames.begin(),
256 CB = B, E = InputFilenames.end(); B != E; ++B) {
257 sys::Path In = sys::Path(*B);
259 // Code for handling the -x option.
260 // Output: std::string* xLanguage (can be NULL).
262 filePos = InputFilenames.getPosition(B - CB);
264 if (xPos < filePos) {
265 if (filePos < xPosNext) {
266 xLanguage = (*xIter == "none") ? 0 : &(*xIter);
268 else { // filePos >= xPosNext
269 // Skip xIters while filePos > xPosNext
270 while (filePos > xPosNext) {
274 cl::list<std::string>::const_iterator xNext = llvm::next(xIter);
276 xPosNext = std::numeric_limits<unsigned>::max();
278 xPosNext = Languages.getPosition(xNext - xBegin);
279 xLanguage = (*xIter == "none") ? 0 : &(*xIter);
285 // Find the toolchain corresponding to this file.
286 const Node* N = FindToolChain(In, xLanguage, InLangs);
287 // Pass file through the chain starting at head.
288 PassThroughGraph(In, N, InLangs, TempDir);
292 // Sort the nodes in topological order.
293 void CompilationGraph::TopologicalSort(std::vector<const Node*>& Out) {
294 std::queue<const Node*> Q;
295 Q.push(&getNode("root"));
298 const Node* A = Q.front();
301 for (Node::const_iterator EB = A->EdgesBegin(), EE = A->EdgesEnd();
303 Node* B = &getNode((*EB)->ToolName());
305 if (B->HasNoInEdges())
312 bool NotJoinNode(const Node* N) {
313 return N->ToolPtr ? !N->ToolPtr->IsJoin() : true;
317 // Call TopologicalSort and filter the resulting list to include
319 void CompilationGraph::
320 TopologicalSortFilterJoinNodes(std::vector<const Node*>& Out) {
321 std::vector<const Node*> TopSorted;
322 TopologicalSort(TopSorted);
323 std::remove_copy_if(TopSorted.begin(), TopSorted.end(),
324 std::back_inserter(Out), NotJoinNode);
327 int CompilationGraph::Build (const sys::Path& TempDir) {
329 InputLanguagesSet InLangs;
331 // Traverse initial parts of the toolchains and fill in InLangs.
332 BuildInitial(InLangs, TempDir);
334 std::vector<const Node*> JTV;
335 TopologicalSortFilterJoinNodes(JTV);
337 // For all join nodes in topological order:
338 for (std::vector<const Node*>::iterator B = JTV.begin(), E = JTV.end();
342 const Node* CurNode = *B;
343 JoinTool* JT = &dynamic_cast<JoinTool&>(*CurNode->ToolPtr.getPtr());
346 // Are there any files in the join list?
347 if (JT->JoinListEmpty())
350 // Is this the last tool in the toolchain?
351 // NOTE: we can process several toolchains in parallel.
352 if (!CurNode->HasChildren() || JT->IsLast()) {
353 if (OutputFilename.empty()) {
355 Out.appendSuffix(JT->OutputSuffix());
358 Out.set(OutputFilename);
362 Out = MakeTempFile(TempDir, "tmp", JT->OutputSuffix());
365 if (int ret = JT->GenerateAction(Out, InLangs).Execute())
366 throw error_code(ret);
369 const Node* NextNode =
370 &getNode(ChooseEdge(CurNode->OutEdges, InLangs,
371 CurNode->Name())->ToolName());
372 PassThroughGraph(Out, NextNode, InLangs, TempDir);
379 // Code related to graph visualization.
383 struct DOTGraphTraits<llvmc::CompilationGraph*>
384 : public DefaultDOTGraphTraits
387 template<typename GraphType>
388 static std::string getNodeLabel(const Node* N, const GraphType&)
391 if (N->ToolPtr->IsJoin())
392 return N->Name() + "\n (join" +
393 (N->HasChildren() ? ")"
394 : std::string(": ") + N->ToolPtr->OutputLanguage() + ')');
401 template<typename EdgeIter>
402 static std::string getEdgeSourceLabel(const Node* N, EdgeIter I) {
404 return N->ToolPtr->OutputLanguage();
407 const char** InLangs = I->ToolPtr->InputLanguages();
410 for (; *InLangs; ++InLangs) {
411 if (*(InLangs + 1)) {
427 void CompilationGraph::writeGraph() {
428 std::ofstream O("compilation-graph.dot");
431 llvm::WriteGraph(this, "compilation-graph");
435 throw std::runtime_error("Error opening file 'compilation-graph.dot'"
440 void CompilationGraph::viewGraph() {
441 llvm::ViewGraph(this, "compilation-graph");