Rename FindExecutable to PrependMainExecutablePath.
[oota-llvm.git] / tools / bugpoint / ToolRunner.cpp
1 //===-- ToolRunner.cpp ----------------------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the interfaces described in the ToolRunner.h file.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "toolrunner"
15 #include "ToolRunner.h"
16 #include "llvm/System/Program.h"
17 #include "llvm/Support/CommandLine.h"
18 #include "llvm/Support/Debug.h"
19 #include "llvm/Support/FileUtilities.h"
20 #include "llvm/Support/raw_ostream.h"
21 #include "llvm/Config/config.h"   // for HAVE_LINK_R
22 #include <fstream>
23 #include <sstream>
24 using namespace llvm;
25
26 namespace llvm {
27   cl::opt<bool>
28   SaveTemps("save-temps", cl::init(false), cl::desc("Save temporary files"));
29 }
30
31 namespace {
32   cl::opt<std::string>
33   RemoteClient("remote-client",
34                cl::desc("Remote execution client (rsh/ssh)"));
35
36   cl::opt<std::string>
37   RemoteHost("remote-host",
38              cl::desc("Remote execution (rsh/ssh) host"));
39
40   cl::opt<std::string>
41   RemotePort("remote-port",
42              cl::desc("Remote execution (rsh/ssh) port"));
43
44   cl::opt<std::string>
45   RemoteUser("remote-user",
46              cl::desc("Remote execution (rsh/ssh) user id"));
47
48   cl::opt<std::string>
49   RemoteExtra("remote-extra-options",
50           cl::desc("Remote execution (rsh/ssh) extra options"));
51 }
52
53 /// RunProgramWithTimeout - This function provides an alternate interface
54 /// to the sys::Program::ExecuteAndWait interface.
55 /// @see sys::Program::ExecuteAndWait
56 static int RunProgramWithTimeout(const sys::Path &ProgramPath,
57                                  const char **Args,
58                                  const sys::Path &StdInFile,
59                                  const sys::Path &StdOutFile,
60                                  const sys::Path &StdErrFile,
61                                  unsigned NumSeconds = 0,
62                                  unsigned MemoryLimit = 0) {
63   const sys::Path* redirects[3];
64   redirects[0] = &StdInFile;
65   redirects[1] = &StdOutFile;
66   redirects[2] = &StdErrFile;
67
68 #if 0 // For debug purposes
69   {
70     errs() << "RUN:";
71     for (unsigned i = 0; Args[i]; ++i)
72       errs() << " " << Args[i];
73     errs() << "\n";
74   }
75 #endif
76
77   return
78     sys::Program::ExecuteAndWait(ProgramPath, Args, 0, redirects,
79                                  NumSeconds, MemoryLimit);
80 }
81
82 /// RunProgramRemotelyWithTimeout - This function runs the given program
83 /// remotely using the given remote client and the sys::Program::ExecuteAndWait.
84 /// Returns the remote program exit code or reports a remote client error if it
85 /// fails. Remote client is required to return 255 if it failed or program exit
86 /// code otherwise.
87 /// @see sys::Program::ExecuteAndWait
88 static int RunProgramRemotelyWithTimeout(const sys::Path &RemoteClientPath,
89                                          const char **Args,
90                                          const sys::Path &StdInFile,
91                                          const sys::Path &StdOutFile,
92                                          const sys::Path &StdErrFile,
93                                          unsigned NumSeconds = 0,
94                                          unsigned MemoryLimit = 0) {
95   const sys::Path* redirects[3];
96   redirects[0] = &StdInFile;
97   redirects[1] = &StdOutFile;
98   redirects[2] = &StdErrFile;
99
100 #if 0 // For debug purposes
101   {
102     errs() << "RUN:";
103     for (unsigned i = 0; Args[i]; ++i)
104       errs() << " " << Args[i];
105     errs() << "\n";
106   }
107 #endif
108
109   // Run the program remotely with the remote client
110   int ReturnCode = sys::Program::ExecuteAndWait(RemoteClientPath, Args,
111                                  0, redirects, NumSeconds, MemoryLimit);
112
113   // Has the remote client fail?
114   if (255 == ReturnCode) {
115     std::ostringstream OS;
116     OS << "\nError running remote client:\n ";
117     for (const char **Arg = Args; *Arg; ++Arg)
118       OS << " " << *Arg;
119     OS << "\n";
120
121     // The error message is in the output file, let's print it out from there.
122     std::ifstream ErrorFile(StdOutFile.c_str());
123     if (ErrorFile) {
124       std::copy(std::istreambuf_iterator<char>(ErrorFile),
125                 std::istreambuf_iterator<char>(),
126                 std::ostreambuf_iterator<char>(OS));
127       ErrorFile.close();
128     }
129
130     errs() << OS;
131   }
132
133   return ReturnCode;
134 }
135
136 static std::string ProcessFailure(sys::Path ProgPath, const char** Args,
137                                   unsigned Timeout = 0,
138                                   unsigned MemoryLimit = 0) {
139   std::ostringstream OS;
140   OS << "\nError running tool:\n ";
141   for (const char **Arg = Args; *Arg; ++Arg)
142     OS << " " << *Arg;
143   OS << "\n";
144
145   // Rerun the compiler, capturing any error messages to print them.
146   sys::Path ErrorFilename("bugpoint.program_error_messages");
147   std::string ErrMsg;
148   if (ErrorFilename.makeUnique(true, &ErrMsg)) {
149     errs() << "Error making unique filename: " << ErrMsg << "\n";
150     exit(1);
151   }
152   RunProgramWithTimeout(ProgPath, Args, sys::Path(""), ErrorFilename,
153                         ErrorFilename, Timeout, MemoryLimit);
154   // FIXME: check return code ?
155
156   // Print out the error messages generated by GCC if possible...
157   std::ifstream ErrorFile(ErrorFilename.c_str());
158   if (ErrorFile) {
159     std::copy(std::istreambuf_iterator<char>(ErrorFile),
160               std::istreambuf_iterator<char>(),
161               std::ostreambuf_iterator<char>(OS));
162     ErrorFile.close();
163   }
164
165   ErrorFilename.eraseFromDisk();
166   return OS.str();
167 }
168
169 //===---------------------------------------------------------------------===//
170 // LLI Implementation of AbstractIntepreter interface
171 //
172 namespace {
173   class LLI : public AbstractInterpreter {
174     std::string LLIPath;          // The path to the LLI executable
175     std::vector<std::string> ToolArgs; // Args to pass to LLI
176   public:
177     LLI(const std::string &Path, const std::vector<std::string> *Args)
178       : LLIPath(Path) {
179       ToolArgs.clear ();
180       if (Args) { ToolArgs = *Args; }
181     }
182
183     virtual int ExecuteProgram(const std::string &Bitcode,
184                                const std::vector<std::string> &Args,
185                                const std::string &InputFile,
186                                const std::string &OutputFile,
187                                std::string *Error,
188                                const std::vector<std::string> &GCCArgs,
189                                const std::vector<std::string> &SharedLibs =
190                                std::vector<std::string>(),
191                                unsigned Timeout = 0,
192                                unsigned MemoryLimit = 0);
193   };
194 }
195
196 int LLI::ExecuteProgram(const std::string &Bitcode,
197                         const std::vector<std::string> &Args,
198                         const std::string &InputFile,
199                         const std::string &OutputFile,
200                         std::string *Error,
201                         const std::vector<std::string> &GCCArgs,
202                         const std::vector<std::string> &SharedLibs,
203                         unsigned Timeout,
204                         unsigned MemoryLimit) {
205   std::vector<const char*> LLIArgs;
206   LLIArgs.push_back(LLIPath.c_str());
207   LLIArgs.push_back("-force-interpreter=true");
208
209   for (std::vector<std::string>::const_iterator i = SharedLibs.begin(),
210          e = SharedLibs.end(); i != e; ++i) {
211     LLIArgs.push_back("-load");
212     LLIArgs.push_back((*i).c_str());
213   }
214
215   // Add any extra LLI args.
216   for (unsigned i = 0, e = ToolArgs.size(); i != e; ++i)
217     LLIArgs.push_back(ToolArgs[i].c_str());
218
219   LLIArgs.push_back(Bitcode.c_str());
220   // Add optional parameters to the running program from Argv
221   for (unsigned i=0, e = Args.size(); i != e; ++i)
222     LLIArgs.push_back(Args[i].c_str());
223   LLIArgs.push_back(0);
224
225   outs() << "<lli>"; outs().flush();
226   DEBUG(errs() << "\nAbout to run:\t";
227         for (unsigned i=0, e = LLIArgs.size()-1; i != e; ++i)
228           errs() << " " << LLIArgs[i];
229         errs() << "\n";
230         );
231   return RunProgramWithTimeout(sys::Path(LLIPath), &LLIArgs[0],
232       sys::Path(InputFile), sys::Path(OutputFile), sys::Path(OutputFile),
233       Timeout, MemoryLimit);
234 }
235
236 // LLI create method - Try to find the LLI executable
237 AbstractInterpreter *AbstractInterpreter::createLLI(const char *Argv0,
238                                                     std::string &Message,
239                                      const std::vector<std::string> *ToolArgs) {
240   std::string LLIPath =
241     PrependMainExecutablePath("lli", Argv0, (void *)(intptr_t)&createLLI).str();
242   if (!LLIPath.empty()) {
243     Message = "Found lli: " + LLIPath + "\n";
244     return new LLI(LLIPath, ToolArgs);
245   }
246
247   Message = "Cannot find `lli' in executable directory!\n";
248   return 0;
249 }
250
251 //===---------------------------------------------------------------------===//
252 // Custom execution command implementation of AbstractIntepreter interface
253 //
254 // Allows using a custom command for executing the bitcode, thus allows,
255 // for example, to invoke a cross compiler for code generation followed by
256 // a simulator that executes the generated binary.
257 namespace {
258   class CustomExecutor : public AbstractInterpreter {
259     std::string ExecutionCommand;
260     std::vector<std::string> ExecutorArgs;
261   public:
262     CustomExecutor(
263       const std::string &ExecutionCmd, std::vector<std::string> ExecArgs) :
264       ExecutionCommand(ExecutionCmd), ExecutorArgs(ExecArgs) {}
265
266     virtual int ExecuteProgram(const std::string &Bitcode,
267                                const std::vector<std::string> &Args,
268                                const std::string &InputFile,
269                                const std::string &OutputFile,
270                                std::string *Error,
271                                const std::vector<std::string> &GCCArgs,
272                                const std::vector<std::string> &SharedLibs =
273                                  std::vector<std::string>(),
274                                unsigned Timeout = 0,
275                                unsigned MemoryLimit = 0);
276   };
277 }
278
279 int CustomExecutor::ExecuteProgram(const std::string &Bitcode,
280                         const std::vector<std::string> &Args,
281                         const std::string &InputFile,
282                         const std::string &OutputFile,
283                         std::string *Error,
284                         const std::vector<std::string> &GCCArgs,
285                         const std::vector<std::string> &SharedLibs,
286                         unsigned Timeout,
287                         unsigned MemoryLimit) {
288
289   std::vector<const char*> ProgramArgs;
290   ProgramArgs.push_back(ExecutionCommand.c_str());
291
292   for (std::size_t i = 0; i < ExecutorArgs.size(); ++i)
293     ProgramArgs.push_back(ExecutorArgs.at(i).c_str());
294   ProgramArgs.push_back(Bitcode.c_str());
295   ProgramArgs.push_back(0);
296
297   // Add optional parameters to the running program from Argv
298   for (unsigned i = 0, e = Args.size(); i != e; ++i)
299     ProgramArgs.push_back(Args[i].c_str());
300
301   return RunProgramWithTimeout(
302     sys::Path(ExecutionCommand),
303     &ProgramArgs[0], sys::Path(InputFile), sys::Path(OutputFile),
304     sys::Path(OutputFile), Timeout, MemoryLimit);
305 }
306
307 // Custom execution environment create method, takes the execution command
308 // as arguments
309 AbstractInterpreter *AbstractInterpreter::createCustom(
310                     std::string &Message,
311                     const std::string &ExecCommandLine) {
312
313   std::string Command = "";
314   std::vector<std::string> Args;
315   std::string delimiters = " ";
316
317   // Tokenize the ExecCommandLine to the command and the args to allow
318   // defining a full command line as the command instead of just the
319   // executed program. We cannot just pass the whole string after the command
320   // as a single argument because then program sees only a single
321   // command line argument (with spaces in it: "foo bar" instead
322   // of "foo" and "bar").
323
324   // code borrowed from:
325   // http://oopweb.com/CPP/Documents/CPPHOWTO/Volume/C++Programming-HOWTO-7.html
326   std::string::size_type lastPos =
327     ExecCommandLine.find_first_not_of(delimiters, 0);
328   std::string::size_type pos =
329     ExecCommandLine.find_first_of(delimiters, lastPos);
330
331   while (std::string::npos != pos || std::string::npos != lastPos) {
332     std::string token = ExecCommandLine.substr(lastPos, pos - lastPos);
333     if (Command == "")
334        Command = token;
335     else
336        Args.push_back(token);
337     // Skip delimiters.  Note the "not_of"
338     lastPos = ExecCommandLine.find_first_not_of(delimiters, pos);
339     // Find next "non-delimiter"
340     pos = ExecCommandLine.find_first_of(delimiters, lastPos);
341   }
342
343   std::string CmdPath = sys::Program::FindProgramByName(Command).str();
344   if (CmdPath.empty()) {
345     Message =
346       std::string("Cannot find '") + Command +
347       "' in PATH!\n";
348     return 0;
349   }
350
351   Message = "Found command in: " + CmdPath + "\n";
352
353   return new CustomExecutor(CmdPath, Args);
354 }
355
356 //===----------------------------------------------------------------------===//
357 // LLC Implementation of AbstractIntepreter interface
358 //
359 GCC::FileType LLC::OutputCode(const std::string &Bitcode,
360                               sys::Path &OutputAsmFile, std::string &Error,
361                               unsigned Timeout, unsigned MemoryLimit) {
362   const char *Suffix = (UseIntegratedAssembler ? ".llc.o" : ".llc.s");
363   sys::Path uniqueFile(Bitcode + Suffix);
364   std::string ErrMsg;
365   if (uniqueFile.makeUnique(true, &ErrMsg)) {
366     errs() << "Error making unique filename: " << ErrMsg << "\n";
367     exit(1);
368   }
369   OutputAsmFile = uniqueFile;
370   std::vector<const char *> LLCArgs;
371   LLCArgs.push_back(LLCPath.c_str());
372
373   // Add any extra LLC args.
374   for (unsigned i = 0, e = ToolArgs.size(); i != e; ++i)
375     LLCArgs.push_back(ToolArgs[i].c_str());
376
377   LLCArgs.push_back("-o");
378   LLCArgs.push_back(OutputAsmFile.c_str()); // Output to the Asm file
379   LLCArgs.push_back(Bitcode.c_str());      // This is the input bitcode
380
381   if (UseIntegratedAssembler)
382     LLCArgs.push_back("-filetype=obj");
383
384   LLCArgs.push_back (0);
385
386   outs() << (UseIntegratedAssembler ? "<llc-ia>" : "<llc>");
387   outs().flush();
388   DEBUG(errs() << "\nAbout to run:\t";
389         for (unsigned i = 0, e = LLCArgs.size()-1; i != e; ++i)
390           errs() << " " << LLCArgs[i];
391         errs() << "\n";
392         );
393   if (RunProgramWithTimeout(sys::Path(LLCPath), &LLCArgs[0],
394                             sys::Path(), sys::Path(), sys::Path(),
395                             Timeout, MemoryLimit))
396     Error = ProcessFailure(sys::Path(LLCPath), &LLCArgs[0],
397                            Timeout, MemoryLimit);
398   return UseIntegratedAssembler ? GCC::ObjectFile : GCC::AsmFile;
399 }
400
401 void LLC::compileProgram(const std::string &Bitcode, std::string *Error,
402                          unsigned Timeout, unsigned MemoryLimit) {
403   sys::Path OutputAsmFile;
404   OutputCode(Bitcode, OutputAsmFile, *Error, Timeout, MemoryLimit);
405   OutputAsmFile.eraseFromDisk();
406 }
407
408 int LLC::ExecuteProgram(const std::string &Bitcode,
409                         const std::vector<std::string> &Args,
410                         const std::string &InputFile,
411                         const std::string &OutputFile,
412                         std::string *Error,
413                         const std::vector<std::string> &ArgsForGCC,
414                         const std::vector<std::string> &SharedLibs,
415                         unsigned Timeout,
416                         unsigned MemoryLimit) {
417
418   sys::Path OutputAsmFile;
419   GCC::FileType FileKind = OutputCode(Bitcode, OutputAsmFile, *Error, Timeout,
420                                       MemoryLimit);
421   FileRemover OutFileRemover(OutputAsmFile, !SaveTemps);
422
423   std::vector<std::string> GCCArgs(ArgsForGCC);
424   GCCArgs.insert(GCCArgs.end(), SharedLibs.begin(), SharedLibs.end());
425
426   // Assuming LLC worked, compile the result with GCC and run it.
427   return gcc->ExecuteProgram(OutputAsmFile.str(), Args, FileKind,
428                              InputFile, OutputFile, Error, GCCArgs,
429                              Timeout, MemoryLimit);
430 }
431
432 /// createLLC - Try to find the LLC executable
433 ///
434 LLC *AbstractInterpreter::createLLC(const char *Argv0,
435                                     std::string &Message,
436                                     const std::string &GCCBinary,
437                                     const std::vector<std::string> *Args,
438                                     const std::vector<std::string> *GCCArgs,
439                                     bool UseIntegratedAssembler) {
440   std::string LLCPath =
441     PrependMainExecutablePath("llc", Argv0, (void *)(intptr_t)&createLLC).str();
442   if (LLCPath.empty()) {
443     Message = "Cannot find `llc' in executable directory!\n";
444     return 0;
445   }
446
447   Message = "Found llc: " + LLCPath + "\n";
448   GCC *gcc = GCC::create(Message, GCCBinary, GCCArgs);
449   if (!gcc) {
450     errs() << Message << "\n";
451     exit(1);
452   }
453   return new LLC(LLCPath, gcc, Args, UseIntegratedAssembler);
454 }
455
456 //===---------------------------------------------------------------------===//
457 // JIT Implementation of AbstractIntepreter interface
458 //
459 namespace {
460   class JIT : public AbstractInterpreter {
461     std::string LLIPath;          // The path to the LLI executable
462     std::vector<std::string> ToolArgs; // Args to pass to LLI
463   public:
464     JIT(const std::string &Path, const std::vector<std::string> *Args)
465       : LLIPath(Path) {
466       ToolArgs.clear ();
467       if (Args) { ToolArgs = *Args; }
468     }
469
470     virtual int ExecuteProgram(const std::string &Bitcode,
471                                const std::vector<std::string> &Args,
472                                const std::string &InputFile,
473                                const std::string &OutputFile,
474                                std::string *Error,
475                                const std::vector<std::string> &GCCArgs =
476                                  std::vector<std::string>(),
477                                const std::vector<std::string> &SharedLibs =
478                                  std::vector<std::string>(),
479                                unsigned Timeout = 0,
480                                unsigned MemoryLimit = 0);
481   };
482 }
483
484 int JIT::ExecuteProgram(const std::string &Bitcode,
485                         const std::vector<std::string> &Args,
486                         const std::string &InputFile,
487                         const std::string &OutputFile,
488                         std::string *Error,
489                         const std::vector<std::string> &GCCArgs,
490                         const std::vector<std::string> &SharedLibs,
491                         unsigned Timeout,
492                         unsigned MemoryLimit) {
493   // Construct a vector of parameters, incorporating those from the command-line
494   std::vector<const char*> JITArgs;
495   JITArgs.push_back(LLIPath.c_str());
496   JITArgs.push_back("-force-interpreter=false");
497
498   // Add any extra LLI args.
499   for (unsigned i = 0, e = ToolArgs.size(); i != e; ++i)
500     JITArgs.push_back(ToolArgs[i].c_str());
501
502   for (unsigned i = 0, e = SharedLibs.size(); i != e; ++i) {
503     JITArgs.push_back("-load");
504     JITArgs.push_back(SharedLibs[i].c_str());
505   }
506   JITArgs.push_back(Bitcode.c_str());
507   // Add optional parameters to the running program from Argv
508   for (unsigned i=0, e = Args.size(); i != e; ++i)
509     JITArgs.push_back(Args[i].c_str());
510   JITArgs.push_back(0);
511
512   outs() << "<jit>"; outs().flush();
513   DEBUG(errs() << "\nAbout to run:\t";
514         for (unsigned i=0, e = JITArgs.size()-1; i != e; ++i)
515           errs() << " " << JITArgs[i];
516         errs() << "\n";
517         );
518   DEBUG(errs() << "\nSending output to " << OutputFile << "\n");
519   return RunProgramWithTimeout(sys::Path(LLIPath), &JITArgs[0],
520       sys::Path(InputFile), sys::Path(OutputFile), sys::Path(OutputFile),
521       Timeout, MemoryLimit);
522 }
523
524 /// createJIT - Try to find the LLI executable
525 ///
526 AbstractInterpreter *AbstractInterpreter::createJIT(const char *Argv0,
527                    std::string &Message, const std::vector<std::string> *Args) {
528   std::string LLIPath =
529     PrependMainExecutablePath("lli", Argv0, (void *)(intptr_t)&createJIT).str();
530   if (!LLIPath.empty()) {
531     Message = "Found lli: " + LLIPath + "\n";
532     return new JIT(LLIPath, Args);
533   }
534
535   Message = "Cannot find `lli' in executable directory!\n";
536   return 0;
537 }
538
539 GCC::FileType CBE::OutputCode(const std::string &Bitcode,
540                               sys::Path &OutputCFile, std::string &Error,
541                               unsigned Timeout, unsigned MemoryLimit) {
542   sys::Path uniqueFile(Bitcode+".cbe.c");
543   std::string ErrMsg;
544   if (uniqueFile.makeUnique(true, &ErrMsg)) {
545     errs() << "Error making unique filename: " << ErrMsg << "\n";
546     exit(1);
547   }
548   OutputCFile = uniqueFile;
549   std::vector<const char *> LLCArgs;
550   LLCArgs.push_back(LLCPath.c_str());
551
552   // Add any extra LLC args.
553   for (unsigned i = 0, e = ToolArgs.size(); i != e; ++i)
554     LLCArgs.push_back(ToolArgs[i].c_str());
555
556   LLCArgs.push_back("-o");
557   LLCArgs.push_back(OutputCFile.c_str());   // Output to the C file
558   LLCArgs.push_back("-march=c");            // Output C language
559   LLCArgs.push_back(Bitcode.c_str());      // This is the input bitcode
560   LLCArgs.push_back(0);
561
562   outs() << "<cbe>"; outs().flush();
563   DEBUG(errs() << "\nAbout to run:\t";
564         for (unsigned i = 0, e = LLCArgs.size()-1; i != e; ++i)
565           errs() << " " << LLCArgs[i];
566         errs() << "\n";
567         );
568   if (RunProgramWithTimeout(LLCPath, &LLCArgs[0], sys::Path(), sys::Path(),
569                             sys::Path(), Timeout, MemoryLimit))
570     Error = ProcessFailure(LLCPath, &LLCArgs[0], Timeout, MemoryLimit);
571   return GCC::CFile;
572 }
573
574 void CBE::compileProgram(const std::string &Bitcode, std::string *Error,
575                          unsigned Timeout, unsigned MemoryLimit) {
576   sys::Path OutputCFile;
577   OutputCode(Bitcode, OutputCFile, *Error, Timeout, MemoryLimit);
578   OutputCFile.eraseFromDisk();
579 }
580
581 int CBE::ExecuteProgram(const std::string &Bitcode,
582                         const std::vector<std::string> &Args,
583                         const std::string &InputFile,
584                         const std::string &OutputFile,
585                         std::string *Error,
586                         const std::vector<std::string> &ArgsForGCC,
587                         const std::vector<std::string> &SharedLibs,
588                         unsigned Timeout,
589                         unsigned MemoryLimit) {
590   sys::Path OutputCFile;
591   OutputCode(Bitcode, OutputCFile, *Error, Timeout, MemoryLimit);
592
593   FileRemover CFileRemove(OutputCFile, !SaveTemps);
594
595   std::vector<std::string> GCCArgs(ArgsForGCC);
596   GCCArgs.insert(GCCArgs.end(), SharedLibs.begin(), SharedLibs.end());
597
598   return gcc->ExecuteProgram(OutputCFile.str(), Args, GCC::CFile,
599                              InputFile, OutputFile, Error, GCCArgs,
600                              Timeout, MemoryLimit);
601 }
602
603 /// createCBE - Try to find the 'llc' executable
604 ///
605 CBE *AbstractInterpreter::createCBE(const char *Argv0,
606                                     std::string &Message,
607                                     const std::string &GCCBinary,
608                                     const std::vector<std::string> *Args,
609                                     const std::vector<std::string> *GCCArgs) {
610   sys::Path LLCPath =
611     PrependMainExecutablePath("llc", Argv0, (void *)(intptr_t)&createCBE);
612   if (LLCPath.isEmpty()) {
613     Message =
614       "Cannot find `llc' in executable directory!\n";
615     return 0;
616   }
617
618   Message = "Found llc: " + LLCPath.str() + "\n";
619   GCC *gcc = GCC::create(Message, GCCBinary, GCCArgs);
620   if (!gcc) {
621     errs() << Message << "\n";
622     exit(1);
623   }
624   return new CBE(LLCPath, gcc, Args);
625 }
626
627 //===---------------------------------------------------------------------===//
628 // GCC abstraction
629 //
630
631 static bool IsARMArchitecture(std::vector<const char*> Args) {
632   for (std::vector<const char*>::const_iterator
633          I = Args.begin(), E = Args.end(); I != E; ++I) {
634     if (StringRef(*I).equals_lower("-arch")) {
635       ++I;
636       if (I != E && StringRef(*I).substr(0, strlen("arm")).equals_lower("arm"))
637         return true;
638     }
639   }
640
641   return false;
642 }
643
644 int GCC::ExecuteProgram(const std::string &ProgramFile,
645                         const std::vector<std::string> &Args,
646                         FileType fileType,
647                         const std::string &InputFile,
648                         const std::string &OutputFile,
649                         std::string *Error,
650                         const std::vector<std::string> &ArgsForGCC,
651                         unsigned Timeout,
652                         unsigned MemoryLimit) {
653   std::vector<const char*> GCCArgs;
654
655   GCCArgs.push_back(GCCPath.c_str());
656
657   if (TargetTriple.getArch() == Triple::x86)
658     GCCArgs.push_back("-m32");
659
660   for (std::vector<std::string>::const_iterator
661          I = gccArgs.begin(), E = gccArgs.end(); I != E; ++I)
662     GCCArgs.push_back(I->c_str());
663
664   // Specify -x explicitly in case the extension is wonky
665   if (fileType != ObjectFile) {
666     GCCArgs.push_back("-x");
667     if (fileType == CFile) {
668       GCCArgs.push_back("c");
669       GCCArgs.push_back("-fno-strict-aliasing");
670     } else {
671       GCCArgs.push_back("assembler");
672
673       // For ARM architectures we don't want this flag. bugpoint isn't
674       // explicitly told what architecture it is working on, so we get
675       // it from gcc flags
676       if ((TargetTriple.getOS() == Triple::Darwin) &&
677           !IsARMArchitecture(GCCArgs))
678         GCCArgs.push_back("-force_cpusubtype_ALL");
679     }
680   }
681
682   GCCArgs.push_back(ProgramFile.c_str());  // Specify the input filename.
683
684   GCCArgs.push_back("-x");
685   GCCArgs.push_back("none");
686   GCCArgs.push_back("-o");
687   sys::Path OutputBinary (ProgramFile+".gcc.exe");
688   std::string ErrMsg;
689   if (OutputBinary.makeUnique(true, &ErrMsg)) {
690     errs() << "Error making unique filename: " << ErrMsg << "\n";
691     exit(1);
692   }
693   GCCArgs.push_back(OutputBinary.c_str()); // Output to the right file...
694
695   // Add any arguments intended for GCC. We locate them here because this is
696   // most likely -L and -l options that need to come before other libraries but
697   // after the source. Other options won't be sensitive to placement on the
698   // command line, so this should be safe.
699   for (unsigned i = 0, e = ArgsForGCC.size(); i != e; ++i)
700     GCCArgs.push_back(ArgsForGCC[i].c_str());
701
702   GCCArgs.push_back("-lm");                // Hard-code the math library...
703   GCCArgs.push_back("-O2");                // Optimize the program a bit...
704 #if defined (HAVE_LINK_R)
705   GCCArgs.push_back("-Wl,-R.");            // Search this dir for .so files
706 #endif
707   if (TargetTriple.getArch() == Triple::sparc)
708     GCCArgs.push_back("-mcpu=v9");
709   GCCArgs.push_back(0);                    // NULL terminator
710
711   outs() << "<gcc>"; outs().flush();
712   DEBUG(errs() << "\nAbout to run:\t";
713         for (unsigned i = 0, e = GCCArgs.size()-1; i != e; ++i)
714           errs() << " " << GCCArgs[i];
715         errs() << "\n";
716         );
717   if (RunProgramWithTimeout(GCCPath, &GCCArgs[0], sys::Path(), sys::Path(),
718         sys::Path())) {
719     *Error = ProcessFailure(GCCPath, &GCCArgs[0]);
720     return -1;
721   }
722
723   std::vector<const char*> ProgramArgs;
724
725   // Declared here so that the destructor only runs after
726   // ProgramArgs is used.
727   std::string Exec;
728
729   if (RemoteClientPath.isEmpty())
730     ProgramArgs.push_back(OutputBinary.c_str());
731   else {
732     ProgramArgs.push_back(RemoteClientPath.c_str());
733     ProgramArgs.push_back(RemoteHost.c_str());
734     if (!RemoteUser.empty()) {
735       ProgramArgs.push_back("-l");
736       ProgramArgs.push_back(RemoteUser.c_str());
737     }
738     if (!RemotePort.empty()) {
739       ProgramArgs.push_back("-p");
740       ProgramArgs.push_back(RemotePort.c_str());
741     }
742     if (!RemoteExtra.empty()) {
743       ProgramArgs.push_back(RemoteExtra.c_str());
744     }
745
746     // Full path to the binary. We need to cd to the exec directory because
747     // there is a dylib there that the exec expects to find in the CWD
748     char* env_pwd = getenv("PWD");
749     Exec = "cd ";
750     Exec += env_pwd;
751     Exec += "; ./";
752     Exec += OutputBinary.c_str();
753     ProgramArgs.push_back(Exec.c_str());
754   }
755
756   // Add optional parameters to the running program from Argv
757   for (unsigned i = 0, e = Args.size(); i != e; ++i)
758     ProgramArgs.push_back(Args[i].c_str());
759   ProgramArgs.push_back(0);                // NULL terminator
760
761   // Now that we have a binary, run it!
762   outs() << "<program>"; outs().flush();
763   DEBUG(errs() << "\nAbout to run:\t";
764         for (unsigned i = 0, e = ProgramArgs.size()-1; i != e; ++i)
765           errs() << " " << ProgramArgs[i];
766         errs() << "\n";
767         );
768
769   FileRemover OutputBinaryRemover(OutputBinary, !SaveTemps);
770
771   if (RemoteClientPath.isEmpty()) {
772     DEBUG(errs() << "<run locally>");
773     return RunProgramWithTimeout(OutputBinary, &ProgramArgs[0],
774         sys::Path(InputFile), sys::Path(OutputFile), sys::Path(OutputFile),
775         Timeout, MemoryLimit);
776   } else {
777     outs() << "<run remotely>"; outs().flush();
778     return RunProgramRemotelyWithTimeout(sys::Path(RemoteClientPath),
779         &ProgramArgs[0], sys::Path(InputFile), sys::Path(OutputFile),
780         sys::Path(OutputFile), Timeout, MemoryLimit);
781   }
782 }
783
784 int GCC::MakeSharedObject(const std::string &InputFile, FileType fileType,
785                           std::string &OutputFile,
786                           const std::vector<std::string> &ArgsForGCC,
787                           std::string &Error) {
788   sys::Path uniqueFilename(InputFile+LTDL_SHLIB_EXT);
789   std::string ErrMsg;
790   if (uniqueFilename.makeUnique(true, &ErrMsg)) {
791     errs() << "Error making unique filename: " << ErrMsg << "\n";
792     exit(1);
793   }
794   OutputFile = uniqueFilename.str();
795
796   std::vector<const char*> GCCArgs;
797
798   GCCArgs.push_back(GCCPath.c_str());
799
800   if (TargetTriple.getArch() == Triple::x86)
801     GCCArgs.push_back("-m32");
802
803   for (std::vector<std::string>::const_iterator
804          I = gccArgs.begin(), E = gccArgs.end(); I != E; ++I)
805     GCCArgs.push_back(I->c_str());
806
807   // Compile the C/asm file into a shared object
808   if (fileType != ObjectFile) {
809     GCCArgs.push_back("-x");
810     GCCArgs.push_back(fileType == AsmFile ? "assembler" : "c");
811   }
812   GCCArgs.push_back("-fno-strict-aliasing");
813   GCCArgs.push_back(InputFile.c_str());   // Specify the input filename.
814   GCCArgs.push_back("-x");
815   GCCArgs.push_back("none");
816   if (TargetTriple.getArch() == Triple::sparc)
817     GCCArgs.push_back("-G");       // Compile a shared library, `-G' for Sparc
818   else if (TargetTriple.getOS() == Triple::Darwin) {
819     // link all source files into a single module in data segment, rather than
820     // generating blocks. dynamic_lookup requires that you set
821     // MACOSX_DEPLOYMENT_TARGET=10.3 in your env.  FIXME: it would be better for
822     // bugpoint to just pass that in the environment of GCC.
823     GCCArgs.push_back("-single_module");
824     GCCArgs.push_back("-dynamiclib");   // `-dynamiclib' for MacOS X/PowerPC
825     GCCArgs.push_back("-undefined");
826     GCCArgs.push_back("dynamic_lookup");
827   } else
828     GCCArgs.push_back("-shared");  // `-shared' for Linux/X86, maybe others
829
830   if ((TargetTriple.getArch() == Triple::alpha) ||
831       (TargetTriple.getArch() == Triple::x86_64))
832     GCCArgs.push_back("-fPIC");   // Requires shared objs to contain PIC
833
834   if (TargetTriple.getArch() == Triple::sparc)
835     GCCArgs.push_back("-mcpu=v9");
836
837   GCCArgs.push_back("-o");
838   GCCArgs.push_back(OutputFile.c_str()); // Output to the right filename.
839   GCCArgs.push_back("-O2");              // Optimize the program a bit.
840
841
842
843   // Add any arguments intended for GCC. We locate them here because this is
844   // most likely -L and -l options that need to come before other libraries but
845   // after the source. Other options won't be sensitive to placement on the
846   // command line, so this should be safe.
847   for (unsigned i = 0, e = ArgsForGCC.size(); i != e; ++i)
848     GCCArgs.push_back(ArgsForGCC[i].c_str());
849   GCCArgs.push_back(0);                    // NULL terminator
850
851
852
853   outs() << "<gcc>"; outs().flush();
854   DEBUG(errs() << "\nAbout to run:\t";
855         for (unsigned i = 0, e = GCCArgs.size()-1; i != e; ++i)
856           errs() << " " << GCCArgs[i];
857         errs() << "\n";
858         );
859   if (RunProgramWithTimeout(GCCPath, &GCCArgs[0], sys::Path(), sys::Path(),
860                             sys::Path())) {
861     Error = ProcessFailure(GCCPath, &GCCArgs[0]);
862     return 1;
863   }
864   return 0;
865 }
866
867 /// create - Try to find the `gcc' executable
868 ///
869 GCC *GCC::create(std::string &Message,
870                  const std::string &GCCBinary,
871                  const std::vector<std::string> *Args) {
872   sys::Path GCCPath = sys::Program::FindProgramByName(GCCBinary);
873   if (GCCPath.isEmpty()) {
874     Message = "Cannot find `"+ GCCBinary +"' in PATH!\n";
875     return 0;
876   }
877
878   sys::Path RemoteClientPath;
879   if (!RemoteClient.empty())
880     RemoteClientPath = sys::Program::FindProgramByName(RemoteClient);
881
882   Message = "Found gcc: " + GCCPath.str() + "\n";
883   return new GCC(GCCPath, RemoteClientPath, Args);
884 }