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