4ae896bd99e28a5665a197cd59b183e2f04decfc
[oota-llvm.git] / lib / Support / ToolRunner.cpp
1 //===-- ToolRunner.cpp ----------------------------------------------------===//
2 //
3 // This file implements the interfaces described in the ToolRunner.h file.
4 //
5 //===----------------------------------------------------------------------===//
6
7 #define DEBUG_TYPE "toolrunner"
8 #include "llvm/Support/ToolRunner.h"
9 #include "Support/Debug.h"
10 #include "Support/FileUtilities.h"
11 #include <iostream>
12 #include <fstream>
13
14 //===---------------------------------------------------------------------===//
15 // LLI Implementation of AbstractIntepreter interface
16 //
17 class LLI : public AbstractInterpreter {
18   std::string LLIPath;          // The path to the LLI executable
19 public:
20   LLI(const std::string &Path) : LLIPath(Path) { }
21
22
23   virtual int ExecuteProgram(const std::string &Bytecode,
24                              const std::vector<std::string> &Args,
25                              const std::string &InputFile,
26                              const std::string &OutputFile,
27                              const std::vector<std::string> &SharedLibs = 
28                                std::vector<std::string>());
29 };
30
31 int LLI::ExecuteProgram(const std::string &Bytecode,
32                         const std::vector<std::string> &Args,
33                         const std::string &InputFile,
34                         const std::string &OutputFile,
35                         const std::vector<std::string> &SharedLibs) {
36   if (!SharedLibs.empty()) {
37     std::cerr << "LLI currently does not support loading shared libraries.\n"
38               << "Exiting.\n";
39     exit(1);
40   }
41
42   std::vector<const char*> LLIArgs;
43   LLIArgs.push_back(LLIPath.c_str());
44   LLIArgs.push_back("-quiet");
45   LLIArgs.push_back("-force-interpreter=true");
46   LLIArgs.push_back(Bytecode.c_str());
47   // Add optional parameters to the running program from Argv
48   for (unsigned i=0, e = Args.size(); i != e; ++i)
49     LLIArgs.push_back(Args[i].c_str());
50   LLIArgs.push_back(0);
51
52   std::cout << "<lli>" << std::flush;
53   DEBUG(std::cerr << "\nAbout to run:\t";
54         for (unsigned i=0, e = LLIArgs.size()-1; i != e; ++i)
55           std::cerr << " " << LLIArgs[i];
56         std::cerr << "\n";
57         );
58   return RunProgramWithTimeout(LLIPath, &LLIArgs[0],
59                                InputFile, OutputFile, OutputFile);
60 }
61
62 // LLI create method - Try to find the LLI executable
63 AbstractInterpreter *AbstractInterpreter::createLLI(const std::string &ProgPath,
64                                                     std::string &Message) {
65   std::string LLIPath = FindExecutable("lli", ProgPath);
66   if (!LLIPath.empty()) {
67     Message = "Found lli: " + LLIPath + "\n";
68     return new LLI(LLIPath);
69   }
70
71   Message = "Cannot find `lli' in executable directory or PATH!\n";
72   return 0;
73 }
74
75 //===----------------------------------------------------------------------===//
76 // LLC Implementation of AbstractIntepreter interface
77 //
78 int LLC::OutputAsm(const std::string &Bytecode, std::string &OutputAsmFile) {
79   OutputAsmFile = getUniqueFilename(Bytecode+".llc.s");
80   const char *LLCArgs[] = {
81     LLCPath.c_str(),
82     "-o", OutputAsmFile.c_str(), // Output to the Asm file
83     "-f",                        // Overwrite as necessary...
84     Bytecode.c_str(),            // This is the input bytecode
85     0
86   };
87
88   std::cout << "<llc>" << std::flush;
89   if (RunProgramWithTimeout(LLCPath, LLCArgs, "/dev/null", "/dev/null",
90                             "/dev/null")) {                            
91     // If LLC failed on the bytecode, print error...
92     std::cerr << "Error: `llc' failed!\n";
93     removeFile(OutputAsmFile);
94     return 1;
95   }
96
97   return 0;
98 }
99
100 int LLC::ExecuteProgram(const std::string &Bytecode,
101                         const std::vector<std::string> &Args,
102                         const std::string &InputFile,
103                         const std::string &OutputFile,
104                         const std::vector<std::string> &SharedLibs) {
105
106   std::string OutputAsmFile;
107   if (OutputAsm(Bytecode, OutputAsmFile)) {
108     std::cerr << "Could not generate asm code with `llc', exiting.\n";
109     exit(1);
110   }
111
112   // Assuming LLC worked, compile the result with GCC and run it.
113   int Result = gcc->ExecuteProgram(OutputAsmFile, Args, GCC::AsmFile,
114                                    InputFile, OutputFile, SharedLibs);
115   removeFile(OutputAsmFile);
116   return Result;
117 }
118
119 /// createLLC - Try to find the LLC executable
120 ///
121 LLC *AbstractInterpreter::createLLC(const std::string &ProgramPath,
122                                     std::string &Message) {
123   std::string LLCPath = FindExecutable("llc", ProgramPath);
124   if (LLCPath.empty()) {
125     Message = "Cannot find `llc' in executable directory or PATH!\n";
126     return 0;
127   }
128
129   Message = "Found llc: " + LLCPath + "\n";
130   GCC *gcc = GCC::create(ProgramPath, Message);
131   if (!gcc) {
132     std::cerr << Message << "\n";
133     exit(1);
134   }
135   return new LLC(LLCPath, gcc);
136 }
137
138 //===---------------------------------------------------------------------===//
139 // JIT Implementation of AbstractIntepreter interface
140 //
141 class JIT : public AbstractInterpreter {
142   std::string LLIPath;          // The path to the LLI executable
143 public:
144   JIT(const std::string &Path) : LLIPath(Path) { }
145
146
147   virtual int ExecuteProgram(const std::string &Bytecode,
148                              const std::vector<std::string> &Args,
149                              const std::string &InputFile,
150                              const std::string &OutputFile,
151                              const std::vector<std::string> &SharedLibs = 
152                                std::vector<std::string>());
153 };
154
155 int JIT::ExecuteProgram(const std::string &Bytecode,
156                         const std::vector<std::string> &Args,
157                         const std::string &InputFile,
158                         const std::string &OutputFile,
159                         const std::vector<std::string> &SharedLibs) {
160   // Construct a vector of parameters, incorporating those from the command-line
161   std::vector<const char*> JITArgs;
162   JITArgs.push_back(LLIPath.c_str());
163   JITArgs.push_back("-quiet");
164   JITArgs.push_back("-force-interpreter=false");
165
166   for (unsigned i = 0, e = SharedLibs.size(); i != e; ++i) {
167     JITArgs.push_back("-load");
168     JITArgs.push_back(SharedLibs[i].c_str());
169   }
170   JITArgs.push_back(Bytecode.c_str());
171   // Add optional parameters to the running program from Argv
172   for (unsigned i=0, e = Args.size(); i != e; ++i)
173     JITArgs.push_back(Args[i].c_str());
174   JITArgs.push_back(0);
175
176   std::cout << "<jit>" << std::flush;
177   DEBUG(std::cerr << "\nAbout to run:\t";
178         for (unsigned i=0, e = JITArgs.size()-1; i != e; ++i)
179           std::cerr << " " << JITArgs[i];
180         std::cerr << "\n";
181         );
182   DEBUG(std::cerr << "\nSending output to " << OutputFile << "\n");
183   return RunProgramWithTimeout(LLIPath, &JITArgs[0],
184                                InputFile, OutputFile, OutputFile);
185 }
186
187 /// createJIT - Try to find the LLI executable
188 ///
189 AbstractInterpreter *AbstractInterpreter::createJIT(const std::string &ProgPath,
190                                                     std::string &Message) {
191   std::string LLIPath = FindExecutable("lli", ProgPath);
192   if (!LLIPath.empty()) {
193     Message = "Found lli: " + LLIPath + "\n";
194     return new JIT(LLIPath);
195   }
196
197   Message = "Cannot find `lli' in executable directory or PATH!\n";
198   return 0;
199 }
200
201 int CBE::OutputC(const std::string &Bytecode,
202                  std::string &OutputCFile) {
203   OutputCFile = getUniqueFilename(Bytecode+".cbe.c");
204   const char *DisArgs[] = {
205     DISPath.c_str(),
206     "-o", OutputCFile.c_str(),   // Output to the C file
207     "-c",                        // Output to C
208     "-f",                        // Overwrite as necessary...
209     Bytecode.c_str(),            // This is the input bytecode
210     0
211   };
212
213   std::cout << "<cbe>" << std::flush;
214   if (RunProgramWithTimeout(DISPath, DisArgs, "/dev/null", "/dev/null",
215                             "/dev/null")) {                            
216     // If dis failed on the bytecode, print error...
217     std::cerr << "Error: `llvm-dis -c' failed!\n";
218     return 1;
219   }
220
221   return 0;
222 }
223
224 int CBE::ExecuteProgram(const std::string &Bytecode,
225                         const std::vector<std::string> &Args,
226                         const std::string &InputFile,
227                         const std::string &OutputFile,
228                         const std::vector<std::string> &SharedLibs) {
229   std::string OutputCFile;
230   if (OutputC(Bytecode, OutputCFile)) {
231     std::cerr << "Could not generate C code with `llvm-dis', exiting.\n";
232     exit(1);
233   }
234
235   int Result = gcc->ExecuteProgram(OutputCFile, Args, GCC::CFile, 
236                                    InputFile, OutputFile, SharedLibs);
237   removeFile(OutputCFile);
238
239   return Result;
240 }
241
242 /// createCBE - Try to find the 'llvm-dis' executable
243 ///
244 CBE *AbstractInterpreter::createCBE(const std::string &ProgramPath,
245                                     std::string &Message) {
246   std::string DISPath = FindExecutable("llvm-dis", ProgramPath);
247   if (DISPath.empty()) {
248     Message = 
249       "Cannot find `llvm-dis' in executable directory or PATH!\n";
250     return 0;
251   }
252
253   Message = "Found llvm-dis: " + DISPath + "\n";
254   GCC *gcc = GCC::create(ProgramPath, Message);
255   if (!gcc) {
256     std::cerr << Message << "\n";
257     exit(1);
258   }
259   return new CBE(DISPath, gcc);
260 }
261
262 //===---------------------------------------------------------------------===//
263 // GCC abstraction
264 //
265 int GCC::ExecuteProgram(const std::string &ProgramFile,
266                         const std::vector<std::string> &Args,
267                         FileType fileType,
268                         const std::string &InputFile,
269                         const std::string &OutputFile,
270                         const std::vector<std::string> &SharedLibs) {
271   std::vector<const char*> GCCArgs;
272
273   GCCArgs.push_back(GCCPath.c_str());
274
275   // Specify the shared libraries to link in...
276   for (unsigned i = 0, e = SharedLibs.size(); i != e; ++i)
277     GCCArgs.push_back(SharedLibs[i].c_str());
278   
279   // Specify -x explicitly in case the extension is wonky
280   GCCArgs.push_back("-x");
281   if (fileType == CFile) {
282     GCCArgs.push_back("c");
283     GCCArgs.push_back("-fno-strict-aliasing");
284   } else {
285     GCCArgs.push_back("assembler");
286   }
287   GCCArgs.push_back(ProgramFile.c_str());  // Specify the input filename...
288   GCCArgs.push_back("-o");
289   std::string OutputBinary = getUniqueFilename(ProgramFile+".gcc.exe");
290   GCCArgs.push_back(OutputBinary.c_str()); // Output to the right file...
291   GCCArgs.push_back("-lm");                // Hard-code the math library...
292   GCCArgs.push_back("-O2");                // Optimize the program a bit...
293   GCCArgs.push_back("-Wl,-R.");            // Search this dir for .so files
294   GCCArgs.push_back(0);                    // NULL terminator
295
296   std::cout << "<gcc>" << std::flush;
297   if (RunProgramWithTimeout(GCCPath, &GCCArgs[0], "/dev/null", "/dev/null",
298                             "/dev/null")) {
299     ProcessFailure(&GCCArgs[0]);
300     exit(1);
301   }
302
303   std::vector<const char*> ProgramArgs;
304   ProgramArgs.push_back(OutputBinary.c_str());
305   // Add optional parameters to the running program from Argv
306   for (unsigned i=0, e = Args.size(); i != e; ++i)
307     ProgramArgs.push_back(Args[i].c_str());
308   ProgramArgs.push_back(0);                // NULL terminator
309
310   // Now that we have a binary, run it!
311   std::cout << "<program>" << std::flush;
312   DEBUG(std::cerr << "\nAbout to run:\t";
313         for (unsigned i=0, e = ProgramArgs.size()-1; i != e; ++i)
314           std::cerr << " " << ProgramArgs[i];
315         std::cerr << "\n";
316         );
317   int ProgramResult = RunProgramWithTimeout(OutputBinary, &ProgramArgs[0],
318                                             InputFile, OutputFile, OutputFile);
319   removeFile(OutputBinary);
320   return ProgramResult;
321 }
322
323 int GCC::MakeSharedObject(const std::string &InputFile, FileType fileType,
324                           std::string &OutputFile) {
325   OutputFile = getUniqueFilename(InputFile+".so");
326   // Compile the C/asm file into a shared object
327   const char* GCCArgs[] = {
328     GCCPath.c_str(),
329     "-x", (fileType == AsmFile) ? "assembler" : "c",
330     "-fno-strict-aliasing",
331     InputFile.c_str(),           // Specify the input filename...
332 #if defined(sparc) || defined(__sparc__) || defined(__sparcv9)
333     "-G",                        // Compile a shared library, `-G' for Sparc
334 #else                             
335     "-shared",                   // `-shared' for Linux/X86, maybe others
336 #endif
337     "-o", OutputFile.c_str(),    // Output to the right filename...
338     "-O2",                       // Optimize the program a bit...
339     0
340   };
341   
342   std::cout << "<gcc>" << std::flush;
343   if (RunProgramWithTimeout(GCCPath, GCCArgs, "/dev/null", "/dev/null",
344                             "/dev/null")) {
345     ProcessFailure(GCCArgs);
346     return 1;
347   }
348   return 0;
349 }
350
351 void GCC::ProcessFailure(const char** GCCArgs) {
352   std::cerr << "\n*** Error: invocation of the C compiler failed!\n";
353   for (const char **Arg = GCCArgs; *Arg; ++Arg)
354     std::cerr << " " << *Arg;
355   std::cerr << "\n";
356
357   // Rerun the compiler, capturing any error messages to print them.
358   std::string ErrorFilename = getUniqueFilename("gcc.errors");
359   RunProgramWithTimeout(GCCPath, GCCArgs, "/dev/null", ErrorFilename.c_str(),
360                         ErrorFilename.c_str());
361
362   // Print out the error messages generated by GCC if possible...
363   std::ifstream ErrorFile(ErrorFilename.c_str());
364   if (ErrorFile) {
365     std::copy(std::istreambuf_iterator<char>(ErrorFile),
366               std::istreambuf_iterator<char>(),
367               std::ostreambuf_iterator<char>(std::cerr));
368     ErrorFile.close();
369     std::cerr << "\n";      
370   }
371
372   removeFile(ErrorFilename);
373 }
374
375 /// create - Try to find the `gcc' executable
376 ///
377 GCC *GCC::create(const std::string &ProgramPath, std::string &Message) {
378   std::string GCCPath = FindExecutable("gcc", ProgramPath);
379   if (GCCPath.empty()) {
380     Message = "Cannot find `gcc' in executable directory or PATH!\n";
381     return 0;
382   }
383
384   Message = "Found gcc: " + GCCPath + "\n";
385   return new GCC(GCCPath);
386 }