blob: 476e117bbf8768fa93cddf7a5197c397999a267e [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
Vedant Kumar08d829d2018-02-08 18:46:49 +0000122using BugTester = bool (*)(const BugDriver &, Module *);
123
Bill Wendling3f833432006-10-25 18:36:14 +0000124namespace {
Vedant Kumar66e85e62018-02-08 20:27:09 +0000125/// ReduceCrashingGlobalInitializers - This works by removing global variable
126/// initializers and seeing if the program still crashes. If it does, then we
127/// keep that program and try again.
128class ReduceCrashingGlobalInitializers : public ListReducer<GlobalVariable *> {
Justin Bogner8d0a0812016-09-02 01:21:37 +0000129 BugDriver &BD;
Vedant Kumar08d829d2018-02-08 18:46:49 +0000130 BugTester TestFn;
Justin Bogner8d0a0812016-09-02 01:21:37 +0000131
132public:
Vedant Kumar66e85e62018-02-08 20:27:09 +0000133 ReduceCrashingGlobalInitializers(BugDriver &bd, BugTester testFn)
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
Vedant Kumar66e85e62018-02-08 20:27:09 +0000149bool ReduceCrashingGlobalInitializers::TestGlobalVariables(
Justin Bogner8d0a0812016-09-02 01:21:37 +0000150 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;
Vedant Kumar66e85e62018-02-08 20:27:09 +0000153 std::unique_ptr<Module> M = CloneModule(BD.getProgram(), VMap);
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...
Vedant Kumar66e85e62018-02-08 20:27:09 +0000178 if (TestFn(BD, M.get())) {
179 BD.setNewProgram(M.release()); // 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
Bill Wendling3f833432006-10-25 18:36:14 +0000187 return false;
188}
189
David Blaikiea379b1812011-12-20 02:50:00 +0000190namespace {
Justin Bogner8d0a0812016-09-02 01:21:37 +0000191/// ReduceCrashingFunctions reducer - This works by removing functions and
192/// seeing if the program still crashes. If it does, then keep the newer,
193/// smaller program.
194///
195class ReduceCrashingFunctions : public ListReducer<Function *> {
196 BugDriver &BD;
Vedant Kumar08d829d2018-02-08 18:46:49 +0000197 BugTester TestFn;
Justin Bogner8d0a0812016-09-02 01:21:37 +0000198
199public:
Vedant Kumar08d829d2018-02-08 18:46:49 +0000200 ReduceCrashingFunctions(BugDriver &bd, BugTester testFn)
Chris Lattner8bda4c42004-02-18 23:26:28 +0000201 : BD(bd), TestFn(testFn) {}
Misha Brukman650ba8e2005-04-22 00:00:37 +0000202
Justin Bogner1c039152016-09-06 17:18:22 +0000203 Expected<TestResult> doTest(std::vector<Function *> &Prefix,
204 std::vector<Function *> &Kept) override {
Justin Bogner8d0a0812016-09-02 01:21:37 +0000205 if (!Kept.empty() && TestFuncs(Kept))
206 return KeepSuffix;
207 if (!Prefix.empty() && TestFuncs(Prefix))
208 return KeepPrefix;
209 return NoFailure;
210 }
Misha Brukman650ba8e2005-04-22 00:00:37 +0000211
Justin Bogner8d0a0812016-09-02 01:21:37 +0000212 bool TestFuncs(std::vector<Function *> &Prefix);
213};
Chris Lattner2f1aa112004-01-14 03:38:37 +0000214}
Chris Lattner1d080f22003-04-24 22:24:58 +0000215
Justin Bogner8d0a0812016-09-02 01:21:37 +0000216static void RemoveFunctionReferences(Module *M, const char *Name) {
JF Bastienf87e20d2015-04-20 23:42:22 +0000217 auto *UsedVar = M->getGlobalVariable(Name, true);
Justin Bogner8d0a0812016-09-02 01:21:37 +0000218 if (!UsedVar || !UsedVar->hasInitializer())
219 return;
JF Bastienf87e20d2015-04-20 23:42:22 +0000220 if (isa<ConstantAggregateZero>(UsedVar->getInitializer())) {
221 assert(UsedVar->use_empty());
222 UsedVar->eraseFromParent();
223 return;
224 }
225 auto *OldUsedVal = cast<ConstantArray>(UsedVar->getInitializer());
Justin Bogner8d0a0812016-09-02 01:21:37 +0000226 std::vector<Constant *> Used;
227 for (Value *V : OldUsedVal->operand_values()) {
JF Bastienf87e20d2015-04-20 23:42:22 +0000228 Constant *Op = cast<Constant>(V->stripPointerCasts());
Justin Bogner8d0a0812016-09-02 01:21:37 +0000229 if (!Op->isNullValue()) {
JF Bastienf87e20d2015-04-20 23:42:22 +0000230 Used.push_back(cast<Constant>(V));
231 }
232 }
233 auto *NewValElemTy = OldUsedVal->getType()->getElementType();
234 auto *NewValTy = ArrayType::get(NewValElemTy, Used.size());
235 auto *NewUsedVal = ConstantArray::get(NewValTy, Used);
236 UsedVar->mutateType(NewUsedVal->getType()->getPointerTo());
237 UsedVar->setInitializer(NewUsedVal);
238}
239
Justin Bogner8d0a0812016-09-02 01:21:37 +0000240bool ReduceCrashingFunctions::TestFuncs(std::vector<Function *> &Funcs) {
Dmitri Gribenko6e0520e2013-09-02 01:18:56 +0000241 // If main isn't present, claim there is no problem.
David Majnemer0d955d02016-08-11 22:21:41 +0000242 if (KeepMain && !is_contained(Funcs, BD.getProgram()->getFunction("main")))
Andrew Lenharthef9aa122006-03-05 22:21:36 +0000243 return false;
244
Misha Brukman8b2bd4e2003-10-10 17:57:28 +0000245 // Clone the program to try hacking it apart...
Rafael Espindola229e38f2010-10-13 01:36:30 +0000246 ValueToValueMapTy VMap;
Rafael Espindolacab951d2015-12-08 23:57:17 +0000247 Module *M = CloneModule(BD.getProgram(), VMap).release();
Misha Brukman650ba8e2005-04-22 00:00:37 +0000248
Chris Lattner1d080f22003-04-24 22:24:58 +0000249 // Convert list to set for fast lookup...
Justin Bogner8d0a0812016-09-02 01:21:37 +0000250 std::set<Function *> Functions;
Chris Lattner1d080f22003-04-24 22:24:58 +0000251 for (unsigned i = 0, e = Funcs.size(); i != e; ++i) {
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000252 Function *CMF = cast<Function>(VMap[Funcs[i]]);
Chris Lattner1d080f22003-04-24 22:24:58 +0000253 assert(CMF && "Function not in module?!");
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000254 assert(CMF->getFunctionType() == Funcs[i]->getFunctionType() && "wrong ty");
Dan Gohmanbcad7182009-03-06 02:16:23 +0000255 assert(CMF->getName() == Funcs[i]->getName() && "wrong name");
Chris Lattnerde39f2b2003-04-24 22:54:06 +0000256 Functions.insert(CMF);
Chris Lattner1d080f22003-04-24 22:24:58 +0000257 }
258
Dan Gohmanee051522009-07-16 15:30:09 +0000259 outs() << "Checking for crash with only these functions: ";
Chris Lattnerfd72bed2004-03-14 20:50:42 +0000260 PrintFunctionList(Funcs);
Dan Gohmanee051522009-07-16 15:30:09 +0000261 outs() << ": ";
JF Bastienf87e20d2015-04-20 23:42:22 +0000262 if (!ReplaceFuncsWithNull) {
263 // Loop over and delete any functions which we aren't supposed to be playing
264 // with...
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000265 for (Function &I : *M)
266 if (!I.isDeclaration() && !Functions.count(&I))
267 DeleteFunctionBody(&I);
JF Bastienf87e20d2015-04-20 23:42:22 +0000268 } else {
Justin Bogner8d0a0812016-09-02 01:21:37 +0000269 std::vector<GlobalValue *> ToRemove;
JF Bastienf87e20d2015-04-20 23:42:22 +0000270 // First, remove aliases to functions we're about to purge.
271 for (GlobalAlias &Alias : M->aliases()) {
David Majnemer95549492016-05-04 00:20:48 +0000272 GlobalObject *Root = Alias.getBaseObject();
273 Function *F = dyn_cast_or_null<Function>(Root);
JF Bastienf87e20d2015-04-20 23:42:22 +0000274 if (F) {
275 if (Functions.count(F))
276 // We're keeping this function.
277 continue;
278 } else if (Root->isNullValue()) {
279 // This referenced a globalalias that we've already replaced,
280 // so we still need to replace this alias.
281 } else if (!F) {
282 // Not a function, therefore not something we mess with.
283 continue;
284 }
Chris Lattner1d080f22003-04-24 22:24:58 +0000285
JF Bastienf87e20d2015-04-20 23:42:22 +0000286 PointerType *Ty = cast<PointerType>(Alias.getType());
287 Constant *Replacement = ConstantPointerNull::get(Ty);
288 Alias.replaceAllUsesWith(Replacement);
289 ToRemove.push_back(&Alias);
290 }
Chris Lattner1d080f22003-04-24 22:24:58 +0000291
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000292 for (Function &I : *M) {
293 if (!I.isDeclaration() && !Functions.count(&I)) {
294 PointerType *Ty = cast<PointerType>(I.getType());
JF Bastienf87e20d2015-04-20 23:42:22 +0000295 Constant *Replacement = ConstantPointerNull::get(Ty);
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000296 I.replaceAllUsesWith(Replacement);
297 ToRemove.push_back(&I);
JF Bastienf87e20d2015-04-20 23:42:22 +0000298 }
299 }
300
301 for (auto *F : ToRemove) {
302 F->eraseFromParent();
303 }
304
305 // Finally, remove any null members from any global intrinsic.
306 RemoveFunctionReferences(M, "llvm.used");
307 RemoveFunctionReferences(M, "llvm.compiler.used");
308 }
Chris Lattner1d080f22003-04-24 22:24:58 +0000309 // Try running the hacked up program...
Chris Lattner8bda4c42004-02-18 23:26:28 +0000310 if (TestFn(BD, M)) {
Justin Bogner8d0a0812016-09-02 01:21:37 +0000311 BD.setNewProgram(M); // It crashed, keep the trimmed version...
Chris Lattner1d080f22003-04-24 22:24:58 +0000312
313 // Make sure to use function pointers that point into the now-current
314 // module.
315 Funcs.assign(Functions.begin(), Functions.end());
316 return true;
317 }
Chris Lattner327019b2004-02-18 21:24:48 +0000318 delete M;
Chris Lattner1d080f22003-04-24 22:24:58 +0000319 return false;
320}
321
Chris Lattner1942f982004-02-18 21:29:46 +0000322namespace {
Daniel Berlin60606262016-07-28 22:29:25 +0000323/// Simplify the CFG without completely destroying it.
324/// This is not well defined, but basically comes down to "try to eliminate
325/// unreachable blocks and constant fold terminators without deciding that
326/// certain undefined behavior cuts off the program at the legs".
327void simpleSimplifyCfg(Function &F, SmallVectorImpl<BasicBlock *> &BBs) {
328 if (F.empty())
329 return;
330
331 for (auto *BB : BBs) {
332 ConstantFoldTerminator(BB);
333 MergeBlockIntoPredecessor(BB);
334 }
335
336 // Remove unreachable blocks
337 // removeUnreachableBlocks can't be used here, it will turn various
338 // undefined behavior into unreachables, but bugpoint was the thing that
339 // generated the undefined behavior, and we don't want it to kill the entire
340 // program.
341 SmallPtrSet<BasicBlock *, 16> Visited;
342 for (auto *BB : depth_first(&F.getEntryBlock()))
343 Visited.insert(BB);
344
345 SmallVector<BasicBlock *, 16> Unreachable;
346 for (auto &BB : F)
347 if (!Visited.count(&BB))
348 Unreachable.push_back(&BB);
349
350 // The dead BB's may be in a dead cycle or otherwise have references to each
351 // other. Because of this, we have to drop all references first, then delete
352 // them all at once.
Justin Bogner8d0a0812016-09-02 01:21:37 +0000353 for (auto *BB : Unreachable) {
Daniel Berlin60606262016-07-28 22:29:25 +0000354 for (BasicBlock *Successor : successors(&*BB))
355 if (Visited.count(Successor))
356 Successor->removePredecessor(&*BB);
357 BB->dropAllReferences();
358 }
359 for (auto *BB : Unreachable)
360 BB->eraseFromParent();
361}
Justin Bogner8d0a0812016-09-02 01:21:37 +0000362/// ReduceCrashingBlocks reducer - This works by setting the terminators of
363/// all terminators except the specified basic blocks to a 'ret' instruction,
364/// then running the simplify-cfg pass. This has the effect of chopping up
365/// the CFG really fast which can reduce large functions quickly.
366///
367class ReduceCrashingBlocks : public ListReducer<const BasicBlock *> {
368 BugDriver &BD;
Vedant Kumar08d829d2018-02-08 18:46:49 +0000369 BugTester TestFn;
Justin Bogner8d0a0812016-09-02 01:21:37 +0000370
371public:
Vedant Kumar08d829d2018-02-08 18:46:49 +0000372 ReduceCrashingBlocks(BugDriver &BD, BugTester testFn)
Daniel Berlin60606262016-07-28 22:29:25 +0000373 : BD(BD), TestFn(testFn) {}
Misha Brukman650ba8e2005-04-22 00:00:37 +0000374
Justin Bogner1c039152016-09-06 17:18:22 +0000375 Expected<TestResult> doTest(std::vector<const BasicBlock *> &Prefix,
376 std::vector<const BasicBlock *> &Kept) override {
Justin Bogner8d0a0812016-09-02 01:21:37 +0000377 if (!Kept.empty() && TestBlocks(Kept))
378 return KeepSuffix;
379 if (!Prefix.empty() && TestBlocks(Prefix))
380 return KeepPrefix;
381 return NoFailure;
382 }
Misha Brukman650ba8e2005-04-22 00:00:37 +0000383
Justin Bogner8d0a0812016-09-02 01:21:37 +0000384 bool TestBlocks(std::vector<const BasicBlock *> &Prefix);
385};
Chris Lattner2f1aa112004-01-14 03:38:37 +0000386}
Chris Lattnerf32939b2003-04-24 23:51:38 +0000387
Justin Bogner8d0a0812016-09-02 01:21:37 +0000388bool ReduceCrashingBlocks::TestBlocks(std::vector<const BasicBlock *> &BBs) {
Misha Brukman8b2bd4e2003-10-10 17:57:28 +0000389 // Clone the program to try hacking it apart...
Rafael Espindola229e38f2010-10-13 01:36:30 +0000390 ValueToValueMapTy VMap;
Rafael Espindolacab951d2015-12-08 23:57:17 +0000391 Module *M = CloneModule(BD.getProgram(), VMap).release();
Misha Brukman650ba8e2005-04-22 00:00:37 +0000392
Chris Lattnerf32939b2003-04-24 23:51:38 +0000393 // Convert list to set for fast lookup...
Justin Bogner8d0a0812016-09-02 01:21:37 +0000394 SmallPtrSet<BasicBlock *, 8> Blocks;
Nick Lewyckyb294e312009-04-04 09:39:23 +0000395 for (unsigned i = 0, e = BBs.size(); i != e; ++i)
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000396 Blocks.insert(cast<BasicBlock>(VMap[BBs[i]]));
Chris Lattnerf32939b2003-04-24 23:51:38 +0000397
Dan Gohmanee051522009-07-16 15:30:09 +0000398 outs() << "Checking for crash with only these blocks:";
Chris Lattner4f50ebd2003-10-27 04:44:59 +0000399 unsigned NumPrint = Blocks.size();
Justin Bogner8d0a0812016-09-02 01:21:37 +0000400 if (NumPrint > 10)
401 NumPrint = 10;
Chris Lattner4f50ebd2003-10-27 04:44:59 +0000402 for (unsigned i = 0, e = NumPrint; i != e; ++i)
Dan Gohmanee051522009-07-16 15:30:09 +0000403 outs() << " " << BBs[i]->getName();
Chris Lattner4f50ebd2003-10-27 04:44:59 +0000404 if (NumPrint < Blocks.size())
Dan Gohmanee051522009-07-16 15:30:09 +0000405 outs() << "... <" << Blocks.size() << " total>";
406 outs() << ": ";
Chris Lattnerf32939b2003-04-24 23:51:38 +0000407
408 // Loop over and delete any hack up any blocks that are not listed...
409 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
410 for (Function::iterator BB = I->begin(), E = I->end(); BB != E; ++BB)
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000411 if (!Blocks.count(&*BB) && BB->getTerminator()->getNumSuccessors()) {
Chris Lattnerf32939b2003-04-24 23:51:38 +0000412 // Loop over all of the successors of this block, deleting any PHI nodes
413 // that might include it.
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000414 for (succ_iterator SI = succ_begin(&*BB), E = succ_end(&*BB); SI != E;
415 ++SI)
416 (*SI)->removePredecessor(&*BB);
Chris Lattnerf32939b2003-04-24 23:51:38 +0000417
Chris Lattner7855a5c2008-04-28 00:04:58 +0000418 TerminatorInst *BBTerm = BB->getTerminator();
Philip Reames29e641c2016-06-29 00:15:35 +0000419 if (BBTerm->isEHPad() || BBTerm->getType()->isTokenTy())
David Majnemer189d7da2015-11-08 04:16:12 +0000420 continue;
Philip Reames29e641c2016-06-29 00:15:35 +0000421 if (!BBTerm->getType()->isVoidTy())
Owen Anderson5a1acd92009-07-31 20:28:14 +0000422 BBTerm->replaceAllUsesWith(Constant::getNullValue(BBTerm->getType()));
Chris Lattner7b233af2003-11-22 02:10:38 +0000423
Chris Lattner7855a5c2008-04-28 00:04:58 +0000424 // Replace the old terminator instruction.
Chris Lattnerf32939b2003-04-24 23:51:38 +0000425 BB->getInstList().pop_back();
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000426 new UnreachableInst(BB->getContext(), &*BB);
Chris Lattnerf32939b2003-04-24 23:51:38 +0000427 }
428
429 // The CFG Simplifier pass may delete one of the basic blocks we are
430 // interested in. If it does we need to take the block out of the list. Make
431 // a "persistent mapping" by turning basic blocks into <function, name> pairs.
432 // This won't work well if blocks are unnamed, but that is just the risk we
433 // have to take.
Justin Bogner8d0a0812016-09-02 01:21:37 +0000434 std::vector<std::pair<std::string, std::string>> BlockInfo;
Chris Lattnerf32939b2003-04-24 23:51:38 +0000435
Craig Topper46276792014-08-24 23:23:06 +0000436 for (BasicBlock *BB : Blocks)
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000437 BlockInfo.emplace_back(BB->getParent()->getName(), BB->getName());
Justin Bogner8d0a0812016-09-02 01:21:37 +0000438
Daniel Berlin60606262016-07-28 22:29:25 +0000439 SmallVector<BasicBlock *, 16> ToProcess;
Justin Bogner8d0a0812016-09-02 01:21:37 +0000440 for (auto &F : *M) {
Daniel Berlin60606262016-07-28 22:29:25 +0000441 for (auto &BB : F)
442 if (!Blocks.count(&BB))
443 ToProcess.push_back(&BB);
444 simpleSimplifyCfg(F, ToProcess);
445 ToProcess.clear();
446 }
447 // Verify we didn't break anything
Rafael Espindolad1e241a2010-08-10 15:46:11 +0000448 std::vector<std::string> Passes;
Rafael Espindolad1e241a2010-08-10 15:46:11 +0000449 Passes.push_back("verify");
Rafael Espindola28b351a2014-08-26 17:19:03 +0000450 std::unique_ptr<Module> New = BD.runPassesOn(M, Passes);
Rafael Espindolad1e241a2010-08-10 15:46:11 +0000451 delete M;
452 if (!New) {
Daniel Berlin60606262016-07-28 22:29:25 +0000453 errs() << "verify failed!\n";
Rafael Espindolad1e241a2010-08-10 15:46:11 +0000454 exit(1);
455 }
Rafael Espindola28b351a2014-08-26 17:19:03 +0000456 M = New.release();
Justin Bogner8d0a0812016-09-02 01:21:37 +0000457
Chris Lattnerf32939b2003-04-24 23:51:38 +0000458 // Try running on the hacked up program...
Chris Lattner8bda4c42004-02-18 23:26:28 +0000459 if (TestFn(BD, M)) {
Justin Bogner8d0a0812016-09-02 01:21:37 +0000460 BD.setNewProgram(M); // It crashed, keep the trimmed version...
Chris Lattnerf32939b2003-04-24 23:51:38 +0000461
462 // Make sure to use basic block pointers that point into the now-current
463 // module, and that they don't include any deleted blocks.
464 BBs.clear();
Rafael Espindolad1e241a2010-08-10 15:46:11 +0000465 const ValueSymbolTable &GST = M->getValueSymbolTable();
Chris Lattnerf32939b2003-04-24 23:51:38 +0000466 for (unsigned i = 0, e = BlockInfo.size(); i != e; ++i) {
Rafael Espindolad1e241a2010-08-10 15:46:11 +0000467 Function *F = cast<Function>(GST.lookup(BlockInfo[i].first));
Mehdi Aminia53d49e2016-09-17 06:00:02 +0000468 Value *V = F->getValueSymbolTable()->lookup(BlockInfo[i].second);
Owen Anderson55f1c092009-08-13 21:58:54 +0000469 if (V && V->getType() == Type::getLabelTy(V->getContext()))
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000470 BBs.push_back(cast<BasicBlock>(V));
Chris Lattnerf32939b2003-04-24 23:51:38 +0000471 }
472 return true;
473 }
Justin Bogner8d0a0812016-09-02 01:21:37 +0000474 delete M; // It didn't crash, try something else.
Chris Lattnerf32939b2003-04-24 23:51:38 +0000475 return false;
476}
477
Nick Lewycky6e090c92009-05-25 05:30:00 +0000478namespace {
Daniel Berlin271ca402016-07-27 16:13:25 +0000479/// ReduceCrashingConditionals reducer - This works by changing
480/// conditional branches to unconditional ones, then simplifying the CFG
481/// This has the effect of chopping up the CFG really fast which can reduce
482/// large functions quickly.
483///
484class ReduceCrashingConditionals : public ListReducer<const BasicBlock *> {
485 BugDriver &BD;
Vedant Kumar08d829d2018-02-08 18:46:49 +0000486 BugTester TestFn;
Daniel Berlin271ca402016-07-27 16:13:25 +0000487 bool Direction;
488
489public:
Vedant Kumar08d829d2018-02-08 18:46:49 +0000490 ReduceCrashingConditionals(BugDriver &bd, BugTester testFn, bool Direction)
Daniel Berlin271ca402016-07-27 16:13:25 +0000491 : BD(bd), TestFn(testFn), Direction(Direction) {}
492
Justin Bogner1c039152016-09-06 17:18:22 +0000493 Expected<TestResult> doTest(std::vector<const BasicBlock *> &Prefix,
494 std::vector<const BasicBlock *> &Kept) override {
Daniel Berlin271ca402016-07-27 16:13:25 +0000495 if (!Kept.empty() && TestBlocks(Kept))
496 return KeepSuffix;
497 if (!Prefix.empty() && TestBlocks(Prefix))
498 return KeepPrefix;
499 return NoFailure;
500 }
501
502 bool TestBlocks(std::vector<const BasicBlock *> &Prefix);
503};
504}
505
506bool ReduceCrashingConditionals::TestBlocks(
507 std::vector<const BasicBlock *> &BBs) {
508 // Clone the program to try hacking it apart...
509 ValueToValueMapTy VMap;
510 Module *M = CloneModule(BD.getProgram(), VMap).release();
511
512 // Convert list to set for fast lookup...
513 SmallPtrSet<const BasicBlock *, 8> Blocks;
Justin Bogner8d0a0812016-09-02 01:21:37 +0000514 for (const auto *BB : BBs)
Daniel Berlin271ca402016-07-27 16:13:25 +0000515 Blocks.insert(cast<BasicBlock>(VMap[BB]));
516
517 outs() << "Checking for crash with changing conditionals to always jump to "
518 << (Direction ? "true" : "false") << ":";
519 unsigned NumPrint = Blocks.size();
520 if (NumPrint > 10)
521 NumPrint = 10;
522 for (unsigned i = 0, e = NumPrint; i != e; ++i)
523 outs() << " " << BBs[i]->getName();
524 if (NumPrint < Blocks.size())
525 outs() << "... <" << Blocks.size() << " total>";
526 outs() << ": ";
527
528 // Loop over and delete any hack up any blocks that are not listed...
Justin Bogner8d0a0812016-09-02 01:21:37 +0000529 for (auto &F : *M)
Daniel Berlin271ca402016-07-27 16:13:25 +0000530 for (auto &BB : F)
531 if (!Blocks.count(&BB)) {
532 auto *BR = dyn_cast<BranchInst>(BB.getTerminator());
533 if (!BR || !BR->isConditional())
534 continue;
535 if (Direction)
536 BR->setCondition(ConstantInt::getTrue(BR->getContext()));
537 else
538 BR->setCondition(ConstantInt::getFalse(BR->getContext()));
539 }
540
541 // The following may destroy some blocks, so we save them first
542 std::vector<std::pair<std::string, std::string>> BlockInfo;
543
544 for (const BasicBlock *BB : Blocks)
545 BlockInfo.emplace_back(BB->getParent()->getName(), BB->getName());
546
547 SmallVector<BasicBlock *, 16> ToProcess;
Justin Bogner8d0a0812016-09-02 01:21:37 +0000548 for (auto &F : *M) {
Daniel Berlin271ca402016-07-27 16:13:25 +0000549 for (auto &BB : F)
550 if (!Blocks.count(&BB))
551 ToProcess.push_back(&BB);
552 simpleSimplifyCfg(F, ToProcess);
553 ToProcess.clear();
554 }
555 // Verify we didn't break anything
556 std::vector<std::string> Passes;
557 Passes.push_back("verify");
558 std::unique_ptr<Module> New = BD.runPassesOn(M, Passes);
559 delete M;
560 if (!New) {
561 errs() << "verify failed!\n";
562 exit(1);
563 }
564 M = New.release();
565
566 // Try running on the hacked up program...
567 if (TestFn(BD, M)) {
568 BD.setNewProgram(M); // It crashed, keep the trimmed version...
569
570 // Make sure to use basic block pointers that point into the now-current
571 // module, and that they don't include any deleted blocks.
572 BBs.clear();
573 const ValueSymbolTable &GST = M->getValueSymbolTable();
574 for (auto &BI : BlockInfo) {
575 auto *F = cast<Function>(GST.lookup(BI.first));
Mehdi Aminia53d49e2016-09-17 06:00:02 +0000576 Value *V = F->getValueSymbolTable()->lookup(BI.second);
Daniel Berlin271ca402016-07-27 16:13:25 +0000577 if (V && V->getType() == Type::getLabelTy(V->getContext()))
578 BBs.push_back(cast<BasicBlock>(V));
579 }
580 return true;
581 }
582 delete M; // It didn't crash, try something else.
583 return false;
584}
585
586namespace {
Daniel Berlin60606262016-07-28 22:29:25 +0000587/// SimplifyCFG reducer - This works by calling SimplifyCFG on each basic block
588/// in the program.
589
590class ReduceSimplifyCFG : public ListReducer<const BasicBlock *> {
591 BugDriver &BD;
Vedant Kumar08d829d2018-02-08 18:46:49 +0000592 BugTester TestFn;
Daniel Berlin60606262016-07-28 22:29:25 +0000593 TargetTransformInfo TTI;
Justin Bogner8d0a0812016-09-02 01:21:37 +0000594
Daniel Berlin60606262016-07-28 22:29:25 +0000595public:
Vedant Kumar08d829d2018-02-08 18:46:49 +0000596 ReduceSimplifyCFG(BugDriver &bd, BugTester testFn)
Justin Bogner8d0a0812016-09-02 01:21:37 +0000597 : BD(bd), TestFn(testFn), TTI(bd.getProgram()->getDataLayout()) {}
Daniel Berlin60606262016-07-28 22:29:25 +0000598
Justin Bogner1c039152016-09-06 17:18:22 +0000599 Expected<TestResult> doTest(std::vector<const BasicBlock *> &Prefix,
600 std::vector<const BasicBlock *> &Kept) override {
Daniel Berlin60606262016-07-28 22:29:25 +0000601 if (!Kept.empty() && TestBlocks(Kept))
602 return KeepSuffix;
603 if (!Prefix.empty() && TestBlocks(Prefix))
604 return KeepPrefix;
605 return NoFailure;
606 }
607
608 bool TestBlocks(std::vector<const BasicBlock *> &Prefix);
609};
610}
611
Justin Bogner8d0a0812016-09-02 01:21:37 +0000612bool ReduceSimplifyCFG::TestBlocks(std::vector<const BasicBlock *> &BBs) {
Daniel Berlin60606262016-07-28 22:29:25 +0000613 // Clone the program to try hacking it apart...
614 ValueToValueMapTy VMap;
615 Module *M = CloneModule(BD.getProgram(), VMap).release();
616
617 // Convert list to set for fast lookup...
618 SmallPtrSet<const BasicBlock *, 8> Blocks;
Justin Bogner8d0a0812016-09-02 01:21:37 +0000619 for (const auto *BB : BBs)
Daniel Berlin60606262016-07-28 22:29:25 +0000620 Blocks.insert(cast<BasicBlock>(VMap[BB]));
621
622 outs() << "Checking for crash with CFG simplifying:";
623 unsigned NumPrint = Blocks.size();
624 if (NumPrint > 10)
625 NumPrint = 10;
626 for (unsigned i = 0, e = NumPrint; i != e; ++i)
627 outs() << " " << BBs[i]->getName();
628 if (NumPrint < Blocks.size())
629 outs() << "... <" << Blocks.size() << " total>";
630 outs() << ": ";
631
Justin Bogner8d0a0812016-09-02 01:21:37 +0000632 // The following may destroy some blocks, so we save them first
Daniel Berlin60606262016-07-28 22:29:25 +0000633 std::vector<std::pair<std::string, std::string>> BlockInfo;
634
635 for (const BasicBlock *BB : Blocks)
636 BlockInfo.emplace_back(BB->getParent()->getName(), BB->getName());
637
Daniel Berlin60606262016-07-28 22:29:25 +0000638 // Loop over and delete any hack up any blocks that are not listed...
Justin Bogner8d0a0812016-09-02 01:21:37 +0000639 for (auto &F : *M)
640 // Loop over all of the basic blocks and remove them if they are unneeded.
641 for (Function::iterator BBIt = F.begin(); BBIt != F.end();) {
642 if (!Blocks.count(&*BBIt)) {
643 ++BBIt;
644 continue;
645 }
Sanjay Patel4c33d522017-10-04 20:26:25 +0000646 simplifyCFG(&*BBIt++, TTI);
Justin Bogner8d0a0812016-09-02 01:21:37 +0000647 }
Daniel Berlin60606262016-07-28 22:29:25 +0000648 // Verify we didn't break anything
649 std::vector<std::string> Passes;
650 Passes.push_back("verify");
651 std::unique_ptr<Module> New = BD.runPassesOn(M, Passes);
652 delete M;
653 if (!New) {
654 errs() << "verify failed!\n";
655 exit(1);
656 }
657 M = New.release();
658
659 // Try running on the hacked up program...
660 if (TestFn(BD, M)) {
661 BD.setNewProgram(M); // It crashed, keep the trimmed version...
662
663 // Make sure to use basic block pointers that point into the now-current
664 // module, and that they don't include any deleted blocks.
665 BBs.clear();
666 const ValueSymbolTable &GST = M->getValueSymbolTable();
Justin Bogner8d0a0812016-09-02 01:21:37 +0000667 for (auto &BI : BlockInfo) {
Daniel Berlin60606262016-07-28 22:29:25 +0000668 auto *F = cast<Function>(GST.lookup(BI.first));
Mehdi Aminia53d49e2016-09-17 06:00:02 +0000669 Value *V = F->getValueSymbolTable()->lookup(BI.second);
Daniel Berlin60606262016-07-28 22:29:25 +0000670 if (V && V->getType() == Type::getLabelTy(V->getContext()))
671 BBs.push_back(cast<BasicBlock>(V));
672 }
673 return true;
674 }
675 delete M; // It didn't crash, try something else.
676 return false;
677}
678
679namespace {
Justin Bogner8d0a0812016-09-02 01:21:37 +0000680/// ReduceCrashingInstructions reducer - This works by removing the specified
681/// non-terminator instructions and replacing them with undef.
682///
683class ReduceCrashingInstructions : public ListReducer<const Instruction *> {
684 BugDriver &BD;
Vedant Kumar08d829d2018-02-08 18:46:49 +0000685 BugTester TestFn;
Justin Bogner8d0a0812016-09-02 01:21:37 +0000686
687public:
Vedant Kumar08d829d2018-02-08 18:46:49 +0000688 ReduceCrashingInstructions(BugDriver &bd, BugTester testFn)
Nick Lewycky6e090c92009-05-25 05:30:00 +0000689 : BD(bd), TestFn(testFn) {}
690
Justin Bogner1c039152016-09-06 17:18:22 +0000691 Expected<TestResult> doTest(std::vector<const Instruction *> &Prefix,
692 std::vector<const Instruction *> &Kept) override {
Justin Bogner8d0a0812016-09-02 01:21:37 +0000693 if (!Kept.empty() && TestInsts(Kept))
694 return KeepSuffix;
695 if (!Prefix.empty() && TestInsts(Prefix))
696 return KeepPrefix;
697 return NoFailure;
698 }
Nick Lewycky6e090c92009-05-25 05:30:00 +0000699
Justin Bogner8d0a0812016-09-02 01:21:37 +0000700 bool TestInsts(std::vector<const Instruction *> &Prefix);
701};
Nick Lewycky6e090c92009-05-25 05:30:00 +0000702}
703
Justin Bogner8d0a0812016-09-02 01:21:37 +0000704bool ReduceCrashingInstructions::TestInsts(
705 std::vector<const Instruction *> &Insts) {
Nick Lewycky6e090c92009-05-25 05:30:00 +0000706 // Clone the program to try hacking it apart...
Rafael Espindola229e38f2010-10-13 01:36:30 +0000707 ValueToValueMapTy VMap;
Rafael Espindolacab951d2015-12-08 23:57:17 +0000708 Module *M = CloneModule(BD.getProgram(), VMap).release();
Nick Lewycky6e090c92009-05-25 05:30:00 +0000709
710 // Convert list to set for fast lookup...
Justin Bogner8d0a0812016-09-02 01:21:37 +0000711 SmallPtrSet<Instruction *, 32> Instructions;
Nick Lewycky6e090c92009-05-25 05:30:00 +0000712 for (unsigned i = 0, e = Insts.size(); i != e; ++i) {
713 assert(!isa<TerminatorInst>(Insts[i]));
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000714 Instructions.insert(cast<Instruction>(VMap[Insts[i]]));
Nick Lewycky6e090c92009-05-25 05:30:00 +0000715 }
716
Dan Gohmanee051522009-07-16 15:30:09 +0000717 outs() << "Checking for crash with only " << Instructions.size();
Nick Lewycky6e090c92009-05-25 05:30:00 +0000718 if (Instructions.size() == 1)
Dan Gohmanee051522009-07-16 15:30:09 +0000719 outs() << " instruction: ";
Nick Lewycky6e090c92009-05-25 05:30:00 +0000720 else
Dan Gohmanee051522009-07-16 15:30:09 +0000721 outs() << " instructions: ";
Nick Lewycky6e090c92009-05-25 05:30:00 +0000722
723 for (Module::iterator MI = M->begin(), ME = M->end(); MI != ME; ++MI)
724 for (Function::iterator FI = MI->begin(), FE = MI->end(); FI != FE; ++FI)
725 for (BasicBlock::iterator I = FI->begin(), E = FI->end(); I != E;) {
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000726 Instruction *Inst = &*I++;
Eli Friedmand4e02a52011-11-01 04:40:56 +0000727 if (!Instructions.count(Inst) && !isa<TerminatorInst>(Inst) &&
Arnold Schwaighofera8f5a822017-03-07 20:28:59 +0000728 !Inst->isEHPad() && !Inst->getType()->isTokenTy() &&
729 !Inst->isSwiftError()) {
Philip Reames29e641c2016-06-29 00:15:35 +0000730 if (!Inst->getType()->isVoidTy())
Nick Lewycky6e090c92009-05-25 05:30:00 +0000731 Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
732 Inst->eraseFromParent();
733 }
734 }
735
736 // Verify that this is still valid.
Chandler Carruth30d69c22015-02-13 10:01:29 +0000737 legacy::PassManager Passes;
Adrian Prantl919bdf12016-10-18 16:24:43 +0000738 Passes.add(createVerifierPass(/*FatalErrors=*/false));
Nick Lewycky6e090c92009-05-25 05:30:00 +0000739 Passes.run(*M);
740
741 // Try running on the hacked up program...
742 if (TestFn(BD, M)) {
Justin Bogner8d0a0812016-09-02 01:21:37 +0000743 BD.setNewProgram(M); // It crashed, keep the trimmed version...
Nick Lewycky6e090c92009-05-25 05:30:00 +0000744
745 // Make sure to use instruction pointers that point into the now-current
746 // module, and that they don't include any deleted blocks.
747 Insts.clear();
Craig Topper46276792014-08-24 23:23:06 +0000748 for (Instruction *Inst : Instructions)
749 Insts.push_back(Inst);
Nick Lewycky6e090c92009-05-25 05:30:00 +0000750 return true;
751 }
Justin Bogner8d0a0812016-09-02 01:21:37 +0000752 delete M; // It didn't crash, try something else.
Nick Lewycky6e090c92009-05-25 05:30:00 +0000753 return false;
754}
755
Keno Fischer34ca8312015-11-06 00:12:50 +0000756namespace {
757// Reduce the list of Named Metadata nodes. We keep this as a list of
758// names to avoid having to convert back and forth every time.
759class ReduceCrashingNamedMD : public ListReducer<std::string> {
760 BugDriver &BD;
Vedant Kumar08d829d2018-02-08 18:46:49 +0000761 BugTester TestFn;
Keno Fischer34ca8312015-11-06 00:12:50 +0000762
763public:
Vedant Kumar08d829d2018-02-08 18:46:49 +0000764 ReduceCrashingNamedMD(BugDriver &bd, BugTester testFn)
Keno Fischer34ca8312015-11-06 00:12:50 +0000765 : BD(bd), TestFn(testFn) {}
766
Justin Bogner1c039152016-09-06 17:18:22 +0000767 Expected<TestResult> doTest(std::vector<std::string> &Prefix,
768 std::vector<std::string> &Kept) override {
Keno Fischer34ca8312015-11-06 00:12:50 +0000769 if (!Kept.empty() && TestNamedMDs(Kept))
770 return KeepSuffix;
771 if (!Prefix.empty() && TestNamedMDs(Prefix))
772 return KeepPrefix;
773 return NoFailure;
774 }
775
776 bool TestNamedMDs(std::vector<std::string> &NamedMDs);
777};
778}
779
780bool ReduceCrashingNamedMD::TestNamedMDs(std::vector<std::string> &NamedMDs) {
781
782 ValueToValueMapTy VMap;
Rafael Espindolacab951d2015-12-08 23:57:17 +0000783 Module *M = CloneModule(BD.getProgram(), VMap).release();
Keno Fischer34ca8312015-11-06 00:12:50 +0000784
785 outs() << "Checking for crash with only these named metadata nodes:";
786 unsigned NumPrint = std::min<size_t>(NamedMDs.size(), 10);
787 for (unsigned i = 0, e = NumPrint; i != e; ++i)
788 outs() << " " << NamedMDs[i];
789 if (NumPrint < NamedMDs.size())
790 outs() << "... <" << NamedMDs.size() << " total>";
791 outs() << ": ";
792
793 // Make a StringMap for faster lookup
794 StringSet<> Names;
795 for (const std::string &Name : NamedMDs)
796 Names.insert(Name);
797
798 // First collect all the metadata to delete in a vector, then
799 // delete them all at once to avoid invalidating the iterator
800 std::vector<NamedMDNode *> ToDelete;
801 ToDelete.reserve(M->named_metadata_size() - Names.size());
802 for (auto &NamedMD : M->named_metadata())
Adrian Prantlfaebbb02016-03-28 21:06:26 +0000803 // Always keep a nonempty llvm.dbg.cu because the Verifier would complain.
804 if (!Names.count(NamedMD.getName()) &&
805 (!(NamedMD.getName() == "llvm.dbg.cu" && NamedMD.getNumOperands() > 0)))
Keno Fischer34ca8312015-11-06 00:12:50 +0000806 ToDelete.push_back(&NamedMD);
807
808 for (auto *NamedMD : ToDelete)
809 NamedMD->eraseFromParent();
810
811 // Verify that this is still valid.
812 legacy::PassManager Passes;
Adrian Prantl919bdf12016-10-18 16:24:43 +0000813 Passes.add(createVerifierPass(/*FatalErrors=*/false));
Keno Fischer34ca8312015-11-06 00:12:50 +0000814 Passes.run(*M);
815
816 // Try running on the hacked up program...
817 if (TestFn(BD, M)) {
818 BD.setNewProgram(M); // It crashed, keep the trimmed version...
819 return true;
820 }
821 delete M; // It didn't crash, try something else.
822 return false;
823}
824
825namespace {
826// Reduce the list of operands to named metadata nodes
827class ReduceCrashingNamedMDOps : public ListReducer<const MDNode *> {
828 BugDriver &BD;
Vedant Kumar08d829d2018-02-08 18:46:49 +0000829 BugTester TestFn;
Keno Fischer34ca8312015-11-06 00:12:50 +0000830
831public:
Vedant Kumar08d829d2018-02-08 18:46:49 +0000832 ReduceCrashingNamedMDOps(BugDriver &bd, BugTester testFn)
Keno Fischer34ca8312015-11-06 00:12:50 +0000833 : BD(bd), TestFn(testFn) {}
834
Justin Bogner1c039152016-09-06 17:18:22 +0000835 Expected<TestResult> doTest(std::vector<const MDNode *> &Prefix,
836 std::vector<const MDNode *> &Kept) override {
Keno Fischer34ca8312015-11-06 00:12:50 +0000837 if (!Kept.empty() && TestNamedMDOps(Kept))
838 return KeepSuffix;
839 if (!Prefix.empty() && TestNamedMDOps(Prefix))
840 return KeepPrefix;
841 return NoFailure;
842 }
843
844 bool TestNamedMDOps(std::vector<const MDNode *> &NamedMDOps);
845};
846}
847
848bool ReduceCrashingNamedMDOps::TestNamedMDOps(
849 std::vector<const MDNode *> &NamedMDOps) {
850 // Convert list to set for fast lookup...
Matthias Braunb30f2f512016-01-30 01:24:31 +0000851 SmallPtrSet<const MDNode *, 32> OldMDNodeOps;
Keno Fischer34ca8312015-11-06 00:12:50 +0000852 for (unsigned i = 0, e = NamedMDOps.size(); i != e; ++i) {
853 OldMDNodeOps.insert(NamedMDOps[i]);
854 }
855
856 outs() << "Checking for crash with only " << OldMDNodeOps.size();
857 if (OldMDNodeOps.size() == 1)
858 outs() << " named metadata operand: ";
859 else
860 outs() << " named metadata operands: ";
861
862 ValueToValueMapTy VMap;
Rafael Espindolacab951d2015-12-08 23:57:17 +0000863 Module *M = CloneModule(BD.getProgram(), VMap).release();
Keno Fischer34ca8312015-11-06 00:12:50 +0000864
865 // This is a little wasteful. In the future it might be good if we could have
866 // these dropped during cloning.
867 for (auto &NamedMD : BD.getProgram()->named_metadata()) {
868 // Drop the old one and create a new one
869 M->eraseNamedMetadata(M->getNamedMetadata(NamedMD.getName()));
870 NamedMDNode *NewNamedMDNode =
871 M->getOrInsertNamedMetadata(NamedMD.getName());
872 for (MDNode *op : NamedMD.operands())
873 if (OldMDNodeOps.count(op))
874 NewNamedMDNode->addOperand(cast<MDNode>(MapMetadata(op, VMap)));
875 }
876
877 // Verify that this is still valid.
878 legacy::PassManager Passes;
Adrian Prantl919bdf12016-10-18 16:24:43 +0000879 Passes.add(createVerifierPass(/*FatalErrors=*/false));
Keno Fischer34ca8312015-11-06 00:12:50 +0000880 Passes.run(*M);
881
882 // Try running on the hacked up program...
883 if (TestFn(BD, M)) {
884 // Make sure to use instruction pointers that point into the now-current
885 // module, and that they don't include any deleted blocks.
886 NamedMDOps.clear();
887 for (const MDNode *Node : OldMDNodeOps)
Duncan P. N. Exon Smithda4a56d2016-04-02 17:04:38 +0000888 NamedMDOps.push_back(cast<MDNode>(*VMap.getMappedMD(Node)));
Keno Fischer34ca8312015-11-06 00:12:50 +0000889
890 BD.setNewProgram(M); // It crashed, keep the trimmed version...
891 return true;
892 }
893 delete M; // It didn't crash, try something else.
894 return false;
895}
896
Vedant Kumar66e85e62018-02-08 20:27:09 +0000897/// Attempt to eliminate as many global initializers as possible.
Vedant Kumar08d829d2018-02-08 18:46:49 +0000898static Error ReduceGlobalInitializers(BugDriver &BD, BugTester TestFn) {
Vedant Kumar66e85e62018-02-08 20:27:09 +0000899 Module *OrigM = BD.getProgram();
900 if (OrigM->global_empty())
901 return Error::success();
Misha Brukman650ba8e2005-04-22 00:00:37 +0000902
Vedant Kumar66e85e62018-02-08 20:27:09 +0000903 // Now try to reduce the number of global variable initializers in the
904 // module to something small.
905 std::unique_ptr<Module> M = CloneModule(OrigM);
906 bool DeletedInit = false;
Bill Wendling3f833432006-10-25 18:36:14 +0000907
Vedant Kumar66e85e62018-02-08 20:27:09 +0000908 for (GlobalVariable &GV : M->globals()) {
909 if (GV.hasInitializer()) {
910 DeleteGlobalInitializer(&GV);
911 GV.setLinkage(GlobalValue::ExternalLinkage);
912 GV.setComdat(nullptr);
913 DeletedInit = true;
Chris Lattner65e5f652003-04-25 00:53:05 +0000914 }
915 }
Vedant Kumar66e85e62018-02-08 20:27:09 +0000916
917 if (!DeletedInit)
918 return Error::success();
919
920 // See if the program still causes a crash...
921 outs() << "\nChecking to see if we can delete global inits: ";
922
923 if (TestFn(BD, M.get())) { // Still crashes?
924 BD.setNewProgram(M.release());
925 outs() << "\n*** Able to remove all global initializers!\n";
926 return Error::success();
927 }
928
929 // No longer crashes.
930 outs() << " - Removing all global inits hides problem!\n";
931
932 std::vector<GlobalVariable *> GVs;
933 for (GlobalVariable &GV : OrigM->globals())
934 if (GV.hasInitializer())
935 GVs.push_back(&GV);
936
937 if (GVs.size() > 1 && !BugpointIsInterrupted) {
938 outs() << "\n*** Attempting to reduce the number of global initializers "
939 << "in the testcase\n";
940
941 unsigned OldSize = GVs.size();
942 Expected<bool> Result =
943 ReduceCrashingGlobalInitializers(BD, TestFn).reduceList(GVs);
944 if (Error E = Result.takeError())
945 return E;
946
947 if (GVs.size() < OldSize)
948 BD.EmitProgressBitcode(BD.getProgram(), "reduced-global-variables");
949 }
Justin Bogner1c039152016-09-06 17:18:22 +0000950 return Error::success();
Philip Reames1c232f92016-06-29 00:43:18 +0000951}
952
Vedant Kumar08d829d2018-02-08 18:46:49 +0000953static Error ReduceInsts(BugDriver &BD, BugTester TestFn) {
Philip Reames1c232f92016-06-29 00:43:18 +0000954 // Attempt to delete instructions using bisection. This should help out nasty
955 // cases with large basic blocks where the problem is at one end.
956 if (!BugpointIsInterrupted) {
Justin Bogner8d0a0812016-09-02 01:21:37 +0000957 std::vector<const Instruction *> Insts;
Philip Reames1c232f92016-06-29 00:43:18 +0000958 for (const Function &F : *BD.getProgram())
959 for (const BasicBlock &BB : F)
960 for (const Instruction &I : BB)
961 if (!isa<TerminatorInst>(&I))
962 Insts.push_back(&I);
963
Justin Bogner1c039152016-09-06 17:18:22 +0000964 Expected<bool> Result =
965 ReduceCrashingInstructions(BD, TestFn).reduceList(Insts);
966 if (Error E = Result.takeError())
967 return E;
Philip Reames1c232f92016-06-29 00:43:18 +0000968 }
969
970 unsigned Simplification = 2;
971 do {
972 if (BugpointIsInterrupted)
Justin Bogner1c039152016-09-06 17:18:22 +0000973 // TODO: Should we distinguish this with an "interrupted error"?
974 return Error::success();
Philip Reames1c232f92016-06-29 00:43:18 +0000975 --Simplification;
976 outs() << "\n*** Attempting to reduce testcase by deleting instruc"
977 << "tions: Simplification Level #" << Simplification << '\n';
978
979 // Now that we have deleted the functions that are unnecessary for the
980 // program, try to remove instructions that are not necessary to cause the
981 // crash. To do this, we loop through all of the instructions in the
982 // remaining functions, deleting them (replacing any values produced with
983 // nulls), and then running ADCE and SimplifyCFG. If the transformed input
984 // still triggers failure, keep deleting until we cannot trigger failure
985 // anymore.
986 //
987 unsigned InstructionsToSkipBeforeDeleting = 0;
988 TryAgain:
989
990 // Loop over all of the (non-terminator) instructions remaining in the
991 // function, attempting to delete them.
992 unsigned CurInstructionNum = 0;
993 for (Module::const_iterator FI = BD.getProgram()->begin(),
Justin Bogner8d0a0812016-09-02 01:21:37 +0000994 E = BD.getProgram()->end();
995 FI != E; ++FI)
Philip Reames1c232f92016-06-29 00:43:18 +0000996 if (!FI->isDeclaration())
997 for (Function::const_iterator BI = FI->begin(), E = FI->end(); BI != E;
998 ++BI)
999 for (BasicBlock::const_iterator I = BI->begin(), E = --BI->end();
1000 I != E; ++I, ++CurInstructionNum) {
1001 if (InstructionsToSkipBeforeDeleting) {
1002 --InstructionsToSkipBeforeDeleting;
1003 } else {
1004 if (BugpointIsInterrupted)
Justin Bogner1c039152016-09-06 17:18:22 +00001005 // TODO: Should this be some kind of interrupted error?
1006 return Error::success();
Philip Reames1c232f92016-06-29 00:43:18 +00001007
Arnold Schwaighofera8f5a822017-03-07 20:28:59 +00001008 if (I->isEHPad() || I->getType()->isTokenTy() ||
1009 I->isSwiftError())
Philip Reames1c232f92016-06-29 00:43:18 +00001010 continue;
1011
1012 outs() << "Checking instruction: " << *I;
1013 std::unique_ptr<Module> M =
1014 BD.deleteInstructionFromProgram(&*I, Simplification);
1015
1016 // Find out if the pass still crashes on this pass...
1017 if (TestFn(BD, M.get())) {
1018 // Yup, it does, we delete the old module, and continue trying
1019 // to reduce the testcase...
1020 BD.setNewProgram(M.release());
1021 InstructionsToSkipBeforeDeleting = CurInstructionNum;
Justin Bogner8d0a0812016-09-02 01:21:37 +00001022 goto TryAgain; // I wish I had a multi-level break here!
Philip Reames1c232f92016-06-29 00:43:18 +00001023 }
1024 }
1025 }
1026
1027 if (InstructionsToSkipBeforeDeleting) {
1028 InstructionsToSkipBeforeDeleting = 0;
1029 goto TryAgain;
1030 }
1031
1032 } while (Simplification);
1033 BD.EmitProgressBitcode(BD.getProgram(), "reduced-instructions");
Justin Bogner1c039152016-09-06 17:18:22 +00001034 return Error::success();
Philip Reames1c232f92016-06-29 00:43:18 +00001035}
1036
Philip Reames1c232f92016-06-29 00:43:18 +00001037/// DebugACrash - Given a predicate that determines whether a component crashes
1038/// on a program, try to destructively reduce the program while still keeping
1039/// the predicate true.
Vedant Kumar08d829d2018-02-08 18:46:49 +00001040static Error DebugACrash(BugDriver &BD, BugTester TestFn) {
Philip Reames1c232f92016-06-29 00:43:18 +00001041 // See if we can get away with nuking some of the global variable initializers
1042 // in the program...
1043 if (!NoGlobalRM)
Justin Bogner1c039152016-09-06 17:18:22 +00001044 if (Error E = ReduceGlobalInitializers(BD, TestFn))
1045 return E;
Misha Brukman650ba8e2005-04-22 00:00:37 +00001046
Chris Lattner1d080f22003-04-24 22:24:58 +00001047 // Now try to reduce the number of functions in the module to something small.
Justin Bogner8d0a0812016-09-02 01:21:37 +00001048 std::vector<Function *> Functions;
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +00001049 for (Function &F : *BD.getProgram())
1050 if (!F.isDeclaration())
1051 Functions.push_back(&F);
Chris Lattner73a6bdd2002-11-20 22:28:10 +00001052
Chris Lattnerbeb01fa2005-08-02 02:16:17 +00001053 if (Functions.size() > 1 && !BugpointIsInterrupted) {
Dan Gohmanee051522009-07-16 15:30:09 +00001054 outs() << "\n*** Attempting to reduce the number of functions "
Justin Bogner8d0a0812016-09-02 01:21:37 +00001055 "in the testcase\n";
Chris Lattner73a6bdd2002-11-20 22:28:10 +00001056
Chris Lattner8bda4c42004-02-18 23:26:28 +00001057 unsigned OldSize = Functions.size();
Justin Bogner1c039152016-09-06 17:18:22 +00001058 Expected<bool> Result =
1059 ReduceCrashingFunctions(BD, TestFn).reduceList(Functions);
1060 if (Error E = Result.takeError())
1061 return E;
Chris Lattner73a6bdd2002-11-20 22:28:10 +00001062
Chris Lattnerbeb01fa2005-08-02 02:16:17 +00001063 if (Functions.size() < OldSize)
Rafael Espindola594994a2010-07-28 18:12:30 +00001064 BD.EmitProgressBitcode(BD.getProgram(), "reduced-function");
Chris Lattner73a6bdd2002-11-20 22:28:10 +00001065 }
1066
Daniel Berlin271ca402016-07-27 16:13:25 +00001067 // Attempt to change conditional branches into unconditional branches to
1068 // eliminate blocks.
1069 if (!DisableSimplifyCFG && !BugpointIsInterrupted) {
Justin Bogner8d0a0812016-09-02 01:21:37 +00001070 std::vector<const BasicBlock *> Blocks;
Daniel Berlin271ca402016-07-27 16:13:25 +00001071 for (Function &F : *BD.getProgram())
1072 for (BasicBlock &BB : F)
1073 Blocks.push_back(&BB);
1074 unsigned OldSize = Blocks.size();
Justin Bogner1c039152016-09-06 17:18:22 +00001075 Expected<bool> Result =
1076 ReduceCrashingConditionals(BD, TestFn, true).reduceList(Blocks);
1077 if (Error E = Result.takeError())
1078 return E;
1079 Result = ReduceCrashingConditionals(BD, TestFn, false).reduceList(Blocks);
1080 if (Error E = Result.takeError())
1081 return E;
Daniel Berlin271ca402016-07-27 16:13:25 +00001082 if (Blocks.size() < OldSize)
1083 BD.EmitProgressBitcode(BD.getProgram(), "reduced-conditionals");
1084 }
1085
Chris Lattnerf32939b2003-04-24 23:51:38 +00001086 // Attempt to delete entire basic blocks at a time to speed up
1087 // convergence... this actually works by setting the terminator of the blocks
1088 // to a return instruction then running simplifycfg, which can potentially
1089 // shrinks the code dramatically quickly
1090 //
Chris Lattnerbeb01fa2005-08-02 02:16:17 +00001091 if (!DisableSimplifyCFG && !BugpointIsInterrupted) {
Justin Bogner8d0a0812016-09-02 01:21:37 +00001092 std::vector<const BasicBlock *> Blocks;
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +00001093 for (Function &F : *BD.getProgram())
1094 for (BasicBlock &BB : F)
1095 Blocks.push_back(&BB);
Torok Edwin6ee6f732009-05-24 09:40:47 +00001096 unsigned OldSize = Blocks.size();
Justin Bogner1c039152016-09-06 17:18:22 +00001097 Expected<bool> Result = ReduceCrashingBlocks(BD, TestFn).reduceList(Blocks);
1098 if (Error E = Result.takeError())
1099 return E;
Torok Edwin6ee6f732009-05-24 09:40:47 +00001100 if (Blocks.size() < OldSize)
Rafael Espindola594994a2010-07-28 18:12:30 +00001101 BD.EmitProgressBitcode(BD.getProgram(), "reduced-blocks");
Chris Lattnerd1e2aae2003-08-05 15:51:05 +00001102 }
Chris Lattnerd4e04742002-12-23 23:49:59 +00001103
Simon Pilgrim0c559f62017-04-14 15:21:15 +00001104 if (!DisableSimplifyCFG && !BugpointIsInterrupted) {
Justin Bogner8d0a0812016-09-02 01:21:37 +00001105 std::vector<const BasicBlock *> Blocks;
Daniel Berlin60606262016-07-28 22:29:25 +00001106 for (Function &F : *BD.getProgram())
1107 for (BasicBlock &BB : F)
1108 Blocks.push_back(&BB);
1109 unsigned OldSize = Blocks.size();
Justin Bogner1c039152016-09-06 17:18:22 +00001110 Expected<bool> Result = ReduceSimplifyCFG(BD, TestFn).reduceList(Blocks);
1111 if (Error E = Result.takeError())
1112 return E;
Daniel Berlin60606262016-07-28 22:29:25 +00001113 if (Blocks.size() < OldSize)
1114 BD.EmitProgressBitcode(BD.getProgram(), "reduced-simplifycfg");
1115 }
Justin Bogner8d0a0812016-09-02 01:21:37 +00001116
Nick Lewycky6e090c92009-05-25 05:30:00 +00001117 // Attempt to delete instructions using bisection. This should help out nasty
1118 // cases with large basic blocks where the problem is at one end.
Philip Reames1c232f92016-06-29 00:43:18 +00001119 if (!BugpointIsInterrupted)
Justin Bogner1c039152016-09-06 17:18:22 +00001120 if (Error E = ReduceInsts(BD, TestFn))
1121 return E;
Keno Fischer34ca8312015-11-06 00:12:50 +00001122
Michael Ilsemane5428042016-10-25 18:44:13 +00001123 // Attempt to strip debug info metadata.
1124 auto stripMetadata = [&](std::function<bool(Module &)> strip) {
1125 std::unique_ptr<Module> M = CloneModule(BD.getProgram());
1126 strip(*M);
1127 if (TestFn(BD, M.get()))
1128 BD.setNewProgram(M.release());
1129 };
1130 if (!NoStripDebugInfo && !BugpointIsInterrupted) {
1131 outs() << "\n*** Attempting to strip the debug info: ";
1132 stripMetadata(StripDebugInfo);
1133 }
1134 if (!NoStripDebugTypeInfo && !BugpointIsInterrupted) {
1135 outs() << "\n*** Attempting to strip the debug type info: ";
1136 stripMetadata(stripNonLineTableDebugInfo);
1137 }
1138
Keno Fischer34ca8312015-11-06 00:12:50 +00001139 if (!NoNamedMDRM) {
Keno Fischer34ca8312015-11-06 00:12:50 +00001140 if (!BugpointIsInterrupted) {
1141 // Try to reduce the amount of global metadata (particularly debug info),
1142 // by dropping global named metadata that anchors them
1143 outs() << "\n*** Attempting to remove named metadata: ";
1144 std::vector<std::string> NamedMDNames;
1145 for (auto &NamedMD : BD.getProgram()->named_metadata())
1146 NamedMDNames.push_back(NamedMD.getName().str());
Justin Bogner1c039152016-09-06 17:18:22 +00001147 Expected<bool> Result =
1148 ReduceCrashingNamedMD(BD, TestFn).reduceList(NamedMDNames);
1149 if (Error E = Result.takeError())
1150 return E;
Keno Fischer34ca8312015-11-06 00:12:50 +00001151 }
1152
1153 if (!BugpointIsInterrupted) {
1154 // Now that we quickly dropped all the named metadata that doesn't
1155 // contribute to the crash, bisect the operands of the remaining ones
1156 std::vector<const MDNode *> NamedMDOps;
1157 for (auto &NamedMD : BD.getProgram()->named_metadata())
Keno Fischer256df862015-11-06 00:45:47 +00001158 for (auto op : NamedMD.operands())
1159 NamedMDOps.push_back(op);
Justin Bogner1c039152016-09-06 17:18:22 +00001160 Expected<bool> Result =
1161 ReduceCrashingNamedMDOps(BD, TestFn).reduceList(NamedMDOps);
1162 if (Error E = Result.takeError())
1163 return E;
Keno Fischer34ca8312015-11-06 00:12:50 +00001164 }
Philip Reamesac285cc2016-06-29 00:10:39 +00001165 BD.EmitProgressBitcode(BD.getProgram(), "reduced-named-md");
Keno Fischer34ca8312015-11-06 00:12:50 +00001166 }
1167
Chris Lattner514c02e2003-02-28 16:13:20 +00001168 // Try to clean up the testcase by running funcresolve and globaldce...
Chris Lattnerbeb01fa2005-08-02 02:16:17 +00001169 if (!BugpointIsInterrupted) {
Dan Gohmanee051522009-07-16 15:30:09 +00001170 outs() << "\n*** Attempting to perform final cleanups: ";
Rafael Espindolacab951d2015-12-08 23:57:17 +00001171 Module *M = CloneModule(BD.getProgram()).release();
Rafael Espindola28b351a2014-08-26 17:19:03 +00001172 M = BD.performFinalCleanups(M, true).release();
Misha Brukman650ba8e2005-04-22 00:00:37 +00001173
Chris Lattnerbeb01fa2005-08-02 02:16:17 +00001174 // Find out if the pass still crashes on the cleaned up program...
1175 if (TestFn(BD, M)) {
Justin Bogner8d0a0812016-09-02 01:21:37 +00001176 BD.setNewProgram(M); // Yup, it does, keep the reduced version...
Chris Lattnerbeb01fa2005-08-02 02:16:17 +00001177 } else {
1178 delete M;
1179 }
Chris Lattner514c02e2003-02-28 16:13:20 +00001180 }
1181
Rafael Espindola594994a2010-07-28 18:12:30 +00001182 BD.EmitProgressBitcode(BD.getProgram(), "reduced-simplified");
Chris Lattner514c02e2003-02-28 16:13:20 +00001183
Justin Bogner1c039152016-09-06 17:18:22 +00001184 return Error::success();
Chris Lattner73a6bdd2002-11-20 22:28:10 +00001185}
Brian Gaeke960707c2003-11-11 22:41:34 +00001186
Rafael Espindolad1c7ef42010-08-05 03:00:22 +00001187static bool TestForOptimizerCrash(const BugDriver &BD, Module *M) {
Philip Reamese5b56022016-06-29 03:01:13 +00001188 return BD.runPasses(M, BD.getPassesToRun());
Chris Lattner8bda4c42004-02-18 23:26:28 +00001189}
Chris Lattneread1dff2004-02-18 21:02:04 +00001190
Chris Lattner8bda4c42004-02-18 23:26:28 +00001191/// debugOptimizerCrash - This method is called when some pass crashes on input.
1192/// It attempts to prune down the testcase to something reasonable, and figure
1193/// out exactly which pass is crashing.
1194///
Justin Bogner1c039152016-09-06 17:18:22 +00001195Error BugDriver::debugOptimizerCrash(const std::string &ID) {
Dan Gohmanee051522009-07-16 15:30:09 +00001196 outs() << "\n*** Debugging optimizer crash!\n";
Chris Lattner8bda4c42004-02-18 23:26:28 +00001197
1198 // Reduce the list of passes which causes the optimizer to crash...
Justin Bogner1c039152016-09-06 17:18:22 +00001199 if (!BugpointIsInterrupted && !DontReducePassList) {
1200 Expected<bool> Result = ReducePassList(*this).reduceList(PassesToRun);
1201 if (Error E = Result.takeError())
1202 return E;
1203 }
Chris Lattner8bda4c42004-02-18 23:26:28 +00001204
Dan Gohmanee051522009-07-16 15:30:09 +00001205 outs() << "\n*** Found crashing pass"
1206 << (PassesToRun.size() == 1 ? ": " : "es: ")
1207 << getPassesString(PassesToRun) << '\n';
Chris Lattner8bda4c42004-02-18 23:26:28 +00001208
Rafael Espindola594994a2010-07-28 18:12:30 +00001209 EmitProgressBitcode(Program, ID);
Chris Lattner8bda4c42004-02-18 23:26:28 +00001210
Justin Bogner1c039152016-09-06 17:18:22 +00001211 return DebugACrash(*this, TestForOptimizerCrash);
Chris Lattner8bda4c42004-02-18 23:26:28 +00001212}
1213
Rafael Espindolad1c7ef42010-08-05 03:00:22 +00001214static bool TestForCodeGenCrash(const BugDriver &BD, Module *M) {
Justin Bogner1c039152016-09-06 17:18:22 +00001215 if (Error E = BD.compileProgram(M)) {
Sebastian Pop8f7d0192016-07-15 23:15:06 +00001216 if (VerboseErrors)
Justin Bogner1c039152016-09-06 17:18:22 +00001217 errs() << toString(std::move(E)) << "\n";
1218 else {
1219 consumeError(std::move(E));
Sebastian Pop8f7d0192016-07-15 23:15:06 +00001220 errs() << "<crash>\n";
Justin Bogner1c039152016-09-06 17:18:22 +00001221 }
Justin Bogner8d0a0812016-09-02 01:21:37 +00001222 return true; // Tool is still crashing.
Chris Lattner8bda4c42004-02-18 23:26:28 +00001223 }
Nick Lewycky6ba630b2010-04-12 05:08:25 +00001224 errs() << '\n';
1225 return false;
Chris Lattner8bda4c42004-02-18 23:26:28 +00001226}
Chris Lattneread1dff2004-02-18 21:02:04 +00001227
1228/// debugCodeGeneratorCrash - This method is called when the code generator
1229/// crashes on an input. It attempts to reduce the input as much as possible
1230/// while still causing the code generator to crash.
Justin Bogner1c039152016-09-06 17:18:22 +00001231Error BugDriver::debugCodeGeneratorCrash() {
Dan Gohmand8db3762009-07-15 16:35:29 +00001232 errs() << "*** Debugging code generator crash!\n";
Chris Lattneread1dff2004-02-18 21:02:04 +00001233
Justin Bogner1c039152016-09-06 17:18:22 +00001234 return DebugACrash(*this, TestForCodeGenCrash);
Chris Lattneread1dff2004-02-18 21:02:04 +00001235}