BugDriver.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. //===- BugDriver.h - Top-Level BugPoint class -------------------*- C++ -*-===//
  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 class contains all of the shared state and information that is used by
  10. // the BugPoint tool to track down errors in optimizations. This class is the
  11. // main driver class that invokes all sub-functionality.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #ifndef LLVM_TOOLS_BUGPOINT_BUGDRIVER_H
  15. #define LLVM_TOOLS_BUGPOINT_BUGDRIVER_H
  16. #include "llvm/IR/ValueMap.h"
  17. #include "llvm/Support/Error.h"
  18. #include "llvm/Support/FileSystem.h"
  19. #include "llvm/Transforms/Utils/ValueMapper.h"
  20. #include <memory>
  21. #include <string>
  22. #include <vector>
  23. namespace llvm {
  24. class Value;
  25. class PassInfo;
  26. class Module;
  27. class GlobalVariable;
  28. class Function;
  29. class BasicBlock;
  30. class AbstractInterpreter;
  31. class Instruction;
  32. class LLVMContext;
  33. class DebugCrashes;
  34. class CC;
  35. extern bool DisableSimplifyCFG;
  36. /// BugpointIsInterrupted - Set to true when the user presses ctrl-c.
  37. ///
  38. extern bool BugpointIsInterrupted;
  39. class BugDriver {
  40. LLVMContext &Context;
  41. const char *ToolName; // argv[0] of bugpoint
  42. std::string ReferenceOutputFile; // Name of `good' output file
  43. std::unique_ptr<Module> Program; // The raw program, linked together
  44. std::vector<std::string> PassesToRun;
  45. AbstractInterpreter *Interpreter; // How to run the program
  46. AbstractInterpreter *SafeInterpreter; // To generate reference output, etc.
  47. CC *cc;
  48. bool run_find_bugs;
  49. unsigned Timeout;
  50. unsigned MemoryLimit;
  51. bool UseValgrind;
  52. // FIXME: sort out public/private distinctions...
  53. friend class ReducePassList;
  54. friend class ReduceMisCodegenFunctions;
  55. public:
  56. BugDriver(const char *toolname, bool find_bugs, unsigned timeout,
  57. unsigned memlimit, bool use_valgrind, LLVMContext &ctxt);
  58. ~BugDriver();
  59. const char *getToolName() const { return ToolName; }
  60. LLVMContext &getContext() const { return Context; }
  61. // Set up methods... these methods are used to copy information about the
  62. // command line arguments into instance variables of BugDriver.
  63. //
  64. bool addSources(const std::vector<std::string> &FileNames);
  65. void addPass(std::string p) { PassesToRun.push_back(std::move(p)); }
  66. void setPassesToRun(const std::vector<std::string> &PTR) {
  67. PassesToRun = PTR;
  68. }
  69. const std::vector<std::string> &getPassesToRun() const { return PassesToRun; }
  70. /// run - The top level method that is invoked after all of the instance
  71. /// variables are set up from command line arguments. The \p as_child argument
  72. /// indicates whether the driver is to run in parent mode or child mode.
  73. ///
  74. Error run();
  75. /// debugOptimizerCrash - This method is called when some optimizer pass
  76. /// crashes on input. It attempts to prune down the testcase to something
  77. /// reasonable, and figure out exactly which pass is crashing.
  78. ///
  79. Error debugOptimizerCrash(const std::string &ID = "passes");
  80. /// debugCodeGeneratorCrash - This method is called when the code generator
  81. /// crashes on an input. It attempts to reduce the input as much as possible
  82. /// while still causing the code generator to crash.
  83. Error debugCodeGeneratorCrash();
  84. /// debugMiscompilation - This method is used when the passes selected are not
  85. /// crashing, but the generated output is semantically different from the
  86. /// input.
  87. Error debugMiscompilation();
  88. /// debugPassMiscompilation - This method is called when the specified pass
  89. /// miscompiles Program as input. It tries to reduce the testcase to
  90. /// something that smaller that still miscompiles the program.
  91. /// ReferenceOutput contains the filename of the file containing the output we
  92. /// are to match.
  93. ///
  94. bool debugPassMiscompilation(const PassInfo *ThePass,
  95. const std::string &ReferenceOutput);
  96. /// compileSharedObject - This method creates a SharedObject from a given
  97. /// BitcodeFile for debugging a code generator.
  98. ///
  99. Expected<std::string> compileSharedObject(const std::string &BitcodeFile);
  100. /// debugCodeGenerator - This method narrows down a module to a function or
  101. /// set of functions, using the CBE as a ``safe'' code generator for other
  102. /// functions that are not under consideration.
  103. Error debugCodeGenerator();
  104. /// isExecutingJIT - Returns true if bugpoint is currently testing the JIT
  105. ///
  106. bool isExecutingJIT();
  107. Module &getProgram() const { return *Program; }
  108. /// Set the current module to the specified module, returning the old one.
  109. std::unique_ptr<Module> swapProgramIn(std::unique_ptr<Module> M);
  110. AbstractInterpreter *switchToSafeInterpreter() {
  111. AbstractInterpreter *Old = Interpreter;
  112. Interpreter = (AbstractInterpreter *)SafeInterpreter;
  113. return Old;
  114. }
  115. void switchToInterpreter(AbstractInterpreter *AI) { Interpreter = AI; }
  116. /// If we reduce or update the program somehow, call this method to update
  117. /// bugdriver with it. This deletes the old module and sets the specified one
  118. /// as the current program.
  119. void setNewProgram(std::unique_ptr<Module> M);
  120. /// Try to compile the specified module. This is used for code generation
  121. /// crash testing.
  122. Error compileProgram(Module &M) const;
  123. /// This method runs "Program", capturing the output of the program to a file.
  124. /// A recommended filename may be optionally specified.
  125. Expected<std::string> executeProgram(const Module &Program,
  126. std::string OutputFilename,
  127. std::string Bitcode,
  128. const std::string &SharedObjects,
  129. AbstractInterpreter *AI) const;
  130. /// Used to create reference output with the "safe" backend, if reference
  131. /// output is not provided. If there is a problem with the code generator
  132. /// (e.g., llc crashes), this will return false and set Error.
  133. Expected<std::string>
  134. executeProgramSafely(const Module &Program,
  135. const std::string &OutputFile) const;
  136. /// Calls compileProgram and then records the output into ReferenceOutputFile.
  137. /// Returns true if reference file created, false otherwise. Note:
  138. /// initializeExecutionEnvironment should be called BEFORE this function.
  139. Error createReferenceFile(Module &M, const std::string &Filename =
  140. "bugpoint.reference.out-%%%%%%%");
  141. /// This method executes the specified module and diffs the output against the
  142. /// file specified by ReferenceOutputFile. If the output is different, 1 is
  143. /// returned. If there is a problem with the code generator (e.g., llc
  144. /// crashes), this will return -1 and set Error.
  145. Expected<bool> diffProgram(const Module &Program,
  146. const std::string &BitcodeFile = "",
  147. const std::string &SharedObj = "",
  148. bool RemoveBitcode = false) const;
  149. /// This function is used to output M to a file named "bugpoint-ID.bc".
  150. void EmitProgressBitcode(const Module &M, const std::string &ID,
  151. bool NoFlyer = false) const;
  152. /// This method clones the current Program and deletes the specified
  153. /// instruction from the cloned module. It then runs a series of cleanup
  154. /// passes (ADCE and SimplifyCFG) to eliminate any code which depends on the
  155. /// value. The modified module is then returned.
  156. ///
  157. std::unique_ptr<Module> deleteInstructionFromProgram(const Instruction *I,
  158. unsigned Simp);
  159. /// This method clones the current Program and performs a series of cleanups
  160. /// intended to get rid of extra cruft on the module. If the
  161. /// MayModifySemantics argument is true, then the cleanups is allowed to
  162. /// modify how the code behaves.
  163. ///
  164. std::unique_ptr<Module> performFinalCleanups(std::unique_ptr<Module> M,
  165. bool MayModifySemantics = false);
  166. /// Given a module, extract up to one loop from it into a new function. This
  167. /// returns null if there are no extractable loops in the program or if the
  168. /// loop extractor crashes.
  169. std::unique_ptr<Module> extractLoop(Module *M);
  170. /// Extract all but the specified basic blocks into their own functions. The
  171. /// only detail is that M is actually a module cloned from the one the BBs are
  172. /// in, so some mapping needs to be performed. If this operation fails for
  173. /// some reason (ie the implementation is buggy), this function should return
  174. /// null, otherwise it returns a new Module.
  175. std::unique_ptr<Module>
  176. extractMappedBlocksFromModule(const std::vector<BasicBlock *> &BBs,
  177. Module *M);
  178. /// Carefully run the specified set of pass on the specified/ module,
  179. /// returning the transformed module on success, or a null pointer on failure.
  180. std::unique_ptr<Module> runPassesOn(Module *M,
  181. const std::vector<std::string> &Passes,
  182. ArrayRef<std::string> ExtraArgs = {});
  183. /// runPasses - Run the specified passes on Program, outputting a bitcode
  184. /// file and writting the filename into OutputFile if successful. If the
  185. /// optimizations fail for some reason (optimizer crashes), return true,
  186. /// otherwise return false. If DeleteOutput is set to true, the bitcode is
  187. /// deleted on success, and the filename string is undefined. This prints to
  188. /// outs() a single line message indicating whether compilation was successful
  189. /// or failed, unless Quiet is set. ExtraArgs specifies additional arguments
  190. /// to pass to the child bugpoint instance.
  191. ///
  192. bool runPasses(Module &Program, const std::vector<std::string> &PassesToRun,
  193. std::string &OutputFilename, bool DeleteOutput = false,
  194. bool Quiet = false,
  195. ArrayRef<std::string> ExtraArgs = {}) const;
  196. /// runPasses - Just like the method above, but this just returns true or
  197. /// false indicating whether or not the optimizer crashed on the specified
  198. /// input (true = crashed). Does not produce any output.
  199. ///
  200. bool runPasses(Module &M, const std::vector<std::string> &PassesToRun) const {
  201. std::string Filename;
  202. return runPasses(M, PassesToRun, Filename, true);
  203. }
  204. /// Take the specified pass list and create different combinations of passes
  205. /// to compile the program with. Compile the program with each set and mark
  206. /// test to see if it compiled correctly. If the passes compiled correctly
  207. /// output nothing and rearrange the passes into a new order. If the passes
  208. /// did not compile correctly, output the command required to recreate the
  209. /// failure.
  210. Error runManyPasses(const std::vector<std::string> &AllPasses);
  211. /// This writes the current "Program" to the named bitcode file. If an error
  212. /// occurs, true is returned.
  213. bool writeProgramToFile(const std::string &Filename, const Module &M) const;
  214. bool writeProgramToFile(const std::string &Filename, int FD,
  215. const Module &M) const;
  216. bool writeProgramToFile(int FD, const Module &M) const;
  217. private:
  218. /// initializeExecutionEnvironment - This method is used to set up the
  219. /// environment for executing LLVM programs.
  220. ///
  221. Error initializeExecutionEnvironment();
  222. };
  223. struct DiscardTemp {
  224. sys::fs::TempFile &File;
  225. ~DiscardTemp();
  226. };
  227. /// Given a bitcode or assembly input filename, parse and return it, or return
  228. /// null if not possible.
  229. ///
  230. std::unique_ptr<Module> parseInputFile(StringRef InputFilename,
  231. LLVMContext &ctxt);
  232. /// getPassesString - Turn a list of passes into a string which indicates the
  233. /// command line options that must be passed to add the passes.
  234. ///
  235. std::string getPassesString(const std::vector<std::string> &Passes);
  236. /// PrintFunctionList - prints out list of problematic functions
  237. ///
  238. void PrintFunctionList(const std::vector<Function *> &Funcs);
  239. /// PrintGlobalVariableList - prints out list of problematic global variables
  240. ///
  241. void PrintGlobalVariableList(const std::vector<GlobalVariable *> &GVs);
  242. // DeleteGlobalInitializer - "Remove" the global variable by deleting its
  243. // initializer, making it external.
  244. //
  245. void DeleteGlobalInitializer(GlobalVariable *GV);
  246. // DeleteFunctionBody - "Remove" the function by deleting all of it's basic
  247. // blocks, making it external.
  248. //
  249. void DeleteFunctionBody(Function *F);
  250. /// Given a module and a list of functions in the module, split the functions
  251. /// OUT of the specified module, and place them in the new module.
  252. std::unique_ptr<Module>
  253. SplitFunctionsOutOfModule(Module *M, const std::vector<Function *> &F,
  254. ValueToValueMapTy &VMap);
  255. } // End llvm namespace
  256. #endif