1 //===- ExecutionDriver.cpp - Allow execution of LLVM program --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains code used to execute the program utilizing one of the
11 // various ways of running LLVM bitcode.
13 //===----------------------------------------------------------------------===//
15 #include "BugDriver.h"
16 #include "ToolRunner.h"
17 #include "llvm/Support/CommandLine.h"
18 #include "llvm/Support/Debug.h"
19 #include "llvm/Support/FileUtilities.h"
20 #include "llvm/Support/SystemUtils.h"
21 #include "llvm/Support/raw_ostream.h"
27 // OutputType - Allow the user to specify the way code should be run, to test
28 // for miscompilation.
31 AutoPick, RunLLI, RunJIT, RunLLC, RunLLCIA, RunCBE, CBE_bug, LLC_Safe,Custom
35 AbsTolerance("abs-tolerance", cl::desc("Absolute error tolerated"),
38 RelTolerance("rel-tolerance", cl::desc("Relative error tolerated"),
42 InterpreterSel(cl::desc("Specify the \"test\" i.e. suspect back-end:"),
43 cl::values(clEnumValN(AutoPick, "auto", "Use best guess"),
44 clEnumValN(RunLLI, "run-int",
45 "Execute with the interpreter"),
46 clEnumValN(RunJIT, "run-jit", "Execute with JIT"),
47 clEnumValN(RunLLC, "run-llc", "Compile with LLC"),
48 clEnumValN(RunLLCIA, "run-llc-ia",
49 "Compile with LLC with integrated assembler"),
50 clEnumValN(RunCBE, "run-cbe", "Compile with CBE"),
51 clEnumValN(CBE_bug,"cbe-bug", "Find CBE bugs"),
52 clEnumValN(LLC_Safe, "llc-safe", "Use LLC for all"),
53 clEnumValN(Custom, "run-custom",
54 "Use -exec-command to define a command to execute "
55 "the bitcode. Useful for cross-compilation."),
60 SafeInterpreterSel(cl::desc("Specify \"safe\" i.e. known-good backend:"),
61 cl::values(clEnumValN(AutoPick, "safe-auto", "Use best guess"),
62 clEnumValN(RunLLC, "safe-run-llc", "Compile with LLC"),
63 clEnumValN(RunCBE, "safe-run-cbe", "Compile with CBE"),
64 clEnumValN(Custom, "safe-run-custom",
65 "Use -exec-command to define a command to execute "
66 "the bitcode. Useful for cross-compilation."),
71 SafeInterpreterPath("safe-path",
72 cl::desc("Specify the path to the \"safe\" backend program"),
76 AppendProgramExitCode("append-exit-code",
77 cl::desc("Append the exit code to the output so it gets diff'd too"),
81 InputFile("input", cl::init("/dev/null"),
82 cl::desc("Filename to pipe in as stdin (default: /dev/null)"));
85 AdditionalSOs("additional-so",
86 cl::desc("Additional shared objects to load "
87 "into executing programs"));
90 AdditionalLinkerArgs("Xlinker",
91 cl::desc("Additional arguments to pass to the linker"));
94 CustomExecCommand("exec-command", cl::init("simulate"),
95 cl::desc("Command to execute the bitcode (use with -run-custom) "
96 "(default: simulate)"));
100 // Anything specified after the --args option are taken as arguments to the
101 // program being debugged.
102 cl::list<std::string>
103 InputArgv("args", cl::Positional, cl::desc("<program arguments>..."),
104 cl::ZeroOrMore, cl::PositionalEatsArgs);
107 OutputPrefix("output-prefix", cl::init("bugpoint"),
108 cl::desc("Prefix to use for outputs (default: 'bugpoint')"));
112 cl::list<std::string>
113 ToolArgv("tool-args", cl::Positional, cl::desc("<tool arguments>..."),
114 cl::ZeroOrMore, cl::PositionalEatsArgs);
116 cl::list<std::string>
117 SafeToolArgv("safe-tool-args", cl::Positional,
118 cl::desc("<safe-tool arguments>..."),
119 cl::ZeroOrMore, cl::PositionalEatsArgs);
122 GCCBinary("gcc", cl::init("gcc"),
123 cl::desc("The gcc binary to use. (default 'gcc')"));
125 cl::list<std::string>
126 GCCToolArgv("gcc-tool-args", cl::Positional,
127 cl::desc("<gcc-tool arguments>..."),
128 cl::ZeroOrMore, cl::PositionalEatsArgs);
131 //===----------------------------------------------------------------------===//
132 // BugDriver method implementation
135 /// initializeExecutionEnvironment - This method is used to set up the
136 /// environment for executing LLVM programs.
138 bool BugDriver::initializeExecutionEnvironment() {
139 outs() << "Initializing execution environment: ";
141 // Create an instance of the AbstractInterpreter interface as specified on
146 switch (InterpreterSel) {
148 InterpreterSel = RunCBE;
150 AbstractInterpreter::createCBE(getToolName(), Message, GCCBinary,
151 &ToolArgv, &GCCToolArgv);
153 InterpreterSel = RunJIT;
154 Interpreter = AbstractInterpreter::createJIT(getToolName(), Message,
158 InterpreterSel = RunLLC;
159 Interpreter = AbstractInterpreter::createLLC(getToolName(), Message,
160 GCCBinary, &ToolArgv,
164 InterpreterSel = RunLLI;
165 Interpreter = AbstractInterpreter::createLLI(getToolName(), Message,
169 InterpreterSel = AutoPick;
170 Message = "Sorry, I can't automatically select an interpreter!\n";
174 Interpreter = AbstractInterpreter::createLLI(getToolName(), Message,
180 Interpreter = AbstractInterpreter::createLLC(getToolName(), Message,
181 GCCBinary, &ToolArgv,
183 InterpreterSel == RunLLCIA);
186 Interpreter = AbstractInterpreter::createJIT(getToolName(), Message,
191 Interpreter = AbstractInterpreter::createCBE(getToolName(), Message,
192 GCCBinary, &ToolArgv,
196 Interpreter = AbstractInterpreter::createCustom(Message, CustomExecCommand);
199 Message = "Sorry, this back-end is not supported by bugpoint right now!\n";
204 else // Display informational messages on stdout instead of stderr
207 std::string Path = SafeInterpreterPath;
209 Path = getToolName();
210 std::vector<std::string> SafeToolArgs = SafeToolArgv;
211 switch (SafeInterpreterSel) {
213 // In "cbe-bug" mode, default to using LLC as the "safe" backend.
214 if (!SafeInterpreter &&
215 InterpreterSel == CBE_bug) {
216 SafeInterpreterSel = RunLLC;
217 SafeToolArgs.push_back("--relocation-model=pic");
218 SafeInterpreter = AbstractInterpreter::createLLC(Path.c_str(), Message,
224 // In "llc-safe" mode, default to using LLC as the "safe" backend.
225 if (!SafeInterpreter &&
226 InterpreterSel == LLC_Safe) {
227 SafeInterpreterSel = RunLLC;
228 SafeToolArgs.push_back("--relocation-model=pic");
229 SafeInterpreter = AbstractInterpreter::createLLC(Path.c_str(), Message,
235 // Pick a backend that's different from the test backend. The JIT and
236 // LLC backends share a lot of code, so prefer to use the CBE as the
237 // safe back-end when testing them.
238 if (!SafeInterpreter &&
239 InterpreterSel != RunCBE) {
240 SafeInterpreterSel = RunCBE;
241 SafeInterpreter = AbstractInterpreter::createCBE(Path.c_str(), Message,
246 if (!SafeInterpreter &&
247 InterpreterSel != RunLLC &&
248 InterpreterSel != RunJIT) {
249 SafeInterpreterSel = RunLLC;
250 SafeToolArgs.push_back("--relocation-model=pic");
251 SafeInterpreter = AbstractInterpreter::createLLC(Path.c_str(), Message,
256 if (!SafeInterpreter) {
257 SafeInterpreterSel = AutoPick;
258 Message = "Sorry, I can't automatically select an interpreter!\n";
263 SafeToolArgs.push_back("--relocation-model=pic");
264 SafeInterpreter = AbstractInterpreter::createLLC(Path.c_str(), Message,
265 GCCBinary, &SafeToolArgs,
267 SafeInterpreterSel == RunLLCIA);
270 SafeInterpreter = AbstractInterpreter::createCBE(Path.c_str(), Message,
271 GCCBinary, &SafeToolArgs,
275 SafeInterpreter = AbstractInterpreter::createCustom(Message,
279 Message = "Sorry, this back-end is not supported by bugpoint as the "
280 "\"safe\" backend right now!\n";
283 if (!SafeInterpreter) { outs() << Message << "\nExiting.\n"; exit(1); }
285 gcc = GCC::create(Message, GCCBinary, &GCCToolArgv);
286 if (!gcc) { outs() << Message << "\nExiting.\n"; exit(1); }
288 // If there was an error creating the selected interpreter, quit with error.
289 return Interpreter == 0;
292 /// compileProgram - Try to compile the specified module, returning false and
293 /// setting Error if an error occurs. This is used for code generation
296 void BugDriver::compileProgram(Module *M, std::string *Error) const {
297 // Emit the program to a bitcode file...
298 sys::Path BitcodeFile (OutputPrefix + "-test-program.bc");
300 if (BitcodeFile.makeUnique(true, &ErrMsg)) {
301 errs() << ToolName << ": Error making unique filename: " << ErrMsg
305 if (writeProgramToFile(BitcodeFile.str(), M)) {
306 errs() << ToolName << ": Error emitting bitcode to file '"
307 << BitcodeFile.str() << "'!\n";
311 // Remove the temporary bitcode file when we are done.
312 FileRemover BitcodeFileRemover(BitcodeFile, !SaveTemps);
314 // Actually compile the program!
315 Interpreter->compileProgram(BitcodeFile.str(), Error, Timeout, MemoryLimit);
319 /// executeProgram - This method runs "Program", capturing the output of the
320 /// program to a file, returning the filename of the file. A recommended
321 /// filename may be optionally specified.
323 std::string BugDriver::executeProgram(const Module *Program,
324 std::string OutputFile,
325 std::string BitcodeFile,
326 const std::string &SharedObj,
327 AbstractInterpreter *AI,
328 std::string *Error) const {
329 if (AI == 0) AI = Interpreter;
330 assert(AI && "Interpreter should have been created already!");
331 bool CreatedBitcode = false;
333 if (BitcodeFile.empty()) {
334 // Emit the program to a bitcode file...
335 sys::Path uniqueFilename(OutputPrefix + "-test-program.bc");
336 if (uniqueFilename.makeUnique(true, &ErrMsg)) {
337 errs() << ToolName << ": Error making unique filename: "
341 BitcodeFile = uniqueFilename.str();
343 if (writeProgramToFile(BitcodeFile, Program)) {
344 errs() << ToolName << ": Error emitting bitcode to file '"
345 << BitcodeFile << "'!\n";
348 CreatedBitcode = true;
351 // Remove the temporary bitcode file when we are done.
352 sys::Path BitcodePath(BitcodeFile);
353 FileRemover BitcodeFileRemover(BitcodePath, CreatedBitcode && !SaveTemps);
355 if (OutputFile.empty()) OutputFile = OutputPrefix + "-execution-output";
357 // Check to see if this is a valid output filename...
358 sys::Path uniqueFile(OutputFile);
359 if (uniqueFile.makeUnique(true, &ErrMsg)) {
360 errs() << ToolName << ": Error making unique filename: "
364 OutputFile = uniqueFile.str();
366 // Figure out which shared objects to run, if any.
367 std::vector<std::string> SharedObjs(AdditionalSOs);
368 if (!SharedObj.empty())
369 SharedObjs.push_back(SharedObj);
371 int RetVal = AI->ExecuteProgram(BitcodeFile, InputArgv, InputFile, OutputFile,
372 Error, AdditionalLinkerArgs, SharedObjs,
373 Timeout, MemoryLimit);
378 errs() << "<timeout>";
379 static bool FirstTimeout = true;
382 "*** Program execution timed out! This mechanism is designed to handle\n"
383 " programs stuck in infinite loops gracefully. The -timeout option\n"
384 " can be used to change the timeout threshold or disable it completely\n"
385 " (with -timeout=0). This message is only displayed once.\n";
386 FirstTimeout = false;
390 if (AppendProgramExitCode) {
391 std::ofstream outFile(OutputFile.c_str(), std::ios_base::app);
392 outFile << "exit " << RetVal << '\n';
396 // Return the filename we captured the output to.
400 /// executeProgramSafely - Used to create reference output with the "safe"
401 /// backend, if reference output is not provided.
403 std::string BugDriver::executeProgramSafely(const Module *Program,
404 std::string OutputFile,
405 std::string *Error) const {
406 return executeProgram(Program, OutputFile, "", "", SafeInterpreter, Error);
409 std::string BugDriver::compileSharedObject(const std::string &BitcodeFile,
410 std::string &Error) {
411 assert(Interpreter && "Interpreter should have been created already!");
412 sys::Path OutputFile;
414 // Using the known-good backend.
415 GCC::FileType FT = SafeInterpreter->OutputCode(BitcodeFile, OutputFile,
420 std::string SharedObjectFile;
421 bool Failure = gcc->MakeSharedObject(OutputFile.str(), FT, SharedObjectFile,
422 AdditionalLinkerArgs, Error);
428 // Remove the intermediate C file
429 OutputFile.eraseFromDisk();
431 return "./" + SharedObjectFile;
434 /// createReferenceFile - calls compileProgram and then records the output
435 /// into ReferenceOutputFile. Returns true if reference file created, false
436 /// otherwise. Note: initializeExecutionEnvironment should be called BEFORE
439 bool BugDriver::createReferenceFile(Module *M, const std::string &Filename) {
441 compileProgram(Program, &Error);
445 ReferenceOutputFile = executeProgramSafely(Program, Filename, &Error);
446 if (!Error.empty()) {
448 if (Interpreter != SafeInterpreter) {
449 errs() << "*** There is a bug running the \"safe\" backend. Either"
450 << " debug it (for example with the -run-cbe bugpoint option,"
451 << " if CBE is being used as the \"safe\" backend), or fix the"
452 << " error some other way.\n";
456 outs() << "\nReference output is: " << ReferenceOutputFile << "\n\n";
460 /// diffProgram - This method executes the specified module and diffs the
461 /// output against the file specified by ReferenceOutputFile. If the output
462 /// is different, 1 is returned. If there is a problem with the code
463 /// generator (e.g., llc crashes), this will return -1 and set Error.
465 bool BugDriver::diffProgram(const Module *Program,
466 const std::string &BitcodeFile,
467 const std::string &SharedObject,
469 std::string *ErrMsg) const {
470 // Execute the program, generating an output file...
471 sys::Path Output(executeProgram(Program, "", BitcodeFile, SharedObject, 0,
473 if (!ErrMsg->empty())
477 bool FilesDifferent = false;
478 if (int Diff = DiffFilesWithTolerance(sys::Path(ReferenceOutputFile),
479 sys::Path(Output.str()),
480 AbsTolerance, RelTolerance, &Error)) {
482 errs() << "While diffing output: " << Error << '\n';
485 FilesDifferent = true;
488 // Remove the generated output if there are no differences.
489 Output.eraseFromDisk();
492 // Remove the bitcode file if we are supposed to.
494 sys::Path(BitcodeFile).eraseFromDisk();
495 return FilesDifferent;
498 bool BugDriver::isExecutingJIT() {
499 return InterpreterSel == RunJIT;