fd711d99fc31ff4020779f96ed6f67e9be0aa25a
[oota-llvm.git] / tools / bugpoint / CrashDebugger.cpp
1 //===- CrashDebugger.cpp - Debug compilation crashes ----------------------===//
2 //
3 // This file defines the bugpoint internals that narrow down compilation crashes
4 //
5 //===----------------------------------------------------------------------===//
6
7 #include "BugDriver.h"
8 #include "SystemUtils.h"
9 #include "ListReducer.h"
10 #include "llvm/Module.h"
11 #include "llvm/PassManager.h"
12 #include "llvm/Pass.h"
13 #include "llvm/Constant.h"
14 #include "llvm/iTerminators.h"
15 #include "llvm/Type.h"
16 #include "llvm/SymbolTable.h"
17 #include "llvm/Support/CFG.h"
18 #include "llvm/Analysis/Verifier.h"
19 #include "llvm/Transforms/Scalar.h"
20 #include "llvm/Transforms/Utils/Cloning.h"
21 #include "llvm/Bytecode/Writer.h"
22 #include <fstream>
23 #include <set>
24
25 class DebugCrashes : public ListReducer<const PassInfo*> {
26   BugDriver &BD;
27 public:
28   DebugCrashes(BugDriver &bd) : BD(bd) {}
29
30   // doTest - Return true iff running the "removed" passes succeeds, and running
31   // the "Kept" passes fail when run on the output of the "removed" passes.  If
32   // we return true, we update the current module of bugpoint.
33   //
34   virtual TestResult doTest(std::vector<const PassInfo*> &Removed,
35                             std::vector<const PassInfo*> &Kept);
36 };
37
38 DebugCrashes::TestResult
39 DebugCrashes::doTest(std::vector<const PassInfo*> &Prefix,
40                      std::vector<const PassInfo*> &Suffix) {
41   std::string PrefixOutput;
42   if (!Prefix.empty()) {
43     std::cout << "Checking to see if these passes crash: "
44               << getPassesString(Prefix) << ": ";
45     if (BD.runPasses(Prefix, PrefixOutput))
46       return KeepPrefix;
47   }
48
49   std::cout << "Checking to see if these passes crash: "
50             << getPassesString(Suffix) << ": ";
51   Module *OrigProgram = BD.Program;
52   BD.Program = BD.ParseInputFile(PrefixOutput);
53   if (BD.Program == 0) {
54     std::cerr << BD.getToolName() << ": Error reading bytecode file '"
55               << PrefixOutput << "'!\n";
56     exit(1);
57   }
58   removeFile(PrefixOutput);
59
60   if (BD.runPasses(Suffix)) {
61     delete OrigProgram;            // The suffix crashes alone...
62     return KeepSuffix;
63   }
64
65   // Nothing failed, restore state...
66   delete BD.Program;
67   BD.Program = OrigProgram;
68   return NoFailure;
69 }
70
71 class ReduceCrashingFunctions : public ListReducer<Function*> {
72   BugDriver &BD;
73 public:
74   ReduceCrashingFunctions(BugDriver &bd) : BD(bd) {}
75
76   virtual TestResult doTest(std::vector<Function*> &Prefix,
77                             std::vector<Function*> &Kept) {
78     if (TestFuncs(Kept))
79       return KeepSuffix;
80     if (!Prefix.empty() && TestFuncs(Prefix))
81       return KeepPrefix;
82     return NoFailure;
83   }
84   
85   bool TestFuncs(std::vector<Function*> &Prefix);
86 };
87
88 bool ReduceCrashingFunctions::TestFuncs(std::vector<Function*> &Funcs) {
89   // Clone the program to try hacking it appart...
90   Module *M = CloneModule(BD.Program);
91   
92   // Convert list to set for fast lookup...
93   std::set<Function*> Functions;
94   for (unsigned i = 0, e = Funcs.size(); i != e; ++i) {
95     Function *CMF = M->getFunction(Funcs[i]->getName(), 
96                                    Funcs[i]->getFunctionType());
97     assert(CMF && "Function not in module?!");
98     Functions.insert(CMF);
99   }
100
101   std::cout << "Checking for crash with only these functions:";
102   for (unsigned i = 0, e = Funcs.size(); i != e; ++i)
103     std::cout << " " << Funcs[i]->getName();
104   std::cout << ": ";
105
106   // Loop over and delete any functions which we aren't supposed to be playing
107   // with...
108   for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
109     if (!I->isExternal() && !Functions.count(I))
110       DeleteFunctionBody(I);
111
112   // Try running the hacked up program...
113   std::swap(BD.Program, M);
114   if (BD.runPasses(BD.PassesToRun)) {
115     delete M;         // It crashed, keep the trimmed version...
116
117     // Make sure to use function pointers that point into the now-current
118     // module.
119     Funcs.assign(Functions.begin(), Functions.end());
120     return true;
121   }
122   delete BD.Program;  // It didn't crash, revert...
123   BD.Program = M;
124   return false;
125 }
126
127
128 /// ReduceCrashingBlocks reducer - This works by setting the terminators of all
129 /// terminators except the specified basic blocks to a 'ret' instruction, then
130 /// running the simplify-cfg pass.  This has the effect of chopping up the CFG
131 /// really fast which can reduce large functions quickly.
132 ///
133 class ReduceCrashingBlocks : public ListReducer<BasicBlock*> {
134   BugDriver &BD;
135 public:
136   ReduceCrashingBlocks(BugDriver &bd) : BD(bd) {}
137     
138   virtual TestResult doTest(std::vector<BasicBlock*> &Prefix,
139                             std::vector<BasicBlock*> &Kept) {
140     if (TestBlocks(Kept))
141       return KeepSuffix;
142     if (!Prefix.empty() && TestBlocks(Prefix))
143       return KeepPrefix;
144     return NoFailure;
145   }
146     
147   bool TestBlocks(std::vector<BasicBlock*> &Prefix);
148 };
149
150 bool ReduceCrashingBlocks::TestBlocks(std::vector<BasicBlock*> &BBs) {
151   // Clone the program to try hacking it appart...
152   Module *M = CloneModule(BD.Program);
153   
154   // Convert list to set for fast lookup...
155   std::set<BasicBlock*> Blocks;
156   for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
157     // Convert the basic block from the original module to the new module...
158     Function *F = BBs[i]->getParent();
159     Function *CMF = M->getFunction(F->getName(), F->getFunctionType());
160     assert(CMF && "Function not in module?!");
161
162     // Get the mapped basic block...
163     Function::iterator CBI = CMF->begin();
164     std::advance(CBI, std::distance(F->begin(), Function::iterator(BBs[i])));
165     Blocks.insert(CBI);
166   }
167
168   std::cout << "Checking for crash with only these blocks:";
169   for (unsigned i = 0, e = Blocks.size(); i != e; ++i)
170     std::cout << " " << BBs[i]->getName();
171   std::cout << ": ";
172
173   // Loop over and delete any hack up any blocks that are not listed...
174   for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
175     for (Function::iterator BB = I->begin(), E = I->end(); BB != E; ++BB)
176       if (!Blocks.count(BB) && !isa<ReturnInst>(BB->getTerminator())) {
177         // Loop over all of the successors of this block, deleting any PHI nodes
178         // that might include it.
179         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
180           (*SI)->removePredecessor(BB);
181
182         // Delete the old terminator instruction...
183         BB->getInstList().pop_back();
184         
185         // Add a new return instruction of the appropriate type...
186         const Type *RetTy = BB->getParent()->getReturnType();
187         ReturnInst *RI = new ReturnInst(RetTy == Type::VoidTy ? 0 :
188                                         Constant::getNullValue(RetTy));
189         BB->getInstList().push_back(RI);
190       }
191
192   // The CFG Simplifier pass may delete one of the basic blocks we are
193   // interested in.  If it does we need to take the block out of the list.  Make
194   // a "persistent mapping" by turning basic blocks into <function, name> pairs.
195   // This won't work well if blocks are unnamed, but that is just the risk we
196   // have to take.
197   std::vector<std::pair<Function*, std::string> > BlockInfo;
198
199   for (std::set<BasicBlock*>::iterator I = Blocks.begin(), E = Blocks.end();
200        I != E; ++I)
201     BlockInfo.push_back(std::make_pair((*I)->getParent(), (*I)->getName()));
202
203   // Now run the CFG simplify pass on the function...
204   PassManager Passes;
205   Passes.add(createCFGSimplificationPass());
206   Passes.add(createVerifierPass());
207   Passes.run(*M);
208
209   // Try running on the hacked up program...
210   std::swap(BD.Program, M);
211   if (BD.runPasses(BD.PassesToRun)) {
212     delete M;         // It crashed, keep the trimmed version...
213
214     // Make sure to use basic block pointers that point into the now-current
215     // module, and that they don't include any deleted blocks.
216     BBs.clear();
217     for (unsigned i = 0, e = BlockInfo.size(); i != e; ++i) {
218       SymbolTable &ST = BlockInfo[i].first->getSymbolTable();
219       SymbolTable::iterator I = ST.find(Type::LabelTy);
220       if (I != ST.end() && I->second.count(BlockInfo[i].second))
221         BBs.push_back(cast<BasicBlock>(I->second[BlockInfo[i].second]));
222     }
223     return true;
224   }
225   delete BD.Program;  // It didn't crash, revert...
226   BD.Program = M;
227   return false;
228 }
229
230 /// debugCrash - This method is called when some pass crashes on input.  It
231 /// attempts to prune down the testcase to something reasonable, and figure
232 /// out exactly which pass is crashing.
233 ///
234 bool BugDriver::debugCrash() {
235   bool AnyReduction = false;
236   std::cout << "\n*** Debugging optimizer crash!\n";
237
238   // Reduce the list of passes which causes the optimizer to crash...
239   unsigned OldSize = PassesToRun.size();
240   DebugCrashes(*this).reduceList(PassesToRun);
241
242   std::cout << "\n*** Found crashing pass"
243             << (PassesToRun.size() == 1 ? ": " : "es: ")
244             << getPassesString(PassesToRun) << "\n";
245
246   EmitProgressBytecode("passinput");
247
248   // See if we can get away with nuking all of the global variable initializers
249   // in the program...
250   if (Program->gbegin() != Program->gend()) {
251     Module *M = CloneModule(Program);
252     bool DeletedInit = false;
253     for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
254       if (I->hasInitializer()) {
255         I->setInitializer(0);
256         I->setLinkage(GlobalValue::ExternalLinkage);
257         DeletedInit = true;
258       }
259     
260     if (!DeletedInit) {
261       delete M;  // No change made...
262     } else {
263       // See if the program still causes a crash...
264       std::cout << "\nChecking to see if we can delete global inits: ";
265       std::swap(Program, M);
266       if (runPasses(PassesToRun)) {  // Still crashes?
267         AnyReduction = true;
268         delete M;
269         std::cout << "\n*** Able to remove all global initializers!\n";
270       } else {                       // No longer crashes?
271         delete Program;              // Restore program.
272         Program = M;
273         std::cout << "  - Removing all global inits hides problem!\n";
274       }
275     }
276   }
277   
278   // Now try to reduce the number of functions in the module to something small.
279   std::vector<Function*> Functions;
280   for (Module::iterator I = Program->begin(), E = Program->end(); I != E; ++I)
281     if (!I->isExternal())
282       Functions.push_back(I);
283
284   if (Functions.size() > 1) {
285     std::cout << "\n*** Attempting to reduce the number of functions "
286       "in the testcase\n";
287
288     OldSize = Functions.size();
289     ReduceCrashingFunctions(*this).reduceList(Functions);
290
291     if (Functions.size() < OldSize) {
292       EmitProgressBytecode("reduced-function");
293       AnyReduction = true;
294     }
295   }
296
297   // Attempt to delete entire basic blocks at a time to speed up
298   // convergence... this actually works by setting the terminator of the blocks
299   // to a return instruction then running simplifycfg, which can potentially
300   // shrinks the code dramatically quickly
301   //
302   std::vector<BasicBlock*> Blocks;
303   for (Module::iterator I = Program->begin(), E = Program->end(); I != E; ++I)
304     for (Function::iterator FI = I->begin(), E = I->end(); FI != E; ++FI)
305       Blocks.push_back(FI);
306   ReduceCrashingBlocks(*this).reduceList(Blocks);
307
308   // FIXME: This should use the list reducer to converge faster by deleting
309   // larger chunks of instructions at a time!
310   unsigned Simplification = 4;
311   do {
312     --Simplification;
313     std::cout << "\n*** Attempting to reduce testcase by deleting instruc"
314               << "tions: Simplification Level #" << Simplification << "\n";
315
316     // Now that we have deleted the functions that are unneccesary for the
317     // program, try to remove instructions that are not neccesary to cause the
318     // crash.  To do this, we loop through all of the instructions in the
319     // remaining functions, deleting them (replacing any values produced with
320     // nulls), and then running ADCE and SimplifyCFG.  If the transformed input
321     // still triggers failure, keep deleting until we cannot trigger failure
322     // anymore.
323     //
324   TryAgain:
325     
326     // Loop over all of the (non-terminator) instructions remaining in the
327     // function, attempting to delete them.
328     for (Module::iterator FI = Program->begin(), E = Program->end();
329          FI != E; ++FI)
330       if (!FI->isExternal()) {
331         for (Function::iterator BI = FI->begin(), E = FI->end(); BI != E; ++BI)
332           for (BasicBlock::iterator I = BI->begin(), E = --BI->end();
333                I != E; ++I) {
334             Module *M = deleteInstructionFromProgram(I, Simplification);
335             
336             // Make the function the current program...
337             std::swap(Program, M);
338             
339             // Find out if the pass still crashes on this pass...
340             std::cout << "Checking instruction '" << I->getName() << "': ";
341             if (runPasses(PassesToRun)) {
342               // Yup, it does, we delete the old module, and continue trying to
343               // reduce the testcase...
344               delete M;
345               AnyReduction = true;
346               goto TryAgain;  // I wish I had a multi-level break here!
347             }
348             
349             // This pass didn't crash without this instruction, try the next
350             // one.
351             delete Program;
352             Program = M;
353           }
354       }
355   } while (Simplification);
356
357   // Try to clean up the testcase by running funcresolve and globaldce...
358   if (AnyReduction) {
359     std::cout << "\n*** Attempting to perform final cleanups: ";
360     Module *M = performFinalCleanups();
361     std::swap(Program, M);
362             
363     // Find out if the pass still crashes on the cleaned up program...
364     if (runPasses(PassesToRun)) {
365       // Yup, it does, keep the reduced version...
366       delete M;
367       AnyReduction = true;
368     } else {
369       delete Program;   // Otherwise, restore the original module...
370       Program = M;
371     }
372   }
373
374   if (AnyReduction)
375     EmitProgressBytecode("reduced-simplified");
376
377   return false;
378 }