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