blob: b25e6ecec19b68197d90b776900c8d2dd3cce4dc [file] [log] [blame]
Chris Lattner73a6bdd2002-11-20 22:28:10 +00001//===- CrashDebugger.cpp - Debug compilation crashes ----------------------===//
Misha Brukman650ba8e2005-04-22 00:00:37 +00002//
John Criswell09344dc2003-10-20 17:47:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner345353d2007-12-29 20:44:31 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman650ba8e2005-04-22 00:00:37 +00007//
John Criswell09344dc2003-10-20 17:47:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner73a6bdd2002-11-20 22:28:10 +00009//
10// This file defines the bugpoint internals that narrow down compilation crashes
11//
12//===----------------------------------------------------------------------===//
13
14#include "BugDriver.h"
Chris Lattner1d080f22003-04-24 22:24:58 +000015#include "ListReducer.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000016#include "ToolRunner.h"
17#include "llvm/ADT/SmallPtrSet.h"
Keno Fischer34ca8312015-11-06 00:12:50 +000018#include "llvm/ADT/StringSet.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000019#include "llvm/IR/CFG.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000020#include "llvm/IR/Constants.h"
21#include "llvm/IR/DerivedTypes.h"
22#include "llvm/IR/Instructions.h"
Chandler Carruth30d69c22015-02-13 10:01:29 +000023#include "llvm/IR/LegacyPassManager.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/Module.h"
25#include "llvm/IR/ValueSymbolTable.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000026#include "llvm/IR/Verifier.h"
Misha Brukman0c2305b2003-08-07 21:19:30 +000027#include "llvm/Pass.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000028#include "llvm/Support/CommandLine.h"
29#include "llvm/Support/FileUtilities.h"
Chris Lattnerf32939b2003-04-24 23:51:38 +000030#include "llvm/Transforms/Scalar.h"
Chris Lattner1d080f22003-04-24 22:24:58 +000031#include "llvm/Transforms/Utils/Cloning.h"
Chris Lattner1d080f22003-04-24 22:24:58 +000032#include <set>
Chris Lattner2f1aa112004-01-14 03:38:37 +000033using namespace llvm;
Chris Lattner73a6bdd2002-11-20 22:28:10 +000034
Andrew Lenharthef9aa122006-03-05 22:21:36 +000035namespace {
36 cl::opt<bool>
37 KeepMain("keep-main",
38 cl::desc("Force function reduction to keep main"),
39 cl::init(false));
Torok Edwin5bd3f7b2009-05-24 09:31:04 +000040 cl::opt<bool>
41 NoGlobalRM ("disable-global-remove",
42 cl::desc("Do not remove global variables"),
43 cl::init(false));
JF Bastienf87e20d2015-04-20 23:42:22 +000044
45 cl::opt<bool>
46 ReplaceFuncsWithNull("replace-funcs-with-null",
47 cl::desc("When stubbing functions, replace all uses will null"),
48 cl::init(false));
49 cl::opt<bool>
50 DontReducePassList("disable-pass-list-reduction",
51 cl::desc("Skip pass list reduction steps"),
52 cl::init(false));
Keno Fischer34ca8312015-11-06 00:12:50 +000053
54 cl::opt<bool> NoNamedMDRM("disable-namedmd-remove",
55 cl::desc("Do not remove global named metadata"),
56 cl::init(false));
Sebastian Pop8f7d0192016-07-15 23:15:06 +000057 cl::opt<bool> VerboseErrors("verbose-errors",
58 cl::desc("Print the output of crashing program"),
59 cl::init(false));
Andrew Lenharthef9aa122006-03-05 22:21:36 +000060}
61
Brian Gaeke960707c2003-11-11 22:41:34 +000062namespace llvm {
Rafael Espindola33e81a82010-08-08 03:55:08 +000063 class ReducePassList : public ListReducer<std::string> {
Chris Lattner2f1aa112004-01-14 03:38:37 +000064 BugDriver &BD;
65 public:
Chris Lattner327019b2004-02-18 21:24:48 +000066 ReducePassList(BugDriver &bd) : BD(bd) {}
Misha Brukman650ba8e2005-04-22 00:00:37 +000067
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +000068 // doTest - Return true iff running the "removed" passes succeeds, and
Chris Lattner2f1aa112004-01-14 03:38:37 +000069 // running the "Kept" passes fail when run on the output of the "removed"
70 // passes. If we return true, we update the current module of bugpoint.
71 //
Craig Toppere56917c2014-03-08 08:27:28 +000072 TestResult doTest(std::vector<std::string> &Removed,
73 std::vector<std::string> &Kept,
74 std::string &Error) override;
Chris Lattner2f1aa112004-01-14 03:38:37 +000075 };
76}
Chris Lattner1d080f22003-04-24 22:24:58 +000077
Chris Lattner327019b2004-02-18 21:24:48 +000078ReducePassList::TestResult
Rafael Espindola33e81a82010-08-08 03:55:08 +000079ReducePassList::doTest(std::vector<std::string> &Prefix,
80 std::vector<std::string> &Suffix,
Nick Lewycky6ba630b2010-04-12 05:08:25 +000081 std::string &Error) {
Rafael Espindolabb876652013-06-17 19:33:18 +000082 std::string PrefixOutput;
Craig Toppere6cb63e2014-04-25 04:24:47 +000083 Module *OrigProgram = nullptr;
Chris Lattner1d080f22003-04-24 22:24:58 +000084 if (!Prefix.empty()) {
Dan Gohmanee051522009-07-16 15:30:09 +000085 outs() << "Checking to see if these passes crash: "
86 << getPassesString(Prefix) << ": ";
Rafael Espindolabb876652013-06-17 19:33:18 +000087 if (BD.runPasses(BD.getProgram(), Prefix, PrefixOutput))
Chris Lattner1d080f22003-04-24 22:24:58 +000088 return KeepPrefix;
Chris Lattnera9656312003-06-02 04:54:29 +000089
90 OrigProgram = BD.Program;
91
Rafael Espindola28b351a2014-08-26 17:19:03 +000092 BD.Program = parseInputFile(PrefixOutput, BD.getContext()).release();
Craig Toppere6cb63e2014-04-25 04:24:47 +000093 if (BD.Program == nullptr) {
Dan Gohmand8db3762009-07-15 16:35:29 +000094 errs() << BD.getToolName() << ": Error reading bitcode file '"
Rafael Espindolabb876652013-06-17 19:33:18 +000095 << PrefixOutput << "'!\n";
Chris Lattnera9656312003-06-02 04:54:29 +000096 exit(1);
97 }
Rafael Espindolabb876652013-06-17 19:33:18 +000098 sys::fs::remove(PrefixOutput);
Chris Lattner1d080f22003-04-24 22:24:58 +000099 }
100
Dan Gohmanee051522009-07-16 15:30:09 +0000101 outs() << "Checking to see if these passes crash: "
102 << getPassesString(Suffix) << ": ";
Misha Brukman650ba8e2005-04-22 00:00:37 +0000103
Rafael Espindola37302ea2010-08-05 02:16:32 +0000104 if (BD.runPasses(BD.getProgram(), Suffix)) {
Chris Lattner1d080f22003-04-24 22:24:58 +0000105 delete OrigProgram; // The suffix crashes alone...
106 return KeepSuffix;
107 }
108
109 // Nothing failed, restore state...
Chris Lattnera9656312003-06-02 04:54:29 +0000110 if (OrigProgram) {
111 delete BD.Program;
112 BD.Program = OrigProgram;
113 }
Chris Lattner1d080f22003-04-24 22:24:58 +0000114 return NoFailure;
115}
116
Bill Wendling3f833432006-10-25 18:36:14 +0000117namespace {
118 /// ReduceCrashingGlobalVariables - This works by removing the global
119 /// variable's initializer and seeing if the program still crashes. If it
120 /// does, then we keep that program and try again.
121 ///
122 class ReduceCrashingGlobalVariables : public ListReducer<GlobalVariable*> {
123 BugDriver &BD;
Rafael Espindolad1c7ef42010-08-05 03:00:22 +0000124 bool (*TestFn)(const BugDriver &, Module *);
Bill Wendling3f833432006-10-25 18:36:14 +0000125 public:
126 ReduceCrashingGlobalVariables(BugDriver &bd,
Rafael Espindolad1c7ef42010-08-05 03:00:22 +0000127 bool (*testFn)(const BugDriver &, Module *))
Bill Wendling3f833432006-10-25 18:36:14 +0000128 : BD(bd), TestFn(testFn) {}
129
Craig Toppere56917c2014-03-08 08:27:28 +0000130 TestResult doTest(std::vector<GlobalVariable*> &Prefix,
131 std::vector<GlobalVariable*> &Kept,
132 std::string &Error) override {
Bill Wendling3f833432006-10-25 18:36:14 +0000133 if (!Kept.empty() && TestGlobalVariables(Kept))
134 return KeepSuffix;
Bill Wendling3f833432006-10-25 18:36:14 +0000135 if (!Prefix.empty() && TestGlobalVariables(Prefix))
136 return KeepPrefix;
Bill Wendling3f833432006-10-25 18:36:14 +0000137 return NoFailure;
138 }
139
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000140 bool TestGlobalVariables(std::vector<GlobalVariable*> &GVs);
Bill Wendling3f833432006-10-25 18:36:14 +0000141 };
142}
143
144bool
145ReduceCrashingGlobalVariables::TestGlobalVariables(
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000146 std::vector<GlobalVariable*> &GVs) {
Bill Wendling3f833432006-10-25 18:36:14 +0000147 // Clone the program to try hacking it apart...
Rafael Espindola229e38f2010-10-13 01:36:30 +0000148 ValueToValueMapTy VMap;
Rafael Espindolacab951d2015-12-08 23:57:17 +0000149 Module *M = CloneModule(BD.getProgram(), VMap).release();
Bill Wendling3f833432006-10-25 18:36:14 +0000150
151 // Convert list to set for fast lookup...
152 std::set<GlobalVariable*> GVSet;
153
154 for (unsigned i = 0, e = GVs.size(); i != e; ++i) {
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000155 GlobalVariable* CMGV = cast<GlobalVariable>(VMap[GVs[i]]);
Bill Wendling3f833432006-10-25 18:36:14 +0000156 assert(CMGV && "Global Variable not in module?!");
157 GVSet.insert(CMGV);
158 }
159
Dan Gohmanee051522009-07-16 15:30:09 +0000160 outs() << "Checking for crash with only these global variables: ";
Bill Wendling3f833432006-10-25 18:36:14 +0000161 PrintGlobalVariableList(GVs);
Dan Gohmanee051522009-07-16 15:30:09 +0000162 outs() << ": ";
Bill Wendling3f833432006-10-25 18:36:14 +0000163
164 // Loop over and delete any global variables which we aren't supposed to be
165 // playing with...
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000166 for (GlobalVariable &I : M->globals())
167 if (I.hasInitializer() && !GVSet.count(&I)) {
Hal Finkel28ad2b42015-11-26 19:23:49 +0000168 DeleteGlobalInitializer(&I);
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000169 I.setLinkage(GlobalValue::ExternalLinkage);
Justin Lebar2a445cf2016-06-15 23:20:12 +0000170 I.setComdat(nullptr);
Bill Wendling3f833432006-10-25 18:36:14 +0000171 }
172
173 // Try running the hacked up program...
174 if (TestFn(BD, M)) {
175 BD.setNewProgram(M); // It crashed, keep the trimmed version...
176
177 // Make sure to use global variable pointers that point into the now-current
178 // module.
179 GVs.assign(GVSet.begin(), GVSet.end());
180 return true;
181 }
182
183 delete M;
184 return false;
185}
186
David Blaikiea379b1812011-12-20 02:50:00 +0000187namespace {
Bill Wendling3f833432006-10-25 18:36:14 +0000188 /// ReduceCrashingFunctions reducer - This works by removing functions and
189 /// seeing if the program still crashes. If it does, then keep the newer,
190 /// smaller program.
191 ///
Chris Lattnerfd72bed2004-03-14 20:50:42 +0000192 class ReduceCrashingFunctions : public ListReducer<Function*> {
Chris Lattner2f1aa112004-01-14 03:38:37 +0000193 BugDriver &BD;
Rafael Espindolad1c7ef42010-08-05 03:00:22 +0000194 bool (*TestFn)(const BugDriver &, Module *);
Chris Lattner2f1aa112004-01-14 03:38:37 +0000195 public:
Chris Lattner8bda4c42004-02-18 23:26:28 +0000196 ReduceCrashingFunctions(BugDriver &bd,
Rafael Espindolad1c7ef42010-08-05 03:00:22 +0000197 bool (*testFn)(const BugDriver &, Module *))
Chris Lattner8bda4c42004-02-18 23:26:28 +0000198 : BD(bd), TestFn(testFn) {}
Misha Brukman650ba8e2005-04-22 00:00:37 +0000199
Craig Toppere56917c2014-03-08 08:27:28 +0000200 TestResult doTest(std::vector<Function*> &Prefix,
201 std::vector<Function*> &Kept,
202 std::string &Error) override {
Chris Lattner2f1aa112004-01-14 03:38:37 +0000203 if (!Kept.empty() && TestFuncs(Kept))
204 return KeepSuffix;
205 if (!Prefix.empty() && TestFuncs(Prefix))
206 return KeepPrefix;
207 return NoFailure;
208 }
Misha Brukman650ba8e2005-04-22 00:00:37 +0000209
Chris Lattnerfd72bed2004-03-14 20:50:42 +0000210 bool TestFuncs(std::vector<Function*> &Prefix);
Chris Lattner2f1aa112004-01-14 03:38:37 +0000211 };
212}
Chris Lattner1d080f22003-04-24 22:24:58 +0000213
JF Bastienf87e20d2015-04-20 23:42:22 +0000214static void RemoveFunctionReferences(Module *M, const char* Name) {
215 auto *UsedVar = M->getGlobalVariable(Name, true);
216 if (!UsedVar || !UsedVar->hasInitializer()) return;
217 if (isa<ConstantAggregateZero>(UsedVar->getInitializer())) {
218 assert(UsedVar->use_empty());
219 UsedVar->eraseFromParent();
220 return;
221 }
222 auto *OldUsedVal = cast<ConstantArray>(UsedVar->getInitializer());
223 std::vector<Constant*> Used;
224 for(Value *V : OldUsedVal->operand_values()) {
225 Constant *Op = cast<Constant>(V->stripPointerCasts());
226 if(!Op->isNullValue()) {
227 Used.push_back(cast<Constant>(V));
228 }
229 }
230 auto *NewValElemTy = OldUsedVal->getType()->getElementType();
231 auto *NewValTy = ArrayType::get(NewValElemTy, Used.size());
232 auto *NewUsedVal = ConstantArray::get(NewValTy, Used);
233 UsedVar->mutateType(NewUsedVal->getType()->getPointerTo());
234 UsedVar->setInitializer(NewUsedVal);
235}
236
Chris Lattnerfd72bed2004-03-14 20:50:42 +0000237bool ReduceCrashingFunctions::TestFuncs(std::vector<Function*> &Funcs) {
Dmitri Gribenko6e0520e2013-09-02 01:18:56 +0000238 // If main isn't present, claim there is no problem.
239 if (KeepMain && std::find(Funcs.begin(), Funcs.end(),
240 BD.getProgram()->getFunction("main")) ==
241 Funcs.end())
Andrew Lenharthef9aa122006-03-05 22:21:36 +0000242 return false;
243
Misha Brukman8b2bd4e2003-10-10 17:57:28 +0000244 // Clone the program to try hacking it apart...
Rafael Espindola229e38f2010-10-13 01:36:30 +0000245 ValueToValueMapTy VMap;
Rafael Espindolacab951d2015-12-08 23:57:17 +0000246 Module *M = CloneModule(BD.getProgram(), VMap).release();
Misha Brukman650ba8e2005-04-22 00:00:37 +0000247
Chris Lattner1d080f22003-04-24 22:24:58 +0000248 // Convert list to set for fast lookup...
249 std::set<Function*> Functions;
250 for (unsigned i = 0, e = Funcs.size(); i != e; ++i) {
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000251 Function *CMF = cast<Function>(VMap[Funcs[i]]);
Chris Lattner1d080f22003-04-24 22:24:58 +0000252 assert(CMF && "Function not in module?!");
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000253 assert(CMF->getFunctionType() == Funcs[i]->getFunctionType() && "wrong ty");
Dan Gohmanbcad7182009-03-06 02:16:23 +0000254 assert(CMF->getName() == Funcs[i]->getName() && "wrong name");
Chris Lattnerde39f2b2003-04-24 22:54:06 +0000255 Functions.insert(CMF);
Chris Lattner1d080f22003-04-24 22:24:58 +0000256 }
257
Dan Gohmanee051522009-07-16 15:30:09 +0000258 outs() << "Checking for crash with only these functions: ";
Chris Lattnerfd72bed2004-03-14 20:50:42 +0000259 PrintFunctionList(Funcs);
Dan Gohmanee051522009-07-16 15:30:09 +0000260 outs() << ": ";
JF Bastienf87e20d2015-04-20 23:42:22 +0000261 if (!ReplaceFuncsWithNull) {
262 // Loop over and delete any functions which we aren't supposed to be playing
263 // with...
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000264 for (Function &I : *M)
265 if (!I.isDeclaration() && !Functions.count(&I))
266 DeleteFunctionBody(&I);
JF Bastienf87e20d2015-04-20 23:42:22 +0000267 } else {
268 std::vector<GlobalValue*> ToRemove;
269 // First, remove aliases to functions we're about to purge.
270 for (GlobalAlias &Alias : M->aliases()) {
David Majnemer95549492016-05-04 00:20:48 +0000271 GlobalObject *Root = Alias.getBaseObject();
272 Function *F = dyn_cast_or_null<Function>(Root);
JF Bastienf87e20d2015-04-20 23:42:22 +0000273 if (F) {
274 if (Functions.count(F))
275 // We're keeping this function.
276 continue;
277 } else if (Root->isNullValue()) {
278 // This referenced a globalalias that we've already replaced,
279 // so we still need to replace this alias.
280 } else if (!F) {
281 // Not a function, therefore not something we mess with.
282 continue;
283 }
Chris Lattner1d080f22003-04-24 22:24:58 +0000284
JF Bastienf87e20d2015-04-20 23:42:22 +0000285 PointerType *Ty = cast<PointerType>(Alias.getType());
286 Constant *Replacement = ConstantPointerNull::get(Ty);
287 Alias.replaceAllUsesWith(Replacement);
288 ToRemove.push_back(&Alias);
289 }
Chris Lattner1d080f22003-04-24 22:24:58 +0000290
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000291 for (Function &I : *M) {
292 if (!I.isDeclaration() && !Functions.count(&I)) {
293 PointerType *Ty = cast<PointerType>(I.getType());
JF Bastienf87e20d2015-04-20 23:42:22 +0000294 Constant *Replacement = ConstantPointerNull::get(Ty);
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000295 I.replaceAllUsesWith(Replacement);
296 ToRemove.push_back(&I);
JF Bastienf87e20d2015-04-20 23:42:22 +0000297 }
298 }
299
300 for (auto *F : ToRemove) {
301 F->eraseFromParent();
302 }
303
304 // Finally, remove any null members from any global intrinsic.
305 RemoveFunctionReferences(M, "llvm.used");
306 RemoveFunctionReferences(M, "llvm.compiler.used");
307 }
Chris Lattner1d080f22003-04-24 22:24:58 +0000308 // Try running the hacked up program...
Chris Lattner8bda4c42004-02-18 23:26:28 +0000309 if (TestFn(BD, M)) {
Chris Lattner327019b2004-02-18 21:24:48 +0000310 BD.setNewProgram(M); // It crashed, keep the trimmed version...
Chris Lattner1d080f22003-04-24 22:24:58 +0000311
312 // Make sure to use function pointers that point into the now-current
313 // module.
314 Funcs.assign(Functions.begin(), Functions.end());
315 return true;
316 }
Chris Lattner327019b2004-02-18 21:24:48 +0000317 delete M;
Chris Lattner1d080f22003-04-24 22:24:58 +0000318 return false;
319}
320
Chris Lattner16a41312003-04-24 17:02:17 +0000321
Chris Lattner1942f982004-02-18 21:29:46 +0000322namespace {
Chris Lattner2f1aa112004-01-14 03:38:37 +0000323 /// ReduceCrashingBlocks reducer - This works by setting the terminators of
324 /// all terminators except the specified basic blocks to a 'ret' instruction,
325 /// then running the simplify-cfg pass. This has the effect of chopping up
326 /// the CFG really fast which can reduce large functions quickly.
327 ///
Chris Lattner8bda4c42004-02-18 23:26:28 +0000328 class ReduceCrashingBlocks : public ListReducer<const BasicBlock*> {
Chris Lattner2f1aa112004-01-14 03:38:37 +0000329 BugDriver &BD;
Rafael Espindolad1c7ef42010-08-05 03:00:22 +0000330 bool (*TestFn)(const BugDriver &, Module *);
Chris Lattner2f1aa112004-01-14 03:38:37 +0000331 public:
Rafael Espindolad1c7ef42010-08-05 03:00:22 +0000332 ReduceCrashingBlocks(BugDriver &bd,
333 bool (*testFn)(const BugDriver &, Module *))
Chris Lattner8bda4c42004-02-18 23:26:28 +0000334 : BD(bd), TestFn(testFn) {}
Misha Brukman650ba8e2005-04-22 00:00:37 +0000335
Craig Toppere56917c2014-03-08 08:27:28 +0000336 TestResult doTest(std::vector<const BasicBlock*> &Prefix,
337 std::vector<const BasicBlock*> &Kept,
338 std::string &Error) override {
Chris Lattner2f1aa112004-01-14 03:38:37 +0000339 if (!Kept.empty() && TestBlocks(Kept))
340 return KeepSuffix;
341 if (!Prefix.empty() && TestBlocks(Prefix))
342 return KeepPrefix;
343 return NoFailure;
344 }
Misha Brukman650ba8e2005-04-22 00:00:37 +0000345
Chris Lattner8bda4c42004-02-18 23:26:28 +0000346 bool TestBlocks(std::vector<const BasicBlock*> &Prefix);
Chris Lattner2f1aa112004-01-14 03:38:37 +0000347 };
348}
Chris Lattnerf32939b2003-04-24 23:51:38 +0000349
Chris Lattner8bda4c42004-02-18 23:26:28 +0000350bool ReduceCrashingBlocks::TestBlocks(std::vector<const BasicBlock*> &BBs) {
Misha Brukman8b2bd4e2003-10-10 17:57:28 +0000351 // Clone the program to try hacking it apart...
Rafael Espindola229e38f2010-10-13 01:36:30 +0000352 ValueToValueMapTy VMap;
Rafael Espindolacab951d2015-12-08 23:57:17 +0000353 Module *M = CloneModule(BD.getProgram(), VMap).release();
Misha Brukman650ba8e2005-04-22 00:00:37 +0000354
Chris Lattnerf32939b2003-04-24 23:51:38 +0000355 // Convert list to set for fast lookup...
Nick Lewyckyb294e312009-04-04 09:39:23 +0000356 SmallPtrSet<BasicBlock*, 8> Blocks;
357 for (unsigned i = 0, e = BBs.size(); i != e; ++i)
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000358 Blocks.insert(cast<BasicBlock>(VMap[BBs[i]]));
Chris Lattnerf32939b2003-04-24 23:51:38 +0000359
Dan Gohmanee051522009-07-16 15:30:09 +0000360 outs() << "Checking for crash with only these blocks:";
Chris Lattner4f50ebd2003-10-27 04:44:59 +0000361 unsigned NumPrint = Blocks.size();
362 if (NumPrint > 10) NumPrint = 10;
363 for (unsigned i = 0, e = NumPrint; i != e; ++i)
Dan Gohmanee051522009-07-16 15:30:09 +0000364 outs() << " " << BBs[i]->getName();
Chris Lattner4f50ebd2003-10-27 04:44:59 +0000365 if (NumPrint < Blocks.size())
Dan Gohmanee051522009-07-16 15:30:09 +0000366 outs() << "... <" << Blocks.size() << " total>";
367 outs() << ": ";
Chris Lattnerf32939b2003-04-24 23:51:38 +0000368
369 // Loop over and delete any hack up any blocks that are not listed...
370 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
371 for (Function::iterator BB = I->begin(), E = I->end(); BB != E; ++BB)
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000372 if (!Blocks.count(&*BB) && BB->getTerminator()->getNumSuccessors()) {
Chris Lattnerf32939b2003-04-24 23:51:38 +0000373 // Loop over all of the successors of this block, deleting any PHI nodes
374 // that might include it.
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000375 for (succ_iterator SI = succ_begin(&*BB), E = succ_end(&*BB); SI != E;
376 ++SI)
377 (*SI)->removePredecessor(&*BB);
Chris Lattnerf32939b2003-04-24 23:51:38 +0000378
Chris Lattner7855a5c2008-04-28 00:04:58 +0000379 TerminatorInst *BBTerm = BB->getTerminator();
Philip Reames29e641c2016-06-29 00:15:35 +0000380 if (BBTerm->isEHPad() || BBTerm->getType()->isTokenTy())
David Majnemer189d7da2015-11-08 04:16:12 +0000381 continue;
Philip Reames29e641c2016-06-29 00:15:35 +0000382 if (!BBTerm->getType()->isVoidTy())
Owen Anderson5a1acd92009-07-31 20:28:14 +0000383 BBTerm->replaceAllUsesWith(Constant::getNullValue(BBTerm->getType()));
Chris Lattner7b233af2003-11-22 02:10:38 +0000384
Chris Lattner7855a5c2008-04-28 00:04:58 +0000385 // Replace the old terminator instruction.
Chris Lattnerf32939b2003-04-24 23:51:38 +0000386 BB->getInstList().pop_back();
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000387 new UnreachableInst(BB->getContext(), &*BB);
Chris Lattnerf32939b2003-04-24 23:51:38 +0000388 }
389
390 // The CFG Simplifier pass may delete one of the basic blocks we are
391 // interested in. If it does we need to take the block out of the list. Make
392 // a "persistent mapping" by turning basic blocks into <function, name> pairs.
393 // This won't work well if blocks are unnamed, but that is just the risk we
394 // have to take.
Rafael Espindolad1e241a2010-08-10 15:46:11 +0000395 std::vector<std::pair<std::string, std::string> > BlockInfo;
Chris Lattnerf32939b2003-04-24 23:51:38 +0000396
Craig Topper46276792014-08-24 23:23:06 +0000397 for (BasicBlock *BB : Blocks)
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000398 BlockInfo.emplace_back(BB->getParent()->getName(), BB->getName());
Chris Lattnerf32939b2003-04-24 23:51:38 +0000399
400 // Now run the CFG simplify pass on the function...
Rafael Espindolad1e241a2010-08-10 15:46:11 +0000401 std::vector<std::string> Passes;
402 Passes.push_back("simplifycfg");
403 Passes.push_back("verify");
Rafael Espindola28b351a2014-08-26 17:19:03 +0000404 std::unique_ptr<Module> New = BD.runPassesOn(M, Passes);
Rafael Espindolad1e241a2010-08-10 15:46:11 +0000405 delete M;
406 if (!New) {
407 errs() << "simplifycfg failed!\n";
408 exit(1);
409 }
Rafael Espindola28b351a2014-08-26 17:19:03 +0000410 M = New.release();
Chris Lattnerf32939b2003-04-24 23:51:38 +0000411
412 // Try running on the hacked up program...
Chris Lattner8bda4c42004-02-18 23:26:28 +0000413 if (TestFn(BD, M)) {
Chris Lattner327019b2004-02-18 21:24:48 +0000414 BD.setNewProgram(M); // It crashed, keep the trimmed version...
Chris Lattnerf32939b2003-04-24 23:51:38 +0000415
416 // Make sure to use basic block pointers that point into the now-current
417 // module, and that they don't include any deleted blocks.
418 BBs.clear();
Rafael Espindolad1e241a2010-08-10 15:46:11 +0000419 const ValueSymbolTable &GST = M->getValueSymbolTable();
Chris Lattnerf32939b2003-04-24 23:51:38 +0000420 for (unsigned i = 0, e = BlockInfo.size(); i != e; ++i) {
Rafael Espindolad1e241a2010-08-10 15:46:11 +0000421 Function *F = cast<Function>(GST.lookup(BlockInfo[i].first));
422 ValueSymbolTable &ST = F->getValueSymbolTable();
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000423 Value* V = ST.lookup(BlockInfo[i].second);
Owen Anderson55f1c092009-08-13 21:58:54 +0000424 if (V && V->getType() == Type::getLabelTy(V->getContext()))
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000425 BBs.push_back(cast<BasicBlock>(V));
Chris Lattnerf32939b2003-04-24 23:51:38 +0000426 }
427 return true;
428 }
Chris Lattner327019b2004-02-18 21:24:48 +0000429 delete M; // It didn't crash, try something else.
Chris Lattnerf32939b2003-04-24 23:51:38 +0000430 return false;
431}
432
Nick Lewycky6e090c92009-05-25 05:30:00 +0000433namespace {
434 /// ReduceCrashingInstructions reducer - This works by removing the specified
435 /// non-terminator instructions and replacing them with undef.
436 ///
437 class ReduceCrashingInstructions : public ListReducer<const Instruction*> {
438 BugDriver &BD;
Rafael Espindolad1c7ef42010-08-05 03:00:22 +0000439 bool (*TestFn)(const BugDriver &, Module *);
Nick Lewycky6e090c92009-05-25 05:30:00 +0000440 public:
Rafael Espindolad1c7ef42010-08-05 03:00:22 +0000441 ReduceCrashingInstructions(BugDriver &bd,
442 bool (*testFn)(const BugDriver &, Module *))
Nick Lewycky6e090c92009-05-25 05:30:00 +0000443 : BD(bd), TestFn(testFn) {}
444
Craig Toppere56917c2014-03-08 08:27:28 +0000445 TestResult doTest(std::vector<const Instruction*> &Prefix,
446 std::vector<const Instruction*> &Kept,
447 std::string &Error) override {
Nick Lewycky6e090c92009-05-25 05:30:00 +0000448 if (!Kept.empty() && TestInsts(Kept))
449 return KeepSuffix;
450 if (!Prefix.empty() && TestInsts(Prefix))
451 return KeepPrefix;
452 return NoFailure;
453 }
454
455 bool TestInsts(std::vector<const Instruction*> &Prefix);
456 };
457}
458
459bool ReduceCrashingInstructions::TestInsts(std::vector<const Instruction*>
460 &Insts) {
461 // Clone the program to try hacking it apart...
Rafael Espindola229e38f2010-10-13 01:36:30 +0000462 ValueToValueMapTy VMap;
Rafael Espindolacab951d2015-12-08 23:57:17 +0000463 Module *M = CloneModule(BD.getProgram(), VMap).release();
Nick Lewycky6e090c92009-05-25 05:30:00 +0000464
465 // Convert list to set for fast lookup...
Matthias Braunb30f2f512016-01-30 01:24:31 +0000466 SmallPtrSet<Instruction*, 32> Instructions;
Nick Lewycky6e090c92009-05-25 05:30:00 +0000467 for (unsigned i = 0, e = Insts.size(); i != e; ++i) {
468 assert(!isa<TerminatorInst>(Insts[i]));
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000469 Instructions.insert(cast<Instruction>(VMap[Insts[i]]));
Nick Lewycky6e090c92009-05-25 05:30:00 +0000470 }
471
Dan Gohmanee051522009-07-16 15:30:09 +0000472 outs() << "Checking for crash with only " << Instructions.size();
Nick Lewycky6e090c92009-05-25 05:30:00 +0000473 if (Instructions.size() == 1)
Dan Gohmanee051522009-07-16 15:30:09 +0000474 outs() << " instruction: ";
Nick Lewycky6e090c92009-05-25 05:30:00 +0000475 else
Dan Gohmanee051522009-07-16 15:30:09 +0000476 outs() << " instructions: ";
Nick Lewycky6e090c92009-05-25 05:30:00 +0000477
478 for (Module::iterator MI = M->begin(), ME = M->end(); MI != ME; ++MI)
479 for (Function::iterator FI = MI->begin(), FE = MI->end(); FI != FE; ++FI)
480 for (BasicBlock::iterator I = FI->begin(), E = FI->end(); I != E;) {
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000481 Instruction *Inst = &*I++;
Eli Friedmand4e02a52011-11-01 04:40:56 +0000482 if (!Instructions.count(Inst) && !isa<TerminatorInst>(Inst) &&
Philip Reames29e641c2016-06-29 00:15:35 +0000483 !Inst->isEHPad() && !Inst->getType()->isTokenTy()) {
484 if (!Inst->getType()->isVoidTy())
Nick Lewycky6e090c92009-05-25 05:30:00 +0000485 Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
486 Inst->eraseFromParent();
487 }
488 }
489
490 // Verify that this is still valid.
Chandler Carruth30d69c22015-02-13 10:01:29 +0000491 legacy::PassManager Passes;
Nick Lewycky6e090c92009-05-25 05:30:00 +0000492 Passes.add(createVerifierPass());
493 Passes.run(*M);
494
495 // Try running on the hacked up program...
496 if (TestFn(BD, M)) {
497 BD.setNewProgram(M); // It crashed, keep the trimmed version...
498
499 // Make sure to use instruction pointers that point into the now-current
500 // module, and that they don't include any deleted blocks.
501 Insts.clear();
Craig Topper46276792014-08-24 23:23:06 +0000502 for (Instruction *Inst : Instructions)
503 Insts.push_back(Inst);
Nick Lewycky6e090c92009-05-25 05:30:00 +0000504 return true;
505 }
506 delete M; // It didn't crash, try something else.
507 return false;
508}
509
Keno Fischer34ca8312015-11-06 00:12:50 +0000510namespace {
511// Reduce the list of Named Metadata nodes. We keep this as a list of
512// names to avoid having to convert back and forth every time.
513class ReduceCrashingNamedMD : public ListReducer<std::string> {
514 BugDriver &BD;
515 bool (*TestFn)(const BugDriver &, Module *);
516
517public:
518 ReduceCrashingNamedMD(BugDriver &bd,
519 bool (*testFn)(const BugDriver &, Module *))
520 : BD(bd), TestFn(testFn) {}
521
522 TestResult doTest(std::vector<std::string> &Prefix,
523 std::vector<std::string> &Kept,
524 std::string &Error) override {
525 if (!Kept.empty() && TestNamedMDs(Kept))
526 return KeepSuffix;
527 if (!Prefix.empty() && TestNamedMDs(Prefix))
528 return KeepPrefix;
529 return NoFailure;
530 }
531
532 bool TestNamedMDs(std::vector<std::string> &NamedMDs);
533};
534}
535
536bool ReduceCrashingNamedMD::TestNamedMDs(std::vector<std::string> &NamedMDs) {
537
538 ValueToValueMapTy VMap;
Rafael Espindolacab951d2015-12-08 23:57:17 +0000539 Module *M = CloneModule(BD.getProgram(), VMap).release();
Keno Fischer34ca8312015-11-06 00:12:50 +0000540
541 outs() << "Checking for crash with only these named metadata nodes:";
542 unsigned NumPrint = std::min<size_t>(NamedMDs.size(), 10);
543 for (unsigned i = 0, e = NumPrint; i != e; ++i)
544 outs() << " " << NamedMDs[i];
545 if (NumPrint < NamedMDs.size())
546 outs() << "... <" << NamedMDs.size() << " total>";
547 outs() << ": ";
548
549 // Make a StringMap for faster lookup
550 StringSet<> Names;
551 for (const std::string &Name : NamedMDs)
552 Names.insert(Name);
553
554 // First collect all the metadata to delete in a vector, then
555 // delete them all at once to avoid invalidating the iterator
556 std::vector<NamedMDNode *> ToDelete;
557 ToDelete.reserve(M->named_metadata_size() - Names.size());
558 for (auto &NamedMD : M->named_metadata())
Adrian Prantlfaebbb02016-03-28 21:06:26 +0000559 // Always keep a nonempty llvm.dbg.cu because the Verifier would complain.
560 if (!Names.count(NamedMD.getName()) &&
561 (!(NamedMD.getName() == "llvm.dbg.cu" && NamedMD.getNumOperands() > 0)))
Keno Fischer34ca8312015-11-06 00:12:50 +0000562 ToDelete.push_back(&NamedMD);
563
564 for (auto *NamedMD : ToDelete)
565 NamedMD->eraseFromParent();
566
567 // Verify that this is still valid.
568 legacy::PassManager Passes;
569 Passes.add(createVerifierPass());
570 Passes.run(*M);
571
572 // Try running on the hacked up program...
573 if (TestFn(BD, M)) {
574 BD.setNewProgram(M); // It crashed, keep the trimmed version...
575 return true;
576 }
577 delete M; // It didn't crash, try something else.
578 return false;
579}
580
581namespace {
582// Reduce the list of operands to named metadata nodes
583class ReduceCrashingNamedMDOps : public ListReducer<const MDNode *> {
584 BugDriver &BD;
585 bool (*TestFn)(const BugDriver &, Module *);
586
587public:
588 ReduceCrashingNamedMDOps(BugDriver &bd,
589 bool (*testFn)(const BugDriver &, Module *))
590 : BD(bd), TestFn(testFn) {}
591
592 TestResult doTest(std::vector<const MDNode *> &Prefix,
593 std::vector<const MDNode *> &Kept,
594 std::string &Error) override {
595 if (!Kept.empty() && TestNamedMDOps(Kept))
596 return KeepSuffix;
597 if (!Prefix.empty() && TestNamedMDOps(Prefix))
598 return KeepPrefix;
599 return NoFailure;
600 }
601
602 bool TestNamedMDOps(std::vector<const MDNode *> &NamedMDOps);
603};
604}
605
606bool ReduceCrashingNamedMDOps::TestNamedMDOps(
607 std::vector<const MDNode *> &NamedMDOps) {
608 // Convert list to set for fast lookup...
Matthias Braunb30f2f512016-01-30 01:24:31 +0000609 SmallPtrSet<const MDNode *, 32> OldMDNodeOps;
Keno Fischer34ca8312015-11-06 00:12:50 +0000610 for (unsigned i = 0, e = NamedMDOps.size(); i != e; ++i) {
611 OldMDNodeOps.insert(NamedMDOps[i]);
612 }
613
614 outs() << "Checking for crash with only " << OldMDNodeOps.size();
615 if (OldMDNodeOps.size() == 1)
616 outs() << " named metadata operand: ";
617 else
618 outs() << " named metadata operands: ";
619
620 ValueToValueMapTy VMap;
Rafael Espindolacab951d2015-12-08 23:57:17 +0000621 Module *M = CloneModule(BD.getProgram(), VMap).release();
Keno Fischer34ca8312015-11-06 00:12:50 +0000622
623 // This is a little wasteful. In the future it might be good if we could have
624 // these dropped during cloning.
625 for (auto &NamedMD : BD.getProgram()->named_metadata()) {
626 // Drop the old one and create a new one
627 M->eraseNamedMetadata(M->getNamedMetadata(NamedMD.getName()));
628 NamedMDNode *NewNamedMDNode =
629 M->getOrInsertNamedMetadata(NamedMD.getName());
630 for (MDNode *op : NamedMD.operands())
631 if (OldMDNodeOps.count(op))
632 NewNamedMDNode->addOperand(cast<MDNode>(MapMetadata(op, VMap)));
633 }
634
635 // Verify that this is still valid.
636 legacy::PassManager Passes;
637 Passes.add(createVerifierPass());
638 Passes.run(*M);
639
640 // Try running on the hacked up program...
641 if (TestFn(BD, M)) {
642 // Make sure to use instruction pointers that point into the now-current
643 // module, and that they don't include any deleted blocks.
644 NamedMDOps.clear();
645 for (const MDNode *Node : OldMDNodeOps)
Duncan P. N. Exon Smithda4a56d2016-04-02 17:04:38 +0000646 NamedMDOps.push_back(cast<MDNode>(*VMap.getMappedMD(Node)));
Keno Fischer34ca8312015-11-06 00:12:50 +0000647
648 BD.setNewProgram(M); // It crashed, keep the trimmed version...
649 return true;
650 }
651 delete M; // It didn't crash, try something else.
652 return false;
653}
654
Philip Reames1c232f92016-06-29 00:43:18 +0000655static void ReduceGlobalInitializers(BugDriver &BD,
656 bool (*TestFn)(const BugDriver &, Module *),
657 std::string &Error) {
658 if (BD.getProgram()->global_begin() != BD.getProgram()->global_end()) {
Bill Wendling3f833432006-10-25 18:36:14 +0000659 // Now try to reduce the number of global variable initializers in the
660 // module to something small.
Rafael Espindolacab951d2015-12-08 23:57:17 +0000661 Module *M = CloneModule(BD.getProgram()).release();
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000662 bool DeletedInit = false;
Misha Brukman650ba8e2005-04-22 00:00:37 +0000663
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000664 for (Module::global_iterator I = M->global_begin(), E = M->global_end();
665 I != E; ++I)
666 if (I->hasInitializer()) {
Hal Finkel28ad2b42015-11-26 19:23:49 +0000667 DeleteGlobalInitializer(&*I);
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000668 I->setLinkage(GlobalValue::ExternalLinkage);
Justin Lebar2a445cf2016-06-15 23:20:12 +0000669 I->setComdat(nullptr);
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000670 DeletedInit = true;
671 }
Bill Wendling3f833432006-10-25 18:36:14 +0000672
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000673 if (!DeletedInit) {
674 delete M; // No change made...
675 } else {
676 // See if the program still causes a crash...
Dan Gohmanee051522009-07-16 15:30:09 +0000677 outs() << "\nChecking to see if we can delete global inits: ";
Bill Wendling3f833432006-10-25 18:36:14 +0000678
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000679 if (TestFn(BD, M)) { // Still crashes?
680 BD.setNewProgram(M);
Dan Gohmanee051522009-07-16 15:30:09 +0000681 outs() << "\n*** Able to remove all global initializers!\n";
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000682 } else { // No longer crashes?
Dan Gohmanee051522009-07-16 15:30:09 +0000683 outs() << " - Removing all global inits hides problem!\n";
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000684 delete M;
Bill Wendling3f833432006-10-25 18:36:14 +0000685
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000686 std::vector<GlobalVariable*> GVs;
687
688 for (Module::global_iterator I = BD.getProgram()->global_begin(),
689 E = BD.getProgram()->global_end(); I != E; ++I)
690 if (I->hasInitializer())
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000691 GVs.push_back(&*I);
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000692
693 if (GVs.size() > 1 && !BugpointIsInterrupted) {
Dan Gohmanee051522009-07-16 15:30:09 +0000694 outs() << "\n*** Attempting to reduce the number of global "
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000695 << "variables in the testcase\n";
696
697 unsigned OldSize = GVs.size();
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000698 ReduceCrashingGlobalVariables(BD, TestFn).reduceList(GVs, Error);
Philip Reames1c232f92016-06-29 00:43:18 +0000699 assert(!Error.empty());
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000700
701 if (GVs.size() < OldSize)
Rafael Espindola594994a2010-07-28 18:12:30 +0000702 BD.EmitProgressBitcode(BD.getProgram(), "reduced-global-variables");
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000703 }
Bill Wendlingce3afd62006-10-27 20:22:04 +0000704 }
Chris Lattner65e5f652003-04-25 00:53:05 +0000705 }
706 }
Philip Reames1c232f92016-06-29 00:43:18 +0000707}
708
709static void ReduceInsts(BugDriver &BD,
710 bool (*TestFn)(const BugDriver &, Module *),
711 std::string &Error) {
712 // Attempt to delete instructions using bisection. This should help out nasty
713 // cases with large basic blocks where the problem is at one end.
714 if (!BugpointIsInterrupted) {
715 std::vector<const Instruction*> Insts;
716 for (const Function &F : *BD.getProgram())
717 for (const BasicBlock &BB : F)
718 for (const Instruction &I : BB)
719 if (!isa<TerminatorInst>(&I))
720 Insts.push_back(&I);
721
722 ReduceCrashingInstructions(BD, TestFn).reduceList(Insts, Error);
723 }
724
725 unsigned Simplification = 2;
726 do {
727 if (BugpointIsInterrupted)
728 return;
729 --Simplification;
730 outs() << "\n*** Attempting to reduce testcase by deleting instruc"
731 << "tions: Simplification Level #" << Simplification << '\n';
732
733 // Now that we have deleted the functions that are unnecessary for the
734 // program, try to remove instructions that are not necessary to cause the
735 // crash. To do this, we loop through all of the instructions in the
736 // remaining functions, deleting them (replacing any values produced with
737 // nulls), and then running ADCE and SimplifyCFG. If the transformed input
738 // still triggers failure, keep deleting until we cannot trigger failure
739 // anymore.
740 //
741 unsigned InstructionsToSkipBeforeDeleting = 0;
742 TryAgain:
743
744 // Loop over all of the (non-terminator) instructions remaining in the
745 // function, attempting to delete them.
746 unsigned CurInstructionNum = 0;
747 for (Module::const_iterator FI = BD.getProgram()->begin(),
748 E = BD.getProgram()->end(); FI != E; ++FI)
749 if (!FI->isDeclaration())
750 for (Function::const_iterator BI = FI->begin(), E = FI->end(); BI != E;
751 ++BI)
752 for (BasicBlock::const_iterator I = BI->begin(), E = --BI->end();
753 I != E; ++I, ++CurInstructionNum) {
754 if (InstructionsToSkipBeforeDeleting) {
755 --InstructionsToSkipBeforeDeleting;
756 } else {
757 if (BugpointIsInterrupted)
758 return;
759
760 if (I->isEHPad() || I->getType()->isTokenTy())
761 continue;
762
763 outs() << "Checking instruction: " << *I;
764 std::unique_ptr<Module> M =
765 BD.deleteInstructionFromProgram(&*I, Simplification);
766
767 // Find out if the pass still crashes on this pass...
768 if (TestFn(BD, M.get())) {
769 // Yup, it does, we delete the old module, and continue trying
770 // to reduce the testcase...
771 BD.setNewProgram(M.release());
772 InstructionsToSkipBeforeDeleting = CurInstructionNum;
773 goto TryAgain; // I wish I had a multi-level break here!
774 }
775 }
776 }
777
778 if (InstructionsToSkipBeforeDeleting) {
779 InstructionsToSkipBeforeDeleting = 0;
780 goto TryAgain;
781 }
782
783 } while (Simplification);
784 BD.EmitProgressBitcode(BD.getProgram(), "reduced-instructions");
785}
786
787
788/// DebugACrash - Given a predicate that determines whether a component crashes
789/// on a program, try to destructively reduce the program while still keeping
790/// the predicate true.
791static bool DebugACrash(BugDriver &BD,
792 bool (*TestFn)(const BugDriver &, Module *),
793 std::string &Error) {
794 // See if we can get away with nuking some of the global variable initializers
795 // in the program...
796 if (!NoGlobalRM)
797 ReduceGlobalInitializers(BD, TestFn, Error);
Misha Brukman650ba8e2005-04-22 00:00:37 +0000798
Chris Lattner1d080f22003-04-24 22:24:58 +0000799 // Now try to reduce the number of functions in the module to something small.
Chris Lattnerfd72bed2004-03-14 20:50:42 +0000800 std::vector<Function*> Functions;
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000801 for (Function &F : *BD.getProgram())
802 if (!F.isDeclaration())
803 Functions.push_back(&F);
Chris Lattner73a6bdd2002-11-20 22:28:10 +0000804
Chris Lattnerbeb01fa2005-08-02 02:16:17 +0000805 if (Functions.size() > 1 && !BugpointIsInterrupted) {
Dan Gohmanee051522009-07-16 15:30:09 +0000806 outs() << "\n*** Attempting to reduce the number of functions "
Chris Lattner1d080f22003-04-24 22:24:58 +0000807 "in the testcase\n";
Chris Lattner73a6bdd2002-11-20 22:28:10 +0000808
Chris Lattner8bda4c42004-02-18 23:26:28 +0000809 unsigned OldSize = Functions.size();
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000810 ReduceCrashingFunctions(BD, TestFn).reduceList(Functions, Error);
Chris Lattner73a6bdd2002-11-20 22:28:10 +0000811
Chris Lattnerbeb01fa2005-08-02 02:16:17 +0000812 if (Functions.size() < OldSize)
Rafael Espindola594994a2010-07-28 18:12:30 +0000813 BD.EmitProgressBitcode(BD.getProgram(), "reduced-function");
Chris Lattner73a6bdd2002-11-20 22:28:10 +0000814 }
815
Chris Lattnerf32939b2003-04-24 23:51:38 +0000816 // Attempt to delete entire basic blocks at a time to speed up
817 // convergence... this actually works by setting the terminator of the blocks
818 // to a return instruction then running simplifycfg, which can potentially
819 // shrinks the code dramatically quickly
820 //
Chris Lattnerbeb01fa2005-08-02 02:16:17 +0000821 if (!DisableSimplifyCFG && !BugpointIsInterrupted) {
Chris Lattner8bda4c42004-02-18 23:26:28 +0000822 std::vector<const BasicBlock*> Blocks;
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000823 for (Function &F : *BD.getProgram())
824 for (BasicBlock &BB : F)
825 Blocks.push_back(&BB);
Torok Edwin6ee6f732009-05-24 09:40:47 +0000826 unsigned OldSize = Blocks.size();
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000827 ReduceCrashingBlocks(BD, TestFn).reduceList(Blocks, Error);
Torok Edwin6ee6f732009-05-24 09:40:47 +0000828 if (Blocks.size() < OldSize)
Rafael Espindola594994a2010-07-28 18:12:30 +0000829 BD.EmitProgressBitcode(BD.getProgram(), "reduced-blocks");
Chris Lattnerd1e2aae2003-08-05 15:51:05 +0000830 }
Chris Lattnerd4e04742002-12-23 23:49:59 +0000831
Nick Lewycky6e090c92009-05-25 05:30:00 +0000832 // Attempt to delete instructions using bisection. This should help out nasty
833 // cases with large basic blocks where the problem is at one end.
Philip Reames1c232f92016-06-29 00:43:18 +0000834 if (!BugpointIsInterrupted)
835 ReduceInsts(BD, TestFn, Error);
Keno Fischer34ca8312015-11-06 00:12:50 +0000836
837 if (!NoNamedMDRM) {
Keno Fischer34ca8312015-11-06 00:12:50 +0000838 if (!BugpointIsInterrupted) {
839 // Try to reduce the amount of global metadata (particularly debug info),
840 // by dropping global named metadata that anchors them
841 outs() << "\n*** Attempting to remove named metadata: ";
842 std::vector<std::string> NamedMDNames;
843 for (auto &NamedMD : BD.getProgram()->named_metadata())
844 NamedMDNames.push_back(NamedMD.getName().str());
845 ReduceCrashingNamedMD(BD, TestFn).reduceList(NamedMDNames, Error);
846 }
847
848 if (!BugpointIsInterrupted) {
849 // Now that we quickly dropped all the named metadata that doesn't
850 // contribute to the crash, bisect the operands of the remaining ones
851 std::vector<const MDNode *> NamedMDOps;
852 for (auto &NamedMD : BD.getProgram()->named_metadata())
Keno Fischer256df862015-11-06 00:45:47 +0000853 for (auto op : NamedMD.operands())
854 NamedMDOps.push_back(op);
Keno Fischer34ca8312015-11-06 00:12:50 +0000855 ReduceCrashingNamedMDOps(BD, TestFn).reduceList(NamedMDOps, Error);
856 }
Philip Reamesac285cc2016-06-29 00:10:39 +0000857 BD.EmitProgressBitcode(BD.getProgram(), "reduced-named-md");
Keno Fischer34ca8312015-11-06 00:12:50 +0000858 }
859
Chris Lattner514c02e2003-02-28 16:13:20 +0000860 // Try to clean up the testcase by running funcresolve and globaldce...
Chris Lattnerbeb01fa2005-08-02 02:16:17 +0000861 if (!BugpointIsInterrupted) {
Dan Gohmanee051522009-07-16 15:30:09 +0000862 outs() << "\n*** Attempting to perform final cleanups: ";
Rafael Espindolacab951d2015-12-08 23:57:17 +0000863 Module *M = CloneModule(BD.getProgram()).release();
Rafael Espindola28b351a2014-08-26 17:19:03 +0000864 M = BD.performFinalCleanups(M, true).release();
Misha Brukman650ba8e2005-04-22 00:00:37 +0000865
Chris Lattnerbeb01fa2005-08-02 02:16:17 +0000866 // Find out if the pass still crashes on the cleaned up program...
867 if (TestFn(BD, M)) {
868 BD.setNewProgram(M); // Yup, it does, keep the reduced version...
869 } else {
870 delete M;
871 }
Chris Lattner514c02e2003-02-28 16:13:20 +0000872 }
873
Rafael Espindola594994a2010-07-28 18:12:30 +0000874 BD.EmitProgressBitcode(BD.getProgram(), "reduced-simplified");
Chris Lattner514c02e2003-02-28 16:13:20 +0000875
Misha Brukman650ba8e2005-04-22 00:00:37 +0000876 return false;
Chris Lattner73a6bdd2002-11-20 22:28:10 +0000877}
Brian Gaeke960707c2003-11-11 22:41:34 +0000878
Rafael Espindolad1c7ef42010-08-05 03:00:22 +0000879static bool TestForOptimizerCrash(const BugDriver &BD, Module *M) {
Philip Reamese5b56022016-06-29 03:01:13 +0000880 return BD.runPasses(M, BD.getPassesToRun());
Chris Lattner8bda4c42004-02-18 23:26:28 +0000881}
Chris Lattneread1dff2004-02-18 21:02:04 +0000882
Chris Lattner8bda4c42004-02-18 23:26:28 +0000883/// debugOptimizerCrash - This method is called when some pass crashes on input.
884/// It attempts to prune down the testcase to something reasonable, and figure
885/// out exactly which pass is crashing.
886///
Patrick Jenkinsc46c0382006-08-15 16:40:49 +0000887bool BugDriver::debugOptimizerCrash(const std::string &ID) {
Dan Gohmanee051522009-07-16 15:30:09 +0000888 outs() << "\n*** Debugging optimizer crash!\n";
Chris Lattner8bda4c42004-02-18 23:26:28 +0000889
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000890 std::string Error;
Chris Lattner8bda4c42004-02-18 23:26:28 +0000891 // Reduce the list of passes which causes the optimizer to crash...
JF Bastienf87e20d2015-04-20 23:42:22 +0000892 if (!BugpointIsInterrupted && !DontReducePassList)
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000893 ReducePassList(*this).reduceList(PassesToRun, Error);
894 assert(Error.empty());
Chris Lattner8bda4c42004-02-18 23:26:28 +0000895
Dan Gohmanee051522009-07-16 15:30:09 +0000896 outs() << "\n*** Found crashing pass"
897 << (PassesToRun.size() == 1 ? ": " : "es: ")
898 << getPassesString(PassesToRun) << '\n';
Chris Lattner8bda4c42004-02-18 23:26:28 +0000899
Rafael Espindola594994a2010-07-28 18:12:30 +0000900 EmitProgressBitcode(Program, ID);
Chris Lattner8bda4c42004-02-18 23:26:28 +0000901
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000902 bool Success = DebugACrash(*this, TestForOptimizerCrash, Error);
903 assert(Error.empty());
904 return Success;
Chris Lattner8bda4c42004-02-18 23:26:28 +0000905}
906
Rafael Espindolad1c7ef42010-08-05 03:00:22 +0000907static bool TestForCodeGenCrash(const BugDriver &BD, Module *M) {
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000908 std::string Error;
909 BD.compileProgram(M, &Error);
910 if (!Error.empty()) {
Sebastian Pop8f7d0192016-07-15 23:15:06 +0000911 if (VerboseErrors)
912 errs() << Error << "\n";
913 else
914 errs() << "<crash>\n";
Chris Lattner8bda4c42004-02-18 23:26:28 +0000915 return true; // Tool is still crashing.
916 }
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000917 errs() << '\n';
918 return false;
Chris Lattner8bda4c42004-02-18 23:26:28 +0000919}
Chris Lattneread1dff2004-02-18 21:02:04 +0000920
921/// debugCodeGeneratorCrash - This method is called when the code generator
922/// crashes on an input. It attempts to reduce the input as much as possible
923/// while still causing the code generator to crash.
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000924bool BugDriver::debugCodeGeneratorCrash(std::string &Error) {
Dan Gohmand8db3762009-07-15 16:35:29 +0000925 errs() << "*** Debugging code generator crash!\n";
Chris Lattneread1dff2004-02-18 21:02:04 +0000926
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000927 return DebugACrash(*this, TestForCodeGenCrash, Error);
Chris Lattneread1dff2004-02-18 21:02:04 +0000928}