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 //===----------------------------------------------------------------------===//
11 // This file defines the bugpoint internals that narrow down compilation crashes
13 //===----------------------------------------------------------------------===//
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"
33 class DebugCrashes : public ListReducer<const PassInfo*> {
36 DebugCrashes(BugDriver &bd) : BD(bd) {}
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.
42 virtual TestResult doTest(std::vector<const PassInfo*> &Removed,
43 std::vector<const PassInfo*> &Kept);
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))
57 OrigProgram = BD.Program;
59 BD.Program = BD.ParseInputFile(PrefixOutput);
60 if (BD.Program == 0) {
61 std::cerr << BD.getToolName() << ": Error reading bytecode file '"
62 << PrefixOutput << "'!\n";
65 removeFile(PrefixOutput);
68 std::cout << "Checking to see if these passes crash: "
69 << getPassesString(Suffix) << ": ";
71 if (BD.runPasses(Suffix)) {
72 delete OrigProgram; // The suffix crashes alone...
76 // Nothing failed, restore state...
79 BD.Program = OrigProgram;
84 class ReduceCrashingFunctions : public ListReducer<Function*> {
87 ReduceCrashingFunctions(BugDriver &bd) : BD(bd) {}
89 virtual TestResult doTest(std::vector<Function*> &Prefix,
90 std::vector<Function*> &Kept) {
91 if (!Kept.empty() && TestFuncs(Kept))
93 if (!Prefix.empty() && TestFuncs(Prefix))
98 bool TestFuncs(std::vector<Function*> &Prefix);
101 bool ReduceCrashingFunctions::TestFuncs(std::vector<Function*> &Funcs) {
102 // Clone the program to try hacking it apart...
103 Module *M = CloneModule(BD.Program);
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);
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();
119 // Loop over and delete any functions which we aren't supposed to be playing
121 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
122 if (!I->isExternal() && !Functions.count(I))
123 DeleteFunctionBody(I);
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...
130 // Make sure to use function pointers that point into the now-current
132 Funcs.assign(Functions.begin(), Functions.end());
135 delete BD.Program; // It didn't crash, revert...
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.
146 class ReduceCrashingBlocks : public ListReducer<BasicBlock*> {
149 ReduceCrashingBlocks(BugDriver &bd) : BD(bd) {}
151 virtual TestResult doTest(std::vector<BasicBlock*> &Prefix,
152 std::vector<BasicBlock*> &Kept) {
153 if (!Kept.empty() && TestBlocks(Kept))
155 if (!Prefix.empty() && TestBlocks(Prefix))
160 bool TestBlocks(std::vector<BasicBlock*> &Prefix);
163 bool ReduceCrashingBlocks::TestBlocks(std::vector<BasicBlock*> &BBs) {
164 // Clone the program to try hacking it apart...
165 Module *M = CloneModule(BD.Program);
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?!");
175 // Get the mapped basic block...
176 Function::iterator CBI = CMF->begin();
177 std::advance(CBI, std::distance(F->begin(), Function::iterator(BBs[i])));
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();
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);
195 // Delete the old terminator instruction...
196 BB->getInstList().pop_back();
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);
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
210 std::vector<std::pair<Function*, std::string> > BlockInfo;
212 for (std::set<BasicBlock*>::iterator I = Blocks.begin(), E = Blocks.end();
214 BlockInfo.push_back(std::make_pair((*I)->getParent(), (*I)->getName()));
216 // Now run the CFG simplify pass on the function...
218 Passes.add(createCFGSimplificationPass());
219 Passes.add(createVerifierPass());
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...
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.
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]));
238 delete BD.Program; // It didn't crash, revert...
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.
247 bool BugDriver::debugCrash() {
248 bool AnyReduction = false;
249 std::cout << "\n*** Debugging optimizer crash!\n";
251 // Reduce the list of passes which causes the optimizer to crash...
252 unsigned OldSize = PassesToRun.size();
253 DebugCrashes(*this).reduceList(PassesToRun);
255 std::cout << "\n*** Found crashing pass"
256 << (PassesToRun.size() == 1 ? ": " : "es: ")
257 << getPassesString(PassesToRun) << "\n";
259 EmitProgressBytecode("passinput");
261 // See if we can get away with nuking all of the global variable initializers
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);
274 delete M; // No change made...
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?
282 std::cout << "\n*** Able to remove all global initializers!\n";
283 } else { // No longer crashes?
284 delete Program; // Restore program.
286 std::cout << " - Removing all global inits hides problem!\n";
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);
297 if (Functions.size() > 1) {
298 std::cout << "\n*** Attempting to reduce the number of functions "
301 OldSize = Functions.size();
302 ReduceCrashingFunctions(*this).reduceList(Functions);
304 if (Functions.size() < OldSize) {
305 EmitProgressBytecode("reduced-function");
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
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);
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;
328 std::cout << "\n*** Attempting to reduce testcase by deleting instruc"
329 << "tions: Simplification Level #" << Simplification << "\n";
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
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();
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();
349 Module *M = deleteInstructionFromProgram(I, Simplification);
351 // Make the function the current program...
352 std::swap(Program, M);
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...
361 goto TryAgain; // I wish I had a multi-level break here!
364 // This pass didn't crash without this instruction, try the next
370 } while (Simplification);
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);
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...
383 delete Program; // Otherwise, restore the original module...
388 EmitProgressBytecode("reduced-simplified");