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 "CompilationGraph.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/Support/CommandLine.h"
18 #include "llvm/Support/DOTGraphTraits.h"
19 #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 // Return the edge with the maximum weight.
39 const Edge* ChooseEdge(const C& EdgesContainer,
40 const InputLanguagesSet& InLangs,
41 const std::string& NodeName = "root") {
42 const Edge* MaxEdge = 0;
43 unsigned MaxWeight = 0;
44 bool SingleMax = true;
46 for (typename C::const_iterator B = EdgesContainer.begin(),
47 E = EdgesContainer.end(); B != E; ++B) {
48 const Edge* E = B->getPtr();
49 unsigned EW = E->Weight(InLangs);
55 else if (EW == MaxWeight) {
61 throw std::runtime_error("Node " + NodeName +
62 ": multiple maximal outward edges found!"
63 " Most probably a specification error.");
65 throw std::runtime_error("Node " + NodeName +
66 ": no maximal outward edge found!"
67 " Most probably a specification error.");
73 CompilationGraph::CompilationGraph() {
74 NodesMap["root"] = Node(this);
77 Node& CompilationGraph::getNode(const std::string& ToolName) {
78 nodes_map_type::iterator I = NodesMap.find(ToolName);
79 if (I == NodesMap.end())
80 throw std::runtime_error("Node " + ToolName + " is not in the graph");
84 const Node& CompilationGraph::getNode(const std::string& ToolName) const {
85 nodes_map_type::const_iterator I = NodesMap.find(ToolName);
86 if (I == NodesMap.end())
87 throw std::runtime_error("Node " + ToolName + " is not in the graph!");
91 const std::string& CompilationGraph::getLanguage(const sys::Path& File) const {
92 LanguageMap::const_iterator Lang = ExtsToLangs.find(File.getSuffix());
93 if (Lang == ExtsToLangs.end())
94 throw std::runtime_error("Unknown suffix: " + File.getSuffix() + '!');
98 const CompilationGraph::tools_vector_type&
99 CompilationGraph::getToolsVector(const std::string& LangName) const
101 tools_map_type::const_iterator I = ToolsMap.find(LangName);
102 if (I == ToolsMap.end())
103 throw std::runtime_error("No tool corresponding to the language "
104 + LangName + "found!");
108 void CompilationGraph::insertNode(Tool* V) {
109 if (NodesMap.count(V->Name()) == 0) {
111 N.OwningGraph = this;
113 NodesMap[V->Name()] = N;
117 void CompilationGraph::insertEdge(const std::string& A, Edge* E) {
118 Node& B = getNode(E->ToolName());
120 const std::string& InputLanguage = B.ToolPtr->InputLanguage();
121 ToolsMap[InputLanguage].push_back(IntrusiveRefCntPtr<Edge>(E));
122 NodesMap["root"].AddEdge(E);
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) {
135 sys::Path Out = TempDir;
136 Out.appendComponent(BaseName);
137 Out.appendSuffix(Suffix);
138 Out.makeUnique(true, NULL);
143 // Pass input file through the chain until we bump into a Join node or
144 // a node that says that it is the last.
145 void CompilationGraph::PassThroughGraph (const sys::Path& InFile,
146 const Node* StartNode,
147 const InputLanguagesSet& InLangs,
148 const sys::Path& TempDir) const {
150 sys::Path In = InFile;
151 const Node* CurNode = StartNode;
155 Tool* CurTool = CurNode->ToolPtr.getPtr();
157 if (CurTool->IsJoin()) {
158 JoinTool& JT = dynamic_cast<JoinTool&>(*CurTool);
159 JT.AddToJoinList(In);
163 // Since toolchains do not have to end with a Join node, we should
164 // check if this Node is the last.
165 if (!CurNode->HasChildren() || CurTool->IsLast()) {
166 if (!OutputFilename.empty()) {
167 Out.set(OutputFilename);
170 Out.set(In.getBasename());
171 Out.appendSuffix(CurTool->OutputSuffix());
176 Out = MakeTempFile(TempDir, In.getBasename(), CurTool->OutputSuffix());
179 if (CurTool->GenerateAction(In, Out).Execute() != 0)
180 throw std::runtime_error("Tool returned error code!");
185 CurNode = &getNode(ChooseEdge(CurNode->OutEdges,
187 CurNode->Name())->ToolName());
188 In = Out; Out.clear();
192 // Sort the nodes in topological order.
193 void CompilationGraph::TopologicalSort(std::vector<const Node*>& Out) {
194 std::queue<const Node*> Q;
195 Q.push(&getNode("root"));
198 const Node* A = Q.front();
201 for (Node::const_iterator EB = A->EdgesBegin(), EE = A->EdgesEnd();
203 Node* B = &getNode((*EB)->ToolName());
205 if (B->HasNoInEdges())
212 bool NotJoinNode(const Node* N) {
213 return N->ToolPtr ? !N->ToolPtr->IsJoin() : true;
217 // Call TopologicalSort and filter the resulting list to include
219 void CompilationGraph::
220 TopologicalSortFilterJoinNodes(std::vector<const Node*>& Out) {
221 std::vector<const Node*> TopSorted;
222 TopologicalSort(TopSorted);
223 std::remove_copy_if(TopSorted.begin(), TopSorted.end(),
224 std::back_inserter(Out), NotJoinNode);
227 // Find head of the toolchain corresponding to the given file.
228 // Also, insert an input language into InLangs.
229 const Node* CompilationGraph::
230 FindToolChain(const sys::Path& In, const std::string* forceLanguage,
231 InputLanguagesSet& InLangs) const {
233 // Determine the input language.
234 const std::string& InLanguage =
235 forceLanguage ? *forceLanguage : getLanguage(In);
237 // Add the current input language to the input language set.
238 InLangs.insert(InLanguage);
240 // Find the toolchain for the input language.
241 const tools_vector_type& TV = getToolsVector(InLanguage);
243 throw std::runtime_error("No toolchain corresponding to language"
244 + InLanguage + " found!");
245 return &getNode(ChooseEdge(TV, InLangs)->ToolName());
248 // Build the targets. Command-line options are passed through
249 // temporary variables.
250 int CompilationGraph::Build (const sys::Path& TempDir) {
252 InputLanguagesSet InLangs;
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);
303 // Pass file through the chain starting at head.
304 PassThroughGraph(In, N, InLangs, TempDir);
307 std::vector<const Node*> JTV;
308 TopologicalSortFilterJoinNodes(JTV);
310 // For all join nodes in topological order:
311 for (std::vector<const Node*>::iterator B = JTV.begin(), E = JTV.end();
315 const Node* CurNode = *B;
316 JoinTool* JT = &dynamic_cast<JoinTool&>(*CurNode->ToolPtr.getPtr());
319 // Are there any files to be joined?
320 if (JT->JoinListEmpty())
323 // Is this the last tool in the chain?
324 // NOTE: we can process several chains in parallel.
325 if (!CurNode->HasChildren() || JT->IsLast()) {
326 if (OutputFilename.empty()) {
328 Out.appendSuffix(JT->OutputSuffix());
331 Out.set(OutputFilename);
335 Out = MakeTempFile(TempDir, "tmp", JT->OutputSuffix());
338 if (JT->GenerateAction(Out).Execute() != 0)
339 throw std::runtime_error("Tool returned error code!");
342 const Node* NextNode =
343 &getNode(ChooseEdge(CurNode->OutEdges, InLangs,
344 CurNode->Name())->ToolName());
345 PassThroughGraph(Out, NextNode, InLangs, TempDir);
352 // Code related to graph visualization.
356 struct DOTGraphTraits<llvmc::CompilationGraph*>
357 : public DefaultDOTGraphTraits
360 template<typename GraphType>
361 static std::string getNodeLabel(const Node* N, const GraphType&)
364 if (N->ToolPtr->IsJoin())
365 return N->Name() + "\n (join" +
366 (N->HasChildren() ? ")"
367 : std::string(": ") + N->ToolPtr->OutputLanguage() + ')');
374 template<typename EdgeIter>
375 static std::string getEdgeSourceLabel(const Node* N, EdgeIter I) {
377 return N->ToolPtr->OutputLanguage();
379 return I->ToolPtr->InputLanguage();
385 void CompilationGraph::writeGraph() {
386 std::ofstream O("CompilationGraph.dot");
389 llvm::WriteGraph(this, "compilation-graph");
393 throw std::runtime_error("");
397 void CompilationGraph::viewGraph() {
398 llvm::ViewGraph(this, "compilation-graph");