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"
27 // OutputType - Allow the user to specify the way code should be run, to test
28 // for miscompilation.
31 AutoPick, RunLLI, RunJIT, RunLLC, 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 how LLVM code should be executed:"),
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(RunCBE, "run-cbe", "Compile with CBE"),
49 clEnumValN(CBE_bug,"cbe-bug", "Find CBE bugs"),
50 clEnumValN(LLC_Safe, "llc-safe", "Use LLC for all"),
51 clEnumValN(Custom, "run-custom",
52 "Use -exec-command to define a command to execute "
53 "the bitcode. Useful for cross-compilation."),
58 CheckProgramExitCode("check-exit-code",
59 cl::desc("Assume nonzero exit code is failure (default on)"),
63 AppendProgramExitCode("append-exit-code",
64 cl::desc("Append the exit code to the output so it gets diff'd too"),
68 InputFile("input", cl::init("/dev/null"),
69 cl::desc("Filename to pipe in as stdin (default: /dev/null)"));
72 AdditionalSOs("additional-so",
73 cl::desc("Additional shared objects to load "
74 "into executing programs"));
77 AdditionalLinkerArgs("Xlinker",
78 cl::desc("Additional arguments to pass to the linker"));
81 CustomExecCommand("exec-command", cl::init("simulate"),
82 cl::desc("Command to execute the bitcode (use with -run-custom) "
83 "(default: simulate)"));
87 // Anything specified after the --args option are taken as arguments to the
88 // program being debugged.
90 InputArgv("args", cl::Positional, cl::desc("<program arguments>..."),
91 cl::ZeroOrMore, cl::PositionalEatsArgs);
94 ToolArgv("tool-args", cl::Positional, cl::desc("<tool arguments>..."),
95 cl::ZeroOrMore, cl::PositionalEatsArgs);
98 //===----------------------------------------------------------------------===//
99 // BugDriver method implementation
102 /// initializeExecutionEnvironment - This method is used to set up the
103 /// environment for executing LLVM programs.
105 bool BugDriver::initializeExecutionEnvironment() {
106 std::cout << "Initializing execution environment: ";
108 // Create an instance of the AbstractInterpreter interface as specified on
113 switch (InterpreterSel) {
115 InterpreterSel = RunCBE;
116 Interpreter = cbe = AbstractInterpreter::createCBE(getToolName(), Message,
119 InterpreterSel = RunJIT;
120 Interpreter = AbstractInterpreter::createJIT(getToolName(), Message,
124 InterpreterSel = RunLLC;
125 Interpreter = AbstractInterpreter::createLLC(getToolName(), Message,
129 InterpreterSel = RunLLI;
130 Interpreter = AbstractInterpreter::createLLI(getToolName(), Message,
134 InterpreterSel = AutoPick;
135 Message = "Sorry, I can't automatically select an interpreter!\n";
139 Interpreter = AbstractInterpreter::createLLI(getToolName(), Message,
143 Interpreter = AbstractInterpreter::createLLC(getToolName(), Message,
147 Interpreter = AbstractInterpreter::createJIT(getToolName(), Message,
151 Interpreter = AbstractInterpreter::createLLC(getToolName(), Message,
156 Interpreter = AbstractInterpreter::createCBE(getToolName(), Message,
160 Interpreter = AbstractInterpreter::createCustom(getToolName(), Message,
164 Message = "Sorry, this back-end is not supported by bugpoint right now!\n";
167 std::cerr << Message;
169 // Initialize auxiliary tools for debugging
170 if (InterpreterSel == RunCBE) {
171 // We already created a CBE, reuse it.
173 } else if (InterpreterSel == CBE_bug || InterpreterSel == LLC_Safe) {
174 // We want to debug the CBE itself or LLC is known-good. Use LLC as the
175 // 'known-good' compiler.
176 std::vector<std::string> ToolArgs;
177 ToolArgs.push_back("--relocation-model=pic");
178 cbe = AbstractInterpreter::createLLC(getToolName(), Message, &ToolArgs);
180 cbe = AbstractInterpreter::createCBE(getToolName(), Message, &ToolArgv);
182 if (!cbe) { std::cout << Message << "\nExiting.\n"; exit(1); }
184 gcc = GCC::create(getToolName(), Message);
185 if (!gcc) { std::cout << Message << "\nExiting.\n"; exit(1); }
187 // If there was an error creating the selected interpreter, quit with error.
188 return Interpreter == 0;
191 /// compileProgram - Try to compile the specified module, throwing an exception
192 /// if an error occurs, or returning normally if not. This is used for code
193 /// generation crash testing.
195 void BugDriver::compileProgram(Module *M) {
196 // Emit the program to a bitcode file...
197 sys::Path BitcodeFile ("bugpoint-test-program.bc");
199 if (BitcodeFile.makeUnique(true,&ErrMsg)) {
200 std::cerr << ToolName << ": Error making unique filename: " << ErrMsg
204 if (writeProgramToFile(BitcodeFile.toString(), M)) {
205 std::cerr << ToolName << ": Error emitting bitcode to file '"
206 << BitcodeFile << "'!\n";
210 // Remove the temporary bitcode file when we are done.
211 FileRemover BitcodeFileRemover(BitcodeFile);
213 // Actually compile the program!
214 Interpreter->compileProgram(BitcodeFile.toString());
218 /// executeProgram - This method runs "Program", capturing the output of the
219 /// program to a file, returning the filename of the file. A recommended
220 /// filename may be optionally specified.
222 std::string BugDriver::executeProgram(std::string OutputFile,
223 std::string BitcodeFile,
224 const std::string &SharedObj,
225 AbstractInterpreter *AI,
226 bool *ProgramExitedNonzero) {
227 if (AI == 0) AI = Interpreter;
228 assert(AI && "Interpreter should have been created already!");
229 bool CreatedBitcode = false;
231 if (BitcodeFile.empty()) {
232 // Emit the program to a bitcode file...
233 sys::Path uniqueFilename("bugpoint-test-program.bc");
234 if (uniqueFilename.makeUnique(true, &ErrMsg)) {
235 std::cerr << ToolName << ": Error making unique filename: "
239 BitcodeFile = uniqueFilename.toString();
241 if (writeProgramToFile(BitcodeFile, Program)) {
242 std::cerr << ToolName << ": Error emitting bitcode to file '"
243 << BitcodeFile << "'!\n";
246 CreatedBitcode = true;
249 // Remove the temporary bitcode file when we are done.
250 sys::Path BitcodePath (BitcodeFile);
251 FileRemover BitcodeFileRemover(BitcodePath, CreatedBitcode);
253 if (OutputFile.empty()) OutputFile = "bugpoint-execution-output";
255 // Check to see if this is a valid output filename...
256 sys::Path uniqueFile(OutputFile);
257 if (uniqueFile.makeUnique(true, &ErrMsg)) {
258 std::cerr << ToolName << ": Error making unique filename: "
262 OutputFile = uniqueFile.toString();
264 // Figure out which shared objects to run, if any.
265 std::vector<std::string> SharedObjs(AdditionalSOs);
266 if (!SharedObj.empty())
267 SharedObjs.push_back(SharedObj);
270 // If this is an LLC or CBE run, then the GCC compiler might get run to
271 // compile the program. If so, we should pass the user's -Xlinker options
274 if (InterpreterSel == RunLLC || InterpreterSel == RunCBE ||
275 InterpreterSel == CBE_bug || InterpreterSel == LLC_Safe)
276 RetVal = AI->ExecuteProgram(BitcodeFile, InputArgv, InputFile,
277 OutputFile, AdditionalLinkerArgs, SharedObjs,
278 Timeout, MemoryLimit);
280 RetVal = AI->ExecuteProgram(BitcodeFile, InputArgv, InputFile,
281 OutputFile, std::vector<std::string>(),
282 SharedObjs, Timeout, MemoryLimit);
285 std::cerr << "<timeout>";
286 static bool FirstTimeout = true;
289 "*** Program execution timed out! This mechanism is designed to handle\n"
290 " programs stuck in infinite loops gracefully. The -timeout option\n"
291 " can be used to change the timeout threshold or disable it completely\n"
292 " (with -timeout=0). This message is only displayed once.\n";
293 FirstTimeout = false;
297 if (AppendProgramExitCode) {
298 std::ofstream outFile(OutputFile.c_str(), std::ios_base::app);
299 outFile << "exit " << RetVal << '\n';
303 if (ProgramExitedNonzero != 0)
304 *ProgramExitedNonzero = (RetVal != 0);
306 // Return the filename we captured the output to.
310 /// executeProgramWithCBE - Used to create reference output with the C
311 /// backend, if reference output is not provided.
313 std::string BugDriver::executeProgramWithCBE(std::string OutputFile) {
314 bool ProgramExitedNonzero;
315 std::string outFN = executeProgram(OutputFile, "", "", cbe,
316 &ProgramExitedNonzero);
317 if (ProgramExitedNonzero) {
319 << "Warning: While generating reference output, program exited with\n"
320 << "non-zero exit code. This will NOT be treated as a failure.\n";
321 CheckProgramExitCode = false;
326 std::string BugDriver::compileSharedObject(const std::string &BitcodeFile) {
327 assert(Interpreter && "Interpreter should have been created already!");
328 sys::Path OutputFile;
331 GCC::FileType FT = cbe->OutputCode(BitcodeFile, OutputFile);
333 std::string SharedObjectFile;
334 if (gcc->MakeSharedObject(OutputFile.toString(), FT,
335 SharedObjectFile, AdditionalLinkerArgs))
338 // Remove the intermediate C file
339 OutputFile.eraseFromDisk();
341 return "./" + SharedObjectFile;
344 /// createReferenceFile - calls compileProgram and then records the output
345 /// into ReferenceOutputFile. Returns true if reference file created, false
346 /// otherwise. Note: initializeExecutionEnvironment should be called BEFORE
349 bool BugDriver::createReferenceFile(Module *M, const std::string &Filename) {
351 compileProgram(Program);
352 } catch (ToolExecutionError &) {
356 ReferenceOutputFile = executeProgramWithCBE(Filename);
357 std::cout << "Reference output is: " << ReferenceOutputFile << "\n\n";
358 } catch (ToolExecutionError &TEE) {
359 std::cerr << TEE.what();
360 if (Interpreter != cbe) {
361 std::cerr << "*** There is a bug running the C backend. Either debug"
362 << " it (use the -run-cbe bugpoint option), or fix the error"
363 << " some other way.\n";
370 /// diffProgram - This method executes the specified module and diffs the
371 /// output against the file specified by ReferenceOutputFile. If the output
372 /// is different, true is returned. If there is a problem with the code
373 /// generator (e.g., llc crashes), this will throw an exception.
375 bool BugDriver::diffProgram(const std::string &BitcodeFile,
376 const std::string &SharedObject,
377 bool RemoveBitcode) {
378 bool ProgramExitedNonzero;
380 // Execute the program, generating an output file...
381 sys::Path Output(executeProgram("", BitcodeFile, SharedObject, 0,
382 &ProgramExitedNonzero));
384 // If we're checking the program exit code, assume anything nonzero is bad.
385 if (CheckProgramExitCode && ProgramExitedNonzero) {
386 Output.eraseFromDisk();
388 sys::Path(BitcodeFile).eraseFromDisk();
393 bool FilesDifferent = false;
394 if (int Diff = DiffFilesWithTolerance(sys::Path(ReferenceOutputFile),
395 sys::Path(Output.toString()),
396 AbsTolerance, RelTolerance, &Error)) {
398 std::cerr << "While diffing output: " << Error << '\n';
401 FilesDifferent = true;
404 // Remove the generated output.
405 Output.eraseFromDisk();
407 // Remove the bitcode file if we are supposed to.
409 sys::Path(BitcodeFile).eraseFromDisk();
410 return FilesDifferent;
413 bool BugDriver::isExecutingJIT() {
414 return InterpreterSel == RunJIT;