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) {
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(std::string OutputFile,
324 std::string BitcodeFile,
325 const std::string &SharedObj,
326 AbstractInterpreter *AI,
327 std::string *Error) {
328 if (AI == 0) AI = Interpreter;
329 assert(AI && "Interpreter should have been created already!");
330 bool CreatedBitcode = false;
332 if (BitcodeFile.empty()) {
333 // Emit the program to a bitcode file...
334 sys::Path uniqueFilename(OutputPrefix + "-test-program.bc");
335 if (uniqueFilename.makeUnique(true, &ErrMsg)) {
336 errs() << ToolName << ": Error making unique filename: "
340 BitcodeFile = uniqueFilename.str();
342 if (writeProgramToFile(BitcodeFile, Program)) {
343 errs() << ToolName << ": Error emitting bitcode to file '"
344 << BitcodeFile << "'!\n";
347 CreatedBitcode = true;
350 // Remove the temporary bitcode file when we are done.
351 sys::Path BitcodePath(BitcodeFile);
352 FileRemover BitcodeFileRemover(BitcodePath, CreatedBitcode && !SaveTemps);
354 if (OutputFile.empty()) OutputFile = OutputPrefix + "-execution-output";
356 // Check to see if this is a valid output filename...
357 sys::Path uniqueFile(OutputFile);
358 if (uniqueFile.makeUnique(true, &ErrMsg)) {
359 errs() << ToolName << ": Error making unique filename: "
363 OutputFile = uniqueFile.str();
365 // Figure out which shared objects to run, if any.
366 std::vector<std::string> SharedObjs(AdditionalSOs);
367 if (!SharedObj.empty())
368 SharedObjs.push_back(SharedObj);
370 int RetVal = AI->ExecuteProgram(BitcodeFile, InputArgv, InputFile, OutputFile,
371 Error, AdditionalLinkerArgs, SharedObjs,
372 Timeout, MemoryLimit);
377 errs() << "<timeout>";
378 static bool FirstTimeout = true;
381 "*** Program execution timed out! This mechanism is designed to handle\n"
382 " programs stuck in infinite loops gracefully. The -timeout option\n"
383 " can be used to change the timeout threshold or disable it completely\n"
384 " (with -timeout=0). This message is only displayed once.\n";
385 FirstTimeout = false;
389 if (AppendProgramExitCode) {
390 std::ofstream outFile(OutputFile.c_str(), std::ios_base::app);
391 outFile << "exit " << RetVal << '\n';
395 // Return the filename we captured the output to.
399 /// executeProgramSafely - Used to create reference output with the "safe"
400 /// backend, if reference output is not provided.
402 std::string BugDriver::executeProgramSafely(std::string OutputFile,
403 std::string *Error) {
404 return executeProgram(OutputFile, "", "", SafeInterpreter, Error);
407 std::string BugDriver::compileSharedObject(const std::string &BitcodeFile,
408 std::string &Error) {
409 assert(Interpreter && "Interpreter should have been created already!");
410 sys::Path OutputFile;
412 // Using the known-good backend.
413 GCC::FileType FT = SafeInterpreter->OutputCode(BitcodeFile, OutputFile,
418 std::string SharedObjectFile;
419 bool Failure = gcc->MakeSharedObject(OutputFile.str(), FT, SharedObjectFile,
420 AdditionalLinkerArgs, Error);
426 // Remove the intermediate C file
427 OutputFile.eraseFromDisk();
429 return "./" + SharedObjectFile;
432 /// createReferenceFile - calls compileProgram and then records the output
433 /// into ReferenceOutputFile. Returns true if reference file created, false
434 /// otherwise. Note: initializeExecutionEnvironment should be called BEFORE
437 bool BugDriver::createReferenceFile(Module *M, const std::string &Filename) {
439 compileProgram(Program, &Error);
443 ReferenceOutputFile = executeProgramSafely(Filename, &Error);
444 if (!Error.empty()) {
446 if (Interpreter != SafeInterpreter) {
447 errs() << "*** There is a bug running the \"safe\" backend. Either"
448 << " debug it (for example with the -run-cbe bugpoint option,"
449 << " if CBE is being used as the \"safe\" backend), or fix the"
450 << " error some other way.\n";
454 outs() << "\nReference output is: " << ReferenceOutputFile << "\n\n";
458 /// diffProgram - This method executes the specified module and diffs the
459 /// output against the file specified by ReferenceOutputFile. If the output
460 /// is different, 1 is returned. If there is a problem with the code
461 /// generator (e.g., llc crashes), this will return -1 and set Error.
463 bool BugDriver::diffProgram(const std::string &BitcodeFile,
464 const std::string &SharedObject,
466 std::string *ErrMsg) {
467 // Execute the program, generating an output file...
468 sys::Path Output(executeProgram("", BitcodeFile, SharedObject, 0, ErrMsg));
469 if (!ErrMsg->empty())
473 bool FilesDifferent = false;
474 if (int Diff = DiffFilesWithTolerance(sys::Path(ReferenceOutputFile),
475 sys::Path(Output.str()),
476 AbsTolerance, RelTolerance, &Error)) {
478 errs() << "While diffing output: " << Error << '\n';
481 FilesDifferent = true;
484 // Remove the generated output if there are no differences.
485 Output.eraseFromDisk();
488 // Remove the bitcode file if we are supposed to.
490 sys::Path(BitcodeFile).eraseFromDisk();
491 return FilesDifferent;
494 bool BugDriver::isExecutingJIT() {
495 return InterpreterSel == RunJIT;