1 //===- CrashDebugger.cpp - Debug compilation crashes ----------------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This file defines the bugpoint internals that narrow down compilation crashes
12 //===----------------------------------------------------------------------===//
14 #include "BugDriver.h"
15 #include "ToolRunner.h"
16 #include "ListReducer.h"
17 #include "llvm/Constant.h"
18 #include "llvm/Instructions.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 "llvm/Support/FileUtilities.h"
30 #include "llvm/Support/CommandLine.h"
38 cl::desc("Force function reduction to keep main"),
43 class ReducePassList : public ListReducer<const PassInfo*> {
46 ReducePassList(BugDriver &bd) : BD(bd) {}
48 // doTest - Return true iff running the "removed" passes succeeds, and
49 // running the "Kept" passes fail when run on the output of the "removed"
50 // passes. If we return true, we update the current module of bugpoint.
52 virtual TestResult doTest(std::vector<const PassInfo*> &Removed,
53 std::vector<const PassInfo*> &Kept);
57 ReducePassList::TestResult
58 ReducePassList::doTest(std::vector<const PassInfo*> &Prefix,
59 std::vector<const PassInfo*> &Suffix) {
60 sys::Path PrefixOutput;
61 Module *OrigProgram = 0;
62 if (!Prefix.empty()) {
63 std::cout << "Checking to see if these passes crash: "
64 << getPassesString(Prefix) << ": ";
65 std::string PfxOutput;
66 if (BD.runPasses(Prefix, PfxOutput))
69 PrefixOutput.set(PfxOutput);
70 OrigProgram = BD.Program;
72 BD.Program = ParseInputFile(PrefixOutput.toString());
73 if (BD.Program == 0) {
74 std::cerr << BD.getToolName() << ": Error reading bytecode file '"
75 << PrefixOutput << "'!\n";
78 PrefixOutput.eraseFromDisk();
81 std::cout << "Checking to see if these passes crash: "
82 << getPassesString(Suffix) << ": ";
84 if (BD.runPasses(Suffix)) {
85 delete OrigProgram; // The suffix crashes alone...
89 // Nothing failed, restore state...
92 BD.Program = OrigProgram;
98 class ReduceCrashingFunctions : public ListReducer<Function*> {
100 bool (*TestFn)(BugDriver &, Module *);
102 ReduceCrashingFunctions(BugDriver &bd,
103 bool (*testFn)(BugDriver &, Module *))
104 : BD(bd), TestFn(testFn) {}
106 virtual TestResult doTest(std::vector<Function*> &Prefix,
107 std::vector<Function*> &Kept) {
108 if (!Kept.empty() && TestFuncs(Kept))
110 if (!Prefix.empty() && TestFuncs(Prefix))
115 bool TestFuncs(std::vector<Function*> &Prefix);
119 bool ReduceCrashingFunctions::TestFuncs(std::vector<Function*> &Funcs) {
121 //if main isn't present, claim there is no problem
122 if (KeepMain && find(Funcs.begin(), Funcs.end(), BD.getProgram()->getMainFunction()) == Funcs.end())
125 // Clone the program to try hacking it apart...
126 Module *M = CloneModule(BD.getProgram());
128 // Convert list to set for fast lookup...
129 std::set<Function*> Functions;
130 for (unsigned i = 0, e = Funcs.size(); i != e; ++i) {
131 // FIXME: bugpoint should add names to all stripped symbols.
132 assert(!Funcs[i]->getName().empty() &&
133 "Bugpoint doesn't work on stripped modules yet PR718!");
134 Function *CMF = M->getFunction(Funcs[i]->getName(),
135 Funcs[i]->getFunctionType());
136 assert(CMF && "Function not in module?!");
137 Functions.insert(CMF);
140 std::cout << "Checking for crash with only these functions: ";
141 PrintFunctionList(Funcs);
144 // Loop over and delete any functions which we aren't supposed to be playing
146 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
147 if (!I->isExternal() && !Functions.count(I))
148 DeleteFunctionBody(I);
150 // Try running the hacked up program...
152 BD.setNewProgram(M); // It crashed, keep the trimmed version...
154 // Make sure to use function pointers that point into the now-current
156 Funcs.assign(Functions.begin(), Functions.end());
165 /// ReduceCrashingBlocks reducer - This works by setting the terminators of
166 /// all terminators except the specified basic blocks to a 'ret' instruction,
167 /// then running the simplify-cfg pass. This has the effect of chopping up
168 /// the CFG really fast which can reduce large functions quickly.
170 class ReduceCrashingBlocks : public ListReducer<const BasicBlock*> {
172 bool (*TestFn)(BugDriver &, Module *);
174 ReduceCrashingBlocks(BugDriver &bd, bool (*testFn)(BugDriver &, Module *))
175 : BD(bd), TestFn(testFn) {}
177 virtual TestResult doTest(std::vector<const BasicBlock*> &Prefix,
178 std::vector<const BasicBlock*> &Kept) {
179 if (!Kept.empty() && TestBlocks(Kept))
181 if (!Prefix.empty() && TestBlocks(Prefix))
186 bool TestBlocks(std::vector<const BasicBlock*> &Prefix);
190 bool ReduceCrashingBlocks::TestBlocks(std::vector<const BasicBlock*> &BBs) {
191 // Clone the program to try hacking it apart...
192 Module *M = CloneModule(BD.getProgram());
194 // Convert list to set for fast lookup...
195 std::set<BasicBlock*> Blocks;
196 for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
197 // Convert the basic block from the original module to the new module...
198 const Function *F = BBs[i]->getParent();
199 Function *CMF = M->getFunction(F->getName(), F->getFunctionType());
200 assert(CMF && "Function not in module?!");
202 // Get the mapped basic block...
203 Function::iterator CBI = CMF->begin();
204 std::advance(CBI, std::distance(F->begin(),
205 Function::const_iterator(BBs[i])));
209 std::cout << "Checking for crash with only these blocks:";
210 unsigned NumPrint = Blocks.size();
211 if (NumPrint > 10) NumPrint = 10;
212 for (unsigned i = 0, e = NumPrint; i != e; ++i)
213 std::cout << " " << BBs[i]->getName();
214 if (NumPrint < Blocks.size())
215 std::cout << "... <" << Blocks.size() << " total>";
218 // Loop over and delete any hack up any blocks that are not listed...
219 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
220 for (Function::iterator BB = I->begin(), E = I->end(); BB != E; ++BB)
221 if (!Blocks.count(BB) && BB->getTerminator()->getNumSuccessors()) {
222 // Loop over all of the successors of this block, deleting any PHI nodes
223 // that might include it.
224 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
225 (*SI)->removePredecessor(BB);
227 if (BB->getTerminator()->getType() != Type::VoidTy)
228 BB->getTerminator()->replaceAllUsesWith(
229 Constant::getNullValue(BB->getTerminator()->getType()));
231 // Delete the old terminator instruction...
232 BB->getInstList().pop_back();
234 // Add a new return instruction of the appropriate type...
235 const Type *RetTy = BB->getParent()->getReturnType();
236 new ReturnInst(RetTy == Type::VoidTy ? 0 :
237 Constant::getNullValue(RetTy), BB);
240 // The CFG Simplifier pass may delete one of the basic blocks we are
241 // interested in. If it does we need to take the block out of the list. Make
242 // a "persistent mapping" by turning basic blocks into <function, name> pairs.
243 // This won't work well if blocks are unnamed, but that is just the risk we
245 std::vector<std::pair<Function*, std::string> > BlockInfo;
247 for (std::set<BasicBlock*>::iterator I = Blocks.begin(), E = Blocks.end();
249 BlockInfo.push_back(std::make_pair((*I)->getParent(), (*I)->getName()));
251 // Now run the CFG simplify pass on the function...
253 Passes.add(createCFGSimplificationPass());
254 Passes.add(createVerifierPass());
257 // Try running on the hacked up program...
259 BD.setNewProgram(M); // It crashed, keep the trimmed version...
261 // Make sure to use basic block pointers that point into the now-current
262 // module, and that they don't include any deleted blocks.
264 for (unsigned i = 0, e = BlockInfo.size(); i != e; ++i) {
265 SymbolTable &ST = BlockInfo[i].first->getSymbolTable();
266 SymbolTable::plane_iterator PI = ST.find(Type::LabelTy);
267 if (PI != ST.plane_end() && PI->second.count(BlockInfo[i].second))
268 BBs.push_back(cast<BasicBlock>(PI->second[BlockInfo[i].second]));
272 delete M; // It didn't crash, try something else.
276 /// DebugACrash - Given a predicate that determines whether a component crashes
277 /// on a program, try to destructively reduce the program while still keeping
278 /// the predicate true.
279 static bool DebugACrash(BugDriver &BD, bool (*TestFn)(BugDriver &, Module *)) {
280 // See if we can get away with nuking all of the global variable initializers
282 if (BD.getProgram()->global_begin() != BD.getProgram()->global_end()) {
283 Module *M = CloneModule(BD.getProgram());
284 bool DeletedInit = false;
285 for (Module::global_iterator I = M->global_begin(), E = M->global_end(); I != E; ++I)
286 if (I->hasInitializer()) {
287 I->setInitializer(0);
288 I->setLinkage(GlobalValue::ExternalLinkage);
293 delete M; // No change made...
295 // See if the program still causes a crash...
296 std::cout << "\nChecking to see if we can delete global inits: ";
297 if (TestFn(BD, M)) { // Still crashes?
299 std::cout << "\n*** Able to remove all global initializers!\n";
300 } else { // No longer crashes?
301 std::cout << " - Removing all global inits hides problem!\n";
307 // Now try to reduce the number of functions in the module to something small.
308 std::vector<Function*> Functions;
309 for (Module::iterator I = BD.getProgram()->begin(),
310 E = BD.getProgram()->end(); I != E; ++I)
311 if (!I->isExternal())
312 Functions.push_back(I);
314 if (Functions.size() > 1 && !BugpointIsInterrupted) {
315 std::cout << "\n*** Attempting to reduce the number of functions "
318 unsigned OldSize = Functions.size();
319 ReduceCrashingFunctions(BD, TestFn).reduceList(Functions);
321 if (Functions.size() < OldSize)
322 BD.EmitProgressBytecode("reduced-function");
325 // Attempt to delete entire basic blocks at a time to speed up
326 // convergence... this actually works by setting the terminator of the blocks
327 // to a return instruction then running simplifycfg, which can potentially
328 // shrinks the code dramatically quickly
330 if (!DisableSimplifyCFG && !BugpointIsInterrupted) {
331 std::vector<const BasicBlock*> Blocks;
332 for (Module::const_iterator I = BD.getProgram()->begin(),
333 E = BD.getProgram()->end(); I != E; ++I)
334 for (Function::const_iterator FI = I->begin(), E = I->end(); FI !=E; ++FI)
335 Blocks.push_back(FI);
336 ReduceCrashingBlocks(BD, TestFn).reduceList(Blocks);
339 // FIXME: This should use the list reducer to converge faster by deleting
340 // larger chunks of instructions at a time!
341 unsigned Simplification = 2;
343 if (BugpointIsInterrupted) break;
345 std::cout << "\n*** Attempting to reduce testcase by deleting instruc"
346 << "tions: Simplification Level #" << Simplification << '\n';
348 // Now that we have deleted the functions that are unnecessary for the
349 // program, try to remove instructions that are not necessary to cause the
350 // crash. To do this, we loop through all of the instructions in the
351 // remaining functions, deleting them (replacing any values produced with
352 // nulls), and then running ADCE and SimplifyCFG. If the transformed input
353 // still triggers failure, keep deleting until we cannot trigger failure
356 unsigned InstructionsToSkipBeforeDeleting = 0;
359 // Loop over all of the (non-terminator) instructions remaining in the
360 // function, attempting to delete them.
361 unsigned CurInstructionNum = 0;
362 for (Module::const_iterator FI = BD.getProgram()->begin(),
363 E = BD.getProgram()->end(); FI != E; ++FI)
364 if (!FI->isExternal())
365 for (Function::const_iterator BI = FI->begin(), E = FI->end(); BI != E;
367 for (BasicBlock::const_iterator I = BI->begin(), E = --BI->end();
368 I != E; ++I, ++CurInstructionNum)
369 if (InstructionsToSkipBeforeDeleting) {
370 --InstructionsToSkipBeforeDeleting;
372 if (BugpointIsInterrupted) goto ExitLoops;
374 std::cout << "Checking instruction '" << I->getName() << "': ";
375 Module *M = BD.deleteInstructionFromProgram(I, Simplification);
377 // Find out if the pass still crashes on this pass...
379 // Yup, it does, we delete the old module, and continue trying
380 // to reduce the testcase...
382 InstructionsToSkipBeforeDeleting = CurInstructionNum;
383 goto TryAgain; // I wish I had a multi-level break here!
386 // This pass didn't crash without this instruction, try the next
391 if (InstructionsToSkipBeforeDeleting) {
392 InstructionsToSkipBeforeDeleting = 0;
396 } while (Simplification);
399 // Try to clean up the testcase by running funcresolve and globaldce...
400 if (!BugpointIsInterrupted) {
401 std::cout << "\n*** Attempting to perform final cleanups: ";
402 Module *M = CloneModule(BD.getProgram());
403 M = BD.performFinalCleanups(M, true);
405 // Find out if the pass still crashes on the cleaned up program...
407 BD.setNewProgram(M); // Yup, it does, keep the reduced version...
413 BD.EmitProgressBytecode("reduced-simplified");
418 static bool TestForOptimizerCrash(BugDriver &BD, Module *M) {
419 return BD.runPasses(M);
422 /// debugOptimizerCrash - This method is called when some pass crashes on input.
423 /// It attempts to prune down the testcase to something reasonable, and figure
424 /// out exactly which pass is crashing.
426 bool BugDriver::debugOptimizerCrash(const std::string &ID) {
427 std::cout << "\n*** Debugging optimizer crash!\n";
429 // Reduce the list of passes which causes the optimizer to crash...
430 unsigned OldSize = PassesToRun.size();
431 if (!BugpointIsInterrupted)
432 ReducePassList(*this).reduceList(PassesToRun);
434 std::cout << "\n*** Found crashing pass"
435 << (PassesToRun.size() == 1 ? ": " : "es: ")
436 << getPassesString(PassesToRun) << '\n';
438 EmitProgressBytecode(ID);
440 return DebugACrash(*this, TestForOptimizerCrash);
443 static bool TestForCodeGenCrash(BugDriver &BD, Module *M) {
446 BD.compileProgram(M);
449 } catch (ToolExecutionError &) {
450 std::cerr << "<crash>\n";
451 return true; // Tool is still crashing.
455 /// debugCodeGeneratorCrash - This method is called when the code generator
456 /// crashes on an input. It attempts to reduce the input as much as possible
457 /// while still causing the code generator to crash.
458 bool BugDriver::debugCodeGeneratorCrash() {
459 std::cerr << "*** Debugging code generator crash!\n";
461 return DebugACrash(*this, TestForCodeGenCrash);