ExecutionDriver.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. //===- ExecutionDriver.cpp - Allow execution of LLVM program --------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file contains code used to execute the program utilizing one of the
  10. // various ways of running LLVM bitcode.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "BugDriver.h"
  14. #include "ToolRunner.h"
  15. #include "llvm/Support/CommandLine.h"
  16. #include "llvm/Support/Debug.h"
  17. #include "llvm/Support/FileUtilities.h"
  18. #include "llvm/Support/Program.h"
  19. #include "llvm/Support/SystemUtils.h"
  20. #include "llvm/Support/raw_ostream.h"
  21. #include <fstream>
  22. using namespace llvm;
  23. namespace {
  24. // OutputType - Allow the user to specify the way code should be run, to test
  25. // for miscompilation.
  26. //
  27. enum OutputType {
  28. AutoPick,
  29. RunLLI,
  30. RunJIT,
  31. RunLLC,
  32. RunLLCIA,
  33. CompileCustom,
  34. Custom
  35. };
  36. cl::opt<double> AbsTolerance("abs-tolerance",
  37. cl::desc("Absolute error tolerated"),
  38. cl::init(0.0));
  39. cl::opt<double> RelTolerance("rel-tolerance",
  40. cl::desc("Relative error tolerated"),
  41. cl::init(0.0));
  42. cl::opt<OutputType> InterpreterSel(
  43. cl::desc("Specify the \"test\" i.e. suspect back-end:"),
  44. cl::values(clEnumValN(AutoPick, "auto", "Use best guess"),
  45. clEnumValN(RunLLI, "run-int", "Execute with the interpreter"),
  46. clEnumValN(RunJIT, "run-jit", "Execute with JIT"),
  47. clEnumValN(RunLLC, "run-llc", "Compile with LLC"),
  48. clEnumValN(RunLLCIA, "run-llc-ia",
  49. "Compile with LLC with integrated assembler"),
  50. clEnumValN(CompileCustom, "compile-custom",
  51. "Use -compile-command to define a command to "
  52. "compile the bitcode. Useful to avoid linking."),
  53. clEnumValN(Custom, "run-custom",
  54. "Use -exec-command to define a command to execute "
  55. "the bitcode. Useful for cross-compilation.")),
  56. cl::init(AutoPick));
  57. cl::opt<OutputType> SafeInterpreterSel(
  58. 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(Custom, "safe-run-custom",
  62. "Use -exec-command to define a command to execute "
  63. "the bitcode. Useful for cross-compilation.")),
  64. cl::init(AutoPick));
  65. cl::opt<std::string> SafeInterpreterPath(
  66. "safe-path", cl::desc("Specify the path to the \"safe\" backend program"),
  67. cl::init(""));
  68. cl::opt<bool> AppendProgramExitCode(
  69. "append-exit-code",
  70. cl::desc("Append the exit code to the output so it gets diff'd too"),
  71. cl::init(false));
  72. cl::opt<std::string>
  73. InputFile("input", cl::init("/dev/null"),
  74. cl::desc("Filename to pipe in as stdin (default: /dev/null)"));
  75. cl::list<std::string>
  76. AdditionalSOs("additional-so", cl::desc("Additional shared objects to load "
  77. "into executing programs"));
  78. cl::list<std::string> AdditionalLinkerArgs(
  79. "Xlinker", cl::desc("Additional arguments to pass to the linker"));
  80. cl::opt<std::string> CustomCompileCommand(
  81. "compile-command", cl::init("llc"),
  82. cl::desc("Command to compile the bitcode (use with -compile-custom) "
  83. "(default: llc)"));
  84. cl::opt<std::string> CustomExecCommand(
  85. "exec-command", cl::init("simulate"),
  86. cl::desc("Command to execute the bitcode (use with -run-custom) "
  87. "(default: simulate)"));
  88. }
  89. namespace llvm {
  90. // Anything specified after the --args option are taken as arguments to the
  91. // program being debugged.
  92. cl::list<std::string> InputArgv("args", cl::Positional,
  93. cl::desc("<program arguments>..."),
  94. cl::PositionalEatsArgs);
  95. cl::opt<std::string>
  96. OutputPrefix("output-prefix", cl::init("bugpoint"),
  97. cl::desc("Prefix to use for outputs (default: 'bugpoint')"));
  98. }
  99. namespace {
  100. cl::list<std::string> ToolArgv("tool-args", cl::Positional,
  101. cl::desc("<tool arguments>..."),
  102. cl::PositionalEatsArgs);
  103. cl::list<std::string> SafeToolArgv("safe-tool-args", cl::Positional,
  104. cl::desc("<safe-tool arguments>..."),
  105. cl::PositionalEatsArgs);
  106. cl::opt<std::string> CCBinary("gcc", cl::init(""),
  107. cl::desc("The gcc binary to use."));
  108. cl::list<std::string> CCToolArgv("gcc-tool-args", cl::Positional,
  109. cl::desc("<gcc-tool arguments>..."),
  110. cl::PositionalEatsArgs);
  111. }
  112. //===----------------------------------------------------------------------===//
  113. // BugDriver method implementation
  114. //
  115. /// initializeExecutionEnvironment - This method is used to set up the
  116. /// environment for executing LLVM programs.
  117. ///
  118. Error BugDriver::initializeExecutionEnvironment() {
  119. outs() << "Initializing execution environment: ";
  120. // Create an instance of the AbstractInterpreter interface as specified on
  121. // the command line
  122. SafeInterpreter = nullptr;
  123. std::string Message;
  124. if (CCBinary.empty()) {
  125. if (ErrorOr<std::string> ClangPath =
  126. FindProgramByName("clang", getToolName(), &AbsTolerance))
  127. CCBinary = *ClangPath;
  128. else
  129. CCBinary = "gcc";
  130. }
  131. switch (InterpreterSel) {
  132. case AutoPick:
  133. if (!Interpreter) {
  134. InterpreterSel = RunJIT;
  135. Interpreter =
  136. AbstractInterpreter::createJIT(getToolName(), Message, &ToolArgv);
  137. }
  138. if (!Interpreter) {
  139. InterpreterSel = RunLLC;
  140. Interpreter = AbstractInterpreter::createLLC(
  141. getToolName(), Message, CCBinary, &ToolArgv, &CCToolArgv);
  142. }
  143. if (!Interpreter) {
  144. InterpreterSel = RunLLI;
  145. Interpreter =
  146. AbstractInterpreter::createLLI(getToolName(), Message, &ToolArgv);
  147. }
  148. if (!Interpreter) {
  149. InterpreterSel = AutoPick;
  150. Message = "Sorry, I can't automatically select an interpreter!\n";
  151. }
  152. break;
  153. case RunLLI:
  154. Interpreter =
  155. AbstractInterpreter::createLLI(getToolName(), Message, &ToolArgv);
  156. break;
  157. case RunLLC:
  158. case RunLLCIA:
  159. Interpreter = AbstractInterpreter::createLLC(
  160. getToolName(), Message, CCBinary, &ToolArgv, &CCToolArgv,
  161. InterpreterSel == RunLLCIA);
  162. break;
  163. case RunJIT:
  164. Interpreter =
  165. AbstractInterpreter::createJIT(getToolName(), Message, &ToolArgv);
  166. break;
  167. case CompileCustom:
  168. Interpreter = AbstractInterpreter::createCustomCompiler(
  169. getToolName(), Message, CustomCompileCommand);
  170. break;
  171. case Custom:
  172. Interpreter = AbstractInterpreter::createCustomExecutor(
  173. getToolName(), Message, CustomExecCommand);
  174. break;
  175. }
  176. if (!Interpreter)
  177. errs() << Message;
  178. else // Display informational messages on stdout instead of stderr
  179. outs() << Message;
  180. std::string Path = SafeInterpreterPath;
  181. if (Path.empty())
  182. Path = getToolName();
  183. std::vector<std::string> SafeToolArgs = SafeToolArgv;
  184. switch (SafeInterpreterSel) {
  185. case AutoPick:
  186. // In "llc-safe" mode, default to using LLC as the "safe" backend.
  187. if (InterpreterSel == RunLLC) {
  188. SafeInterpreterSel = RunLLC;
  189. SafeToolArgs.push_back("--relocation-model=pic");
  190. SafeInterpreter = AbstractInterpreter::createLLC(
  191. Path.c_str(), Message, CCBinary, &SafeToolArgs, &CCToolArgv);
  192. } else if (InterpreterSel != CompileCustom) {
  193. SafeInterpreterSel = AutoPick;
  194. Message = "Sorry, I can't automatically select a safe interpreter!\n";
  195. }
  196. break;
  197. case RunLLC:
  198. case RunLLCIA:
  199. SafeToolArgs.push_back("--relocation-model=pic");
  200. SafeInterpreter = AbstractInterpreter::createLLC(
  201. Path.c_str(), Message, CCBinary, &SafeToolArgs, &CCToolArgv,
  202. SafeInterpreterSel == RunLLCIA);
  203. break;
  204. case Custom:
  205. SafeInterpreter = AbstractInterpreter::createCustomExecutor(
  206. getToolName(), Message, CustomExecCommand);
  207. break;
  208. default:
  209. Message = "Sorry, this back-end is not supported by bugpoint as the "
  210. "\"safe\" backend right now!\n";
  211. break;
  212. }
  213. if (!SafeInterpreter && InterpreterSel != CompileCustom) {
  214. outs() << Message << "\nExiting.\n";
  215. exit(1);
  216. }
  217. cc = CC::create(getToolName(), Message, CCBinary, &CCToolArgv);
  218. if (!cc) {
  219. outs() << Message << "\nExiting.\n";
  220. exit(1);
  221. }
  222. // If there was an error creating the selected interpreter, quit with error.
  223. if (Interpreter == nullptr)
  224. return make_error<StringError>("Failed to init execution environment",
  225. inconvertibleErrorCode());
  226. return Error::success();
  227. }
  228. /// Try to compile the specified module, returning false and setting Error if an
  229. /// error occurs. This is used for code generation crash testing.
  230. Error BugDriver::compileProgram(Module &M) const {
  231. // Emit the program to a bitcode file...
  232. auto Temp =
  233. sys::fs::TempFile::create(OutputPrefix + "-test-program-%%%%%%%.bc");
  234. if (!Temp) {
  235. errs() << ToolName
  236. << ": Error making unique filename: " << toString(Temp.takeError())
  237. << "\n";
  238. exit(1);
  239. }
  240. DiscardTemp Discard{*Temp};
  241. if (writeProgramToFile(Temp->FD, M)) {
  242. errs() << ToolName << ": Error emitting bitcode to file '" << Temp->TmpName
  243. << "'!\n";
  244. exit(1);
  245. }
  246. // Actually compile the program!
  247. return Interpreter->compileProgram(Temp->TmpName, Timeout, MemoryLimit);
  248. }
  249. /// This method runs "Program", capturing the output of the program to a file,
  250. /// returning the filename of the file. A recommended filename may be
  251. /// optionally specified.
  252. Expected<std::string> BugDriver::executeProgram(const Module &Program,
  253. std::string OutputFile,
  254. std::string BitcodeFile,
  255. const std::string &SharedObj,
  256. AbstractInterpreter *AI) const {
  257. if (!AI)
  258. AI = Interpreter;
  259. assert(AI && "Interpreter should have been created already!");
  260. bool CreatedBitcode = false;
  261. if (BitcodeFile.empty()) {
  262. // Emit the program to a bitcode file...
  263. SmallString<128> UniqueFilename;
  264. int UniqueFD;
  265. std::error_code EC = sys::fs::createUniqueFile(
  266. OutputPrefix + "-test-program-%%%%%%%.bc", UniqueFD, UniqueFilename);
  267. if (EC) {
  268. errs() << ToolName << ": Error making unique filename: " << EC.message()
  269. << "!\n";
  270. exit(1);
  271. }
  272. BitcodeFile = std::string(UniqueFilename.str());
  273. if (writeProgramToFile(BitcodeFile, UniqueFD, Program)) {
  274. errs() << ToolName << ": Error emitting bitcode to file '" << BitcodeFile
  275. << "'!\n";
  276. exit(1);
  277. }
  278. CreatedBitcode = true;
  279. }
  280. // Remove the temporary bitcode file when we are done.
  281. std::string BitcodePath(BitcodeFile);
  282. FileRemover BitcodeFileRemover(BitcodePath, CreatedBitcode && !SaveTemps);
  283. if (OutputFile.empty())
  284. OutputFile = OutputPrefix + "-execution-output-%%%%%%%";
  285. // Check to see if this is a valid output filename...
  286. SmallString<128> UniqueFile;
  287. std::error_code EC = sys::fs::createUniqueFile(OutputFile, UniqueFile);
  288. if (EC) {
  289. errs() << ToolName << ": Error making unique filename: " << EC.message()
  290. << "\n";
  291. exit(1);
  292. }
  293. OutputFile = std::string(UniqueFile.str());
  294. // Figure out which shared objects to run, if any.
  295. std::vector<std::string> SharedObjs(AdditionalSOs);
  296. if (!SharedObj.empty())
  297. SharedObjs.push_back(SharedObj);
  298. Expected<int> RetVal = AI->ExecuteProgram(BitcodeFile, InputArgv, InputFile,
  299. OutputFile, AdditionalLinkerArgs,
  300. SharedObjs, Timeout, MemoryLimit);
  301. if (Error E = RetVal.takeError())
  302. return std::move(E);
  303. if (*RetVal == -1) {
  304. errs() << "<timeout>";
  305. static bool FirstTimeout = true;
  306. if (FirstTimeout) {
  307. outs()
  308. << "\n"
  309. "*** Program execution timed out! This mechanism is designed to "
  310. "handle\n"
  311. " programs stuck in infinite loops gracefully. The -timeout "
  312. "option\n"
  313. " can be used to change the timeout threshold or disable it "
  314. "completely\n"
  315. " (with -timeout=0). This message is only displayed once.\n";
  316. FirstTimeout = false;
  317. }
  318. }
  319. if (AppendProgramExitCode) {
  320. std::ofstream outFile(OutputFile.c_str(), std::ios_base::app);
  321. outFile << "exit " << *RetVal << '\n';
  322. outFile.close();
  323. }
  324. // Return the filename we captured the output to.
  325. return OutputFile;
  326. }
  327. /// Used to create reference output with the "safe" backend, if reference output
  328. /// is not provided.
  329. Expected<std::string>
  330. BugDriver::executeProgramSafely(const Module &Program,
  331. const std::string &OutputFile) const {
  332. return executeProgram(Program, OutputFile, "", "", SafeInterpreter);
  333. }
  334. Expected<std::string>
  335. BugDriver::compileSharedObject(const std::string &BitcodeFile) {
  336. assert(Interpreter && "Interpreter should have been created already!");
  337. std::string OutputFile;
  338. // Using the known-good backend.
  339. Expected<CC::FileType> FT =
  340. SafeInterpreter->OutputCode(BitcodeFile, OutputFile);
  341. if (Error E = FT.takeError())
  342. return std::move(E);
  343. std::string SharedObjectFile;
  344. if (Error E = cc->MakeSharedObject(OutputFile, *FT, SharedObjectFile,
  345. AdditionalLinkerArgs))
  346. return std::move(E);
  347. // Remove the intermediate C file
  348. sys::fs::remove(OutputFile);
  349. return SharedObjectFile;
  350. }
  351. /// Calls compileProgram and then records the output into ReferenceOutputFile.
  352. /// Returns true if reference file created, false otherwise. Note:
  353. /// initializeExecutionEnvironment should be called BEFORE this function.
  354. Error BugDriver::createReferenceFile(Module &M, const std::string &Filename) {
  355. if (Error E = compileProgram(*Program))
  356. return E;
  357. Expected<std::string> Result = executeProgramSafely(*Program, Filename);
  358. if (Error E = Result.takeError()) {
  359. if (Interpreter != SafeInterpreter) {
  360. E = joinErrors(
  361. std::move(E),
  362. make_error<StringError>(
  363. "*** There is a bug running the \"safe\" backend. Either"
  364. " debug it (for example with the -run-jit bugpoint option,"
  365. " if JIT is being used as the \"safe\" backend), or fix the"
  366. " error some other way.\n",
  367. inconvertibleErrorCode()));
  368. }
  369. return E;
  370. }
  371. ReferenceOutputFile = *Result;
  372. outs() << "\nReference output is: " << ReferenceOutputFile << "\n\n";
  373. return Error::success();
  374. }
  375. /// This method executes the specified module and diffs the output against the
  376. /// file specified by ReferenceOutputFile. If the output is different, 1 is
  377. /// returned. If there is a problem with the code generator (e.g., llc
  378. /// crashes), this will set ErrMsg.
  379. Expected<bool> BugDriver::diffProgram(const Module &Program,
  380. const std::string &BitcodeFile,
  381. const std::string &SharedObject,
  382. bool RemoveBitcode) const {
  383. // Execute the program, generating an output file...
  384. Expected<std::string> Output =
  385. executeProgram(Program, "", BitcodeFile, SharedObject, nullptr);
  386. if (Error E = Output.takeError())
  387. return std::move(E);
  388. std::string Error;
  389. bool FilesDifferent = false;
  390. if (int Diff = DiffFilesWithTolerance(ReferenceOutputFile, *Output,
  391. AbsTolerance, RelTolerance, &Error)) {
  392. if (Diff == 2) {
  393. errs() << "While diffing output: " << Error << '\n';
  394. exit(1);
  395. }
  396. FilesDifferent = true;
  397. } else {
  398. // Remove the generated output if there are no differences.
  399. sys::fs::remove(*Output);
  400. }
  401. // Remove the bitcode file if we are supposed to.
  402. if (RemoveBitcode)
  403. sys::fs::remove(BitcodeFile);
  404. return FilesDifferent;
  405. }
  406. bool BugDriver::isExecutingJIT() { return InterpreterSel == RunJIT; }