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/PathV1.h"
21 #include "llvm/Support/SystemUtils.h"
22 #include "llvm/Support/raw_ostream.h"
28 // OutputType - Allow the user to specify the way code should be run, to test
29 // for miscompilation.
32 AutoPick, RunLLI, RunJIT, RunLLC, RunLLCIA, LLC_Safe, CompileCustom, Custom
36 AbsTolerance("abs-tolerance", cl::desc("Absolute error tolerated"),
39 RelTolerance("rel-tolerance", cl::desc("Relative error tolerated"),
43 InterpreterSel(cl::desc("Specify the \"test\" i.e. suspect back-end:"),
44 cl::values(clEnumValN(AutoPick, "auto", "Use best guess"),
45 clEnumValN(RunLLI, "run-int",
46 "Execute with the interpreter"),
47 clEnumValN(RunJIT, "run-jit", "Execute with JIT"),
48 clEnumValN(RunLLC, "run-llc", "Compile with LLC"),
49 clEnumValN(RunLLCIA, "run-llc-ia",
50 "Compile with LLC with integrated assembler"),
51 clEnumValN(LLC_Safe, "llc-safe", "Use LLC for all"),
52 clEnumValN(CompileCustom, "compile-custom",
53 "Use -compile-command to define a command to "
54 "compile the bitcode. Useful to avoid linking."),
55 clEnumValN(Custom, "run-custom",
56 "Use -exec-command to define a command to execute "
57 "the bitcode. Useful for cross-compilation."),
62 SafeInterpreterSel(cl::desc("Specify \"safe\" i.e. known-good backend:"),
63 cl::values(clEnumValN(AutoPick, "safe-auto", "Use best guess"),
64 clEnumValN(RunLLC, "safe-run-llc", "Compile with LLC"),
65 clEnumValN(Custom, "safe-run-custom",
66 "Use -exec-command to define a command to execute "
67 "the bitcode. Useful for cross-compilation."),
72 SafeInterpreterPath("safe-path",
73 cl::desc("Specify the path to the \"safe\" backend program"),
77 AppendProgramExitCode("append-exit-code",
78 cl::desc("Append the exit code to the output so it gets diff'd too"),
82 InputFile("input", cl::init("/dev/null"),
83 cl::desc("Filename to pipe in as stdin (default: /dev/null)"));
86 AdditionalSOs("additional-so",
87 cl::desc("Additional shared objects to load "
88 "into executing programs"));
91 AdditionalLinkerArgs("Xlinker",
92 cl::desc("Additional arguments to pass to the linker"));
95 CustomCompileCommand("compile-command", cl::init("llc"),
96 cl::desc("Command to compile the bitcode (use with -compile-custom) "
100 CustomExecCommand("exec-command", cl::init("simulate"),
101 cl::desc("Command to execute the bitcode (use with -run-custom) "
102 "(default: simulate)"));
106 // Anything specified after the --args option are taken as arguments to the
107 // program being debugged.
108 cl::list<std::string>
109 InputArgv("args", cl::Positional, cl::desc("<program arguments>..."),
110 cl::ZeroOrMore, cl::PositionalEatsArgs);
113 OutputPrefix("output-prefix", cl::init("bugpoint"),
114 cl::desc("Prefix to use for outputs (default: 'bugpoint')"));
118 cl::list<std::string>
119 ToolArgv("tool-args", cl::Positional, cl::desc("<tool arguments>..."),
120 cl::ZeroOrMore, cl::PositionalEatsArgs);
122 cl::list<std::string>
123 SafeToolArgv("safe-tool-args", cl::Positional,
124 cl::desc("<safe-tool arguments>..."),
125 cl::ZeroOrMore, cl::PositionalEatsArgs);
128 GCCBinary("gcc", cl::init("gcc"),
129 cl::desc("The gcc binary to use. (default 'gcc')"));
131 cl::list<std::string>
132 GCCToolArgv("gcc-tool-args", cl::Positional,
133 cl::desc("<gcc-tool arguments>..."),
134 cl::ZeroOrMore, cl::PositionalEatsArgs);
137 //===----------------------------------------------------------------------===//
138 // BugDriver method implementation
141 /// initializeExecutionEnvironment - This method is used to set up the
142 /// environment for executing LLVM programs.
144 bool BugDriver::initializeExecutionEnvironment() {
145 outs() << "Initializing execution environment: ";
147 // Create an instance of the AbstractInterpreter interface as specified on
152 switch (InterpreterSel) {
155 InterpreterSel = RunJIT;
156 Interpreter = AbstractInterpreter::createJIT(getToolName(), Message,
160 InterpreterSel = RunLLC;
161 Interpreter = AbstractInterpreter::createLLC(getToolName(), Message,
162 GCCBinary, &ToolArgv,
166 InterpreterSel = RunLLI;
167 Interpreter = AbstractInterpreter::createLLI(getToolName(), Message,
171 InterpreterSel = AutoPick;
172 Message = "Sorry, I can't automatically select an interpreter!\n";
176 Interpreter = AbstractInterpreter::createLLI(getToolName(), Message,
182 Interpreter = AbstractInterpreter::createLLC(getToolName(), Message,
183 GCCBinary, &ToolArgv,
185 InterpreterSel == RunLLCIA);
188 Interpreter = AbstractInterpreter::createJIT(getToolName(), Message,
193 AbstractInterpreter::createCustomCompiler(Message, CustomCompileCommand);
197 AbstractInterpreter::createCustomExecutor(Message, CustomExecCommand);
202 else // Display informational messages on stdout instead of stderr
205 std::string Path = SafeInterpreterPath;
207 Path = getToolName();
208 std::vector<std::string> SafeToolArgs = SafeToolArgv;
209 switch (SafeInterpreterSel) {
211 // In "llc-safe" mode, default to using LLC as the "safe" backend.
212 if (!SafeInterpreter &&
213 InterpreterSel == LLC_Safe) {
214 SafeInterpreterSel = RunLLC;
215 SafeToolArgs.push_back("--relocation-model=pic");
216 SafeInterpreter = AbstractInterpreter::createLLC(Path.c_str(), Message,
222 if (!SafeInterpreter &&
223 InterpreterSel != RunLLC &&
224 InterpreterSel != RunJIT) {
225 SafeInterpreterSel = RunLLC;
226 SafeToolArgs.push_back("--relocation-model=pic");
227 SafeInterpreter = AbstractInterpreter::createLLC(Path.c_str(), Message,
232 if (!SafeInterpreter) {
233 SafeInterpreterSel = AutoPick;
234 Message = "Sorry, I can't automatically select a safe interpreter!\n";
239 SafeToolArgs.push_back("--relocation-model=pic");
240 SafeInterpreter = AbstractInterpreter::createLLC(Path.c_str(), Message,
241 GCCBinary, &SafeToolArgs,
243 SafeInterpreterSel == RunLLCIA);
247 AbstractInterpreter::createCustomExecutor(Message, CustomExecCommand);
250 Message = "Sorry, this back-end is not supported by bugpoint as the "
251 "\"safe\" backend right now!\n";
254 if (!SafeInterpreter) { outs() << Message << "\nExiting.\n"; exit(1); }
256 gcc = GCC::create(Message, GCCBinary, &GCCToolArgv);
257 if (!gcc) { outs() << Message << "\nExiting.\n"; exit(1); }
259 // If there was an error creating the selected interpreter, quit with error.
260 return Interpreter == 0;
263 /// compileProgram - Try to compile the specified module, returning false and
264 /// setting Error if an error occurs. This is used for code generation
267 void BugDriver::compileProgram(Module *M, std::string *Error) const {
268 // Emit the program to a bitcode file...
269 sys::Path BitcodeFile (OutputPrefix + "-test-program.bc");
271 if (BitcodeFile.makeUnique(true, &ErrMsg)) {
272 errs() << ToolName << ": Error making unique filename: " << ErrMsg
276 if (writeProgramToFile(BitcodeFile.str(), M)) {
277 errs() << ToolName << ": Error emitting bitcode to file '"
278 << BitcodeFile.str() << "'!\n";
282 // Remove the temporary bitcode file when we are done.
283 FileRemover BitcodeFileRemover(BitcodeFile.str(), !SaveTemps);
285 // Actually compile the program!
286 Interpreter->compileProgram(BitcodeFile.str(), Error, Timeout, MemoryLimit);
290 /// executeProgram - This method runs "Program", capturing the output of the
291 /// program to a file, returning the filename of the file. A recommended
292 /// filename may be optionally specified.
294 std::string BugDriver::executeProgram(const Module *Program,
295 std::string OutputFile,
296 std::string BitcodeFile,
297 const std::string &SharedObj,
298 AbstractInterpreter *AI,
299 std::string *Error) const {
300 if (AI == 0) AI = Interpreter;
301 assert(AI && "Interpreter should have been created already!");
302 bool CreatedBitcode = false;
304 if (BitcodeFile.empty()) {
305 // Emit the program to a bitcode file...
306 sys::Path uniqueFilename(OutputPrefix + "-test-program.bc");
307 if (uniqueFilename.makeUnique(true, &ErrMsg)) {
308 errs() << ToolName << ": Error making unique filename: "
312 BitcodeFile = uniqueFilename.str();
314 if (writeProgramToFile(BitcodeFile, Program)) {
315 errs() << ToolName << ": Error emitting bitcode to file '"
316 << BitcodeFile << "'!\n";
319 CreatedBitcode = true;
322 // Remove the temporary bitcode file when we are done.
323 sys::Path BitcodePath(BitcodeFile);
324 FileRemover BitcodeFileRemover(BitcodePath.str(),
325 CreatedBitcode && !SaveTemps);
327 if (OutputFile.empty()) OutputFile = OutputPrefix + "-execution-output";
329 // Check to see if this is a valid output filename...
330 sys::Path uniqueFile(OutputFile);
331 if (uniqueFile.makeUnique(true, &ErrMsg)) {
332 errs() << ToolName << ": Error making unique filename: "
336 OutputFile = uniqueFile.str();
338 // Figure out which shared objects to run, if any.
339 std::vector<std::string> SharedObjs(AdditionalSOs);
340 if (!SharedObj.empty())
341 SharedObjs.push_back(SharedObj);
343 int RetVal = AI->ExecuteProgram(BitcodeFile, InputArgv, InputFile, OutputFile,
344 Error, AdditionalLinkerArgs, SharedObjs,
345 Timeout, MemoryLimit);
350 errs() << "<timeout>";
351 static bool FirstTimeout = true;
354 "*** Program execution timed out! This mechanism is designed to handle\n"
355 " programs stuck in infinite loops gracefully. The -timeout option\n"
356 " can be used to change the timeout threshold or disable it completely\n"
357 " (with -timeout=0). This message is only displayed once.\n";
358 FirstTimeout = false;
362 if (AppendProgramExitCode) {
363 std::ofstream outFile(OutputFile.c_str(), std::ios_base::app);
364 outFile << "exit " << RetVal << '\n';
368 // Return the filename we captured the output to.
372 /// executeProgramSafely - Used to create reference output with the "safe"
373 /// backend, if reference output is not provided.
375 std::string BugDriver::executeProgramSafely(const Module *Program,
376 std::string OutputFile,
377 std::string *Error) const {
378 return executeProgram(Program, OutputFile, "", "", SafeInterpreter, Error);
381 std::string BugDriver::compileSharedObject(const std::string &BitcodeFile,
382 std::string &Error) {
383 assert(Interpreter && "Interpreter should have been created already!");
384 std::string OutputFile;
386 // Using the known-good backend.
387 GCC::FileType FT = SafeInterpreter->OutputCode(BitcodeFile, OutputFile,
392 std::string SharedObjectFile;
393 bool Failure = gcc->MakeSharedObject(OutputFile, FT, SharedObjectFile,
394 AdditionalLinkerArgs, Error);
400 // Remove the intermediate C file
401 sys::fs::remove(OutputFile);
403 return "./" + SharedObjectFile;
406 /// createReferenceFile - calls compileProgram and then records the output
407 /// into ReferenceOutputFile. Returns true if reference file created, false
408 /// otherwise. Note: initializeExecutionEnvironment should be called BEFORE
411 bool BugDriver::createReferenceFile(Module *M, const std::string &Filename) {
413 compileProgram(Program, &Error);
417 ReferenceOutputFile = executeProgramSafely(Program, Filename, &Error);
418 if (!Error.empty()) {
420 if (Interpreter != SafeInterpreter) {
421 errs() << "*** There is a bug running the \"safe\" backend. Either"
422 << " debug it (for example with the -run-jit bugpoint option,"
423 << " if JIT is being used as the \"safe\" backend), or fix the"
424 << " error some other way.\n";
428 outs() << "\nReference output is: " << ReferenceOutputFile << "\n\n";
432 /// diffProgram - This method executes the specified module and diffs the
433 /// output against the file specified by ReferenceOutputFile. If the output
434 /// is different, 1 is returned. If there is a problem with the code
435 /// generator (e.g., llc crashes), this will set ErrMsg.
437 bool BugDriver::diffProgram(const Module *Program,
438 const std::string &BitcodeFile,
439 const std::string &SharedObject,
441 std::string *ErrMsg) const {
442 // Execute the program, generating an output file...
443 sys::Path Output(executeProgram(Program, "", BitcodeFile, SharedObject, 0,
445 if (!ErrMsg->empty())
449 bool FilesDifferent = false;
450 if (int Diff = DiffFilesWithTolerance(ReferenceOutputFile,
452 AbsTolerance, RelTolerance, &Error)) {
454 errs() << "While diffing output: " << Error << '\n';
457 FilesDifferent = true;
460 // Remove the generated output if there are no differences.
461 Output.eraseFromDisk();
464 // Remove the bitcode file if we are supposed to.
466 sys::Path(BitcodeFile).eraseFromDisk();
467 return FilesDifferent;
470 bool BugDriver::isExecutingJIT() {
471 return InterpreterSel == RunJIT;