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