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.
51 const Edge* ChooseEdge(const C& EdgesContainer,
52 const InputLanguagesSet& InLangs,
53 const std::string& NodeName = "root") {
54 const Edge* MaxEdge = 0;
55 unsigned MaxWeight = 0;
56 bool SingleMax = true;
58 for (typename C::const_iterator B = EdgesContainer.begin(),
59 E = EdgesContainer.end(); B != E; ++B) {
60 const Edge* e = B->getPtr();
61 unsigned EW = e->Weight(InLangs);
66 } else if (EW == MaxWeight) {
72 PrintError("Node " + NodeName + ": multiple maximal outward edges found!"
73 " Most probably a specification error.");
77 PrintError("Node " + NodeName + ": no maximal outward edge found!"
78 " Most probably a specification error.");
86 void Node::AddEdge(Edge* Edg) {
87 // If there already was an edge between two nodes, modify it instead
88 // of adding a new edge.
89 const std::string& ToolName = Edg->ToolName();
90 for (container_type::iterator B = OutEdges.begin(), E = OutEdges.end();
92 if ((*B)->ToolName() == ToolName) {
93 llvm::IntrusiveRefCntPtr<Edge>(Edg).swap(*B);
97 OutEdges.push_back(llvm::IntrusiveRefCntPtr<Edge>(Edg));
100 CompilationGraph::CompilationGraph() {
101 NodesMap["root"] = Node(this);
104 Node* CompilationGraph::getNode(const std::string& ToolName) {
105 nodes_map_type::iterator I = NodesMap.find(ToolName);
106 if (I == NodesMap.end()) {
107 PrintError("Node " + ToolName + " is not in the graph");
113 const Node* CompilationGraph::getNode(const std::string& ToolName) const {
114 nodes_map_type::const_iterator I = NodesMap.find(ToolName);
115 if (I == NodesMap.end()) {
116 PrintError("Node " + ToolName + " is not in the graph!");
122 // Find the tools list corresponding to the given language name.
123 const CompilationGraph::tools_vector_type*
124 CompilationGraph::getToolsVector(const std::string& LangName) const
126 tools_map_type::const_iterator I = ToolsMap.find(LangName);
127 if (I == ToolsMap.end()) {
128 PrintError("No tool corresponding to the language " + LangName + " found");
134 void CompilationGraph::insertNode(Tool* V) {
135 if (NodesMap.count(V->Name()) == 0)
136 NodesMap[V->Name()] = Node(this, V);
139 int CompilationGraph::insertEdge(const std::string& A, Edge* Edg) {
140 Node* B = getNode(Edg->ToolName());
145 const char** InLangs = B->ToolPtr->InputLanguages();
146 for (;*InLangs; ++InLangs)
147 ToolsMap[*InLangs].push_back(IntrusiveRefCntPtr<Edge>(Edg));
148 NodesMap["root"].AddEdge(Edg);
151 Node* N = getNode(A);
157 // Increase the inward edge counter.
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 int CompilationGraph::PassThroughGraph (const sys::Path& InFile,
166 const Node* StartNode,
167 const InputLanguagesSet& InLangs,
168 const sys::Path& TempDir,
169 const LanguageMap& LangMap) const {
170 sys::Path In = InFile;
171 const Node* CurNode = StartNode;
174 Tool* CurTool = CurNode->ToolPtr.getPtr();
176 if (CurTool->IsJoin()) {
177 JoinTool& JT = static_cast<JoinTool&>(*CurTool);
178 JT.AddToJoinList(In);
183 if (int ret = CurTool->GenerateAction(CurAction, In, CurNode->HasChildren(),
184 TempDir, InLangs, LangMap)) {
188 if (int ret = CurAction.Execute())
191 if (CurAction.StopCompilation())
194 const Edge* Edg = ChooseEdge(CurNode->OutEdges, InLangs, CurNode->Name());
198 CurNode = getNode(Edg->ToolName());
202 In = CurAction.OutFile();
208 // Find the head of the toolchain corresponding to the given file.
209 // Also, insert an input language into InLangs.
210 const Node* CompilationGraph::
211 FindToolChain(const sys::Path& In, const std::string* ForceLanguage,
212 InputLanguagesSet& InLangs, const LanguageMap& LangMap) const {
214 // Determine the input language.
215 const std::string* InLang = LangMap.GetLanguage(In);
218 const std::string& InLanguage = (ForceLanguage ? *ForceLanguage : *InLang);
220 // Add the current input language to the input language set.
221 InLangs.insert(InLanguage);
223 // Find the toolchain for the input language.
224 const tools_vector_type* pTV = getToolsVector(InLanguage);
228 const tools_vector_type& TV = *pTV;
230 PrintError("No toolchain corresponding to language "
231 + InLanguage + " found");
235 const Edge* Edg = ChooseEdge(TV, InLangs);
239 return getNode(Edg->ToolName());
242 // Helper function used by Build().
243 // Traverses initial portions of the toolchains (up to the first Join node).
244 // This function is also responsible for handling the -x option.
245 int CompilationGraph::BuildInitial (InputLanguagesSet& InLangs,
246 const sys::Path& TempDir,
247 const LanguageMap& LangMap) {
248 // This is related to -x option handling.
249 cl::list<std::string>::const_iterator xIter = Languages.begin(),
250 xBegin = xIter, xEnd = Languages.end();
252 const std::string* xLanguage = 0;
253 unsigned xPos = 0, xPosNext = 0, filePos = 0;
257 xPos = Languages.getPosition(xIter - xBegin);
258 cl::list<std::string>::const_iterator xNext = llvm::next(xIter);
259 xPosNext = (xNext == xEnd) ? std::numeric_limits<unsigned>::max()
260 : Languages.getPosition(xNext - xBegin);
261 xLanguage = (*xIter == "none") ? 0 : &(*xIter);
264 // For each input file:
265 for (cl::list<std::string>::const_iterator B = InputFilenames.begin(),
266 CB = B, E = InputFilenames.end(); B != E; ++B) {
267 sys::Path In = sys::Path(*B);
269 // Code for handling the -x option.
270 // Output: std::string* xLanguage (can be NULL).
272 filePos = InputFilenames.getPosition(B - CB);
274 if (xPos < filePos) {
275 if (filePos < xPosNext) {
276 xLanguage = (*xIter == "none") ? 0 : &(*xIter);
278 else { // filePos >= xPosNext
279 // Skip xIters while filePos > xPosNext
280 while (filePos > xPosNext) {
284 cl::list<std::string>::const_iterator xNext = llvm::next(xIter);
286 xPosNext = std::numeric_limits<unsigned>::max();
288 xPosNext = Languages.getPosition(xNext - xBegin);
289 xLanguage = (*xIter == "none") ? 0 : &(*xIter);
295 // Find the toolchain corresponding to this file.
296 const Node* N = FindToolChain(In, xLanguage, InLangs, LangMap);
299 // Pass file through the chain starting at head.
300 if (int ret = PassThroughGraph(In, N, InLangs, TempDir, LangMap))
307 // Sort the nodes in topological order.
308 int CompilationGraph::TopologicalSort(std::vector<const Node*>& Out) {
309 std::queue<const Node*> Q;
311 Node* Root = getNode("root");
318 const Node* A = Q.front();
321 for (Node::const_iterator EB = A->EdgesBegin(), EE = A->EdgesEnd();
323 Node* B = getNode((*EB)->ToolName());
328 if (B->HasNoInEdges())
337 bool NotJoinNode(const Node* N) {
338 return N->ToolPtr ? !N->ToolPtr->IsJoin() : true;
342 // Call TopologicalSort and filter the resulting list to include
344 int CompilationGraph::
345 TopologicalSortFilterJoinNodes(std::vector<const Node*>& Out) {
346 std::vector<const Node*> TopSorted;
347 if (int ret = TopologicalSort(TopSorted))
349 std::remove_copy_if(TopSorted.begin(), TopSorted.end(),
350 std::back_inserter(Out), NotJoinNode);
355 int CompilationGraph::Build (const sys::Path& TempDir,
356 const LanguageMap& LangMap) {
357 InputLanguagesSet InLangs;
358 bool WasSomeActionGenerated = !InputFilenames.empty();
360 // Traverse initial parts of the toolchains and fill in InLangs.
361 if (int ret = BuildInitial(InLangs, TempDir, LangMap))
364 std::vector<const Node*> JTV;
365 if (int ret = TopologicalSortFilterJoinNodes(JTV))
368 // For all join nodes in topological order:
369 for (std::vector<const Node*>::iterator B = JTV.begin(), E = JTV.end();
372 const Node* CurNode = *B;
373 JoinTool* JT = &static_cast<JoinTool&>(*CurNode->ToolPtr.getPtr());
375 // Are there any files in the join list?
376 if (JT->JoinListEmpty() && !(JT->WorksOnEmpty() && InputFilenames.empty()))
379 WasSomeActionGenerated = true;
381 if (int ret = JT->GenerateAction(CurAction, CurNode->HasChildren(),
382 TempDir, InLangs, LangMap)) {
386 if (int ret = CurAction.Execute())
389 if (CurAction.StopCompilation())
392 const Edge* Edg = ChooseEdge(CurNode->OutEdges, InLangs, CurNode->Name());
396 const Node* NextNode = getNode(Edg->ToolName());
400 if (int ret = PassThroughGraph(sys::Path(CurAction.OutFile()), NextNode,
401 InLangs, TempDir, LangMap)) {
406 if (!WasSomeActionGenerated) {
407 PrintError("no input files");
414 int CompilationGraph::CheckLanguageNames() const {
417 // Check that names for output and input languages on all edges do match.
418 for (const_nodes_iterator B = this->NodesMap.begin(),
419 E = this->NodesMap.end(); B != E; ++B) {
421 const Node & N1 = B->second;
423 for (Node::const_iterator EB = N1.EdgesBegin(), EE = N1.EdgesEnd();
425 const Node* N2 = this->getNode((*EB)->ToolName());
431 errs() << "Error: there is an edge from '" << N1.ToolPtr->Name()
432 << "' back to the root!\n\n";
436 const char* OutLang = N1.ToolPtr->OutputLanguage();
437 const char** InLangs = N2->ToolPtr->InputLanguages();
439 for (;*InLangs; ++InLangs) {
440 if (std::strcmp(OutLang, *InLangs) == 0) {
448 errs() << "Error: Output->input language mismatch in the edge '"
449 << N1.ToolPtr->Name() << "' -> '" << N2->ToolPtr->Name()
451 << "Expected one of { ";
453 InLangs = N2->ToolPtr->InputLanguages();
454 for (;*InLangs; ++InLangs) {
455 errs() << '\'' << *InLangs << (*(InLangs+1) ? "', " : "'");
458 errs() << " }, but got '" << OutLang << "'!\n\n";
468 int CompilationGraph::CheckMultipleDefaultEdges() const {
470 InputLanguagesSet Dummy;
472 // For all nodes, just iterate over the outgoing edges and check if there is
473 // more than one edge with maximum weight.
474 for (const_nodes_iterator B = this->NodesMap.begin(),
475 E = this->NodesMap.end(); B != E; ++B) {
476 const Node& N = B->second;
477 unsigned MaxWeight = 0;
479 // Ignore the root node.
483 for (Node::const_iterator EB = N.EdgesBegin(), EE = N.EdgesEnd();
485 unsigned EdgeWeight = (*EB)->Weight(Dummy);
486 if (EdgeWeight > MaxWeight) {
487 MaxWeight = EdgeWeight;
489 else if (EdgeWeight == MaxWeight) {
491 errs() << "Error: there are multiple maximal edges stemming from the '"
492 << N.ToolPtr->Name() << "' node!\n\n";
501 int CompilationGraph::CheckCycles() {
502 unsigned deleted = 0;
505 Node* Root = getNode("root");
511 // Try to delete all nodes that have no ingoing edges, starting from the
512 // root. If there are any nodes left after this operation, then we have a
513 // cycle. This relies on '--check-graph' not performing the topological sort.
519 for (Node::iterator EB = A->EdgesBegin(), EE = A->EdgesEnd();
521 Node* B = getNode((*EB)->ToolName());
526 if (B->HasNoInEdges())
531 if (deleted != NodesMap.size()) {
532 errs() << "Error: there are cycles in the compilation graph!\n"
533 << "Try inspecting the diagram produced by "
534 << "'llvmc --view-graph'.\n\n";
541 int CompilationGraph::Check () {
542 // We try to catch as many errors as we can in one go.
546 // Check that output/input language names match.
547 ret = this->CheckLanguageNames();
552 // Check for multiple default edges.
553 ret = this->CheckMultipleDefaultEdges();
559 ret = this->CheckCycles();
567 // Code related to graph visualization.
571 struct DOTGraphTraits<llvmc::CompilationGraph*>
572 : public DefaultDOTGraphTraits
574 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
576 template<typename GraphType>
577 static std::string getNodeLabel(const Node* N, const GraphType&)
580 if (N->ToolPtr->IsJoin())
581 return N->Name() + "\n (join" +
582 (N->HasChildren() ? ")"
583 : std::string(": ") + N->ToolPtr->OutputLanguage() + ')');
590 template<typename EdgeIter>
591 static std::string getEdgeSourceLabel(const Node* N, EdgeIter I) {
593 return N->ToolPtr->OutputLanguage();
596 const char** InLangs = I->ToolPtr->InputLanguages();
599 for (; *InLangs; ++InLangs) {
600 if (*(InLangs + 1)) {
616 int CompilationGraph::writeGraph(const std::string& OutputFilename) {
617 std::string ErrorInfo;
618 raw_fd_ostream O(OutputFilename.c_str(), ErrorInfo);
620 if (ErrorInfo.empty()) {
621 errs() << "Writing '"<< OutputFilename << "' file...";
622 llvm::WriteGraph(O, this);
626 PrintError("Error opening file '" + OutputFilename + "' for writing!");
633 void CompilationGraph::viewGraph() {
634 llvm::ViewGraph(this, "compilation-graph");