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