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