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 AppendProgramExitCode("append-exit-code",
59 cl::desc("Append the exit code to the output so it gets diff'd too"),
63 InputFile("input", cl::init("/dev/null"),
64 cl::desc("Filename to pipe in as stdin (default: /dev/null)"));
67 AdditionalSOs("additional-so",
68 cl::desc("Additional shared objects to load "
69 "into executing programs"));
72 AdditionalLinkerArgs("Xlinker",
73 cl::desc("Additional arguments to pass to the linker"));
76 CustomExecCommand("exec-command", cl::init("simulate"),
77 cl::desc("Command to execute the bitcode (use with -run-custom) "
78 "(default: simulate)"));
82 // Anything specified after the --args option are taken as arguments to the
83 // program being debugged.
85 InputArgv("args", cl::Positional, cl::desc("<program arguments>..."),
86 cl::ZeroOrMore, cl::PositionalEatsArgs);
89 ToolArgv("tool-args", cl::Positional, cl::desc("<tool arguments>..."),
90 cl::ZeroOrMore, cl::PositionalEatsArgs);
93 //===----------------------------------------------------------------------===//
94 // BugDriver method implementation
97 /// initializeExecutionEnvironment - This method is used to set up the
98 /// environment for executing LLVM programs.
100 bool BugDriver::initializeExecutionEnvironment() {
101 std::cout << "Initializing execution environment: ";
103 // Create an instance of the AbstractInterpreter interface as specified on
108 switch (InterpreterSel) {
110 InterpreterSel = RunCBE;
111 Interpreter = cbe = AbstractInterpreter::createCBE(getToolName(), Message,
114 InterpreterSel = RunJIT;
115 Interpreter = AbstractInterpreter::createJIT(getToolName(), Message,
119 InterpreterSel = RunLLC;
120 Interpreter = AbstractInterpreter::createLLC(getToolName(), Message,
124 InterpreterSel = RunLLI;
125 Interpreter = AbstractInterpreter::createLLI(getToolName(), Message,
129 InterpreterSel = AutoPick;
130 Message = "Sorry, I can't automatically select an interpreter!\n";
134 Interpreter = AbstractInterpreter::createLLI(getToolName(), Message,
138 Interpreter = AbstractInterpreter::createLLC(getToolName(), Message,
142 Interpreter = AbstractInterpreter::createJIT(getToolName(), Message,
146 Interpreter = AbstractInterpreter::createLLC(getToolName(), Message,
151 Interpreter = AbstractInterpreter::createCBE(getToolName(), Message,
155 Interpreter = AbstractInterpreter::createCustom(getToolName(), Message,
159 Message = "Sorry, this back-end is not supported by bugpoint right now!\n";
163 std::cerr << Message;
164 else // Display informational messages on stdout instead of stderr
165 std::cout << Message;
167 // Initialize auxiliary tools for debugging
168 if (InterpreterSel == RunCBE) {
169 // We already created a CBE, reuse it.
171 } else if (InterpreterSel == CBE_bug || InterpreterSel == LLC_Safe) {
172 // We want to debug the CBE itself or LLC is known-good. Use LLC as the
173 // 'known-good' compiler.
174 std::vector<std::string> ToolArgs;
175 ToolArgs.push_back("--relocation-model=pic");
176 cbe = AbstractInterpreter::createLLC(getToolName(), Message, &ToolArgs);
178 cbe = AbstractInterpreter::createCBE(getToolName(), Message, &ToolArgv);
180 if (!cbe) { std::cout << Message << "\nExiting.\n"; exit(1); }
182 gcc = GCC::create(getToolName(), Message);
183 if (!gcc) { std::cout << Message << "\nExiting.\n"; exit(1); }
185 // If there was an error creating the selected interpreter, quit with error.
186 return Interpreter == 0;
189 /// compileProgram - Try to compile the specified module, throwing an exception
190 /// if an error occurs, or returning normally if not. This is used for code
191 /// generation crash testing.
193 void BugDriver::compileProgram(Module *M) {
194 // Emit the program to a bitcode file...
195 sys::Path BitcodeFile ("bugpoint-test-program.bc");
197 if (BitcodeFile.makeUnique(true,&ErrMsg)) {
198 std::cerr << ToolName << ": Error making unique filename: " << ErrMsg
202 if (writeProgramToFile(BitcodeFile.toString(), M)) {
203 std::cerr << ToolName << ": Error emitting bitcode to file '"
204 << BitcodeFile << "'!\n";
208 // Remove the temporary bitcode file when we are done.
209 FileRemover BitcodeFileRemover(BitcodeFile);
211 // Actually compile the program!
212 Interpreter->compileProgram(BitcodeFile.toString());
216 /// executeProgram - This method runs "Program", capturing the output of the
217 /// program to a file, returning the filename of the file. A recommended
218 /// filename may be optionally specified.
220 std::string BugDriver::executeProgram(std::string OutputFile,
221 std::string BitcodeFile,
222 const std::string &SharedObj,
223 AbstractInterpreter *AI,
224 bool *ProgramExitedNonzero) {
225 if (AI == 0) AI = Interpreter;
226 assert(AI && "Interpreter should have been created already!");
227 bool CreatedBitcode = false;
229 if (BitcodeFile.empty()) {
230 // Emit the program to a bitcode file...
231 sys::Path uniqueFilename("bugpoint-test-program.bc");
232 if (uniqueFilename.makeUnique(true, &ErrMsg)) {
233 std::cerr << ToolName << ": Error making unique filename: "
237 BitcodeFile = uniqueFilename.toString();
239 if (writeProgramToFile(BitcodeFile, Program)) {
240 std::cerr << ToolName << ": Error emitting bitcode to file '"
241 << BitcodeFile << "'!\n";
244 CreatedBitcode = true;
247 // Remove the temporary bitcode file when we are done.
248 sys::Path BitcodePath (BitcodeFile);
249 FileRemover BitcodeFileRemover(BitcodePath, CreatedBitcode);
251 if (OutputFile.empty()) OutputFile = "bugpoint-execution-output";
253 // Check to see if this is a valid output filename...
254 sys::Path uniqueFile(OutputFile);
255 if (uniqueFile.makeUnique(true, &ErrMsg)) {
256 std::cerr << ToolName << ": Error making unique filename: "
260 OutputFile = uniqueFile.toString();
262 // Figure out which shared objects to run, if any.
263 std::vector<std::string> SharedObjs(AdditionalSOs);
264 if (!SharedObj.empty())
265 SharedObjs.push_back(SharedObj);
268 // If this is an LLC or CBE run, then the GCC compiler might get run to
269 // compile the program. If so, we should pass the user's -Xlinker options
272 if (InterpreterSel == RunLLC || InterpreterSel == RunCBE ||
273 InterpreterSel == CBE_bug || InterpreterSel == LLC_Safe)
274 RetVal = AI->ExecuteProgram(BitcodeFile, InputArgv, InputFile,
275 OutputFile, AdditionalLinkerArgs, SharedObjs,
276 Timeout, MemoryLimit);
278 RetVal = AI->ExecuteProgram(BitcodeFile, InputArgv, InputFile,
279 OutputFile, std::vector<std::string>(),
280 SharedObjs, Timeout, MemoryLimit);
283 std::cerr << "<timeout>";
284 static bool FirstTimeout = true;
287 "*** Program execution timed out! This mechanism is designed to handle\n"
288 " programs stuck in infinite loops gracefully. The -timeout option\n"
289 " can be used to change the timeout threshold or disable it completely\n"
290 " (with -timeout=0). This message is only displayed once.\n";
291 FirstTimeout = false;
295 if (AppendProgramExitCode) {
296 std::ofstream outFile(OutputFile.c_str(), std::ios_base::app);
297 outFile << "exit " << RetVal << '\n';
301 if (ProgramExitedNonzero != 0)
302 *ProgramExitedNonzero = (RetVal != 0);
304 // Return the filename we captured the output to.
308 /// executeProgramWithCBE - Used to create reference output with the C
309 /// backend, if reference output is not provided.
311 std::string BugDriver::executeProgramWithCBE(std::string OutputFile) {
312 bool ProgramExitedNonzero;
313 std::string outFN = executeProgram(OutputFile, "", "", cbe,
314 &ProgramExitedNonzero);
318 std::string BugDriver::compileSharedObject(const std::string &BitcodeFile) {
319 assert(Interpreter && "Interpreter should have been created already!");
320 sys::Path OutputFile;
323 GCC::FileType FT = cbe->OutputCode(BitcodeFile, OutputFile);
325 std::string SharedObjectFile;
326 if (gcc->MakeSharedObject(OutputFile.toString(), FT,
327 SharedObjectFile, AdditionalLinkerArgs))
330 // Remove the intermediate C file
331 OutputFile.eraseFromDisk();
333 return "./" + SharedObjectFile;
336 /// createReferenceFile - calls compileProgram and then records the output
337 /// into ReferenceOutputFile. Returns true if reference file created, false
338 /// otherwise. Note: initializeExecutionEnvironment should be called BEFORE
341 bool BugDriver::createReferenceFile(Module *M, const std::string &Filename) {
343 compileProgram(Program);
344 } catch (ToolExecutionError &) {
348 ReferenceOutputFile = executeProgramWithCBE(Filename);
349 std::cout << "Reference output is: " << ReferenceOutputFile << "\n\n";
350 } catch (ToolExecutionError &TEE) {
351 std::cerr << TEE.what();
352 if (Interpreter != cbe) {
353 std::cerr << "*** There is a bug running the C backend. Either debug"
354 << " it (use the -run-cbe bugpoint option), or fix the error"
355 << " some other way.\n";
362 /// diffProgram - This method executes the specified module and diffs the
363 /// output against the file specified by ReferenceOutputFile. If the output
364 /// is different, true is returned. If there is a problem with the code
365 /// generator (e.g., llc crashes), this will throw an exception.
367 bool BugDriver::diffProgram(const std::string &BitcodeFile,
368 const std::string &SharedObject,
369 bool RemoveBitcode) {
370 bool ProgramExitedNonzero;
372 // Execute the program, generating an output file...
373 sys::Path Output(executeProgram("", BitcodeFile, SharedObject, 0,
374 &ProgramExitedNonzero));
377 bool FilesDifferent = false;
378 if (int Diff = DiffFilesWithTolerance(sys::Path(ReferenceOutputFile),
379 sys::Path(Output.toString()),
380 AbsTolerance, RelTolerance, &Error)) {
382 std::cerr << "While diffing output: " << Error << '\n';
385 FilesDifferent = true;
388 // Remove the generated output.
389 Output.eraseFromDisk();
391 // Remove the bitcode file if we are supposed to.
393 sys::Path(BitcodeFile).eraseFromDisk();
394 return FilesDifferent;
397 bool BugDriver::isExecutingJIT() {
398 return InterpreterSel == RunJIT;