Remove VISIBILITY_HIDDEN from this file.
[llvm/avr.git] / tools / bugpoint / ExecutionDriver.cpp
blob72b971764197ee73a7ceadddb41ae29b4a851cee
1 //===- ExecutionDriver.cpp - Allow execution of LLVM program --------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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"
22 #include <fstream>
24 using namespace llvm;
26 namespace {
27 // OutputType - Allow the user to specify the way code should be run, to test
28 // for miscompilation.
30 enum OutputType {
31 AutoPick, RunLLI, RunJIT, RunLLC, RunCBE, CBE_bug, LLC_Safe, Custom
34 cl::opt<double>
35 AbsTolerance("abs-tolerance", cl::desc("Absolute error tolerated"),
36 cl::init(0.0));
37 cl::opt<double>
38 RelTolerance("rel-tolerance", cl::desc("Relative error tolerated"),
39 cl::init(0.0));
41 cl::opt<OutputType>
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(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."),
54 clEnumValEnd),
55 cl::init(AutoPick));
57 cl::opt<OutputType>
58 SafeInterpreterSel(cl::desc("Specify \"safe\" i.e. known-good backend:"),
59 cl::values(clEnumValN(AutoPick, "safe-auto", "Use best guess"),
60 clEnumValN(RunLLC, "safe-run-llc", "Compile with LLC"),
61 clEnumValN(RunCBE, "safe-run-cbe", "Compile with CBE"),
62 clEnumValN(Custom, "safe-run-custom",
63 "Use -exec-command to define a command to execute "
64 "the bitcode. Useful for cross-compilation."),
65 clEnumValEnd),
66 cl::init(AutoPick));
68 cl::opt<std::string>
69 SafeInterpreterPath("safe-path",
70 cl::desc("Specify the path to the \"safe\" backend program"),
71 cl::init(""));
73 cl::opt<bool>
74 AppendProgramExitCode("append-exit-code",
75 cl::desc("Append the exit code to the output so it gets diff'd too"),
76 cl::init(false));
78 cl::opt<std::string>
79 InputFile("input", cl::init("/dev/null"),
80 cl::desc("Filename to pipe in as stdin (default: /dev/null)"));
82 cl::list<std::string>
83 AdditionalSOs("additional-so",
84 cl::desc("Additional shared objects to load "
85 "into executing programs"));
87 cl::list<std::string>
88 AdditionalLinkerArgs("Xlinker",
89 cl::desc("Additional arguments to pass to the linker"));
91 cl::opt<std::string>
92 CustomExecCommand("exec-command", cl::init("simulate"),
93 cl::desc("Command to execute the bitcode (use with -run-custom) "
94 "(default: simulate)"));
97 namespace llvm {
98 // Anything specified after the --args option are taken as arguments to the
99 // program being debugged.
100 cl::list<std::string>
101 InputArgv("args", cl::Positional, cl::desc("<program arguments>..."),
102 cl::ZeroOrMore, cl::PositionalEatsArgs);
105 namespace {
106 cl::list<std::string>
107 ToolArgv("tool-args", cl::Positional, cl::desc("<tool arguments>..."),
108 cl::ZeroOrMore, cl::PositionalEatsArgs);
110 cl::list<std::string>
111 SafeToolArgv("safe-tool-args", cl::Positional,
112 cl::desc("<safe-tool arguments>..."),
113 cl::ZeroOrMore, cl::PositionalEatsArgs);
115 cl::list<std::string>
116 GCCToolArgv("gcc-tool-args", cl::Positional,
117 cl::desc("<gcc-tool arguments>..."),
118 cl::ZeroOrMore, cl::PositionalEatsArgs);
121 //===----------------------------------------------------------------------===//
122 // BugDriver method implementation
125 /// initializeExecutionEnvironment - This method is used to set up the
126 /// environment for executing LLVM programs.
128 bool BugDriver::initializeExecutionEnvironment() {
129 outs() << "Initializing execution environment: ";
131 // Create an instance of the AbstractInterpreter interface as specified on
132 // the command line
133 SafeInterpreter = 0;
134 std::string Message;
136 switch (InterpreterSel) {
137 case AutoPick:
138 InterpreterSel = RunCBE;
139 Interpreter =
140 AbstractInterpreter::createCBE(getToolName(), Message, &ToolArgv,
141 &GCCToolArgv);
142 if (!Interpreter) {
143 InterpreterSel = RunJIT;
144 Interpreter = AbstractInterpreter::createJIT(getToolName(), Message,
145 &ToolArgv);
147 if (!Interpreter) {
148 InterpreterSel = RunLLC;
149 Interpreter = AbstractInterpreter::createLLC(getToolName(), Message,
150 &ToolArgv, &GCCToolArgv);
152 if (!Interpreter) {
153 InterpreterSel = RunLLI;
154 Interpreter = AbstractInterpreter::createLLI(getToolName(), Message,
155 &ToolArgv);
157 if (!Interpreter) {
158 InterpreterSel = AutoPick;
159 Message = "Sorry, I can't automatically select an interpreter!\n";
161 break;
162 case RunLLI:
163 Interpreter = AbstractInterpreter::createLLI(getToolName(), Message,
164 &ToolArgv);
165 break;
166 case RunLLC:
167 case LLC_Safe:
168 Interpreter = AbstractInterpreter::createLLC(getToolName(), Message,
169 &ToolArgv, &GCCToolArgv);
170 break;
171 case RunJIT:
172 Interpreter = AbstractInterpreter::createJIT(getToolName(), Message,
173 &ToolArgv);
174 break;
175 case RunCBE:
176 case CBE_bug:
177 Interpreter = AbstractInterpreter::createCBE(getToolName(), Message,
178 &ToolArgv, &GCCToolArgv);
179 break;
180 case Custom:
181 Interpreter = AbstractInterpreter::createCustom(Message, CustomExecCommand);
182 break;
183 default:
184 Message = "Sorry, this back-end is not supported by bugpoint right now!\n";
185 break;
187 if (!Interpreter)
188 errs() << Message;
189 else // Display informational messages on stdout instead of stderr
190 outs() << Message;
192 std::string Path = SafeInterpreterPath;
193 if (Path.empty())
194 Path = getToolName();
195 std::vector<std::string> SafeToolArgs = SafeToolArgv;
196 switch (SafeInterpreterSel) {
197 case AutoPick:
198 // In "cbe-bug" mode, default to using LLC as the "safe" backend.
199 if (!SafeInterpreter &&
200 InterpreterSel == CBE_bug) {
201 SafeInterpreterSel = RunLLC;
202 SafeToolArgs.push_back("--relocation-model=pic");
203 SafeInterpreter = AbstractInterpreter::createLLC(Path.c_str(), Message,
204 &SafeToolArgs,
205 &GCCToolArgv);
208 // In "llc-safe" mode, default to using LLC as the "safe" backend.
209 if (!SafeInterpreter &&
210 InterpreterSel == LLC_Safe) {
211 SafeInterpreterSel = RunLLC;
212 SafeToolArgs.push_back("--relocation-model=pic");
213 SafeInterpreter = AbstractInterpreter::createLLC(Path.c_str(), Message,
214 &SafeToolArgs,
215 &GCCToolArgv);
218 // Pick a backend that's different from the test backend. The JIT and
219 // LLC backends share a lot of code, so prefer to use the CBE as the
220 // safe back-end when testing them.
221 if (!SafeInterpreter &&
222 InterpreterSel != RunCBE) {
223 SafeInterpreterSel = RunCBE;
224 SafeInterpreter = AbstractInterpreter::createCBE(Path.c_str(), Message,
225 &SafeToolArgs,
226 &GCCToolArgv);
228 if (!SafeInterpreter &&
229 InterpreterSel != RunLLC &&
230 InterpreterSel != RunJIT) {
231 SafeInterpreterSel = RunLLC;
232 SafeToolArgs.push_back("--relocation-model=pic");
233 SafeInterpreter = AbstractInterpreter::createLLC(Path.c_str(), Message,
234 &SafeToolArgs,
235 &GCCToolArgv);
237 if (!SafeInterpreter) {
238 SafeInterpreterSel = AutoPick;
239 Message = "Sorry, I can't automatically select an interpreter!\n";
241 break;
242 case RunLLC:
243 SafeToolArgs.push_back("--relocation-model=pic");
244 SafeInterpreter = AbstractInterpreter::createLLC(Path.c_str(), Message,
245 &SafeToolArgs,
246 &GCCToolArgv);
247 break;
248 case RunCBE:
249 SafeInterpreter = AbstractInterpreter::createCBE(Path.c_str(), Message,
250 &SafeToolArgs,
251 &GCCToolArgv);
252 break;
253 case Custom:
254 SafeInterpreter = AbstractInterpreter::createCustom(Message,
255 CustomExecCommand);
256 break;
257 default:
258 Message = "Sorry, this back-end is not supported by bugpoint as the "
259 "\"safe\" backend right now!\n";
260 break;
262 if (!SafeInterpreter) { outs() << Message << "\nExiting.\n"; exit(1); }
264 gcc = GCC::create(Message, &GCCToolArgv);
265 if (!gcc) { outs() << Message << "\nExiting.\n"; exit(1); }
267 // If there was an error creating the selected interpreter, quit with error.
268 return Interpreter == 0;
271 /// compileProgram - Try to compile the specified module, throwing an exception
272 /// if an error occurs, or returning normally if not. This is used for code
273 /// generation crash testing.
275 void BugDriver::compileProgram(Module *M) {
276 // Emit the program to a bitcode file...
277 sys::Path BitcodeFile ("bugpoint-test-program.bc");
278 std::string ErrMsg;
279 if (BitcodeFile.makeUnique(true,&ErrMsg)) {
280 errs() << ToolName << ": Error making unique filename: " << ErrMsg
281 << "\n";
282 exit(1);
284 if (writeProgramToFile(BitcodeFile.str(), M)) {
285 errs() << ToolName << ": Error emitting bitcode to file '"
286 << BitcodeFile.str() << "'!\n";
287 exit(1);
290 // Remove the temporary bitcode file when we are done.
291 FileRemover BitcodeFileRemover(BitcodeFile, !SaveTemps);
293 // Actually compile the program!
294 Interpreter->compileProgram(BitcodeFile.str());
298 /// executeProgram - This method runs "Program", capturing the output of the
299 /// program to a file, returning the filename of the file. A recommended
300 /// filename may be optionally specified.
302 std::string BugDriver::executeProgram(std::string OutputFile,
303 std::string BitcodeFile,
304 const std::string &SharedObj,
305 AbstractInterpreter *AI,
306 bool *ProgramExitedNonzero) {
307 if (AI == 0) AI = Interpreter;
308 assert(AI && "Interpreter should have been created already!");
309 bool CreatedBitcode = false;
310 std::string ErrMsg;
311 if (BitcodeFile.empty()) {
312 // Emit the program to a bitcode file...
313 sys::Path uniqueFilename("bugpoint-test-program.bc");
314 if (uniqueFilename.makeUnique(true, &ErrMsg)) {
315 errs() << ToolName << ": Error making unique filename: "
316 << ErrMsg << "!\n";
317 exit(1);
319 BitcodeFile = uniqueFilename.str();
321 if (writeProgramToFile(BitcodeFile, Program)) {
322 errs() << ToolName << ": Error emitting bitcode to file '"
323 << BitcodeFile << "'!\n";
324 exit(1);
326 CreatedBitcode = true;
329 // Remove the temporary bitcode file when we are done.
330 sys::Path BitcodePath (BitcodeFile);
331 FileRemover BitcodeFileRemover(BitcodePath, CreatedBitcode && !SaveTemps);
333 if (OutputFile.empty()) OutputFile = "bugpoint-execution-output";
335 // Check to see if this is a valid output filename...
336 sys::Path uniqueFile(OutputFile);
337 if (uniqueFile.makeUnique(true, &ErrMsg)) {
338 errs() << ToolName << ": Error making unique filename: "
339 << ErrMsg << "\n";
340 exit(1);
342 OutputFile = uniqueFile.str();
344 // Figure out which shared objects to run, if any.
345 std::vector<std::string> SharedObjs(AdditionalSOs);
346 if (!SharedObj.empty())
347 SharedObjs.push_back(SharedObj);
349 int RetVal = AI->ExecuteProgram(BitcodeFile, InputArgv, InputFile,
350 OutputFile, AdditionalLinkerArgs, SharedObjs,
351 Timeout, MemoryLimit);
353 if (RetVal == -1) {
354 errs() << "<timeout>";
355 static bool FirstTimeout = true;
356 if (FirstTimeout) {
357 outs() << "\n"
358 "*** Program execution timed out! This mechanism is designed to handle\n"
359 " programs stuck in infinite loops gracefully. The -timeout option\n"
360 " can be used to change the timeout threshold or disable it completely\n"
361 " (with -timeout=0). This message is only displayed once.\n";
362 FirstTimeout = false;
366 if (AppendProgramExitCode) {
367 std::ofstream outFile(OutputFile.c_str(), std::ios_base::app);
368 outFile << "exit " << RetVal << '\n';
369 outFile.close();
372 if (ProgramExitedNonzero != 0)
373 *ProgramExitedNonzero = (RetVal != 0);
375 // Return the filename we captured the output to.
376 return OutputFile;
379 /// executeProgramSafely - Used to create reference output with the "safe"
380 /// backend, if reference output is not provided.
382 std::string BugDriver::executeProgramSafely(std::string OutputFile) {
383 bool ProgramExitedNonzero;
384 std::string outFN = executeProgram(OutputFile, "", "", SafeInterpreter,
385 &ProgramExitedNonzero);
386 return outFN;
389 std::string BugDriver::compileSharedObject(const std::string &BitcodeFile) {
390 assert(Interpreter && "Interpreter should have been created already!");
391 sys::Path OutputFile;
393 // Using the known-good backend.
394 GCC::FileType FT = SafeInterpreter->OutputCode(BitcodeFile, OutputFile);
396 std::string SharedObjectFile;
397 if (gcc->MakeSharedObject(OutputFile.str(), FT,
398 SharedObjectFile, AdditionalLinkerArgs))
399 exit(1);
401 // Remove the intermediate C file
402 OutputFile.eraseFromDisk();
404 return "./" + SharedObjectFile;
407 /// createReferenceFile - calls compileProgram and then records the output
408 /// into ReferenceOutputFile. Returns true if reference file created, false
409 /// otherwise. Note: initializeExecutionEnvironment should be called BEFORE
410 /// this function.
412 bool BugDriver::createReferenceFile(Module *M, const std::string &Filename) {
413 try {
414 compileProgram(Program);
415 } catch (ToolExecutionError &) {
416 return false;
418 try {
419 ReferenceOutputFile = executeProgramSafely(Filename);
420 outs() << "\nReference output is: " << ReferenceOutputFile << "\n\n";
421 } catch (ToolExecutionError &TEE) {
422 errs() << TEE.what();
423 if (Interpreter != SafeInterpreter) {
424 errs() << "*** There is a bug running the \"safe\" backend. Either"
425 << " debug it (for example with the -run-cbe bugpoint option,"
426 << " if CBE is being used as the \"safe\" backend), or fix the"
427 << " error some other way.\n";
429 return false;
431 return true;
434 /// diffProgram - This method executes the specified module and diffs the
435 /// output against the file specified by ReferenceOutputFile. If the output
436 /// is different, true is returned. If there is a problem with the code
437 /// generator (e.g., llc crashes), this will throw an exception.
439 bool BugDriver::diffProgram(const std::string &BitcodeFile,
440 const std::string &SharedObject,
441 bool RemoveBitcode) {
442 bool ProgramExitedNonzero;
444 // Execute the program, generating an output file...
445 sys::Path Output(executeProgram("", BitcodeFile, SharedObject, 0,
446 &ProgramExitedNonzero));
448 std::string Error;
449 bool FilesDifferent = false;
450 if (int Diff = DiffFilesWithTolerance(sys::Path(ReferenceOutputFile),
451 sys::Path(Output.str()),
452 AbsTolerance, RelTolerance, &Error)) {
453 if (Diff == 2) {
454 errs() << "While diffing output: " << Error << '\n';
455 exit(1);
457 FilesDifferent = true;
459 else {
460 // Remove the generated output if there are no differences.
461 Output.eraseFromDisk();
464 // Remove the bitcode file if we are supposed to.
465 if (RemoveBitcode)
466 sys::Path(BitcodeFile).eraseFromDisk();
467 return FilesDifferent;
470 bool BugDriver::isExecutingJIT() {
471 return InterpreterSel == RunJIT;