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