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 "llvm/CompilerDriver/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;
37 const std::string& LanguageMap::GetLanguage(const sys::Path& File) const {
38 LanguageMap::const_iterator Lang = this->find(File.getSuffix());
39 if (Lang == this->end())
40 throw std::runtime_error("Unknown suffix: " + File.getSuffix());
47 /// ChooseEdge - Return the edge with the maximum weight.
49 const Edge* ChooseEdge(const C& EdgesContainer,
50 const InputLanguagesSet& InLangs,
51 const std::string& NodeName = "root") {
52 const Edge* MaxEdge = 0;
53 unsigned MaxWeight = 0;
54 bool SingleMax = true;
56 for (typename C::const_iterator B = EdgesContainer.begin(),
57 E = EdgesContainer.end(); B != E; ++B) {
58 const Edge* e = B->getPtr();
59 unsigned EW = e->Weight(InLangs);
64 } else if (EW == MaxWeight) {
70 throw std::runtime_error("Node " + NodeName +
71 ": multiple maximal outward edges found!"
72 " Most probably a specification error.");
74 throw std::runtime_error("Node " + NodeName +
75 ": no maximal outward edge found!"
76 " Most probably a specification error.");
82 CompilationGraph::CompilationGraph() {
83 NodesMap["root"] = Node(this);
86 Node& CompilationGraph::getNode(const std::string& ToolName) {
87 nodes_map_type::iterator I = NodesMap.find(ToolName);
88 if (I == NodesMap.end())
89 throw std::runtime_error("Node " + ToolName + " is not in the graph");
93 const Node& CompilationGraph::getNode(const std::string& ToolName) const {
94 nodes_map_type::const_iterator I = NodesMap.find(ToolName);
95 if (I == NodesMap.end())
96 throw std::runtime_error("Node " + ToolName + " is not in the graph!");
100 // Find the tools list corresponding to the given language name.
101 const CompilationGraph::tools_vector_type&
102 CompilationGraph::getToolsVector(const std::string& LangName) const
104 tools_map_type::const_iterator I = ToolsMap.find(LangName);
105 if (I == ToolsMap.end())
106 throw std::runtime_error("No tool corresponding to the language "
107 + LangName + " found");
111 void CompilationGraph::insertNode(Tool* V) {
112 if (NodesMap.count(V->Name()) == 0)
113 NodesMap[V->Name()] = Node(this, V);
116 void CompilationGraph::insertEdge(const std::string& A, Edge* Edg) {
117 Node& B = getNode(Edg->ToolName());
119 const char** InLangs = B.ToolPtr->InputLanguages();
120 for (;*InLangs; ++InLangs)
121 ToolsMap[*InLangs].push_back(IntrusiveRefCntPtr<Edge>(Edg));
122 NodesMap["root"].AddEdge(Edg);
125 Node& N = getNode(A);
128 // Increase the inward edge counter.
133 sys::Path MakeTempFile(const sys::Path& TempDir, const std::string& BaseName,
134 const std::string& Suffix) {
137 // Make sure we don't end up with path names like '/file.o' if the
139 if (TempDir.empty()) {
144 Out.appendComponent(BaseName);
146 Out.appendSuffix(Suffix);
147 // NOTE: makeUnique always *creates* a unique temporary file,
148 // which is good, since there will be no races. However, some
149 // tools do not like it when the output file already exists, so
150 // they have to be placated with -f or something like that.
151 Out.makeUnique(true, NULL);
156 // Pass input file through the chain until we bump into a Join node or
157 // a node that says that it is the last.
158 void CompilationGraph::PassThroughGraph (const sys::Path& InFile,
159 const Node* StartNode,
160 const InputLanguagesSet& InLangs,
161 const sys::Path& TempDir,
162 const LanguageMap& LangMap) const {
164 sys::Path In = InFile;
165 const Node* CurNode = StartNode;
169 Tool* CurTool = CurNode->ToolPtr.getPtr();
171 if (CurTool->IsJoin()) {
172 JoinTool& JT = dynamic_cast<JoinTool&>(*CurTool);
173 JT.AddToJoinList(In);
177 // Since toolchains do not have to end with a Join node, we should
178 // check if this Node is the last.
179 if (!CurNode->HasChildren() || CurTool->IsLast()) {
180 if (!OutputFilename.empty()) {
181 Out.set(OutputFilename);
184 Out.set(In.getBasename());
185 Out.appendSuffix(CurTool->OutputSuffix());
190 Out = MakeTempFile(TempDir, In.getBasename(), CurTool->OutputSuffix());
193 if (int ret = CurTool->GenerateAction(In, Out, InLangs, LangMap).Execute())
194 throw error_code(ret);
199 CurNode = &getNode(ChooseEdge(CurNode->OutEdges,
201 CurNode->Name())->ToolName());
202 In = Out; Out.clear();
206 // Find the head of the toolchain corresponding to the given file.
207 // Also, insert an input language into InLangs.
208 const Node* CompilationGraph::
209 FindToolChain(const sys::Path& In, const std::string* ForceLanguage,
210 InputLanguagesSet& InLangs, const LanguageMap& LangMap) const {
212 // Determine the input language.
213 const std::string& InLanguage =
214 ForceLanguage ? *ForceLanguage : LangMap.GetLanguage(In);
216 // Add the current input language to the input language set.
217 InLangs.insert(InLanguage);
219 // Find the toolchain for the input language.
220 const tools_vector_type& TV = getToolsVector(InLanguage);
222 throw std::runtime_error("No toolchain corresponding to language "
223 + InLanguage + " found");
224 return &getNode(ChooseEdge(TV, InLangs)->ToolName());
227 // Helper function used by Build().
228 // Traverses initial portions of the toolchains (up to the first Join node).
229 // This function is also responsible for handling the -x option.
230 void CompilationGraph::BuildInitial (InputLanguagesSet& InLangs,
231 const sys::Path& TempDir,
232 const LanguageMap& LangMap) {
233 // This is related to -x option handling.
234 cl::list<std::string>::const_iterator xIter = Languages.begin(),
235 xBegin = xIter, xEnd = Languages.end();
237 const std::string* xLanguage = 0;
238 unsigned xPos = 0, xPosNext = 0, filePos = 0;
242 xPos = Languages.getPosition(xIter - xBegin);
243 cl::list<std::string>::const_iterator xNext = llvm::next(xIter);
244 xPosNext = (xNext == xEnd) ? std::numeric_limits<unsigned>::max()
245 : Languages.getPosition(xNext - xBegin);
246 xLanguage = (*xIter == "none") ? 0 : &(*xIter);
249 // For each input file:
250 for (cl::list<std::string>::const_iterator B = InputFilenames.begin(),
251 CB = B, E = InputFilenames.end(); B != E; ++B) {
252 sys::Path In = sys::Path(*B);
254 // Code for handling the -x option.
255 // Output: std::string* xLanguage (can be NULL).
257 filePos = InputFilenames.getPosition(B - CB);
259 if (xPos < filePos) {
260 if (filePos < xPosNext) {
261 xLanguage = (*xIter == "none") ? 0 : &(*xIter);
263 else { // filePos >= xPosNext
264 // Skip xIters while filePos > xPosNext
265 while (filePos > xPosNext) {
269 cl::list<std::string>::const_iterator xNext = llvm::next(xIter);
271 xPosNext = std::numeric_limits<unsigned>::max();
273 xPosNext = Languages.getPosition(xNext - xBegin);
274 xLanguage = (*xIter == "none") ? 0 : &(*xIter);
280 // Find the toolchain corresponding to this file.
281 const Node* N = FindToolChain(In, xLanguage, InLangs, LangMap);
282 // Pass file through the chain starting at head.
283 PassThroughGraph(In, N, InLangs, TempDir, LangMap);
287 // Sort the nodes in topological order.
288 void CompilationGraph::TopologicalSort(std::vector<const Node*>& Out) {
289 std::queue<const Node*> Q;
290 Q.push(&getNode("root"));
293 const Node* A = Q.front();
296 for (Node::const_iterator EB = A->EdgesBegin(), EE = A->EdgesEnd();
298 Node* B = &getNode((*EB)->ToolName());
300 if (B->HasNoInEdges())
307 bool NotJoinNode(const Node* N) {
308 return N->ToolPtr ? !N->ToolPtr->IsJoin() : true;
312 // Call TopologicalSort and filter the resulting list to include
314 void CompilationGraph::
315 TopologicalSortFilterJoinNodes(std::vector<const Node*>& Out) {
316 std::vector<const Node*> TopSorted;
317 TopologicalSort(TopSorted);
318 std::remove_copy_if(TopSorted.begin(), TopSorted.end(),
319 std::back_inserter(Out), NotJoinNode);
322 int CompilationGraph::Build (const sys::Path& TempDir,
323 const LanguageMap& LangMap) {
325 InputLanguagesSet InLangs;
327 // Traverse initial parts of the toolchains and fill in InLangs.
328 BuildInitial(InLangs, TempDir, LangMap);
330 std::vector<const Node*> JTV;
331 TopologicalSortFilterJoinNodes(JTV);
333 // For all join nodes in topological order:
334 for (std::vector<const Node*>::iterator B = JTV.begin(), E = JTV.end();
338 const Node* CurNode = *B;
339 JoinTool* JT = &dynamic_cast<JoinTool&>(*CurNode->ToolPtr.getPtr());
342 // Are there any files in the join list?
343 if (JT->JoinListEmpty())
346 // Is this the last tool in the toolchain?
347 // NOTE: we can process several toolchains in parallel.
348 if (!CurNode->HasChildren() || JT->IsLast()) {
349 if (OutputFilename.empty()) {
351 Out.appendSuffix(JT->OutputSuffix());
354 Out.set(OutputFilename);
358 Out = MakeTempFile(TempDir, "tmp", JT->OutputSuffix());
361 if (int ret = JT->GenerateAction(Out, InLangs, LangMap).Execute())
362 throw error_code(ret);
365 const Node* NextNode =
366 &getNode(ChooseEdge(CurNode->OutEdges, InLangs,
367 CurNode->Name())->ToolName());
368 PassThroughGraph(Out, NextNode, InLangs, TempDir, LangMap);
375 // Code related to graph visualization.
379 struct DOTGraphTraits<llvmc::CompilationGraph*>
380 : public DefaultDOTGraphTraits
383 template<typename GraphType>
384 static std::string getNodeLabel(const Node* N, const GraphType&)
387 if (N->ToolPtr->IsJoin())
388 return N->Name() + "\n (join" +
389 (N->HasChildren() ? ")"
390 : std::string(": ") + N->ToolPtr->OutputLanguage() + ')');
397 template<typename EdgeIter>
398 static std::string getEdgeSourceLabel(const Node* N, EdgeIter I) {
400 return N->ToolPtr->OutputLanguage();
403 const char** InLangs = I->ToolPtr->InputLanguages();
406 for (; *InLangs; ++InLangs) {
407 if (*(InLangs + 1)) {
423 void CompilationGraph::writeGraph() {
424 std::ofstream O("compilation-graph.dot");
427 llvm::WriteGraph(this, "compilation-graph");
431 throw std::runtime_error("Error opening file 'compilation-graph.dot'"
436 void CompilationGraph::viewGraph() {
437 llvm::ViewGraph(this, "compilation-graph");