1193323Sed//===- BugDriver.h - Top-Level BugPoint class -------------------*- C++ -*-===//
2193323Sed//
3193323Sed//                     The LLVM Compiler Infrastructure
4193323Sed//
5193323Sed// This file is distributed under the University of Illinois Open Source
6193323Sed// License. See LICENSE.TXT for details.
7193323Sed//
8193323Sed//===----------------------------------------------------------------------===//
9193323Sed//
10193323Sed// This class contains all of the shared state and information that is used by
11193323Sed// the BugPoint tool to track down errors in optimizations.  This class is the
12193323Sed// main driver class that invokes all sub-functionality.
13193323Sed//
14193323Sed//===----------------------------------------------------------------------===//
15193323Sed
16193323Sed#ifndef BUGDRIVER_H
17193323Sed#define BUGDRIVER_H
18193323Sed
19210006Srdivacky#include "llvm/ADT/ValueMap.h"
20218885Sdim#include "llvm/Transforms/Utils/ValueMapper.h"
21249423Sdim#include <string>
22193323Sed#include <vector>
23193323Sed
24193323Sednamespace llvm {
25193323Sed
26193323Sedclass Value;
27193323Sedclass PassInfo;
28193323Sedclass Module;
29193323Sedclass GlobalVariable;
30193323Sedclass Function;
31193323Sedclass BasicBlock;
32193323Sedclass AbstractInterpreter;
33193323Sedclass Instruction;
34195340Sedclass LLVMContext;
35193323Sed
36193323Sedclass DebugCrashes;
37193323Sed
38193323Sedclass GCC;
39193323Sed
40193323Sedextern bool DisableSimplifyCFG;
41193323Sed
42193323Sed/// BugpointIsInterrupted - Set to true when the user presses ctrl-c.
43193323Sed///
44193323Sedextern bool BugpointIsInterrupted;
45193323Sed
46193323Sedclass BugDriver {
47195340Sed  LLVMContext& Context;
48198090Srdivacky  const char *ToolName;            // argv[0] of bugpoint
49193323Sed  std::string ReferenceOutputFile; // Name of `good' output file
50193323Sed  Module *Program;             // The raw program, linked together
51212793Sdim  std::vector<std::string> PassesToRun;
52193323Sed  AbstractInterpreter *Interpreter;   // How to run the program
53193323Sed  AbstractInterpreter *SafeInterpreter;  // To generate reference output, etc.
54193323Sed  GCC *gcc;
55193323Sed  bool run_find_bugs;
56193323Sed  unsigned Timeout;
57193323Sed  unsigned MemoryLimit;
58205407Srdivacky  bool UseValgrind;
59193323Sed
60193323Sed  // FIXME: sort out public/private distinctions...
61193323Sed  friend class ReducePassList;
62193323Sed  friend class ReduceMisCodegenFunctions;
63193323Sed
64193323Sedpublic:
65212793Sdim  BugDriver(const char *toolname, bool find_bugs,
66205407Srdivacky            unsigned timeout, unsigned memlimit, bool use_valgrind,
67205407Srdivacky            LLVMContext& ctxt);
68206083Srdivacky  ~BugDriver();
69193323Sed
70198090Srdivacky  const char *getToolName() const { return ToolName; }
71193323Sed
72212793Sdim  LLVMContext& getContext() const { return Context; }
73195340Sed
74193323Sed  // Set up methods... these methods are used to copy information about the
75193323Sed  // command line arguments into instance variables of BugDriver.
76193323Sed  //
77193323Sed  bool addSources(const std::vector<std::string> &FileNames);
78212793Sdim  void addPass(std::string p) { PassesToRun.push_back(p); }
79212793Sdim  void setPassesToRun(const std::vector<std::string> &PTR) {
80193323Sed    PassesToRun = PTR;
81193323Sed  }
82212793Sdim  const std::vector<std::string> &getPassesToRun() const {
83193323Sed    return PassesToRun;
84193323Sed  }
85193323Sed
86193323Sed  /// run - The top level method that is invoked after all of the instance
87193323Sed  /// variables are set up from command line arguments. The \p as_child argument
88193323Sed  /// indicates whether the driver is to run in parent mode or child mode.
89193323Sed  ///
90207618Srdivacky  bool run(std::string &ErrMsg);
91193323Sed
92193323Sed  /// debugOptimizerCrash - This method is called when some optimizer pass
93193323Sed  /// crashes on input.  It attempts to prune down the testcase to something
94193323Sed  /// reasonable, and figure out exactly which pass is crashing.
95193323Sed  ///
96193323Sed  bool debugOptimizerCrash(const std::string &ID = "passes");
97193323Sed
98193323Sed  /// debugCodeGeneratorCrash - This method is called when the code generator
99193323Sed  /// crashes on an input.  It attempts to reduce the input as much as possible
100193323Sed  /// while still causing the code generator to crash.
101207618Srdivacky  bool debugCodeGeneratorCrash(std::string &Error);
102193323Sed
103193323Sed  /// debugMiscompilation - This method is used when the passes selected are not
104193323Sed  /// crashing, but the generated output is semantically different from the
105193323Sed  /// input.
106207618Srdivacky  void debugMiscompilation(std::string *Error);
107193323Sed
108193323Sed  /// debugPassMiscompilation - This method is called when the specified pass
109193323Sed  /// miscompiles Program as input.  It tries to reduce the testcase to
110193323Sed  /// something that smaller that still miscompiles the program.
111193323Sed  /// ReferenceOutput contains the filename of the file containing the output we
112193323Sed  /// are to match.
113193323Sed  ///
114193323Sed  bool debugPassMiscompilation(const PassInfo *ThePass,
115193323Sed                               const std::string &ReferenceOutput);
116193323Sed
117193323Sed  /// compileSharedObject - This method creates a SharedObject from a given
118193323Sed  /// BitcodeFile for debugging a code generator.
119193323Sed  ///
120207618Srdivacky  std::string compileSharedObject(const std::string &BitcodeFile,
121207618Srdivacky                                  std::string &Error);
122193323Sed
123193323Sed  /// debugCodeGenerator - This method narrows down a module to a function or
124193323Sed  /// set of functions, using the CBE as a ``safe'' code generator for other
125193323Sed  /// functions that are not under consideration.
126207618Srdivacky  bool debugCodeGenerator(std::string *Error);
127193323Sed
128193323Sed  /// isExecutingJIT - Returns true if bugpoint is currently testing the JIT
129193323Sed  ///
130193323Sed  bool isExecutingJIT();
131193323Sed
132193323Sed  /// runPasses - Run all of the passes in the "PassesToRun" list, discard the
133193323Sed  /// output, and return true if any of the passes crashed.
134212793Sdim  bool runPasses(Module *M) const {
135212793Sdim    return runPasses(M, PassesToRun);
136193323Sed  }
137193323Sed
138193323Sed  Module *getProgram() const { return Program; }
139193323Sed
140193323Sed  /// swapProgramIn - Set the current module to the specified module, returning
141193323Sed  /// the old one.
142193323Sed  Module *swapProgramIn(Module *M) {
143193323Sed    Module *OldProgram = Program;
144193323Sed    Program = M;
145193323Sed    return OldProgram;
146193323Sed  }
147193323Sed
148193323Sed  AbstractInterpreter *switchToSafeInterpreter() {
149193323Sed    AbstractInterpreter *Old = Interpreter;
150193323Sed    Interpreter = (AbstractInterpreter*)SafeInterpreter;
151193323Sed    return Old;
152193323Sed  }
153193323Sed
154193323Sed  void switchToInterpreter(AbstractInterpreter *AI) {
155193323Sed    Interpreter = AI;
156193323Sed  }
157193323Sed
158193323Sed  /// setNewProgram - If we reduce or update the program somehow, call this
159193323Sed  /// method to update bugdriver with it.  This deletes the old module and sets
160193323Sed  /// the specified one as the current program.
161193323Sed  void setNewProgram(Module *M);
162193323Sed
163207618Srdivacky  /// compileProgram - Try to compile the specified module, returning false and
164207618Srdivacky  /// setting Error if an error occurs.  This is used for code generation
165207618Srdivacky  /// crash testing.
166193323Sed  ///
167212793Sdim  void compileProgram(Module *M, std::string *Error) const;
168193323Sed
169193323Sed  /// executeProgram - This method runs "Program", capturing the output of the
170207618Srdivacky  /// program to a file.  A recommended filename may be optionally specified.
171193323Sed  ///
172212793Sdim  std::string executeProgram(const Module *Program,
173212793Sdim                             std::string OutputFilename,
174207618Srdivacky                             std::string Bitcode,
175207618Srdivacky                             const std::string &SharedObjects,
176207618Srdivacky                             AbstractInterpreter *AI,
177212793Sdim                             std::string *Error) const;
178193323Sed
179193323Sed  /// executeProgramSafely - Used to create reference output with the "safe"
180193323Sed  /// backend, if reference output is not provided.  If there is a problem with
181207618Srdivacky  /// the code generator (e.g., llc crashes), this will return false and set
182207618Srdivacky  /// Error.
183193323Sed  ///
184212793Sdim  std::string executeProgramSafely(const Module *Program,
185212793Sdim                                   std::string OutputFile,
186212793Sdim                                   std::string *Error) const;
187193323Sed
188193323Sed  /// createReferenceFile - calls compileProgram and then records the output
189193323Sed  /// into ReferenceOutputFile. Returns true if reference file created, false
190193323Sed  /// otherwise. Note: initializeExecutionEnvironment should be called BEFORE
191193323Sed  /// this function.
192193323Sed  ///
193193323Sed  bool createReferenceFile(Module *M, const std::string &Filename
194263508Sdim                                            = "bugpoint.reference.out-%%%%%%%");
195193323Sed
196193323Sed  /// diffProgram - This method executes the specified module and diffs the
197193323Sed  /// output against the file specified by ReferenceOutputFile.  If the output
198207618Srdivacky  /// is different, 1 is returned.  If there is a problem with the code
199207618Srdivacky  /// generator (e.g., llc crashes), this will return -1 and set Error.
200193323Sed  ///
201212793Sdim  bool diffProgram(const Module *Program,
202212793Sdim                   const std::string &BitcodeFile = "",
203193323Sed                   const std::string &SharedObj = "",
204207618Srdivacky                   bool RemoveBitcode = false,
205212793Sdim                   std::string *Error = 0) const;
206207618Srdivacky
207212793Sdim  /// EmitProgressBitcode - This function is used to output M to a file named
208212793Sdim  /// "bugpoint-ID.bc".
209193323Sed  ///
210212793Sdim  void EmitProgressBitcode(const Module *M, const std::string &ID,
211212793Sdim                           bool NoFlyer = false) const;
212193323Sed
213193323Sed  /// deleteInstructionFromProgram - This method clones the current Program and
214193323Sed  /// deletes the specified instruction from the cloned module.  It then runs a
215193323Sed  /// series of cleanup passes (ADCE and SimplifyCFG) to eliminate any code
216193323Sed  /// which depends on the value.  The modified module is then returned.
217193323Sed  ///
218212793Sdim  Module *deleteInstructionFromProgram(const Instruction *I, unsigned Simp);
219193323Sed
220193323Sed  /// performFinalCleanups - This method clones the current Program and performs
221193323Sed  /// a series of cleanups intended to get rid of extra cruft on the module.  If
222193323Sed  /// the MayModifySemantics argument is true, then the cleanups is allowed to
223193323Sed  /// modify how the code behaves.
224193323Sed  ///
225193323Sed  Module *performFinalCleanups(Module *M, bool MayModifySemantics = false);
226193323Sed
227193323Sed  /// ExtractLoop - Given a module, extract up to one loop from it into a new
228193323Sed  /// function.  This returns null if there are no extractable loops in the
229193323Sed  /// program or if the loop extractor crashes.
230193323Sed  Module *ExtractLoop(Module *M);
231193323Sed
232193323Sed  /// ExtractMappedBlocksFromModule - Extract all but the specified basic blocks
233193323Sed  /// into their own functions.  The only detail is that M is actually a module
234193323Sed  /// cloned from the one the BBs are in, so some mapping needs to be performed.
235193323Sed  /// If this operation fails for some reason (ie the implementation is buggy),
236193323Sed  /// this function should return null, otherwise it returns a new Module.
237193323Sed  Module *ExtractMappedBlocksFromModule(const std::vector<BasicBlock*> &BBs,
238193323Sed                                        Module *M);
239193323Sed
240193323Sed  /// runPassesOn - Carefully run the specified set of pass on the specified
241193323Sed  /// module, returning the transformed module on success, or a null pointer on
242193323Sed  /// failure.  If AutoDebugCrashes is set to true, then bugpoint will
243193323Sed  /// automatically attempt to track down a crashing pass if one exists, and
244193323Sed  /// this method will never return null.
245212793Sdim  Module *runPassesOn(Module *M, const std::vector<std::string> &Passes,
246193323Sed                      bool AutoDebugCrashes = false, unsigned NumExtraArgs = 0,
247193323Sed                      const char * const *ExtraArgs = NULL);
248193323Sed
249193323Sed  /// runPasses - Run the specified passes on Program, outputting a bitcode
250193323Sed  /// file and writting the filename into OutputFile if successful.  If the
251193323Sed  /// optimizations fail for some reason (optimizer crashes), return true,
252193323Sed  /// otherwise return false.  If DeleteOutput is set to true, the bitcode is
253193323Sed  /// deleted on success, and the filename string is undefined.  This prints to
254198090Srdivacky  /// outs() a single line message indicating whether compilation was successful
255193323Sed  /// or failed, unless Quiet is set.  ExtraArgs specifies additional arguments
256193323Sed  /// to pass to the child bugpoint instance.
257193323Sed  ///
258212793Sdim  bool runPasses(Module *Program,
259212793Sdim                 const std::vector<std::string> &PassesToRun,
260193323Sed                 std::string &OutputFilename, bool DeleteOutput = false,
261193323Sed                 bool Quiet = false, unsigned NumExtraArgs = 0,
262193323Sed                 const char * const *ExtraArgs = NULL) const;
263193323Sed
264193323Sed  /// runManyPasses - Take the specified pass list and create different
265193323Sed  /// combinations of passes to compile the program with. Compile the program with
266193323Sed  /// each set and mark test to see if it compiled correctly. If the passes
267193323Sed  /// compiled correctly output nothing and rearrange the passes into a new order.
268193323Sed  /// If the passes did not compile correctly, output the command required to
269193323Sed  /// recreate the failure. This returns true if a compiler error is found.
270193323Sed  ///
271212793Sdim  bool runManyPasses(const std::vector<std::string> &AllPasses,
272210006Srdivacky                     std::string &ErrMsg);
273193323Sed
274193323Sed  /// writeProgramToFile - This writes the current "Program" to the named
275193323Sed  /// bitcode file.  If an error occurs, true is returned.
276193323Sed  ///
277212793Sdim  bool writeProgramToFile(const std::string &Filename, const Module *M) const;
278263508Sdim  bool writeProgramToFile(const std::string &Filename, int FD,
279263508Sdim                          const Module *M) const;
280193323Sed
281193323Sedprivate:
282193323Sed  /// runPasses - Just like the method above, but this just returns true or
283193323Sed  /// false indicating whether or not the optimizer crashed on the specified
284193323Sed  /// input (true = crashed).
285193323Sed  ///
286212793Sdim  bool runPasses(Module *M,
287212793Sdim                 const std::vector<std::string> &PassesToRun,
288193323Sed                 bool DeleteOutput = true) const {
289193323Sed    std::string Filename;
290212793Sdim    return runPasses(M, PassesToRun, Filename, DeleteOutput);
291193323Sed  }
292193323Sed
293193323Sed  /// initializeExecutionEnvironment - This method is used to set up the
294193323Sed  /// environment for executing LLVM programs.
295193323Sed  ///
296193323Sed  bool initializeExecutionEnvironment();
297193323Sed};
298193323Sed
299193323Sed/// ParseInputFile - Given a bitcode or assembly input filename, parse and
300193323Sed/// return it, or return null if not possible.
301193323Sed///
302195340SedModule *ParseInputFile(const std::string &InputFilename,
303195340Sed                       LLVMContext& ctxt);
304193323Sed
305193323Sed
306193323Sed/// getPassesString - Turn a list of passes into a string which indicates the
307193323Sed/// command line options that must be passed to add the passes.
308193323Sed///
309212793Sdimstd::string getPassesString(const std::vector<std::string> &Passes);
310193323Sed
311193323Sed/// PrintFunctionList - prints out list of problematic functions
312193323Sed///
313193323Sedvoid PrintFunctionList(const std::vector<Function*> &Funcs);
314193323Sed
315193323Sed/// PrintGlobalVariableList - prints out list of problematic global variables
316193323Sed///
317193323Sedvoid PrintGlobalVariableList(const std::vector<GlobalVariable*> &GVs);
318193323Sed
319193323Sed// DeleteFunctionBody - "Remove" the function by deleting all of it's basic
320193323Sed// blocks, making it external.
321193323Sed//
322193323Sedvoid DeleteFunctionBody(Function *F);
323193323Sed
324193323Sed/// SplitFunctionsOutOfModule - Given a module and a list of functions in the
325193323Sed/// module, split the functions OUT of the specified module, and place them in
326193323Sed/// the new module.
327193323SedModule *SplitFunctionsOutOfModule(Module *M, const std::vector<Function*> &F,
328218885Sdim                                  ValueToValueMapTy &VMap);
329193323Sed
330193323Sed} // End llvm namespace
331193323Sed
332193323Sed#endif
333