1 //===- ExecutionDriver.cpp - Allow execution of LLVM program --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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 bytecode.
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
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"),
54 CheckProgramExitCode("check-exit-code",
55 cl::desc("Assume nonzero exit code is failure (default on)"),
59 InputFile("input", cl::init("/dev/null"),
60 cl::desc("Filename to pipe in as stdin (default: /dev/null)"));
63 AdditionalSOs("additional-so",
64 cl::desc("Additional shared objects to load "
65 "into executing programs"));
68 AdditionalLinkerArgs("Xlinker",
69 cl::desc("Additional arguments to pass to the linker"));
73 // Anything specified after the --args option are taken as arguments to the
74 // program being debugged.
76 InputArgv("args", cl::Positional, cl::desc("<program arguments>..."),
77 cl::ZeroOrMore, cl::PositionalEatsArgs);
80 ToolArgv("tool-args", cl::Positional, cl::desc("<tool arguments>..."),
81 cl::ZeroOrMore, cl::PositionalEatsArgs);
84 //===----------------------------------------------------------------------===//
85 // BugDriver method implementation
88 /// initializeExecutionEnvironment - This method is used to set up the
89 /// environment for executing LLVM programs.
91 bool BugDriver::initializeExecutionEnvironment() {
92 std::cout << "Initializing execution environment: ";
94 // Create an instance of the AbstractInterpreter interface as specified on
99 switch (InterpreterSel) {
101 InterpreterSel = RunCBE;
102 Interpreter = cbe = AbstractInterpreter::createCBE(getToolName(), Message,
105 InterpreterSel = RunJIT;
106 Interpreter = AbstractInterpreter::createJIT(getToolName(), Message,
110 InterpreterSel = RunLLC;
111 Interpreter = AbstractInterpreter::createLLC(getToolName(), Message,
115 InterpreterSel = RunLLI;
116 Interpreter = AbstractInterpreter::createLLI(getToolName(), Message,
120 InterpreterSel = AutoPick;
121 Message = "Sorry, I can't automatically select an interpreter!\n";
125 Interpreter = AbstractInterpreter::createLLI(getToolName(), Message,
129 Interpreter = AbstractInterpreter::createLLC(getToolName(), Message,
133 Interpreter = AbstractInterpreter::createJIT(getToolName(), Message,
138 Interpreter = AbstractInterpreter::createCBE(getToolName(), Message,
142 Message = "Sorry, this back-end is not supported by bugpoint right now!\n";
145 std::cerr << Message;
147 // Initialize auxiliary tools for debugging
148 if (InterpreterSel == RunCBE) {
149 // We already created a CBE, reuse it.
151 } else if (InterpreterSel == CBE_bug) {
152 // We want to debug the CBE itself. Use LLC as the 'known-good' compiler.
153 std::vector<std::string> ToolArgs;
154 ToolArgs.push_back("--relocation-model=pic");
155 cbe = AbstractInterpreter::createLLC(getToolName(), Message, &ToolArgs);
157 cbe = AbstractInterpreter::createCBE(getToolName(), Message, &ToolArgv);
159 if (!cbe) { std::cout << Message << "\nExiting.\n"; exit(1); }
161 gcc = GCC::create(getToolName(), Message);
162 if (!gcc) { std::cout << Message << "\nExiting.\n"; exit(1); }
164 // If there was an error creating the selected interpreter, quit with error.
165 return Interpreter == 0;
168 /// compileProgram - Try to compile the specified module, throwing an exception
169 /// if an error occurs, or returning normally if not. This is used for code
170 /// generation crash testing.
172 void BugDriver::compileProgram(Module *M) {
173 // Emit the program to a bytecode file...
174 sys::Path BytecodeFile ("bugpoint-test-program.bc");
176 if (BytecodeFile.makeUnique(true,&ErrMsg)) {
177 std::cerr << ToolName << ": Error making unique filename: " << ErrMsg
181 if (writeProgramToFile(BytecodeFile.toString(), M)) {
182 std::cerr << ToolName << ": Error emitting bytecode to file '"
183 << BytecodeFile << "'!\n";
187 // Remove the temporary bytecode file when we are done.
188 FileRemover BytecodeFileRemover(BytecodeFile);
190 // Actually compile the program!
191 Interpreter->compileProgram(BytecodeFile.toString());
195 /// executeProgram - This method runs "Program", capturing the output of the
196 /// program to a file, returning the filename of the file. A recommended
197 /// filename may be optionally specified.
199 std::string BugDriver::executeProgram(std::string OutputFile,
200 std::string BytecodeFile,
201 const std::string &SharedObj,
202 AbstractInterpreter *AI,
203 bool *ProgramExitedNonzero) {
204 if (AI == 0) AI = Interpreter;
205 assert(AI && "Interpreter should have been created already!");
206 bool CreatedBytecode = false;
208 if (BytecodeFile.empty()) {
209 // Emit the program to a bytecode file...
210 sys::Path uniqueFilename("bugpoint-test-program.bc");
211 if (uniqueFilename.makeUnique(true, &ErrMsg)) {
212 std::cerr << ToolName << ": Error making unique filename: "
216 BytecodeFile = uniqueFilename.toString();
218 if (writeProgramToFile(BytecodeFile, Program)) {
219 std::cerr << ToolName << ": Error emitting bytecode to file '"
220 << BytecodeFile << "'!\n";
223 CreatedBytecode = true;
226 // Remove the temporary bytecode file when we are done.
227 sys::Path BytecodePath (BytecodeFile);
228 FileRemover BytecodeFileRemover(BytecodePath, CreatedBytecode);
230 if (OutputFile.empty()) OutputFile = "bugpoint-execution-output";
232 // Check to see if this is a valid output filename...
233 sys::Path uniqueFile(OutputFile);
234 if (uniqueFile.makeUnique(true, &ErrMsg)) {
235 std::cerr << ToolName << ": Error making unique filename: "
239 OutputFile = uniqueFile.toString();
241 // Figure out which shared objects to run, if any.
242 std::vector<std::string> SharedObjs(AdditionalSOs);
243 if (!SharedObj.empty())
244 SharedObjs.push_back(SharedObj);
247 // If this is an LLC or CBE run, then the GCC compiler might get run to
248 // compile the program. If so, we should pass the user's -Xlinker options
251 if (InterpreterSel == RunLLC || InterpreterSel == RunCBE ||
252 InterpreterSel == CBE_bug)
253 RetVal = AI->ExecuteProgram(BytecodeFile, InputArgv, InputFile,
254 OutputFile, AdditionalLinkerArgs, SharedObjs,
257 RetVal = AI->ExecuteProgram(BytecodeFile, InputArgv, InputFile,
258 OutputFile, std::vector<std::string>(),
259 SharedObjs, Timeout);
262 std::cerr << "<timeout>";
263 static bool FirstTimeout = true;
266 "*** Program execution timed out! This mechanism is designed to handle\n"
267 " programs stuck in infinite loops gracefully. The -timeout option\n"
268 " can be used to change the timeout threshold or disable it completely\n"
269 " (with -timeout=0). This message is only displayed once.\n";
270 FirstTimeout = false;
274 if (ProgramExitedNonzero != 0)
275 *ProgramExitedNonzero = (RetVal != 0);
277 // Return the filename we captured the output to.
281 /// executeProgramWithCBE - Used to create reference output with the C
282 /// backend, if reference output is not provided.
284 std::string BugDriver::executeProgramWithCBE(std::string OutputFile) {
285 bool ProgramExitedNonzero;
286 std::string outFN = executeProgram(OutputFile, "", "", cbe,
287 &ProgramExitedNonzero);
288 if (ProgramExitedNonzero) {
290 << "Warning: While generating reference output, program exited with\n"
291 << "non-zero exit code. This will NOT be treated as a failure.\n";
292 CheckProgramExitCode = false;
297 std::string BugDriver::compileSharedObject(const std::string &BytecodeFile) {
298 assert(Interpreter && "Interpreter should have been created already!");
299 sys::Path OutputFile;
302 GCC::FileType FT = cbe->OutputCode(BytecodeFile, OutputFile);
304 std::string SharedObjectFile;
305 if (gcc->MakeSharedObject(OutputFile.toString(), FT,
306 SharedObjectFile, AdditionalLinkerArgs))
309 // Remove the intermediate C file
310 OutputFile.eraseFromDisk();
312 return "./" + SharedObjectFile;
315 /// createReferenceFile - calls compileProgram and then records the output
316 /// into ReferenceOutputFile. Returns true if reference file created, false
317 /// otherwise. Note: initializeExecutionEnvironment should be called BEFORE
320 bool BugDriver::createReferenceFile(Module *M, const std::string &Filename) {
322 compileProgram(Program);
323 } catch (ToolExecutionError &) {
327 ReferenceOutputFile = executeProgramWithCBE(Filename);
328 std::cout << "Reference output is: " << ReferenceOutputFile << "\n\n";
329 } catch (ToolExecutionError &TEE) {
330 std::cerr << TEE.what();
331 if (Interpreter != cbe) {
332 std::cerr << "*** There is a bug running the C backend. Either debug"
333 << " it (use the -run-cbe bugpoint option), or fix the error"
334 << " some other way.\n";
341 /// diffProgram - This method executes the specified module and diffs the
342 /// output against the file specified by ReferenceOutputFile. If the output
343 /// is different, true is returned. If there is a problem with the code
344 /// generator (e.g., llc crashes), this will throw an exception.
346 bool BugDriver::diffProgram(const std::string &BytecodeFile,
347 const std::string &SharedObject,
348 bool RemoveBytecode) {
349 bool ProgramExitedNonzero;
351 // Execute the program, generating an output file...
352 sys::Path Output(executeProgram("", BytecodeFile, SharedObject, 0,
353 &ProgramExitedNonzero));
355 // If we're checking the program exit code, assume anything nonzero is bad.
356 if (CheckProgramExitCode && ProgramExitedNonzero) {
357 Output.eraseFromDisk();
359 sys::Path(BytecodeFile).eraseFromDisk();
364 bool FilesDifferent = false;
365 if (int Diff = DiffFilesWithTolerance(sys::Path(ReferenceOutputFile),
366 sys::Path(Output.toString()),
367 AbsTolerance, RelTolerance, &Error)) {
369 std::cerr << "While diffing output: " << Error << '\n';
372 FilesDifferent = true;
375 // Remove the generated output.
376 Output.eraseFromDisk();
378 // Remove the bytecode file if we are supposed to.
380 sys::Path(BytecodeFile).eraseFromDisk();
381 return FilesDifferent;
384 bool BugDriver::isExecutingJIT() {
385 return InterpreterSel == RunJIT;