1 //===- CrashDebugger.cpp - Debug compilation crashes ----------------------===//
3 // This file defines the bugpoint internals that narrow down compilation crashes
5 //===----------------------------------------------------------------------===//
8 #include "ListReducer.h"
9 #include "llvm/Constant.h"
10 #include "llvm/iTerminators.h"
11 #include "llvm/Module.h"
12 #include "llvm/Pass.h"
13 #include "llvm/PassManager.h"
14 #include "llvm/SymbolTable.h"
15 #include "llvm/Type.h"
16 #include "llvm/Analysis/Verifier.h"
17 #include "llvm/Bytecode/Writer.h"
18 #include "llvm/Support/CFG.h"
19 #include "llvm/Transforms/Scalar.h"
20 #include "llvm/Transforms/Utils/Cloning.h"
21 #include "Support/FileUtilities.h"
25 class DebugCrashes : public ListReducer<const PassInfo*> {
28 DebugCrashes(BugDriver &bd) : BD(bd) {}
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.
34 virtual TestResult doTest(std::vector<const PassInfo*> &Removed,
35 std::vector<const PassInfo*> &Kept);
38 DebugCrashes::TestResult
39 DebugCrashes::doTest(std::vector<const PassInfo*> &Prefix,
40 std::vector<const PassInfo*> &Suffix) {
41 std::string PrefixOutput;
42 Module *OrigProgram = 0;
43 if (!Prefix.empty()) {
44 std::cout << "Checking to see if these passes crash: "
45 << getPassesString(Prefix) << ": ";
46 if (BD.runPasses(Prefix, PrefixOutput))
49 OrigProgram = BD.Program;
51 BD.Program = BD.ParseInputFile(PrefixOutput);
52 if (BD.Program == 0) {
53 std::cerr << BD.getToolName() << ": Error reading bytecode file '"
54 << PrefixOutput << "'!\n";
57 removeFile(PrefixOutput);
60 std::cout << "Checking to see if these passes crash: "
61 << getPassesString(Suffix) << ": ";
63 if (BD.runPasses(Suffix)) {
64 delete OrigProgram; // The suffix crashes alone...
68 // Nothing failed, restore state...
71 BD.Program = OrigProgram;
76 class ReduceCrashingFunctions : public ListReducer<Function*> {
79 ReduceCrashingFunctions(BugDriver &bd) : BD(bd) {}
81 virtual TestResult doTest(std::vector<Function*> &Prefix,
82 std::vector<Function*> &Kept) {
83 if (!Kept.empty() && TestFuncs(Kept))
85 if (!Prefix.empty() && TestFuncs(Prefix))
90 bool TestFuncs(std::vector<Function*> &Prefix);
93 bool ReduceCrashingFunctions::TestFuncs(std::vector<Function*> &Funcs) {
94 // Clone the program to try hacking it appart...
95 Module *M = CloneModule(BD.Program);
97 // Convert list to set for fast lookup...
98 std::set<Function*> Functions;
99 for (unsigned i = 0, e = Funcs.size(); i != e; ++i) {
100 Function *CMF = M->getFunction(Funcs[i]->getName(),
101 Funcs[i]->getFunctionType());
102 assert(CMF && "Function not in module?!");
103 Functions.insert(CMF);
106 std::cout << "Checking for crash with only these functions:";
107 for (unsigned i = 0, e = Funcs.size(); i != e; ++i)
108 std::cout << " " << Funcs[i]->getName();
111 // Loop over and delete any functions which we aren't supposed to be playing
113 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
114 if (!I->isExternal() && !Functions.count(I))
115 DeleteFunctionBody(I);
117 // Try running the hacked up program...
118 std::swap(BD.Program, M);
119 if (BD.runPasses(BD.PassesToRun)) {
120 delete M; // It crashed, keep the trimmed version...
122 // Make sure to use function pointers that point into the now-current
124 Funcs.assign(Functions.begin(), Functions.end());
127 delete BD.Program; // It didn't crash, revert...
133 /// ReduceCrashingBlocks reducer - This works by setting the terminators of all
134 /// terminators except the specified basic blocks to a 'ret' instruction, then
135 /// running the simplify-cfg pass. This has the effect of chopping up the CFG
136 /// really fast which can reduce large functions quickly.
138 class ReduceCrashingBlocks : public ListReducer<BasicBlock*> {
141 ReduceCrashingBlocks(BugDriver &bd) : BD(bd) {}
143 virtual TestResult doTest(std::vector<BasicBlock*> &Prefix,
144 std::vector<BasicBlock*> &Kept) {
145 if (!Kept.empty() && TestBlocks(Kept))
147 if (!Prefix.empty() && TestBlocks(Prefix))
152 bool TestBlocks(std::vector<BasicBlock*> &Prefix);
155 bool ReduceCrashingBlocks::TestBlocks(std::vector<BasicBlock*> &BBs) {
156 // Clone the program to try hacking it appart...
157 Module *M = CloneModule(BD.Program);
159 // Convert list to set for fast lookup...
160 std::set<BasicBlock*> Blocks;
161 for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
162 // Convert the basic block from the original module to the new module...
163 Function *F = BBs[i]->getParent();
164 Function *CMF = M->getFunction(F->getName(), F->getFunctionType());
165 assert(CMF && "Function not in module?!");
167 // Get the mapped basic block...
168 Function::iterator CBI = CMF->begin();
169 std::advance(CBI, std::distance(F->begin(), Function::iterator(BBs[i])));
173 std::cout << "Checking for crash with only these blocks:";
174 for (unsigned i = 0, e = Blocks.size(); i != e; ++i)
175 std::cout << " " << BBs[i]->getName();
178 // Loop over and delete any hack up any blocks that are not listed...
179 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
180 for (Function::iterator BB = I->begin(), E = I->end(); BB != E; ++BB)
181 if (!Blocks.count(BB) && !isa<ReturnInst>(BB->getTerminator())) {
182 // Loop over all of the successors of this block, deleting any PHI nodes
183 // that might include it.
184 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
185 (*SI)->removePredecessor(BB);
187 // Delete the old terminator instruction...
188 BB->getInstList().pop_back();
190 // Add a new return instruction of the appropriate type...
191 const Type *RetTy = BB->getParent()->getReturnType();
192 ReturnInst *RI = new ReturnInst(RetTy == Type::VoidTy ? 0 :
193 Constant::getNullValue(RetTy));
194 BB->getInstList().push_back(RI);
197 // The CFG Simplifier pass may delete one of the basic blocks we are
198 // interested in. If it does we need to take the block out of the list. Make
199 // a "persistent mapping" by turning basic blocks into <function, name> pairs.
200 // This won't work well if blocks are unnamed, but that is just the risk we
202 std::vector<std::pair<Function*, std::string> > BlockInfo;
204 for (std::set<BasicBlock*>::iterator I = Blocks.begin(), E = Blocks.end();
206 BlockInfo.push_back(std::make_pair((*I)->getParent(), (*I)->getName()));
208 // Now run the CFG simplify pass on the function...
210 Passes.add(createCFGSimplificationPass());
211 Passes.add(createVerifierPass());
214 // Try running on the hacked up program...
215 std::swap(BD.Program, M);
216 if (BD.runPasses(BD.PassesToRun)) {
217 delete M; // It crashed, keep the trimmed version...
219 // Make sure to use basic block pointers that point into the now-current
220 // module, and that they don't include any deleted blocks.
222 for (unsigned i = 0, e = BlockInfo.size(); i != e; ++i) {
223 SymbolTable &ST = BlockInfo[i].first->getSymbolTable();
224 SymbolTable::iterator I = ST.find(Type::LabelTy);
225 if (I != ST.end() && I->second.count(BlockInfo[i].second))
226 BBs.push_back(cast<BasicBlock>(I->second[BlockInfo[i].second]));
230 delete BD.Program; // It didn't crash, revert...
235 /// debugCrash - This method is called when some pass crashes on input. It
236 /// attempts to prune down the testcase to something reasonable, and figure
237 /// out exactly which pass is crashing.
239 bool BugDriver::debugCrash() {
240 bool AnyReduction = false;
241 std::cout << "\n*** Debugging optimizer crash!\n";
243 // Reduce the list of passes which causes the optimizer to crash...
244 unsigned OldSize = PassesToRun.size();
245 DebugCrashes(*this).reduceList(PassesToRun);
247 std::cout << "\n*** Found crashing pass"
248 << (PassesToRun.size() == 1 ? ": " : "es: ")
249 << getPassesString(PassesToRun) << "\n";
251 EmitProgressBytecode("passinput");
253 // See if we can get away with nuking all of the global variable initializers
255 if (Program->gbegin() != Program->gend()) {
256 Module *M = CloneModule(Program);
257 bool DeletedInit = false;
258 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
259 if (I->hasInitializer()) {
260 I->setInitializer(0);
261 I->setLinkage(GlobalValue::ExternalLinkage);
266 delete M; // No change made...
268 // See if the program still causes a crash...
269 std::cout << "\nChecking to see if we can delete global inits: ";
270 std::swap(Program, M);
271 if (runPasses(PassesToRun)) { // Still crashes?
274 std::cout << "\n*** Able to remove all global initializers!\n";
275 } else { // No longer crashes?
276 delete Program; // Restore program.
278 std::cout << " - Removing all global inits hides problem!\n";
283 // Now try to reduce the number of functions in the module to something small.
284 std::vector<Function*> Functions;
285 for (Module::iterator I = Program->begin(), E = Program->end(); I != E; ++I)
286 if (!I->isExternal())
287 Functions.push_back(I);
289 if (Functions.size() > 1) {
290 std::cout << "\n*** Attempting to reduce the number of functions "
293 OldSize = Functions.size();
294 ReduceCrashingFunctions(*this).reduceList(Functions);
296 if (Functions.size() < OldSize) {
297 EmitProgressBytecode("reduced-function");
302 // Attempt to delete entire basic blocks at a time to speed up
303 // convergence... this actually works by setting the terminator of the blocks
304 // to a return instruction then running simplifycfg, which can potentially
305 // shrinks the code dramatically quickly
307 if (!DisableSimplifyCFG) {
308 std::vector<BasicBlock*> Blocks;
309 for (Module::iterator I = Program->begin(), E = Program->end(); I != E; ++I)
310 for (Function::iterator FI = I->begin(), E = I->end(); FI != E; ++FI)
311 Blocks.push_back(FI);
312 ReduceCrashingBlocks(*this).reduceList(Blocks);
315 // FIXME: This should use the list reducer to converge faster by deleting
316 // larger chunks of instructions at a time!
317 unsigned Simplification = 4;
320 std::cout << "\n*** Attempting to reduce testcase by deleting instruc"
321 << "tions: Simplification Level #" << Simplification << "\n";
323 // Now that we have deleted the functions that are unnecessary for the
324 // program, try to remove instructions that are not necessary to cause the
325 // crash. To do this, we loop through all of the instructions in the
326 // remaining functions, deleting them (replacing any values produced with
327 // nulls), and then running ADCE and SimplifyCFG. If the transformed input
328 // still triggers failure, keep deleting until we cannot trigger failure
333 // Loop over all of the (non-terminator) instructions remaining in the
334 // function, attempting to delete them.
335 for (Module::iterator FI = Program->begin(), E = Program->end();
337 if (!FI->isExternal()) {
338 for (Function::iterator BI = FI->begin(), E = FI->end(); BI != E; ++BI)
339 for (BasicBlock::iterator I = BI->begin(), E = --BI->end();
341 Module *M = deleteInstructionFromProgram(I, Simplification);
343 // Make the function the current program...
344 std::swap(Program, M);
346 // Find out if the pass still crashes on this pass...
347 std::cout << "Checking instruction '" << I->getName() << "': ";
348 if (runPasses(PassesToRun)) {
349 // Yup, it does, we delete the old module, and continue trying to
350 // reduce the testcase...
353 goto TryAgain; // I wish I had a multi-level break here!
356 // This pass didn't crash without this instruction, try the next
362 } while (Simplification);
364 // Try to clean up the testcase by running funcresolve and globaldce...
365 std::cout << "\n*** Attempting to perform final cleanups: ";
366 Module *M = performFinalCleanups();
367 std::swap(Program, M);
369 // Find out if the pass still crashes on the cleaned up program...
370 if (runPasses(PassesToRun)) {
371 // Yup, it does, keep the reduced version...
375 delete Program; // Otherwise, restore the original module...
380 EmitProgressBytecode("reduced-simplified");