blob: 0cae0669477f2f5be640ca44cd384c771d9eb516 [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"
Justin Bogner8d0a0812016-09-02 01:21:37 +000019#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000020#include "llvm/IR/CFG.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000021#include "llvm/IR/Constants.h"
Michael Ilsemane5428042016-10-25 18:44:13 +000022#include "llvm/IR/DebugInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/DerivedTypes.h"
24#include "llvm/IR/Instructions.h"
Chandler Carruth30d69c22015-02-13 10:01:29 +000025#include "llvm/IR/LegacyPassManager.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/Module.h"
27#include "llvm/IR/ValueSymbolTable.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000028#include "llvm/IR/Verifier.h"
Misha Brukman0c2305b2003-08-07 21:19:30 +000029#include "llvm/Pass.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000030#include "llvm/Support/CommandLine.h"
31#include "llvm/Support/FileUtilities.h"
Chris Lattnerf32939b2003-04-24 23:51:38 +000032#include "llvm/Transforms/Scalar.h"
Daniel Berlin271ca402016-07-27 16:13:25 +000033#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattner1d080f22003-04-24 22:24:58 +000034#include "llvm/Transforms/Utils/Cloning.h"
Daniel Berlin271ca402016-07-27 16:13:25 +000035#include "llvm/Transforms/Utils/Local.h"
Chris Lattner1d080f22003-04-24 22:24:58 +000036#include <set>
Chris Lattner2f1aa112004-01-14 03:38:37 +000037using namespace llvm;
Chris Lattner73a6bdd2002-11-20 22:28:10 +000038
Andrew Lenharthef9aa122006-03-05 22:21:36 +000039namespace {
Justin Bogner8d0a0812016-09-02 01:21:37 +000040cl::opt<bool> KeepMain("keep-main",
41 cl::desc("Force function reduction to keep main"),
42 cl::init(false));
43cl::opt<bool> NoGlobalRM("disable-global-remove",
44 cl::desc("Do not remove global variables"),
45 cl::init(false));
JF Bastienf87e20d2015-04-20 23:42:22 +000046
Justin Bogner8d0a0812016-09-02 01:21:37 +000047cl::opt<bool> ReplaceFuncsWithNull(
48 "replace-funcs-with-null",
49 cl::desc("When stubbing functions, replace all uses will null"),
50 cl::init(false));
51cl::opt<bool> DontReducePassList("disable-pass-list-reduction",
52 cl::desc("Skip pass list reduction steps"),
53 cl::init(false));
Keno Fischer34ca8312015-11-06 00:12:50 +000054
Justin Bogner8d0a0812016-09-02 01:21:37 +000055cl::opt<bool> NoNamedMDRM("disable-namedmd-remove",
56 cl::desc("Do not remove global named metadata"),
57 cl::init(false));
Michael Ilsemane5428042016-10-25 18:44:13 +000058cl::opt<bool> NoStripDebugInfo("disable-strip-debuginfo",
59 cl::desc("Do not strip debug info metadata"),
60 cl::init(false));
61cl::opt<bool> NoStripDebugTypeInfo("disable-strip-debug-types",
62 cl::desc("Do not strip debug type info metadata"),
63 cl::init(false));
Justin Bogner8d0a0812016-09-02 01:21:37 +000064cl::opt<bool> VerboseErrors("verbose-errors",
Sebastian Pop8f7d0192016-07-15 23:15:06 +000065 cl::desc("Print the output of crashing program"),
66 cl::init(false));
Andrew Lenharthef9aa122006-03-05 22:21:36 +000067}
68
Brian Gaeke960707c2003-11-11 22:41:34 +000069namespace llvm {
Justin Bogner8d0a0812016-09-02 01:21:37 +000070class ReducePassList : public ListReducer<std::string> {
71 BugDriver &BD;
Misha Brukman650ba8e2005-04-22 00:00:37 +000072
Justin Bogner8d0a0812016-09-02 01:21:37 +000073public:
74 ReducePassList(BugDriver &bd) : BD(bd) {}
75
Justin Bogner1c039152016-09-06 17:18:22 +000076 // Return true iff running the "removed" passes succeeds, and running the
77 // "Kept" passes fail when run on the output of the "removed" passes. If we
78 // return true, we update the current module of bugpoint.
79 Expected<TestResult> doTest(std::vector<std::string> &Removed,
80 std::vector<std::string> &Kept) override;
Justin Bogner8d0a0812016-09-02 01:21:37 +000081};
Chris Lattner2f1aa112004-01-14 03:38:37 +000082}
Chris Lattner1d080f22003-04-24 22:24:58 +000083
Justin Bogner1c039152016-09-06 17:18:22 +000084Expected<ReducePassList::TestResult>
Rafael Espindola33e81a82010-08-08 03:55:08 +000085ReducePassList::doTest(std::vector<std::string> &Prefix,
Justin Bogner1c039152016-09-06 17:18:22 +000086 std::vector<std::string> &Suffix) {
Rafael Espindolabb876652013-06-17 19:33:18 +000087 std::string PrefixOutput;
Craig Toppere6cb63e2014-04-25 04:24:47 +000088 Module *OrigProgram = nullptr;
Chris Lattner1d080f22003-04-24 22:24:58 +000089 if (!Prefix.empty()) {
Dan Gohmanee051522009-07-16 15:30:09 +000090 outs() << "Checking to see if these passes crash: "
91 << getPassesString(Prefix) << ": ";
Rafael Espindolabb876652013-06-17 19:33:18 +000092 if (BD.runPasses(BD.getProgram(), Prefix, PrefixOutput))
Chris Lattner1d080f22003-04-24 22:24:58 +000093 return KeepPrefix;
Chris Lattnera9656312003-06-02 04:54:29 +000094
95 OrigProgram = BD.Program;
96
Rafael Espindola28b351a2014-08-26 17:19:03 +000097 BD.Program = parseInputFile(PrefixOutput, BD.getContext()).release();
Craig Toppere6cb63e2014-04-25 04:24:47 +000098 if (BD.Program == nullptr) {
Dan Gohmand8db3762009-07-15 16:35:29 +000099 errs() << BD.getToolName() << ": Error reading bitcode file '"
Rafael Espindolabb876652013-06-17 19:33:18 +0000100 << PrefixOutput << "'!\n";
Chris Lattnera9656312003-06-02 04:54:29 +0000101 exit(1);
102 }
Rafael Espindolabb876652013-06-17 19:33:18 +0000103 sys::fs::remove(PrefixOutput);
Chris Lattner1d080f22003-04-24 22:24:58 +0000104 }
105
Justin Bogner8d0a0812016-09-02 01:21:37 +0000106 outs() << "Checking to see if these passes crash: " << getPassesString(Suffix)
107 << ": ";
Misha Brukman650ba8e2005-04-22 00:00:37 +0000108
Rafael Espindola37302ea2010-08-05 02:16:32 +0000109 if (BD.runPasses(BD.getProgram(), Suffix)) {
Justin Bogner8d0a0812016-09-02 01:21:37 +0000110 delete OrigProgram; // The suffix crashes alone...
Chris Lattner1d080f22003-04-24 22:24:58 +0000111 return KeepSuffix;
112 }
113
114 // Nothing failed, restore state...
Chris Lattnera9656312003-06-02 04:54:29 +0000115 if (OrigProgram) {
116 delete BD.Program;
117 BD.Program = OrigProgram;
118 }
Chris Lattner1d080f22003-04-24 22:24:58 +0000119 return NoFailure;
120}
121
Bill Wendling3f833432006-10-25 18:36:14 +0000122namespace {
Justin Bogner8d0a0812016-09-02 01:21:37 +0000123/// ReduceCrashingGlobalVariables - This works by removing the global
124/// variable's initializer and seeing if the program still crashes. If it
125/// does, then we keep that program and try again.
126///
127class ReduceCrashingGlobalVariables : public ListReducer<GlobalVariable *> {
128 BugDriver &BD;
129 bool (*TestFn)(const BugDriver &, Module *);
130
131public:
132 ReduceCrashingGlobalVariables(BugDriver &bd,
133 bool (*testFn)(const BugDriver &, Module *))
Bill Wendling3f833432006-10-25 18:36:14 +0000134 : BD(bd), TestFn(testFn) {}
135
Justin Bogner1c039152016-09-06 17:18:22 +0000136 Expected<TestResult> doTest(std::vector<GlobalVariable *> &Prefix,
137 std::vector<GlobalVariable *> &Kept) override {
Justin Bogner8d0a0812016-09-02 01:21:37 +0000138 if (!Kept.empty() && TestGlobalVariables(Kept))
139 return KeepSuffix;
140 if (!Prefix.empty() && TestGlobalVariables(Prefix))
141 return KeepPrefix;
142 return NoFailure;
143 }
Bill Wendling3f833432006-10-25 18:36:14 +0000144
Justin Bogner8d0a0812016-09-02 01:21:37 +0000145 bool TestGlobalVariables(std::vector<GlobalVariable *> &GVs);
146};
Bill Wendling3f833432006-10-25 18:36:14 +0000147}
148
Justin Bogner8d0a0812016-09-02 01:21:37 +0000149bool ReduceCrashingGlobalVariables::TestGlobalVariables(
150 std::vector<GlobalVariable *> &GVs) {
Bill Wendling3f833432006-10-25 18:36:14 +0000151 // Clone the program to try hacking it apart...
Rafael Espindola229e38f2010-10-13 01:36:30 +0000152 ValueToValueMapTy VMap;
Rafael Espindolacab951d2015-12-08 23:57:17 +0000153 Module *M = CloneModule(BD.getProgram(), VMap).release();
Bill Wendling3f833432006-10-25 18:36:14 +0000154
155 // Convert list to set for fast lookup...
Justin Bogner8d0a0812016-09-02 01:21:37 +0000156 std::set<GlobalVariable *> GVSet;
Bill Wendling3f833432006-10-25 18:36:14 +0000157
158 for (unsigned i = 0, e = GVs.size(); i != e; ++i) {
Justin Bogner8d0a0812016-09-02 01:21:37 +0000159 GlobalVariable *CMGV = cast<GlobalVariable>(VMap[GVs[i]]);
Bill Wendling3f833432006-10-25 18:36:14 +0000160 assert(CMGV && "Global Variable not in module?!");
161 GVSet.insert(CMGV);
162 }
163
Dan Gohmanee051522009-07-16 15:30:09 +0000164 outs() << "Checking for crash with only these global variables: ";
Bill Wendling3f833432006-10-25 18:36:14 +0000165 PrintGlobalVariableList(GVs);
Dan Gohmanee051522009-07-16 15:30:09 +0000166 outs() << ": ";
Bill Wendling3f833432006-10-25 18:36:14 +0000167
168 // Loop over and delete any global variables which we aren't supposed to be
169 // playing with...
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000170 for (GlobalVariable &I : M->globals())
171 if (I.hasInitializer() && !GVSet.count(&I)) {
Hal Finkel28ad2b42015-11-26 19:23:49 +0000172 DeleteGlobalInitializer(&I);
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000173 I.setLinkage(GlobalValue::ExternalLinkage);
Justin Lebar2a445cf2016-06-15 23:20:12 +0000174 I.setComdat(nullptr);
Bill Wendling3f833432006-10-25 18:36:14 +0000175 }
176
177 // Try running the hacked up program...
178 if (TestFn(BD, M)) {
Justin Bogner8d0a0812016-09-02 01:21:37 +0000179 BD.setNewProgram(M); // It crashed, keep the trimmed version...
Bill Wendling3f833432006-10-25 18:36:14 +0000180
181 // Make sure to use global variable pointers that point into the now-current
182 // module.
183 GVs.assign(GVSet.begin(), GVSet.end());
184 return true;
185 }
186
187 delete M;
188 return false;
189}
190
David Blaikiea379b1812011-12-20 02:50:00 +0000191namespace {
Justin Bogner8d0a0812016-09-02 01:21:37 +0000192/// ReduceCrashingFunctions reducer - This works by removing functions and
193/// seeing if the program still crashes. If it does, then keep the newer,
194/// smaller program.
195///
196class ReduceCrashingFunctions : public ListReducer<Function *> {
197 BugDriver &BD;
198 bool (*TestFn)(const BugDriver &, Module *);
199
200public:
201 ReduceCrashingFunctions(BugDriver &bd,
202 bool (*testFn)(const BugDriver &, Module *))
Chris Lattner8bda4c42004-02-18 23:26:28 +0000203 : BD(bd), TestFn(testFn) {}
Misha Brukman650ba8e2005-04-22 00:00:37 +0000204
Justin Bogner1c039152016-09-06 17:18:22 +0000205 Expected<TestResult> doTest(std::vector<Function *> &Prefix,
206 std::vector<Function *> &Kept) override {
Justin Bogner8d0a0812016-09-02 01:21:37 +0000207 if (!Kept.empty() && TestFuncs(Kept))
208 return KeepSuffix;
209 if (!Prefix.empty() && TestFuncs(Prefix))
210 return KeepPrefix;
211 return NoFailure;
212 }
Misha Brukman650ba8e2005-04-22 00:00:37 +0000213
Justin Bogner8d0a0812016-09-02 01:21:37 +0000214 bool TestFuncs(std::vector<Function *> &Prefix);
215};
Chris Lattner2f1aa112004-01-14 03:38:37 +0000216}
Chris Lattner1d080f22003-04-24 22:24:58 +0000217
Justin Bogner8d0a0812016-09-02 01:21:37 +0000218static void RemoveFunctionReferences(Module *M, const char *Name) {
JF Bastienf87e20d2015-04-20 23:42:22 +0000219 auto *UsedVar = M->getGlobalVariable(Name, true);
Justin Bogner8d0a0812016-09-02 01:21:37 +0000220 if (!UsedVar || !UsedVar->hasInitializer())
221 return;
JF Bastienf87e20d2015-04-20 23:42:22 +0000222 if (isa<ConstantAggregateZero>(UsedVar->getInitializer())) {
223 assert(UsedVar->use_empty());
224 UsedVar->eraseFromParent();
225 return;
226 }
227 auto *OldUsedVal = cast<ConstantArray>(UsedVar->getInitializer());
Justin Bogner8d0a0812016-09-02 01:21:37 +0000228 std::vector<Constant *> Used;
229 for (Value *V : OldUsedVal->operand_values()) {
JF Bastienf87e20d2015-04-20 23:42:22 +0000230 Constant *Op = cast<Constant>(V->stripPointerCasts());
Justin Bogner8d0a0812016-09-02 01:21:37 +0000231 if (!Op->isNullValue()) {
JF Bastienf87e20d2015-04-20 23:42:22 +0000232 Used.push_back(cast<Constant>(V));
233 }
234 }
235 auto *NewValElemTy = OldUsedVal->getType()->getElementType();
236 auto *NewValTy = ArrayType::get(NewValElemTy, Used.size());
237 auto *NewUsedVal = ConstantArray::get(NewValTy, Used);
238 UsedVar->mutateType(NewUsedVal->getType()->getPointerTo());
239 UsedVar->setInitializer(NewUsedVal);
240}
241
Justin Bogner8d0a0812016-09-02 01:21:37 +0000242bool ReduceCrashingFunctions::TestFuncs(std::vector<Function *> &Funcs) {
Dmitri Gribenko6e0520e2013-09-02 01:18:56 +0000243 // If main isn't present, claim there is no problem.
David Majnemer0d955d02016-08-11 22:21:41 +0000244 if (KeepMain && !is_contained(Funcs, BD.getProgram()->getFunction("main")))
Andrew Lenharthef9aa122006-03-05 22:21:36 +0000245 return false;
246
Misha Brukman8b2bd4e2003-10-10 17:57:28 +0000247 // Clone the program to try hacking it apart...
Rafael Espindola229e38f2010-10-13 01:36:30 +0000248 ValueToValueMapTy VMap;
Rafael Espindolacab951d2015-12-08 23:57:17 +0000249 Module *M = CloneModule(BD.getProgram(), VMap).release();
Misha Brukman650ba8e2005-04-22 00:00:37 +0000250
Chris Lattner1d080f22003-04-24 22:24:58 +0000251 // Convert list to set for fast lookup...
Justin Bogner8d0a0812016-09-02 01:21:37 +0000252 std::set<Function *> Functions;
Chris Lattner1d080f22003-04-24 22:24:58 +0000253 for (unsigned i = 0, e = Funcs.size(); i != e; ++i) {
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000254 Function *CMF = cast<Function>(VMap[Funcs[i]]);
Chris Lattner1d080f22003-04-24 22:24:58 +0000255 assert(CMF && "Function not in module?!");
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000256 assert(CMF->getFunctionType() == Funcs[i]->getFunctionType() && "wrong ty");
Dan Gohmanbcad7182009-03-06 02:16:23 +0000257 assert(CMF->getName() == Funcs[i]->getName() && "wrong name");
Chris Lattnerde39f2b2003-04-24 22:54:06 +0000258 Functions.insert(CMF);
Chris Lattner1d080f22003-04-24 22:24:58 +0000259 }
260
Dan Gohmanee051522009-07-16 15:30:09 +0000261 outs() << "Checking for crash with only these functions: ";
Chris Lattnerfd72bed2004-03-14 20:50:42 +0000262 PrintFunctionList(Funcs);
Dan Gohmanee051522009-07-16 15:30:09 +0000263 outs() << ": ";
JF Bastienf87e20d2015-04-20 23:42:22 +0000264 if (!ReplaceFuncsWithNull) {
265 // Loop over and delete any functions which we aren't supposed to be playing
266 // with...
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000267 for (Function &I : *M)
268 if (!I.isDeclaration() && !Functions.count(&I))
269 DeleteFunctionBody(&I);
JF Bastienf87e20d2015-04-20 23:42:22 +0000270 } else {
Justin Bogner8d0a0812016-09-02 01:21:37 +0000271 std::vector<GlobalValue *> ToRemove;
JF Bastienf87e20d2015-04-20 23:42:22 +0000272 // First, remove aliases to functions we're about to purge.
273 for (GlobalAlias &Alias : M->aliases()) {
David Majnemer95549492016-05-04 00:20:48 +0000274 GlobalObject *Root = Alias.getBaseObject();
275 Function *F = dyn_cast_or_null<Function>(Root);
JF Bastienf87e20d2015-04-20 23:42:22 +0000276 if (F) {
277 if (Functions.count(F))
278 // We're keeping this function.
279 continue;
280 } else if (Root->isNullValue()) {
281 // This referenced a globalalias that we've already replaced,
282 // so we still need to replace this alias.
283 } else if (!F) {
284 // Not a function, therefore not something we mess with.
285 continue;
286 }
Chris Lattner1d080f22003-04-24 22:24:58 +0000287
JF Bastienf87e20d2015-04-20 23:42:22 +0000288 PointerType *Ty = cast<PointerType>(Alias.getType());
289 Constant *Replacement = ConstantPointerNull::get(Ty);
290 Alias.replaceAllUsesWith(Replacement);
291 ToRemove.push_back(&Alias);
292 }
Chris Lattner1d080f22003-04-24 22:24:58 +0000293
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000294 for (Function &I : *M) {
295 if (!I.isDeclaration() && !Functions.count(&I)) {
296 PointerType *Ty = cast<PointerType>(I.getType());
JF Bastienf87e20d2015-04-20 23:42:22 +0000297 Constant *Replacement = ConstantPointerNull::get(Ty);
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000298 I.replaceAllUsesWith(Replacement);
299 ToRemove.push_back(&I);
JF Bastienf87e20d2015-04-20 23:42:22 +0000300 }
301 }
302
303 for (auto *F : ToRemove) {
304 F->eraseFromParent();
305 }
306
307 // Finally, remove any null members from any global intrinsic.
308 RemoveFunctionReferences(M, "llvm.used");
309 RemoveFunctionReferences(M, "llvm.compiler.used");
310 }
Chris Lattner1d080f22003-04-24 22:24:58 +0000311 // Try running the hacked up program...
Chris Lattner8bda4c42004-02-18 23:26:28 +0000312 if (TestFn(BD, M)) {
Justin Bogner8d0a0812016-09-02 01:21:37 +0000313 BD.setNewProgram(M); // It crashed, keep the trimmed version...
Chris Lattner1d080f22003-04-24 22:24:58 +0000314
315 // Make sure to use function pointers that point into the now-current
316 // module.
317 Funcs.assign(Functions.begin(), Functions.end());
318 return true;
319 }
Chris Lattner327019b2004-02-18 21:24:48 +0000320 delete M;
Chris Lattner1d080f22003-04-24 22:24:58 +0000321 return false;
322}
323
Chris Lattner1942f982004-02-18 21:29:46 +0000324namespace {
Daniel Berlin60606262016-07-28 22:29:25 +0000325/// Simplify the CFG without completely destroying it.
326/// This is not well defined, but basically comes down to "try to eliminate
327/// unreachable blocks and constant fold terminators without deciding that
328/// certain undefined behavior cuts off the program at the legs".
329void simpleSimplifyCfg(Function &F, SmallVectorImpl<BasicBlock *> &BBs) {
330 if (F.empty())
331 return;
332
333 for (auto *BB : BBs) {
334 ConstantFoldTerminator(BB);
335 MergeBlockIntoPredecessor(BB);
336 }
337
338 // Remove unreachable blocks
339 // removeUnreachableBlocks can't be used here, it will turn various
340 // undefined behavior into unreachables, but bugpoint was the thing that
341 // generated the undefined behavior, and we don't want it to kill the entire
342 // program.
343 SmallPtrSet<BasicBlock *, 16> Visited;
344 for (auto *BB : depth_first(&F.getEntryBlock()))
345 Visited.insert(BB);
346
347 SmallVector<BasicBlock *, 16> Unreachable;
348 for (auto &BB : F)
349 if (!Visited.count(&BB))
350 Unreachable.push_back(&BB);
351
352 // The dead BB's may be in a dead cycle or otherwise have references to each
353 // other. Because of this, we have to drop all references first, then delete
354 // them all at once.
Justin Bogner8d0a0812016-09-02 01:21:37 +0000355 for (auto *BB : Unreachable) {
Daniel Berlin60606262016-07-28 22:29:25 +0000356 for (BasicBlock *Successor : successors(&*BB))
357 if (Visited.count(Successor))
358 Successor->removePredecessor(&*BB);
359 BB->dropAllReferences();
360 }
361 for (auto *BB : Unreachable)
362 BB->eraseFromParent();
363}
Justin Bogner8d0a0812016-09-02 01:21:37 +0000364/// ReduceCrashingBlocks reducer - This works by setting the terminators of
365/// all terminators except the specified basic blocks to a 'ret' instruction,
366/// then running the simplify-cfg pass. This has the effect of chopping up
367/// the CFG really fast which can reduce large functions quickly.
368///
369class ReduceCrashingBlocks : public ListReducer<const BasicBlock *> {
370 BugDriver &BD;
371 bool (*TestFn)(const BugDriver &, Module *);
372
373public:
374 ReduceCrashingBlocks(BugDriver &BD,
375 bool (*testFn)(const BugDriver &, Module *))
Daniel Berlin60606262016-07-28 22:29:25 +0000376 : BD(BD), TestFn(testFn) {}
Misha Brukman650ba8e2005-04-22 00:00:37 +0000377
Justin Bogner1c039152016-09-06 17:18:22 +0000378 Expected<TestResult> doTest(std::vector<const BasicBlock *> &Prefix,
379 std::vector<const BasicBlock *> &Kept) override {
Justin Bogner8d0a0812016-09-02 01:21:37 +0000380 if (!Kept.empty() && TestBlocks(Kept))
381 return KeepSuffix;
382 if (!Prefix.empty() && TestBlocks(Prefix))
383 return KeepPrefix;
384 return NoFailure;
385 }
Misha Brukman650ba8e2005-04-22 00:00:37 +0000386
Justin Bogner8d0a0812016-09-02 01:21:37 +0000387 bool TestBlocks(std::vector<const BasicBlock *> &Prefix);
388};
Chris Lattner2f1aa112004-01-14 03:38:37 +0000389}
Chris Lattnerf32939b2003-04-24 23:51:38 +0000390
Justin Bogner8d0a0812016-09-02 01:21:37 +0000391bool ReduceCrashingBlocks::TestBlocks(std::vector<const BasicBlock *> &BBs) {
Misha Brukman8b2bd4e2003-10-10 17:57:28 +0000392 // Clone the program to try hacking it apart...
Rafael Espindola229e38f2010-10-13 01:36:30 +0000393 ValueToValueMapTy VMap;
Rafael Espindolacab951d2015-12-08 23:57:17 +0000394 Module *M = CloneModule(BD.getProgram(), VMap).release();
Misha Brukman650ba8e2005-04-22 00:00:37 +0000395
Chris Lattnerf32939b2003-04-24 23:51:38 +0000396 // Convert list to set for fast lookup...
Justin Bogner8d0a0812016-09-02 01:21:37 +0000397 SmallPtrSet<BasicBlock *, 8> Blocks;
Nick Lewyckyb294e312009-04-04 09:39:23 +0000398 for (unsigned i = 0, e = BBs.size(); i != e; ++i)
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000399 Blocks.insert(cast<BasicBlock>(VMap[BBs[i]]));
Chris Lattnerf32939b2003-04-24 23:51:38 +0000400
Dan Gohmanee051522009-07-16 15:30:09 +0000401 outs() << "Checking for crash with only these blocks:";
Chris Lattner4f50ebd2003-10-27 04:44:59 +0000402 unsigned NumPrint = Blocks.size();
Justin Bogner8d0a0812016-09-02 01:21:37 +0000403 if (NumPrint > 10)
404 NumPrint = 10;
Chris Lattner4f50ebd2003-10-27 04:44:59 +0000405 for (unsigned i = 0, e = NumPrint; i != e; ++i)
Dan Gohmanee051522009-07-16 15:30:09 +0000406 outs() << " " << BBs[i]->getName();
Chris Lattner4f50ebd2003-10-27 04:44:59 +0000407 if (NumPrint < Blocks.size())
Dan Gohmanee051522009-07-16 15:30:09 +0000408 outs() << "... <" << Blocks.size() << " total>";
409 outs() << ": ";
Chris Lattnerf32939b2003-04-24 23:51:38 +0000410
411 // Loop over and delete any hack up any blocks that are not listed...
412 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
413 for (Function::iterator BB = I->begin(), E = I->end(); BB != E; ++BB)
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000414 if (!Blocks.count(&*BB) && BB->getTerminator()->getNumSuccessors()) {
Chris Lattnerf32939b2003-04-24 23:51:38 +0000415 // Loop over all of the successors of this block, deleting any PHI nodes
416 // that might include it.
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000417 for (succ_iterator SI = succ_begin(&*BB), E = succ_end(&*BB); SI != E;
418 ++SI)
419 (*SI)->removePredecessor(&*BB);
Chris Lattnerf32939b2003-04-24 23:51:38 +0000420
Chris Lattner7855a5c2008-04-28 00:04:58 +0000421 TerminatorInst *BBTerm = BB->getTerminator();
Philip Reames29e641c2016-06-29 00:15:35 +0000422 if (BBTerm->isEHPad() || BBTerm->getType()->isTokenTy())
David Majnemer189d7da2015-11-08 04:16:12 +0000423 continue;
Philip Reames29e641c2016-06-29 00:15:35 +0000424 if (!BBTerm->getType()->isVoidTy())
Owen Anderson5a1acd92009-07-31 20:28:14 +0000425 BBTerm->replaceAllUsesWith(Constant::getNullValue(BBTerm->getType()));
Chris Lattner7b233af2003-11-22 02:10:38 +0000426
Chris Lattner7855a5c2008-04-28 00:04:58 +0000427 // Replace the old terminator instruction.
Chris Lattnerf32939b2003-04-24 23:51:38 +0000428 BB->getInstList().pop_back();
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000429 new UnreachableInst(BB->getContext(), &*BB);
Chris Lattnerf32939b2003-04-24 23:51:38 +0000430 }
431
432 // The CFG Simplifier pass may delete one of the basic blocks we are
433 // interested in. If it does we need to take the block out of the list. Make
434 // a "persistent mapping" by turning basic blocks into <function, name> pairs.
435 // This won't work well if blocks are unnamed, but that is just the risk we
436 // have to take.
Justin Bogner8d0a0812016-09-02 01:21:37 +0000437 std::vector<std::pair<std::string, std::string>> BlockInfo;
Chris Lattnerf32939b2003-04-24 23:51:38 +0000438
Craig Topper46276792014-08-24 23:23:06 +0000439 for (BasicBlock *BB : Blocks)
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000440 BlockInfo.emplace_back(BB->getParent()->getName(), BB->getName());
Justin Bogner8d0a0812016-09-02 01:21:37 +0000441
Daniel Berlin60606262016-07-28 22:29:25 +0000442 SmallVector<BasicBlock *, 16> ToProcess;
Justin Bogner8d0a0812016-09-02 01:21:37 +0000443 for (auto &F : *M) {
Daniel Berlin60606262016-07-28 22:29:25 +0000444 for (auto &BB : F)
445 if (!Blocks.count(&BB))
446 ToProcess.push_back(&BB);
447 simpleSimplifyCfg(F, ToProcess);
448 ToProcess.clear();
449 }
450 // Verify we didn't break anything
Rafael Espindolad1e241a2010-08-10 15:46:11 +0000451 std::vector<std::string> Passes;
Rafael Espindolad1e241a2010-08-10 15:46:11 +0000452 Passes.push_back("verify");
Rafael Espindola28b351a2014-08-26 17:19:03 +0000453 std::unique_ptr<Module> New = BD.runPassesOn(M, Passes);
Rafael Espindolad1e241a2010-08-10 15:46:11 +0000454 delete M;
455 if (!New) {
Daniel Berlin60606262016-07-28 22:29:25 +0000456 errs() << "verify failed!\n";
Rafael Espindolad1e241a2010-08-10 15:46:11 +0000457 exit(1);
458 }
Rafael Espindola28b351a2014-08-26 17:19:03 +0000459 M = New.release();
Justin Bogner8d0a0812016-09-02 01:21:37 +0000460
Chris Lattnerf32939b2003-04-24 23:51:38 +0000461 // Try running on the hacked up program...
Chris Lattner8bda4c42004-02-18 23:26:28 +0000462 if (TestFn(BD, M)) {
Justin Bogner8d0a0812016-09-02 01:21:37 +0000463 BD.setNewProgram(M); // It crashed, keep the trimmed version...
Chris Lattnerf32939b2003-04-24 23:51:38 +0000464
465 // Make sure to use basic block pointers that point into the now-current
466 // module, and that they don't include any deleted blocks.
467 BBs.clear();
Rafael Espindolad1e241a2010-08-10 15:46:11 +0000468 const ValueSymbolTable &GST = M->getValueSymbolTable();
Chris Lattnerf32939b2003-04-24 23:51:38 +0000469 for (unsigned i = 0, e = BlockInfo.size(); i != e; ++i) {
Rafael Espindolad1e241a2010-08-10 15:46:11 +0000470 Function *F = cast<Function>(GST.lookup(BlockInfo[i].first));
Mehdi Aminia53d49e2016-09-17 06:00:02 +0000471 Value *V = F->getValueSymbolTable()->lookup(BlockInfo[i].second);
Owen Anderson55f1c092009-08-13 21:58:54 +0000472 if (V && V->getType() == Type::getLabelTy(V->getContext()))
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000473 BBs.push_back(cast<BasicBlock>(V));
Chris Lattnerf32939b2003-04-24 23:51:38 +0000474 }
475 return true;
476 }
Justin Bogner8d0a0812016-09-02 01:21:37 +0000477 delete M; // It didn't crash, try something else.
Chris Lattnerf32939b2003-04-24 23:51:38 +0000478 return false;
479}
480
Nick Lewycky6e090c92009-05-25 05:30:00 +0000481namespace {
Daniel Berlin271ca402016-07-27 16:13:25 +0000482/// ReduceCrashingConditionals reducer - This works by changing
483/// conditional branches to unconditional ones, then simplifying the CFG
484/// This has the effect of chopping up the CFG really fast which can reduce
485/// large functions quickly.
486///
487class ReduceCrashingConditionals : public ListReducer<const BasicBlock *> {
488 BugDriver &BD;
489 bool (*TestFn)(const BugDriver &, Module *);
490 bool Direction;
491
492public:
493 ReduceCrashingConditionals(BugDriver &bd,
494 bool (*testFn)(const BugDriver &, Module *),
495 bool Direction)
496 : BD(bd), TestFn(testFn), Direction(Direction) {}
497
Justin Bogner1c039152016-09-06 17:18:22 +0000498 Expected<TestResult> doTest(std::vector<const BasicBlock *> &Prefix,
499 std::vector<const BasicBlock *> &Kept) override {
Daniel Berlin271ca402016-07-27 16:13:25 +0000500 if (!Kept.empty() && TestBlocks(Kept))
501 return KeepSuffix;
502 if (!Prefix.empty() && TestBlocks(Prefix))
503 return KeepPrefix;
504 return NoFailure;
505 }
506
507 bool TestBlocks(std::vector<const BasicBlock *> &Prefix);
508};
509}
510
511bool ReduceCrashingConditionals::TestBlocks(
512 std::vector<const BasicBlock *> &BBs) {
513 // Clone the program to try hacking it apart...
514 ValueToValueMapTy VMap;
515 Module *M = CloneModule(BD.getProgram(), VMap).release();
516
517 // Convert list to set for fast lookup...
518 SmallPtrSet<const BasicBlock *, 8> Blocks;
Justin Bogner8d0a0812016-09-02 01:21:37 +0000519 for (const auto *BB : BBs)
Daniel Berlin271ca402016-07-27 16:13:25 +0000520 Blocks.insert(cast<BasicBlock>(VMap[BB]));
521
522 outs() << "Checking for crash with changing conditionals to always jump to "
523 << (Direction ? "true" : "false") << ":";
524 unsigned NumPrint = Blocks.size();
525 if (NumPrint > 10)
526 NumPrint = 10;
527 for (unsigned i = 0, e = NumPrint; i != e; ++i)
528 outs() << " " << BBs[i]->getName();
529 if (NumPrint < Blocks.size())
530 outs() << "... <" << Blocks.size() << " total>";
531 outs() << ": ";
532
533 // Loop over and delete any hack up any blocks that are not listed...
Justin Bogner8d0a0812016-09-02 01:21:37 +0000534 for (auto &F : *M)
Daniel Berlin271ca402016-07-27 16:13:25 +0000535 for (auto &BB : F)
536 if (!Blocks.count(&BB)) {
537 auto *BR = dyn_cast<BranchInst>(BB.getTerminator());
538 if (!BR || !BR->isConditional())
539 continue;
540 if (Direction)
541 BR->setCondition(ConstantInt::getTrue(BR->getContext()));
542 else
543 BR->setCondition(ConstantInt::getFalse(BR->getContext()));
544 }
545
546 // The following may destroy some blocks, so we save them first
547 std::vector<std::pair<std::string, std::string>> BlockInfo;
548
549 for (const BasicBlock *BB : Blocks)
550 BlockInfo.emplace_back(BB->getParent()->getName(), BB->getName());
551
552 SmallVector<BasicBlock *, 16> ToProcess;
Justin Bogner8d0a0812016-09-02 01:21:37 +0000553 for (auto &F : *M) {
Daniel Berlin271ca402016-07-27 16:13:25 +0000554 for (auto &BB : F)
555 if (!Blocks.count(&BB))
556 ToProcess.push_back(&BB);
557 simpleSimplifyCfg(F, ToProcess);
558 ToProcess.clear();
559 }
560 // Verify we didn't break anything
561 std::vector<std::string> Passes;
562 Passes.push_back("verify");
563 std::unique_ptr<Module> New = BD.runPassesOn(M, Passes);
564 delete M;
565 if (!New) {
566 errs() << "verify failed!\n";
567 exit(1);
568 }
569 M = New.release();
570
571 // Try running on the hacked up program...
572 if (TestFn(BD, M)) {
573 BD.setNewProgram(M); // It crashed, keep the trimmed version...
574
575 // Make sure to use basic block pointers that point into the now-current
576 // module, and that they don't include any deleted blocks.
577 BBs.clear();
578 const ValueSymbolTable &GST = M->getValueSymbolTable();
579 for (auto &BI : BlockInfo) {
580 auto *F = cast<Function>(GST.lookup(BI.first));
Mehdi Aminia53d49e2016-09-17 06:00:02 +0000581 Value *V = F->getValueSymbolTable()->lookup(BI.second);
Daniel Berlin271ca402016-07-27 16:13:25 +0000582 if (V && V->getType() == Type::getLabelTy(V->getContext()))
583 BBs.push_back(cast<BasicBlock>(V));
584 }
585 return true;
586 }
587 delete M; // It didn't crash, try something else.
588 return false;
589}
590
591namespace {
Daniel Berlin60606262016-07-28 22:29:25 +0000592/// SimplifyCFG reducer - This works by calling SimplifyCFG on each basic block
593/// in the program.
594
595class ReduceSimplifyCFG : public ListReducer<const BasicBlock *> {
596 BugDriver &BD;
597 bool (*TestFn)(const BugDriver &, Module *);
598 TargetTransformInfo TTI;
Justin Bogner8d0a0812016-09-02 01:21:37 +0000599
Daniel Berlin60606262016-07-28 22:29:25 +0000600public:
Justin Bogner8d0a0812016-09-02 01:21:37 +0000601 ReduceSimplifyCFG(BugDriver &bd, bool (*testFn)(const BugDriver &, Module *))
602 : BD(bd), TestFn(testFn), TTI(bd.getProgram()->getDataLayout()) {}
Daniel Berlin60606262016-07-28 22:29:25 +0000603
Justin Bogner1c039152016-09-06 17:18:22 +0000604 Expected<TestResult> doTest(std::vector<const BasicBlock *> &Prefix,
605 std::vector<const BasicBlock *> &Kept) override {
Daniel Berlin60606262016-07-28 22:29:25 +0000606 if (!Kept.empty() && TestBlocks(Kept))
607 return KeepSuffix;
608 if (!Prefix.empty() && TestBlocks(Prefix))
609 return KeepPrefix;
610 return NoFailure;
611 }
612
613 bool TestBlocks(std::vector<const BasicBlock *> &Prefix);
614};
615}
616
Justin Bogner8d0a0812016-09-02 01:21:37 +0000617bool ReduceSimplifyCFG::TestBlocks(std::vector<const BasicBlock *> &BBs) {
Daniel Berlin60606262016-07-28 22:29:25 +0000618 // Clone the program to try hacking it apart...
619 ValueToValueMapTy VMap;
620 Module *M = CloneModule(BD.getProgram(), VMap).release();
621
622 // Convert list to set for fast lookup...
623 SmallPtrSet<const BasicBlock *, 8> Blocks;
Justin Bogner8d0a0812016-09-02 01:21:37 +0000624 for (const auto *BB : BBs)
Daniel Berlin60606262016-07-28 22:29:25 +0000625 Blocks.insert(cast<BasicBlock>(VMap[BB]));
626
627 outs() << "Checking for crash with CFG simplifying:";
628 unsigned NumPrint = Blocks.size();
629 if (NumPrint > 10)
630 NumPrint = 10;
631 for (unsigned i = 0, e = NumPrint; i != e; ++i)
632 outs() << " " << BBs[i]->getName();
633 if (NumPrint < Blocks.size())
634 outs() << "... <" << Blocks.size() << " total>";
635 outs() << ": ";
636
Justin Bogner8d0a0812016-09-02 01:21:37 +0000637 // The following may destroy some blocks, so we save them first
Daniel Berlin60606262016-07-28 22:29:25 +0000638 std::vector<std::pair<std::string, std::string>> BlockInfo;
639
640 for (const BasicBlock *BB : Blocks)
641 BlockInfo.emplace_back(BB->getParent()->getName(), BB->getName());
642
Daniel Berlin60606262016-07-28 22:29:25 +0000643 // Loop over and delete any hack up any blocks that are not listed...
Justin Bogner8d0a0812016-09-02 01:21:37 +0000644 for (auto &F : *M)
645 // Loop over all of the basic blocks and remove them if they are unneeded.
646 for (Function::iterator BBIt = F.begin(); BBIt != F.end();) {
647 if (!Blocks.count(&*BBIt)) {
648 ++BBIt;
649 continue;
650 }
651 SimplifyCFG(&*BBIt++, TTI, 1);
652 }
Daniel Berlin60606262016-07-28 22:29:25 +0000653 // Verify we didn't break anything
654 std::vector<std::string> Passes;
655 Passes.push_back("verify");
656 std::unique_ptr<Module> New = BD.runPassesOn(M, Passes);
657 delete M;
658 if (!New) {
659 errs() << "verify failed!\n";
660 exit(1);
661 }
662 M = New.release();
663
664 // Try running on the hacked up program...
665 if (TestFn(BD, M)) {
666 BD.setNewProgram(M); // It crashed, keep the trimmed version...
667
668 // Make sure to use basic block pointers that point into the now-current
669 // module, and that they don't include any deleted blocks.
670 BBs.clear();
671 const ValueSymbolTable &GST = M->getValueSymbolTable();
Justin Bogner8d0a0812016-09-02 01:21:37 +0000672 for (auto &BI : BlockInfo) {
Daniel Berlin60606262016-07-28 22:29:25 +0000673 auto *F = cast<Function>(GST.lookup(BI.first));
Mehdi Aminia53d49e2016-09-17 06:00:02 +0000674 Value *V = F->getValueSymbolTable()->lookup(BI.second);
Daniel Berlin60606262016-07-28 22:29:25 +0000675 if (V && V->getType() == Type::getLabelTy(V->getContext()))
676 BBs.push_back(cast<BasicBlock>(V));
677 }
678 return true;
679 }
680 delete M; // It didn't crash, try something else.
681 return false;
682}
683
684namespace {
Justin Bogner8d0a0812016-09-02 01:21:37 +0000685/// ReduceCrashingInstructions reducer - This works by removing the specified
686/// non-terminator instructions and replacing them with undef.
687///
688class ReduceCrashingInstructions : public ListReducer<const Instruction *> {
689 BugDriver &BD;
690 bool (*TestFn)(const BugDriver &, Module *);
691
692public:
693 ReduceCrashingInstructions(BugDriver &bd,
694 bool (*testFn)(const BugDriver &, Module *))
Nick Lewycky6e090c92009-05-25 05:30:00 +0000695 : BD(bd), TestFn(testFn) {}
696
Justin Bogner1c039152016-09-06 17:18:22 +0000697 Expected<TestResult> doTest(std::vector<const Instruction *> &Prefix,
698 std::vector<const Instruction *> &Kept) override {
Justin Bogner8d0a0812016-09-02 01:21:37 +0000699 if (!Kept.empty() && TestInsts(Kept))
700 return KeepSuffix;
701 if (!Prefix.empty() && TestInsts(Prefix))
702 return KeepPrefix;
703 return NoFailure;
704 }
Nick Lewycky6e090c92009-05-25 05:30:00 +0000705
Justin Bogner8d0a0812016-09-02 01:21:37 +0000706 bool TestInsts(std::vector<const Instruction *> &Prefix);
707};
Nick Lewycky6e090c92009-05-25 05:30:00 +0000708}
709
Justin Bogner8d0a0812016-09-02 01:21:37 +0000710bool ReduceCrashingInstructions::TestInsts(
711 std::vector<const Instruction *> &Insts) {
Nick Lewycky6e090c92009-05-25 05:30:00 +0000712 // Clone the program to try hacking it apart...
Rafael Espindola229e38f2010-10-13 01:36:30 +0000713 ValueToValueMapTy VMap;
Rafael Espindolacab951d2015-12-08 23:57:17 +0000714 Module *M = CloneModule(BD.getProgram(), VMap).release();
Nick Lewycky6e090c92009-05-25 05:30:00 +0000715
716 // Convert list to set for fast lookup...
Justin Bogner8d0a0812016-09-02 01:21:37 +0000717 SmallPtrSet<Instruction *, 32> Instructions;
Nick Lewycky6e090c92009-05-25 05:30:00 +0000718 for (unsigned i = 0, e = Insts.size(); i != e; ++i) {
719 assert(!isa<TerminatorInst>(Insts[i]));
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000720 Instructions.insert(cast<Instruction>(VMap[Insts[i]]));
Nick Lewycky6e090c92009-05-25 05:30:00 +0000721 }
722
Dan Gohmanee051522009-07-16 15:30:09 +0000723 outs() << "Checking for crash with only " << Instructions.size();
Nick Lewycky6e090c92009-05-25 05:30:00 +0000724 if (Instructions.size() == 1)
Dan Gohmanee051522009-07-16 15:30:09 +0000725 outs() << " instruction: ";
Nick Lewycky6e090c92009-05-25 05:30:00 +0000726 else
Dan Gohmanee051522009-07-16 15:30:09 +0000727 outs() << " instructions: ";
Nick Lewycky6e090c92009-05-25 05:30:00 +0000728
729 for (Module::iterator MI = M->begin(), ME = M->end(); MI != ME; ++MI)
730 for (Function::iterator FI = MI->begin(), FE = MI->end(); FI != FE; ++FI)
731 for (BasicBlock::iterator I = FI->begin(), E = FI->end(); I != E;) {
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000732 Instruction *Inst = &*I++;
Eli Friedmand4e02a52011-11-01 04:40:56 +0000733 if (!Instructions.count(Inst) && !isa<TerminatorInst>(Inst) &&
Philip Reames29e641c2016-06-29 00:15:35 +0000734 !Inst->isEHPad() && !Inst->getType()->isTokenTy()) {
735 if (!Inst->getType()->isVoidTy())
Nick Lewycky6e090c92009-05-25 05:30:00 +0000736 Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
737 Inst->eraseFromParent();
738 }
739 }
740
741 // Verify that this is still valid.
Chandler Carruth30d69c22015-02-13 10:01:29 +0000742 legacy::PassManager Passes;
Adrian Prantl919bdf12016-10-18 16:24:43 +0000743 Passes.add(createVerifierPass(/*FatalErrors=*/false));
Nick Lewycky6e090c92009-05-25 05:30:00 +0000744 Passes.run(*M);
745
746 // Try running on the hacked up program...
747 if (TestFn(BD, M)) {
Justin Bogner8d0a0812016-09-02 01:21:37 +0000748 BD.setNewProgram(M); // It crashed, keep the trimmed version...
Nick Lewycky6e090c92009-05-25 05:30:00 +0000749
750 // Make sure to use instruction pointers that point into the now-current
751 // module, and that they don't include any deleted blocks.
752 Insts.clear();
Craig Topper46276792014-08-24 23:23:06 +0000753 for (Instruction *Inst : Instructions)
754 Insts.push_back(Inst);
Nick Lewycky6e090c92009-05-25 05:30:00 +0000755 return true;
756 }
Justin Bogner8d0a0812016-09-02 01:21:37 +0000757 delete M; // It didn't crash, try something else.
Nick Lewycky6e090c92009-05-25 05:30:00 +0000758 return false;
759}
760
Keno Fischer34ca8312015-11-06 00:12:50 +0000761namespace {
762// Reduce the list of Named Metadata nodes. We keep this as a list of
763// names to avoid having to convert back and forth every time.
764class ReduceCrashingNamedMD : public ListReducer<std::string> {
765 BugDriver &BD;
766 bool (*TestFn)(const BugDriver &, Module *);
767
768public:
769 ReduceCrashingNamedMD(BugDriver &bd,
770 bool (*testFn)(const BugDriver &, Module *))
771 : BD(bd), TestFn(testFn) {}
772
Justin Bogner1c039152016-09-06 17:18:22 +0000773 Expected<TestResult> doTest(std::vector<std::string> &Prefix,
774 std::vector<std::string> &Kept) override {
Keno Fischer34ca8312015-11-06 00:12:50 +0000775 if (!Kept.empty() && TestNamedMDs(Kept))
776 return KeepSuffix;
777 if (!Prefix.empty() && TestNamedMDs(Prefix))
778 return KeepPrefix;
779 return NoFailure;
780 }
781
782 bool TestNamedMDs(std::vector<std::string> &NamedMDs);
783};
784}
785
786bool ReduceCrashingNamedMD::TestNamedMDs(std::vector<std::string> &NamedMDs) {
787
788 ValueToValueMapTy VMap;
Rafael Espindolacab951d2015-12-08 23:57:17 +0000789 Module *M = CloneModule(BD.getProgram(), VMap).release();
Keno Fischer34ca8312015-11-06 00:12:50 +0000790
791 outs() << "Checking for crash with only these named metadata nodes:";
792 unsigned NumPrint = std::min<size_t>(NamedMDs.size(), 10);
793 for (unsigned i = 0, e = NumPrint; i != e; ++i)
794 outs() << " " << NamedMDs[i];
795 if (NumPrint < NamedMDs.size())
796 outs() << "... <" << NamedMDs.size() << " total>";
797 outs() << ": ";
798
799 // Make a StringMap for faster lookup
800 StringSet<> Names;
801 for (const std::string &Name : NamedMDs)
802 Names.insert(Name);
803
804 // First collect all the metadata to delete in a vector, then
805 // delete them all at once to avoid invalidating the iterator
806 std::vector<NamedMDNode *> ToDelete;
807 ToDelete.reserve(M->named_metadata_size() - Names.size());
808 for (auto &NamedMD : M->named_metadata())
Adrian Prantlfaebbb02016-03-28 21:06:26 +0000809 // Always keep a nonempty llvm.dbg.cu because the Verifier would complain.
810 if (!Names.count(NamedMD.getName()) &&
811 (!(NamedMD.getName() == "llvm.dbg.cu" && NamedMD.getNumOperands() > 0)))
Keno Fischer34ca8312015-11-06 00:12:50 +0000812 ToDelete.push_back(&NamedMD);
813
814 for (auto *NamedMD : ToDelete)
815 NamedMD->eraseFromParent();
816
817 // Verify that this is still valid.
818 legacy::PassManager Passes;
Adrian Prantl919bdf12016-10-18 16:24:43 +0000819 Passes.add(createVerifierPass(/*FatalErrors=*/false));
Keno Fischer34ca8312015-11-06 00:12:50 +0000820 Passes.run(*M);
821
822 // Try running on the hacked up program...
823 if (TestFn(BD, M)) {
824 BD.setNewProgram(M); // It crashed, keep the trimmed version...
825 return true;
826 }
827 delete M; // It didn't crash, try something else.
828 return false;
829}
830
831namespace {
832// Reduce the list of operands to named metadata nodes
833class ReduceCrashingNamedMDOps : public ListReducer<const MDNode *> {
834 BugDriver &BD;
835 bool (*TestFn)(const BugDriver &, Module *);
836
837public:
838 ReduceCrashingNamedMDOps(BugDriver &bd,
839 bool (*testFn)(const BugDriver &, Module *))
840 : BD(bd), TestFn(testFn) {}
841
Justin Bogner1c039152016-09-06 17:18:22 +0000842 Expected<TestResult> doTest(std::vector<const MDNode *> &Prefix,
843 std::vector<const MDNode *> &Kept) override {
Keno Fischer34ca8312015-11-06 00:12:50 +0000844 if (!Kept.empty() && TestNamedMDOps(Kept))
845 return KeepSuffix;
846 if (!Prefix.empty() && TestNamedMDOps(Prefix))
847 return KeepPrefix;
848 return NoFailure;
849 }
850
851 bool TestNamedMDOps(std::vector<const MDNode *> &NamedMDOps);
852};
853}
854
855bool ReduceCrashingNamedMDOps::TestNamedMDOps(
856 std::vector<const MDNode *> &NamedMDOps) {
857 // Convert list to set for fast lookup...
Matthias Braunb30f2f512016-01-30 01:24:31 +0000858 SmallPtrSet<const MDNode *, 32> OldMDNodeOps;
Keno Fischer34ca8312015-11-06 00:12:50 +0000859 for (unsigned i = 0, e = NamedMDOps.size(); i != e; ++i) {
860 OldMDNodeOps.insert(NamedMDOps[i]);
861 }
862
863 outs() << "Checking for crash with only " << OldMDNodeOps.size();
864 if (OldMDNodeOps.size() == 1)
865 outs() << " named metadata operand: ";
866 else
867 outs() << " named metadata operands: ";
868
869 ValueToValueMapTy VMap;
Rafael Espindolacab951d2015-12-08 23:57:17 +0000870 Module *M = CloneModule(BD.getProgram(), VMap).release();
Keno Fischer34ca8312015-11-06 00:12:50 +0000871
872 // This is a little wasteful. In the future it might be good if we could have
873 // these dropped during cloning.
874 for (auto &NamedMD : BD.getProgram()->named_metadata()) {
875 // Drop the old one and create a new one
876 M->eraseNamedMetadata(M->getNamedMetadata(NamedMD.getName()));
877 NamedMDNode *NewNamedMDNode =
878 M->getOrInsertNamedMetadata(NamedMD.getName());
879 for (MDNode *op : NamedMD.operands())
880 if (OldMDNodeOps.count(op))
881 NewNamedMDNode->addOperand(cast<MDNode>(MapMetadata(op, VMap)));
882 }
883
884 // Verify that this is still valid.
885 legacy::PassManager Passes;
Adrian Prantl919bdf12016-10-18 16:24:43 +0000886 Passes.add(createVerifierPass(/*FatalErrors=*/false));
Keno Fischer34ca8312015-11-06 00:12:50 +0000887 Passes.run(*M);
888
889 // Try running on the hacked up program...
890 if (TestFn(BD, M)) {
891 // Make sure to use instruction pointers that point into the now-current
892 // module, and that they don't include any deleted blocks.
893 NamedMDOps.clear();
894 for (const MDNode *Node : OldMDNodeOps)
Duncan P. N. Exon Smithda4a56d2016-04-02 17:04:38 +0000895 NamedMDOps.push_back(cast<MDNode>(*VMap.getMappedMD(Node)));
Keno Fischer34ca8312015-11-06 00:12:50 +0000896
897 BD.setNewProgram(M); // It crashed, keep the trimmed version...
898 return true;
899 }
900 delete M; // It didn't crash, try something else.
901 return false;
902}
903
Justin Bogner1c039152016-09-06 17:18:22 +0000904static Error ReduceGlobalInitializers(BugDriver &BD,
905 bool (*TestFn)(const BugDriver &,
906 Module *)) {
Philip Reames1c232f92016-06-29 00:43:18 +0000907 if (BD.getProgram()->global_begin() != BD.getProgram()->global_end()) {
Bill Wendling3f833432006-10-25 18:36:14 +0000908 // Now try to reduce the number of global variable initializers in the
909 // module to something small.
Rafael Espindolacab951d2015-12-08 23:57:17 +0000910 Module *M = CloneModule(BD.getProgram()).release();
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000911 bool DeletedInit = false;
Misha Brukman650ba8e2005-04-22 00:00:37 +0000912
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000913 for (Module::global_iterator I = M->global_begin(), E = M->global_end();
914 I != E; ++I)
915 if (I->hasInitializer()) {
Hal Finkel28ad2b42015-11-26 19:23:49 +0000916 DeleteGlobalInitializer(&*I);
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000917 I->setLinkage(GlobalValue::ExternalLinkage);
Justin Lebar2a445cf2016-06-15 23:20:12 +0000918 I->setComdat(nullptr);
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000919 DeletedInit = true;
920 }
Bill Wendling3f833432006-10-25 18:36:14 +0000921
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000922 if (!DeletedInit) {
Justin Bogner8d0a0812016-09-02 01:21:37 +0000923 delete M; // No change made...
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000924 } else {
925 // See if the program still causes a crash...
Dan Gohmanee051522009-07-16 15:30:09 +0000926 outs() << "\nChecking to see if we can delete global inits: ";
Bill Wendling3f833432006-10-25 18:36:14 +0000927
Justin Bogner8d0a0812016-09-02 01:21:37 +0000928 if (TestFn(BD, M)) { // Still crashes?
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000929 BD.setNewProgram(M);
Dan Gohmanee051522009-07-16 15:30:09 +0000930 outs() << "\n*** Able to remove all global initializers!\n";
Justin Bogner8d0a0812016-09-02 01:21:37 +0000931 } else { // No longer crashes?
Dan Gohmanee051522009-07-16 15:30:09 +0000932 outs() << " - Removing all global inits hides problem!\n";
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000933 delete M;
Bill Wendling3f833432006-10-25 18:36:14 +0000934
Justin Bogner8d0a0812016-09-02 01:21:37 +0000935 std::vector<GlobalVariable *> GVs;
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000936
937 for (Module::global_iterator I = BD.getProgram()->global_begin(),
Justin Bogner8d0a0812016-09-02 01:21:37 +0000938 E = BD.getProgram()->global_end();
939 I != E; ++I)
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000940 if (I->hasInitializer())
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000941 GVs.push_back(&*I);
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000942
943 if (GVs.size() > 1 && !BugpointIsInterrupted) {
Dan Gohmanee051522009-07-16 15:30:09 +0000944 outs() << "\n*** Attempting to reduce the number of global "
Justin Bogner8d0a0812016-09-02 01:21:37 +0000945 << "variables in the testcase\n";
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000946
947 unsigned OldSize = GVs.size();
Justin Bogner1c039152016-09-06 17:18:22 +0000948 Expected<bool> Result =
949 ReduceCrashingGlobalVariables(BD, TestFn).reduceList(GVs);
950 if (Error E = Result.takeError())
951 return E;
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000952
953 if (GVs.size() < OldSize)
Rafael Espindola594994a2010-07-28 18:12:30 +0000954 BD.EmitProgressBitcode(BD.getProgram(), "reduced-global-variables");
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000955 }
Bill Wendlingce3afd62006-10-27 20:22:04 +0000956 }
Chris Lattner65e5f652003-04-25 00:53:05 +0000957 }
958 }
Justin Bogner1c039152016-09-06 17:18:22 +0000959 return Error::success();
Philip Reames1c232f92016-06-29 00:43:18 +0000960}
961
Justin Bogner1c039152016-09-06 17:18:22 +0000962static Error ReduceInsts(BugDriver &BD,
963 bool (*TestFn)(const BugDriver &, Module *)) {
Philip Reames1c232f92016-06-29 00:43:18 +0000964 // Attempt to delete instructions using bisection. This should help out nasty
965 // cases with large basic blocks where the problem is at one end.
966 if (!BugpointIsInterrupted) {
Justin Bogner8d0a0812016-09-02 01:21:37 +0000967 std::vector<const Instruction *> Insts;
Philip Reames1c232f92016-06-29 00:43:18 +0000968 for (const Function &F : *BD.getProgram())
969 for (const BasicBlock &BB : F)
970 for (const Instruction &I : BB)
971 if (!isa<TerminatorInst>(&I))
972 Insts.push_back(&I);
973
Justin Bogner1c039152016-09-06 17:18:22 +0000974 Expected<bool> Result =
975 ReduceCrashingInstructions(BD, TestFn).reduceList(Insts);
976 if (Error E = Result.takeError())
977 return E;
Philip Reames1c232f92016-06-29 00:43:18 +0000978 }
979
980 unsigned Simplification = 2;
981 do {
982 if (BugpointIsInterrupted)
Justin Bogner1c039152016-09-06 17:18:22 +0000983 // TODO: Should we distinguish this with an "interrupted error"?
984 return Error::success();
Philip Reames1c232f92016-06-29 00:43:18 +0000985 --Simplification;
986 outs() << "\n*** Attempting to reduce testcase by deleting instruc"
987 << "tions: Simplification Level #" << Simplification << '\n';
988
989 // Now that we have deleted the functions that are unnecessary for the
990 // program, try to remove instructions that are not necessary to cause the
991 // crash. To do this, we loop through all of the instructions in the
992 // remaining functions, deleting them (replacing any values produced with
993 // nulls), and then running ADCE and SimplifyCFG. If the transformed input
994 // still triggers failure, keep deleting until we cannot trigger failure
995 // anymore.
996 //
997 unsigned InstructionsToSkipBeforeDeleting = 0;
998 TryAgain:
999
1000 // Loop over all of the (non-terminator) instructions remaining in the
1001 // function, attempting to delete them.
1002 unsigned CurInstructionNum = 0;
1003 for (Module::const_iterator FI = BD.getProgram()->begin(),
Justin Bogner8d0a0812016-09-02 01:21:37 +00001004 E = BD.getProgram()->end();
1005 FI != E; ++FI)
Philip Reames1c232f92016-06-29 00:43:18 +00001006 if (!FI->isDeclaration())
1007 for (Function::const_iterator BI = FI->begin(), E = FI->end(); BI != E;
1008 ++BI)
1009 for (BasicBlock::const_iterator I = BI->begin(), E = --BI->end();
1010 I != E; ++I, ++CurInstructionNum) {
1011 if (InstructionsToSkipBeforeDeleting) {
1012 --InstructionsToSkipBeforeDeleting;
1013 } else {
1014 if (BugpointIsInterrupted)
Justin Bogner1c039152016-09-06 17:18:22 +00001015 // TODO: Should this be some kind of interrupted error?
1016 return Error::success();
Philip Reames1c232f92016-06-29 00:43:18 +00001017
1018 if (I->isEHPad() || I->getType()->isTokenTy())
1019 continue;
1020
1021 outs() << "Checking instruction: " << *I;
1022 std::unique_ptr<Module> M =
1023 BD.deleteInstructionFromProgram(&*I, Simplification);
1024
1025 // Find out if the pass still crashes on this pass...
1026 if (TestFn(BD, M.get())) {
1027 // Yup, it does, we delete the old module, and continue trying
1028 // to reduce the testcase...
1029 BD.setNewProgram(M.release());
1030 InstructionsToSkipBeforeDeleting = CurInstructionNum;
Justin Bogner8d0a0812016-09-02 01:21:37 +00001031 goto TryAgain; // I wish I had a multi-level break here!
Philip Reames1c232f92016-06-29 00:43:18 +00001032 }
1033 }
1034 }
1035
1036 if (InstructionsToSkipBeforeDeleting) {
1037 InstructionsToSkipBeforeDeleting = 0;
1038 goto TryAgain;
1039 }
1040
1041 } while (Simplification);
1042 BD.EmitProgressBitcode(BD.getProgram(), "reduced-instructions");
Justin Bogner1c039152016-09-06 17:18:22 +00001043 return Error::success();
Philip Reames1c232f92016-06-29 00:43:18 +00001044}
1045
Philip Reames1c232f92016-06-29 00:43:18 +00001046/// DebugACrash - Given a predicate that determines whether a component crashes
1047/// on a program, try to destructively reduce the program while still keeping
1048/// the predicate true.
Justin Bogner1c039152016-09-06 17:18:22 +00001049static Error DebugACrash(BugDriver &BD,
1050 bool (*TestFn)(const BugDriver &, Module *)) {
Philip Reames1c232f92016-06-29 00:43:18 +00001051 // See if we can get away with nuking some of the global variable initializers
1052 // in the program...
1053 if (!NoGlobalRM)
Justin Bogner1c039152016-09-06 17:18:22 +00001054 if (Error E = ReduceGlobalInitializers(BD, TestFn))
1055 return E;
Misha Brukman650ba8e2005-04-22 00:00:37 +00001056
Chris Lattner1d080f22003-04-24 22:24:58 +00001057 // Now try to reduce the number of functions in the module to something small.
Justin Bogner8d0a0812016-09-02 01:21:37 +00001058 std::vector<Function *> Functions;
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +00001059 for (Function &F : *BD.getProgram())
1060 if (!F.isDeclaration())
1061 Functions.push_back(&F);
Chris Lattner73a6bdd2002-11-20 22:28:10 +00001062
Chris Lattnerbeb01fa2005-08-02 02:16:17 +00001063 if (Functions.size() > 1 && !BugpointIsInterrupted) {
Dan Gohmanee051522009-07-16 15:30:09 +00001064 outs() << "\n*** Attempting to reduce the number of functions "
Justin Bogner8d0a0812016-09-02 01:21:37 +00001065 "in the testcase\n";
Chris Lattner73a6bdd2002-11-20 22:28:10 +00001066
Chris Lattner8bda4c42004-02-18 23:26:28 +00001067 unsigned OldSize = Functions.size();
Justin Bogner1c039152016-09-06 17:18:22 +00001068 Expected<bool> Result =
1069 ReduceCrashingFunctions(BD, TestFn).reduceList(Functions);
1070 if (Error E = Result.takeError())
1071 return E;
Chris Lattner73a6bdd2002-11-20 22:28:10 +00001072
Chris Lattnerbeb01fa2005-08-02 02:16:17 +00001073 if (Functions.size() < OldSize)
Rafael Espindola594994a2010-07-28 18:12:30 +00001074 BD.EmitProgressBitcode(BD.getProgram(), "reduced-function");
Chris Lattner73a6bdd2002-11-20 22:28:10 +00001075 }
1076
Daniel Berlin271ca402016-07-27 16:13:25 +00001077 // Attempt to change conditional branches into unconditional branches to
1078 // eliminate blocks.
1079 if (!DisableSimplifyCFG && !BugpointIsInterrupted) {
Justin Bogner8d0a0812016-09-02 01:21:37 +00001080 std::vector<const BasicBlock *> Blocks;
Daniel Berlin271ca402016-07-27 16:13:25 +00001081 for (Function &F : *BD.getProgram())
1082 for (BasicBlock &BB : F)
1083 Blocks.push_back(&BB);
1084 unsigned OldSize = Blocks.size();
Justin Bogner1c039152016-09-06 17:18:22 +00001085 Expected<bool> Result =
1086 ReduceCrashingConditionals(BD, TestFn, true).reduceList(Blocks);
1087 if (Error E = Result.takeError())
1088 return E;
1089 Result = ReduceCrashingConditionals(BD, TestFn, false).reduceList(Blocks);
1090 if (Error E = Result.takeError())
1091 return E;
Daniel Berlin271ca402016-07-27 16:13:25 +00001092 if (Blocks.size() < OldSize)
1093 BD.EmitProgressBitcode(BD.getProgram(), "reduced-conditionals");
1094 }
1095
Chris Lattnerf32939b2003-04-24 23:51:38 +00001096 // Attempt to delete entire basic blocks at a time to speed up
1097 // convergence... this actually works by setting the terminator of the blocks
1098 // to a return instruction then running simplifycfg, which can potentially
1099 // shrinks the code dramatically quickly
1100 //
Chris Lattnerbeb01fa2005-08-02 02:16:17 +00001101 if (!DisableSimplifyCFG && !BugpointIsInterrupted) {
Justin Bogner8d0a0812016-09-02 01:21:37 +00001102 std::vector<const BasicBlock *> Blocks;
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +00001103 for (Function &F : *BD.getProgram())
1104 for (BasicBlock &BB : F)
1105 Blocks.push_back(&BB);
Torok Edwin6ee6f732009-05-24 09:40:47 +00001106 unsigned OldSize = Blocks.size();
Justin Bogner1c039152016-09-06 17:18:22 +00001107 Expected<bool> Result = ReduceCrashingBlocks(BD, TestFn).reduceList(Blocks);
1108 if (Error E = Result.takeError())
1109 return E;
Torok Edwin6ee6f732009-05-24 09:40:47 +00001110 if (Blocks.size() < OldSize)
Rafael Espindola594994a2010-07-28 18:12:30 +00001111 BD.EmitProgressBitcode(BD.getProgram(), "reduced-blocks");
Chris Lattnerd1e2aae2003-08-05 15:51:05 +00001112 }
Chris Lattnerd4e04742002-12-23 23:49:59 +00001113
Daniel Berlin60606262016-07-28 22:29:25 +00001114 if (!DisableSimplifyCFG & !BugpointIsInterrupted) {
Justin Bogner8d0a0812016-09-02 01:21:37 +00001115 std::vector<const BasicBlock *> Blocks;
Daniel Berlin60606262016-07-28 22:29:25 +00001116 for (Function &F : *BD.getProgram())
1117 for (BasicBlock &BB : F)
1118 Blocks.push_back(&BB);
1119 unsigned OldSize = Blocks.size();
Justin Bogner1c039152016-09-06 17:18:22 +00001120 Expected<bool> Result = ReduceSimplifyCFG(BD, TestFn).reduceList(Blocks);
1121 if (Error E = Result.takeError())
1122 return E;
Daniel Berlin60606262016-07-28 22:29:25 +00001123 if (Blocks.size() < OldSize)
1124 BD.EmitProgressBitcode(BD.getProgram(), "reduced-simplifycfg");
1125 }
Justin Bogner8d0a0812016-09-02 01:21:37 +00001126
Nick Lewycky6e090c92009-05-25 05:30:00 +00001127 // Attempt to delete instructions using bisection. This should help out nasty
1128 // cases with large basic blocks where the problem is at one end.
Philip Reames1c232f92016-06-29 00:43:18 +00001129 if (!BugpointIsInterrupted)
Justin Bogner1c039152016-09-06 17:18:22 +00001130 if (Error E = ReduceInsts(BD, TestFn))
1131 return E;
Keno Fischer34ca8312015-11-06 00:12:50 +00001132
Michael Ilsemane5428042016-10-25 18:44:13 +00001133 // Attempt to strip debug info metadata.
1134 auto stripMetadata = [&](std::function<bool(Module &)> strip) {
1135 std::unique_ptr<Module> M = CloneModule(BD.getProgram());
1136 strip(*M);
1137 if (TestFn(BD, M.get()))
1138 BD.setNewProgram(M.release());
1139 };
1140 if (!NoStripDebugInfo && !BugpointIsInterrupted) {
1141 outs() << "\n*** Attempting to strip the debug info: ";
1142 stripMetadata(StripDebugInfo);
1143 }
1144 if (!NoStripDebugTypeInfo && !BugpointIsInterrupted) {
1145 outs() << "\n*** Attempting to strip the debug type info: ";
1146 stripMetadata(stripNonLineTableDebugInfo);
1147 }
1148
Keno Fischer34ca8312015-11-06 00:12:50 +00001149 if (!NoNamedMDRM) {
Keno Fischer34ca8312015-11-06 00:12:50 +00001150 if (!BugpointIsInterrupted) {
1151 // Try to reduce the amount of global metadata (particularly debug info),
1152 // by dropping global named metadata that anchors them
1153 outs() << "\n*** Attempting to remove named metadata: ";
1154 std::vector<std::string> NamedMDNames;
1155 for (auto &NamedMD : BD.getProgram()->named_metadata())
1156 NamedMDNames.push_back(NamedMD.getName().str());
Justin Bogner1c039152016-09-06 17:18:22 +00001157 Expected<bool> Result =
1158 ReduceCrashingNamedMD(BD, TestFn).reduceList(NamedMDNames);
1159 if (Error E = Result.takeError())
1160 return E;
Keno Fischer34ca8312015-11-06 00:12:50 +00001161 }
1162
1163 if (!BugpointIsInterrupted) {
1164 // Now that we quickly dropped all the named metadata that doesn't
1165 // contribute to the crash, bisect the operands of the remaining ones
1166 std::vector<const MDNode *> NamedMDOps;
1167 for (auto &NamedMD : BD.getProgram()->named_metadata())
Keno Fischer256df862015-11-06 00:45:47 +00001168 for (auto op : NamedMD.operands())
1169 NamedMDOps.push_back(op);
Justin Bogner1c039152016-09-06 17:18:22 +00001170 Expected<bool> Result =
1171 ReduceCrashingNamedMDOps(BD, TestFn).reduceList(NamedMDOps);
1172 if (Error E = Result.takeError())
1173 return E;
Keno Fischer34ca8312015-11-06 00:12:50 +00001174 }
Philip Reamesac285cc2016-06-29 00:10:39 +00001175 BD.EmitProgressBitcode(BD.getProgram(), "reduced-named-md");
Keno Fischer34ca8312015-11-06 00:12:50 +00001176 }
1177
Chris Lattner514c02e2003-02-28 16:13:20 +00001178 // Try to clean up the testcase by running funcresolve and globaldce...
Chris Lattnerbeb01fa2005-08-02 02:16:17 +00001179 if (!BugpointIsInterrupted) {
Dan Gohmanee051522009-07-16 15:30:09 +00001180 outs() << "\n*** Attempting to perform final cleanups: ";
Rafael Espindolacab951d2015-12-08 23:57:17 +00001181 Module *M = CloneModule(BD.getProgram()).release();
Rafael Espindola28b351a2014-08-26 17:19:03 +00001182 M = BD.performFinalCleanups(M, true).release();
Misha Brukman650ba8e2005-04-22 00:00:37 +00001183
Chris Lattnerbeb01fa2005-08-02 02:16:17 +00001184 // Find out if the pass still crashes on the cleaned up program...
1185 if (TestFn(BD, M)) {
Justin Bogner8d0a0812016-09-02 01:21:37 +00001186 BD.setNewProgram(M); // Yup, it does, keep the reduced version...
Chris Lattnerbeb01fa2005-08-02 02:16:17 +00001187 } else {
1188 delete M;
1189 }
Chris Lattner514c02e2003-02-28 16:13:20 +00001190 }
1191
Rafael Espindola594994a2010-07-28 18:12:30 +00001192 BD.EmitProgressBitcode(BD.getProgram(), "reduced-simplified");
Chris Lattner514c02e2003-02-28 16:13:20 +00001193
Justin Bogner1c039152016-09-06 17:18:22 +00001194 return Error::success();
Chris Lattner73a6bdd2002-11-20 22:28:10 +00001195}
Brian Gaeke960707c2003-11-11 22:41:34 +00001196
Rafael Espindolad1c7ef42010-08-05 03:00:22 +00001197static bool TestForOptimizerCrash(const BugDriver &BD, Module *M) {
Philip Reamese5b56022016-06-29 03:01:13 +00001198 return BD.runPasses(M, BD.getPassesToRun());
Chris Lattner8bda4c42004-02-18 23:26:28 +00001199}
Chris Lattneread1dff2004-02-18 21:02:04 +00001200
Chris Lattner8bda4c42004-02-18 23:26:28 +00001201/// debugOptimizerCrash - This method is called when some pass crashes on input.
1202/// It attempts to prune down the testcase to something reasonable, and figure
1203/// out exactly which pass is crashing.
1204///
Justin Bogner1c039152016-09-06 17:18:22 +00001205Error BugDriver::debugOptimizerCrash(const std::string &ID) {
Dan Gohmanee051522009-07-16 15:30:09 +00001206 outs() << "\n*** Debugging optimizer crash!\n";
Chris Lattner8bda4c42004-02-18 23:26:28 +00001207
1208 // Reduce the list of passes which causes the optimizer to crash...
Justin Bogner1c039152016-09-06 17:18:22 +00001209 if (!BugpointIsInterrupted && !DontReducePassList) {
1210 Expected<bool> Result = ReducePassList(*this).reduceList(PassesToRun);
1211 if (Error E = Result.takeError())
1212 return E;
1213 }
Chris Lattner8bda4c42004-02-18 23:26:28 +00001214
Dan Gohmanee051522009-07-16 15:30:09 +00001215 outs() << "\n*** Found crashing pass"
1216 << (PassesToRun.size() == 1 ? ": " : "es: ")
1217 << getPassesString(PassesToRun) << '\n';
Chris Lattner8bda4c42004-02-18 23:26:28 +00001218
Rafael Espindola594994a2010-07-28 18:12:30 +00001219 EmitProgressBitcode(Program, ID);
Chris Lattner8bda4c42004-02-18 23:26:28 +00001220
Justin Bogner1c039152016-09-06 17:18:22 +00001221 return DebugACrash(*this, TestForOptimizerCrash);
Chris Lattner8bda4c42004-02-18 23:26:28 +00001222}
1223
Rafael Espindolad1c7ef42010-08-05 03:00:22 +00001224static bool TestForCodeGenCrash(const BugDriver &BD, Module *M) {
Justin Bogner1c039152016-09-06 17:18:22 +00001225 if (Error E = BD.compileProgram(M)) {
Sebastian Pop8f7d0192016-07-15 23:15:06 +00001226 if (VerboseErrors)
Justin Bogner1c039152016-09-06 17:18:22 +00001227 errs() << toString(std::move(E)) << "\n";
1228 else {
1229 consumeError(std::move(E));
Sebastian Pop8f7d0192016-07-15 23:15:06 +00001230 errs() << "<crash>\n";
Justin Bogner1c039152016-09-06 17:18:22 +00001231 }
Justin Bogner8d0a0812016-09-02 01:21:37 +00001232 return true; // Tool is still crashing.
Chris Lattner8bda4c42004-02-18 23:26:28 +00001233 }
Nick Lewycky6ba630b2010-04-12 05:08:25 +00001234 errs() << '\n';
1235 return false;
Chris Lattner8bda4c42004-02-18 23:26:28 +00001236}
Chris Lattneread1dff2004-02-18 21:02:04 +00001237
1238/// debugCodeGeneratorCrash - This method is called when the code generator
1239/// crashes on an input. It attempts to reduce the input as much as possible
1240/// while still causing the code generator to crash.
Justin Bogner1c039152016-09-06 17:18:22 +00001241Error BugDriver::debugCodeGeneratorCrash() {
Dan Gohmand8db3762009-07-15 16:35:29 +00001242 errs() << "*** Debugging code generator crash!\n";
Chris Lattneread1dff2004-02-18 21:02:04 +00001243
Justin Bogner1c039152016-09-06 17:18:22 +00001244 return DebugACrash(*this, TestForCodeGenCrash);
Chris Lattneread1dff2004-02-18 21:02:04 +00001245}