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