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 //===----------------------------------------------------------------------===//
14 #include "llvm/CompilerDriver/BuiltinOptions.h"
15 #include "llvm/CompilerDriver/CompilationGraph.h"
16 #include "llvm/CompilerDriver/Error.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/Support/DOTGraphTraits.h"
20 #include "llvm/Support/GraphWriter.h"
21 #include "llvm/Support/raw_ostream.h"
30 using namespace llvmc;
34 const std::string* LanguageMap::GetLanguage(const sys::Path& File) const {
35 StringRef suf = File.getSuffix();
36 LanguageMap::const_iterator Lang =
37 this->find(suf.empty() ? "*empty*" : suf);
38 if (Lang == this->end()) {
39 PrintError("File '" + File.str() + "' has unknown suffix '"
49 /// ChooseEdge - Return the edge with the maximum weight. Returns 0 on error.
51 const Edge* ChooseEdge(const C& EdgesContainer,
52 const InputLanguagesSet& InLangs,
53 const std::string& NodeName = "root") {
54 const Edge* MaxEdge = 0;
56 bool SingleMax = true;
58 // TODO: fix calculation of SingleMax.
59 for (typename C::const_iterator B = EdgesContainer.begin(),
60 E = EdgesContainer.end(); B != E; ++B) {
61 const Edge* e = B->getPtr();
62 int EW = e->Weight(InLangs);
64 // (error) invocation in TableGen -> we don't need to print an error
72 } else if (EW == MaxWeight) {
78 PrintError("Node " + NodeName + ": multiple maximal outward edges found!"
79 " Most probably a specification error.");
83 PrintError("Node " + NodeName + ": no maximal outward edge found!"
84 " Most probably a specification error.");
92 void Node::AddEdge(Edge* Edg) {
93 // If there already was an edge between two nodes, modify it instead
94 // of adding a new edge.
95 const std::string& ToolName = Edg->ToolName();
96 for (container_type::iterator B = OutEdges.begin(), E = OutEdges.end();
98 if ((*B)->ToolName() == ToolName) {
99 llvm::IntrusiveRefCntPtr<Edge>(Edg).swap(*B);
103 OutEdges.push_back(llvm::IntrusiveRefCntPtr<Edge>(Edg));
106 CompilationGraph::CompilationGraph() {
107 NodesMap["root"] = Node(this);
110 Node* CompilationGraph::getNode(const std::string& ToolName) {
111 nodes_map_type::iterator I = NodesMap.find(ToolName);
112 if (I == NodesMap.end()) {
113 PrintError("Node " + ToolName + " is not in the graph");
119 const Node* CompilationGraph::getNode(const std::string& ToolName) const {
120 nodes_map_type::const_iterator I = NodesMap.find(ToolName);
121 if (I == NodesMap.end()) {
122 PrintError("Node " + ToolName + " is not in the graph!");
128 // Find the tools list corresponding to the given language name.
129 const CompilationGraph::tools_vector_type*
130 CompilationGraph::getToolsVector(const std::string& LangName) const
132 tools_map_type::const_iterator I = ToolsMap.find(LangName);
133 if (I == ToolsMap.end()) {
134 PrintError("No tool corresponding to the language " + LangName + " found");
140 void CompilationGraph::insertNode(Tool* V) {
141 if (NodesMap.count(V->Name()) == 0)
142 NodesMap[V->Name()] = Node(this, V);
145 int CompilationGraph::insertEdge(const std::string& A, Edge* Edg) {
146 Node* B = getNode(Edg->ToolName());
151 const char** InLangs = B->ToolPtr->InputLanguages();
152 for (;*InLangs; ++InLangs)
153 ToolsMap[*InLangs].push_back(IntrusiveRefCntPtr<Edge>(Edg));
154 NodesMap["root"].AddEdge(Edg);
157 Node* N = getNode(A);
163 // Increase the inward edge counter.
169 // Pass input file through the chain until we bump into a Join node or
170 // a node that says that it is the last.
171 int CompilationGraph::PassThroughGraph (const sys::Path& InFile,
172 const Node* StartNode,
173 const InputLanguagesSet& InLangs,
174 const sys::Path& TempDir,
175 const LanguageMap& LangMap) const {
176 sys::Path In = InFile;
177 const Node* CurNode = StartNode;
180 Tool* CurTool = CurNode->ToolPtr.getPtr();
182 if (CurTool->IsJoin()) {
183 JoinTool& JT = static_cast<JoinTool&>(*CurTool);
184 JT.AddToJoinList(In);
189 if (int ret = CurTool->GenerateAction(CurAction, In, CurNode->HasChildren(),
190 TempDir, InLangs, LangMap)) {
194 if (int ret = CurAction.Execute())
197 if (CurAction.StopCompilation())
200 const Edge* Edg = ChooseEdge(CurNode->OutEdges, InLangs, CurNode->Name());
204 CurNode = getNode(Edg->ToolName());
208 In = CurAction.OutFile();
214 // Find the head of the toolchain corresponding to the given file.
215 // Also, insert an input language into InLangs.
216 const Node* CompilationGraph::
217 FindToolChain(const sys::Path& In, const std::string* ForceLanguage,
218 InputLanguagesSet& InLangs, const LanguageMap& LangMap) const {
220 // Determine the input language.
221 const std::string* InLang = LangMap.GetLanguage(In);
224 const std::string& InLanguage = (ForceLanguage ? *ForceLanguage : *InLang);
226 // Add the current input language to the input language set.
227 InLangs.insert(InLanguage);
229 // Find the toolchain for the input language.
230 const tools_vector_type* pTV = getToolsVector(InLanguage);
234 const tools_vector_type& TV = *pTV;
236 PrintError("No toolchain corresponding to language "
237 + InLanguage + " found");
241 const Edge* Edg = ChooseEdge(TV, InLangs);
245 return getNode(Edg->ToolName());
248 // Helper function used by Build().
249 // Traverses initial portions of the toolchains (up to the first Join node).
250 // This function is also responsible for handling the -x option.
251 int CompilationGraph::BuildInitial (InputLanguagesSet& InLangs,
252 const sys::Path& TempDir,
253 const LanguageMap& LangMap) {
254 // This is related to -x option handling.
255 cl::list<std::string>::const_iterator xIter = Languages.begin(),
256 xBegin = xIter, xEnd = Languages.end();
258 const std::string* xLanguage = 0;
259 unsigned xPos = 0, xPosNext = 0, filePos = 0;
263 xPos = Languages.getPosition(xIter - xBegin);
264 cl::list<std::string>::const_iterator xNext = llvm::next(xIter);
265 xPosNext = (xNext == xEnd) ? std::numeric_limits<unsigned>::max()
266 : Languages.getPosition(xNext - xBegin);
267 xLanguage = (*xIter == "none") ? 0 : &(*xIter);
270 // For each input file:
271 for (cl::list<std::string>::const_iterator B = InputFilenames.begin(),
272 CB = B, E = InputFilenames.end(); B != E; ++B) {
273 sys::Path In = sys::Path(*B);
275 // Code for handling the -x option.
276 // Output: std::string* xLanguage (can be NULL).
278 filePos = InputFilenames.getPosition(B - CB);
280 if (xPos < filePos) {
281 if (filePos < xPosNext) {
282 xLanguage = (*xIter == "none") ? 0 : &(*xIter);
284 else { // filePos >= xPosNext
285 // Skip xIters while filePos > xPosNext
286 while (filePos > xPosNext) {
290 cl::list<std::string>::const_iterator xNext = llvm::next(xIter);
292 xPosNext = std::numeric_limits<unsigned>::max();
294 xPosNext = Languages.getPosition(xNext - xBegin);
295 xLanguage = (*xIter == "none") ? 0 : &(*xIter);
301 // Find the toolchain corresponding to this file.
302 const Node* N = FindToolChain(In, xLanguage, InLangs, LangMap);
305 // Pass file through the chain starting at head.
306 if (int ret = PassThroughGraph(In, N, InLangs, TempDir, LangMap))
313 // Sort the nodes in topological order.
314 int CompilationGraph::TopologicalSort(std::vector<const Node*>& Out) {
315 std::queue<const Node*> Q;
317 Node* Root = getNode("root");
324 const Node* A = Q.front();
327 for (Node::const_iterator EB = A->EdgesBegin(), EE = A->EdgesEnd();
329 Node* B = getNode((*EB)->ToolName());
334 if (B->HasNoInEdges())
343 bool NotJoinNode(const Node* N) {
344 return N->ToolPtr ? !N->ToolPtr->IsJoin() : true;
348 // Call TopologicalSort and filter the resulting list to include
350 int CompilationGraph::
351 TopologicalSortFilterJoinNodes(std::vector<const Node*>& Out) {
352 std::vector<const Node*> TopSorted;
353 if (int ret = TopologicalSort(TopSorted))
355 std::remove_copy_if(TopSorted.begin(), TopSorted.end(),
356 std::back_inserter(Out), NotJoinNode);
361 int CompilationGraph::Build (const sys::Path& TempDir,
362 const LanguageMap& LangMap) {
363 InputLanguagesSet InLangs;
364 bool WasSomeActionGenerated = !InputFilenames.empty();
366 // Traverse initial parts of the toolchains and fill in InLangs.
367 if (int ret = BuildInitial(InLangs, TempDir, LangMap))
370 std::vector<const Node*> JTV;
371 if (int ret = TopologicalSortFilterJoinNodes(JTV))
374 // For all join nodes in topological order:
375 for (std::vector<const Node*>::iterator B = JTV.begin(), E = JTV.end();
378 const Node* CurNode = *B;
379 JoinTool* JT = &static_cast<JoinTool&>(*CurNode->ToolPtr.getPtr());
381 // Are there any files in the join list?
382 if (JT->JoinListEmpty() && !(JT->WorksOnEmpty() && InputFilenames.empty()))
385 WasSomeActionGenerated = true;
387 if (int ret = JT->GenerateAction(CurAction, CurNode->HasChildren(),
388 TempDir, InLangs, LangMap)) {
392 if (int ret = CurAction.Execute())
395 if (CurAction.StopCompilation())
398 const Edge* Edg = ChooseEdge(CurNode->OutEdges, InLangs, CurNode->Name());
402 const Node* NextNode = getNode(Edg->ToolName());
406 if (int ret = PassThroughGraph(sys::Path(CurAction.OutFile()), NextNode,
407 InLangs, TempDir, LangMap)) {
412 if (!WasSomeActionGenerated) {
413 PrintError("no input files");
420 int CompilationGraph::CheckLanguageNames() const {
423 // Check that names for output and input languages on all edges do match.
424 for (const_nodes_iterator B = this->NodesMap.begin(),
425 E = this->NodesMap.end(); B != E; ++B) {
427 const Node & N1 = B->second;
429 for (Node::const_iterator EB = N1.EdgesBegin(), EE = N1.EdgesEnd();
431 const Node* N2 = this->getNode((*EB)->ToolName());
437 errs() << "Error: there is an edge from '" << N1.ToolPtr->Name()
438 << "' back to the root!\n\n";
442 const char* OutLang = N1.ToolPtr->OutputLanguage();
443 const char** InLangs = N2->ToolPtr->InputLanguages();
445 for (;*InLangs; ++InLangs) {
446 if (std::strcmp(OutLang, *InLangs) == 0) {
454 errs() << "Error: Output->input language mismatch in the edge '"
455 << N1.ToolPtr->Name() << "' -> '" << N2->ToolPtr->Name()
457 << "Expected one of { ";
459 InLangs = N2->ToolPtr->InputLanguages();
460 for (;*InLangs; ++InLangs) {
461 errs() << '\'' << *InLangs << (*(InLangs+1) ? "', " : "'");
464 errs() << " }, but got '" << OutLang << "'!\n\n";
474 int CompilationGraph::CheckMultipleDefaultEdges() const {
476 InputLanguagesSet Dummy;
478 // For all nodes, just iterate over the outgoing edges and check if there is
479 // more than one edge with maximum weight.
480 for (const_nodes_iterator B = this->NodesMap.begin(),
481 E = this->NodesMap.end(); B != E; ++B) {
482 const Node& N = B->second;
485 // Ignore the root node.
489 for (Node::const_iterator EB = N.EdgesBegin(), EE = N.EdgesEnd();
491 int EdgeWeight = (*EB)->Weight(Dummy);
492 if (EdgeWeight > MaxWeight) {
493 MaxWeight = EdgeWeight;
495 else if (EdgeWeight == MaxWeight) {
497 errs() << "Error: there are multiple maximal edges stemming from the '"
498 << N.ToolPtr->Name() << "' node!\n\n";
507 int CompilationGraph::CheckCycles() {
508 unsigned deleted = 0;
511 Node* Root = getNode("root");
517 // Try to delete all nodes that have no ingoing edges, starting from the
518 // root. If there are any nodes left after this operation, then we have a
519 // cycle. This relies on '--check-graph' not performing the topological sort.
525 for (Node::iterator EB = A->EdgesBegin(), EE = A->EdgesEnd();
527 Node* B = getNode((*EB)->ToolName());
532 if (B->HasNoInEdges())
537 if (deleted != NodesMap.size()) {
538 errs() << "Error: there are cycles in the compilation graph!\n"
539 << "Try inspecting the diagram produced by "
540 << "'llvmc --view-graph'.\n\n";
547 int CompilationGraph::Check () {
548 // We try to catch as many errors as we can in one go.
552 // Check that output/input language names match.
553 ret = this->CheckLanguageNames();
558 // Check for multiple default edges.
559 ret = this->CheckMultipleDefaultEdges();
565 ret = this->CheckCycles();
573 // Code related to graph visualization.
577 struct DOTGraphTraits<llvmc::CompilationGraph*>
578 : public DefaultDOTGraphTraits
580 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
582 template<typename GraphType>
583 static std::string getNodeLabel(const Node* N, const GraphType&)
586 if (N->ToolPtr->IsJoin())
587 return N->Name() + "\n (join" +
588 (N->HasChildren() ? ")"
589 : std::string(": ") + N->ToolPtr->OutputLanguage() + ')');
596 template<typename EdgeIter>
597 static std::string getEdgeSourceLabel(const Node* N, EdgeIter I) {
599 return N->ToolPtr->OutputLanguage();
602 const char** InLangs = I->ToolPtr->InputLanguages();
605 for (; *InLangs; ++InLangs) {
606 if (*(InLangs + 1)) {
622 int CompilationGraph::writeGraph(const std::string& OutputFilename) {
623 std::string ErrorInfo;
624 raw_fd_ostream O(OutputFilename.c_str(), ErrorInfo);
626 if (ErrorInfo.empty()) {
627 errs() << "Writing '"<< OutputFilename << "' file...";
628 llvm::WriteGraph(O, this);
632 PrintError("Error opening file '" + OutputFilename + "' for writing!");
639 void CompilationGraph::viewGraph() {
640 llvm::ViewGraph(this, "compilation-graph");