blob: a5766833b6e1776c08769f058a312324be7fc64e [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;
Rafael Espindola71867532018-02-14 19:50:40 +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 Espindola71867532018-02-14 19:50:40 +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 Espindola71867532018-02-14 19:50:40 +0000391 std::unique_ptr<Module> M = CloneModule(*BD.getProgram(), VMap);
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...
Vedant Kumare84e7672018-02-09 05:09:50 +0000409 for (Function &F : M->functions()) {
410 for (BasicBlock &BB : F) {
411 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.
Vedant Kumare84e7672018-02-09 05:09:50 +0000414 for (BasicBlock *Succ : successors(&BB))
415 Succ->removePredecessor(&BB);
Chris Lattnerf32939b2003-04-24 23:51:38 +0000416
Vedant Kumare84e7672018-02-09 05:09:50 +0000417 TerminatorInst *BBTerm = BB.getTerminator();
Philip Reames29e641c2016-06-29 00:15:35 +0000418 if (BBTerm->isEHPad() || BBTerm->getType()->isTokenTy())
David Majnemer189d7da2015-11-08 04:16:12 +0000419 continue;
Philip Reames29e641c2016-06-29 00:15:35 +0000420 if (!BBTerm->getType()->isVoidTy())
Owen Anderson5a1acd92009-07-31 20:28:14 +0000421 BBTerm->replaceAllUsesWith(Constant::getNullValue(BBTerm->getType()));
Chris Lattner7b233af2003-11-22 02:10:38 +0000422
Chris Lattner7855a5c2008-04-28 00:04:58 +0000423 // Replace the old terminator instruction.
Vedant Kumare84e7672018-02-09 05:09:50 +0000424 BB.getInstList().pop_back();
425 new UnreachableInst(BB.getContext(), &BB);
Chris Lattnerf32939b2003-04-24 23:51:38 +0000426 }
Vedant Kumare84e7672018-02-09 05:09:50 +0000427 }
428 }
Chris Lattnerf32939b2003-04-24 23:51:38 +0000429
430 // The CFG Simplifier pass may delete one of the basic blocks we are
431 // interested in. If it does we need to take the block out of the list. Make
432 // a "persistent mapping" by turning basic blocks into <function, name> pairs.
433 // This won't work well if blocks are unnamed, but that is just the risk we
Vedant Kumare84e7672018-02-09 05:09:50 +0000434 // have to take. FIXME: Can we just name the blocks?
Justin Bogner8d0a0812016-09-02 01:21:37 +0000435 std::vector<std::pair<std::string, std::string>> BlockInfo;
Chris Lattnerf32939b2003-04-24 23:51:38 +0000436
Craig Topper46276792014-08-24 23:23:06 +0000437 for (BasicBlock *BB : Blocks)
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000438 BlockInfo.emplace_back(BB->getParent()->getName(), BB->getName());
Justin Bogner8d0a0812016-09-02 01:21:37 +0000439
Daniel Berlin60606262016-07-28 22:29:25 +0000440 SmallVector<BasicBlock *, 16> ToProcess;
Justin Bogner8d0a0812016-09-02 01:21:37 +0000441 for (auto &F : *M) {
Daniel Berlin60606262016-07-28 22:29:25 +0000442 for (auto &BB : F)
443 if (!Blocks.count(&BB))
444 ToProcess.push_back(&BB);
445 simpleSimplifyCfg(F, ToProcess);
446 ToProcess.clear();
447 }
448 // Verify we didn't break anything
Rafael Espindolad1e241a2010-08-10 15:46:11 +0000449 std::vector<std::string> Passes;
Rafael Espindolad1e241a2010-08-10 15:46:11 +0000450 Passes.push_back("verify");
Vedant Kumare84e7672018-02-09 05:09:50 +0000451 std::unique_ptr<Module> New = BD.runPassesOn(M.get(), Passes);
Rafael Espindolad1e241a2010-08-10 15:46:11 +0000452 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 }
Vedant Kumare84e7672018-02-09 05:09:50 +0000456 M = std::move(New);
Justin Bogner8d0a0812016-09-02 01:21:37 +0000457
Chris Lattnerf32939b2003-04-24 23:51:38 +0000458 // Try running on the hacked up program...
Vedant Kumare84e7672018-02-09 05:09:50 +0000459 if (TestFn(BD, M.get())) {
460 BD.setNewProgram(M.release()); // 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();
Vedant Kumare84e7672018-02-09 05:09:50 +0000465 const ValueSymbolTable &GST = BD.getProgram()->getValueSymbolTable();
466 for (const auto &BI : BlockInfo) {
467 Function *F = cast<Function>(GST.lookup(BI.first));
468 Value *V = F->getValueSymbolTable()->lookup(BI.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 }
Vedant Kumare84e7672018-02-09 05:09:50 +0000474 // 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;
Rafael Espindola71867532018-02-14 19:50:40 +0000510 std::unique_ptr<Module> M = CloneModule(*BD.getProgram(), VMap);
Daniel Berlin271ca402016-07-27 16:13:25 +0000511
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");
Vedant Kumare84e7672018-02-09 05:09:50 +0000558 std::unique_ptr<Module> New = BD.runPassesOn(M.get(), Passes);
Daniel Berlin271ca402016-07-27 16:13:25 +0000559 if (!New) {
560 errs() << "verify failed!\n";
561 exit(1);
562 }
Vedant Kumare84e7672018-02-09 05:09:50 +0000563 M = std::move(New);
Daniel Berlin271ca402016-07-27 16:13:25 +0000564
565 // Try running on the hacked up program...
Vedant Kumare84e7672018-02-09 05:09:50 +0000566 if (TestFn(BD, M.get())) {
567 BD.setNewProgram(M.release()); // It crashed, keep the trimmed version...
Daniel Berlin271ca402016-07-27 16:13:25 +0000568
569 // Make sure to use basic block pointers that point into the now-current
570 // module, and that they don't include any deleted blocks.
571 BBs.clear();
Vedant Kumare84e7672018-02-09 05:09:50 +0000572 const ValueSymbolTable &GST = BD.getProgram()->getValueSymbolTable();
Daniel Berlin271ca402016-07-27 16:13:25 +0000573 for (auto &BI : BlockInfo) {
574 auto *F = cast<Function>(GST.lookup(BI.first));
Mehdi Aminia53d49e2016-09-17 06:00:02 +0000575 Value *V = F->getValueSymbolTable()->lookup(BI.second);
Daniel Berlin271ca402016-07-27 16:13:25 +0000576 if (V && V->getType() == Type::getLabelTy(V->getContext()))
577 BBs.push_back(cast<BasicBlock>(V));
578 }
579 return true;
580 }
Vedant Kumare84e7672018-02-09 05:09:50 +0000581 // It didn't crash, try something else.
Daniel Berlin271ca402016-07-27 16:13:25 +0000582 return false;
583}
584
585namespace {
Daniel Berlin60606262016-07-28 22:29:25 +0000586/// SimplifyCFG reducer - This works by calling SimplifyCFG on each basic block
587/// in the program.
588
589class ReduceSimplifyCFG : public ListReducer<const BasicBlock *> {
590 BugDriver &BD;
Vedant Kumar08d829d2018-02-08 18:46:49 +0000591 BugTester TestFn;
Daniel Berlin60606262016-07-28 22:29:25 +0000592 TargetTransformInfo TTI;
Justin Bogner8d0a0812016-09-02 01:21:37 +0000593
Daniel Berlin60606262016-07-28 22:29:25 +0000594public:
Vedant Kumar08d829d2018-02-08 18:46:49 +0000595 ReduceSimplifyCFG(BugDriver &bd, BugTester testFn)
Justin Bogner8d0a0812016-09-02 01:21:37 +0000596 : BD(bd), TestFn(testFn), TTI(bd.getProgram()->getDataLayout()) {}
Daniel Berlin60606262016-07-28 22:29:25 +0000597
Justin Bogner1c039152016-09-06 17:18:22 +0000598 Expected<TestResult> doTest(std::vector<const BasicBlock *> &Prefix,
599 std::vector<const BasicBlock *> &Kept) override {
Daniel Berlin60606262016-07-28 22:29:25 +0000600 if (!Kept.empty() && TestBlocks(Kept))
601 return KeepSuffix;
602 if (!Prefix.empty() && TestBlocks(Prefix))
603 return KeepPrefix;
604 return NoFailure;
605 }
606
607 bool TestBlocks(std::vector<const BasicBlock *> &Prefix);
608};
609}
610
Justin Bogner8d0a0812016-09-02 01:21:37 +0000611bool ReduceSimplifyCFG::TestBlocks(std::vector<const BasicBlock *> &BBs) {
Daniel Berlin60606262016-07-28 22:29:25 +0000612 // Clone the program to try hacking it apart...
613 ValueToValueMapTy VMap;
Rafael Espindola71867532018-02-14 19:50:40 +0000614 std::unique_ptr<Module> M = CloneModule(*BD.getProgram(), VMap);
Daniel Berlin60606262016-07-28 22:29:25 +0000615
616 // Convert list to set for fast lookup...
617 SmallPtrSet<const BasicBlock *, 8> Blocks;
Justin Bogner8d0a0812016-09-02 01:21:37 +0000618 for (const auto *BB : BBs)
Daniel Berlin60606262016-07-28 22:29:25 +0000619 Blocks.insert(cast<BasicBlock>(VMap[BB]));
620
621 outs() << "Checking for crash with CFG simplifying:";
622 unsigned NumPrint = Blocks.size();
623 if (NumPrint > 10)
624 NumPrint = 10;
625 for (unsigned i = 0, e = NumPrint; i != e; ++i)
626 outs() << " " << BBs[i]->getName();
627 if (NumPrint < Blocks.size())
628 outs() << "... <" << Blocks.size() << " total>";
629 outs() << ": ";
630
Justin Bogner8d0a0812016-09-02 01:21:37 +0000631 // The following may destroy some blocks, so we save them first
Daniel Berlin60606262016-07-28 22:29:25 +0000632 std::vector<std::pair<std::string, std::string>> BlockInfo;
633
634 for (const BasicBlock *BB : Blocks)
635 BlockInfo.emplace_back(BB->getParent()->getName(), BB->getName());
636
Daniel Berlin60606262016-07-28 22:29:25 +0000637 // Loop over and delete any hack up any blocks that are not listed...
Justin Bogner8d0a0812016-09-02 01:21:37 +0000638 for (auto &F : *M)
639 // Loop over all of the basic blocks and remove them if they are unneeded.
640 for (Function::iterator BBIt = F.begin(); BBIt != F.end();) {
641 if (!Blocks.count(&*BBIt)) {
642 ++BBIt;
643 continue;
644 }
Sanjay Patel4c33d522017-10-04 20:26:25 +0000645 simplifyCFG(&*BBIt++, TTI);
Justin Bogner8d0a0812016-09-02 01:21:37 +0000646 }
Daniel Berlin60606262016-07-28 22:29:25 +0000647 // Verify we didn't break anything
648 std::vector<std::string> Passes;
649 Passes.push_back("verify");
Vedant Kumare84e7672018-02-09 05:09:50 +0000650 std::unique_ptr<Module> New = BD.runPassesOn(M.get(), Passes);
Daniel Berlin60606262016-07-28 22:29:25 +0000651 if (!New) {
652 errs() << "verify failed!\n";
653 exit(1);
654 }
Vedant Kumare84e7672018-02-09 05:09:50 +0000655 M = std::move(New);
Daniel Berlin60606262016-07-28 22:29:25 +0000656
657 // Try running on the hacked up program...
Vedant Kumare84e7672018-02-09 05:09:50 +0000658 if (TestFn(BD, M.get())) {
659 BD.setNewProgram(M.release()); // It crashed, keep the trimmed version...
Daniel Berlin60606262016-07-28 22:29:25 +0000660
661 // Make sure to use basic block pointers that point into the now-current
662 // module, and that they don't include any deleted blocks.
663 BBs.clear();
Vedant Kumare84e7672018-02-09 05:09:50 +0000664 const ValueSymbolTable &GST = BD.getProgram()->getValueSymbolTable();
Justin Bogner8d0a0812016-09-02 01:21:37 +0000665 for (auto &BI : BlockInfo) {
Daniel Berlin60606262016-07-28 22:29:25 +0000666 auto *F = cast<Function>(GST.lookup(BI.first));
Mehdi Aminia53d49e2016-09-17 06:00:02 +0000667 Value *V = F->getValueSymbolTable()->lookup(BI.second);
Daniel Berlin60606262016-07-28 22:29:25 +0000668 if (V && V->getType() == Type::getLabelTy(V->getContext()))
669 BBs.push_back(cast<BasicBlock>(V));
670 }
671 return true;
672 }
Vedant Kumare84e7672018-02-09 05:09:50 +0000673 // It didn't crash, try something else.
Daniel Berlin60606262016-07-28 22:29:25 +0000674 return false;
675}
676
677namespace {
Justin Bogner8d0a0812016-09-02 01:21:37 +0000678/// ReduceCrashingInstructions reducer - This works by removing the specified
679/// non-terminator instructions and replacing them with undef.
680///
681class ReduceCrashingInstructions : public ListReducer<const Instruction *> {
682 BugDriver &BD;
Vedant Kumar08d829d2018-02-08 18:46:49 +0000683 BugTester TestFn;
Justin Bogner8d0a0812016-09-02 01:21:37 +0000684
685public:
Vedant Kumar08d829d2018-02-08 18:46:49 +0000686 ReduceCrashingInstructions(BugDriver &bd, BugTester testFn)
Nick Lewycky6e090c92009-05-25 05:30:00 +0000687 : BD(bd), TestFn(testFn) {}
688
Justin Bogner1c039152016-09-06 17:18:22 +0000689 Expected<TestResult> doTest(std::vector<const Instruction *> &Prefix,
690 std::vector<const Instruction *> &Kept) override {
Justin Bogner8d0a0812016-09-02 01:21:37 +0000691 if (!Kept.empty() && TestInsts(Kept))
692 return KeepSuffix;
693 if (!Prefix.empty() && TestInsts(Prefix))
694 return KeepPrefix;
695 return NoFailure;
696 }
Nick Lewycky6e090c92009-05-25 05:30:00 +0000697
Justin Bogner8d0a0812016-09-02 01:21:37 +0000698 bool TestInsts(std::vector<const Instruction *> &Prefix);
699};
Nick Lewycky6e090c92009-05-25 05:30:00 +0000700}
701
Justin Bogner8d0a0812016-09-02 01:21:37 +0000702bool ReduceCrashingInstructions::TestInsts(
703 std::vector<const Instruction *> &Insts) {
Nick Lewycky6e090c92009-05-25 05:30:00 +0000704 // Clone the program to try hacking it apart...
Rafael Espindola229e38f2010-10-13 01:36:30 +0000705 ValueToValueMapTy VMap;
Rafael Espindola71867532018-02-14 19:50:40 +0000706 Module *M = CloneModule(*BD.getProgram(), VMap).release();
Nick Lewycky6e090c92009-05-25 05:30:00 +0000707
708 // Convert list to set for fast lookup...
Justin Bogner8d0a0812016-09-02 01:21:37 +0000709 SmallPtrSet<Instruction *, 32> Instructions;
Nick Lewycky6e090c92009-05-25 05:30:00 +0000710 for (unsigned i = 0, e = Insts.size(); i != e; ++i) {
711 assert(!isa<TerminatorInst>(Insts[i]));
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000712 Instructions.insert(cast<Instruction>(VMap[Insts[i]]));
Nick Lewycky6e090c92009-05-25 05:30:00 +0000713 }
714
Dan Gohmanee051522009-07-16 15:30:09 +0000715 outs() << "Checking for crash with only " << Instructions.size();
Nick Lewycky6e090c92009-05-25 05:30:00 +0000716 if (Instructions.size() == 1)
Dan Gohmanee051522009-07-16 15:30:09 +0000717 outs() << " instruction: ";
Nick Lewycky6e090c92009-05-25 05:30:00 +0000718 else
Dan Gohmanee051522009-07-16 15:30:09 +0000719 outs() << " instructions: ";
Nick Lewycky6e090c92009-05-25 05:30:00 +0000720
721 for (Module::iterator MI = M->begin(), ME = M->end(); MI != ME; ++MI)
722 for (Function::iterator FI = MI->begin(), FE = MI->end(); FI != FE; ++FI)
723 for (BasicBlock::iterator I = FI->begin(), E = FI->end(); I != E;) {
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000724 Instruction *Inst = &*I++;
Eli Friedmand4e02a52011-11-01 04:40:56 +0000725 if (!Instructions.count(Inst) && !isa<TerminatorInst>(Inst) &&
Arnold Schwaighofera8f5a822017-03-07 20:28:59 +0000726 !Inst->isEHPad() && !Inst->getType()->isTokenTy() &&
727 !Inst->isSwiftError()) {
Philip Reames29e641c2016-06-29 00:15:35 +0000728 if (!Inst->getType()->isVoidTy())
Nick Lewycky6e090c92009-05-25 05:30:00 +0000729 Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
730 Inst->eraseFromParent();
731 }
732 }
733
734 // Verify that this is still valid.
Chandler Carruth30d69c22015-02-13 10:01:29 +0000735 legacy::PassManager Passes;
Adrian Prantl919bdf12016-10-18 16:24:43 +0000736 Passes.add(createVerifierPass(/*FatalErrors=*/false));
Nick Lewycky6e090c92009-05-25 05:30:00 +0000737 Passes.run(*M);
738
739 // Try running on the hacked up program...
740 if (TestFn(BD, M)) {
Justin Bogner8d0a0812016-09-02 01:21:37 +0000741 BD.setNewProgram(M); // It crashed, keep the trimmed version...
Nick Lewycky6e090c92009-05-25 05:30:00 +0000742
743 // Make sure to use instruction pointers that point into the now-current
744 // module, and that they don't include any deleted blocks.
745 Insts.clear();
Craig Topper46276792014-08-24 23:23:06 +0000746 for (Instruction *Inst : Instructions)
747 Insts.push_back(Inst);
Nick Lewycky6e090c92009-05-25 05:30:00 +0000748 return true;
749 }
Justin Bogner8d0a0812016-09-02 01:21:37 +0000750 delete M; // It didn't crash, try something else.
Nick Lewycky6e090c92009-05-25 05:30:00 +0000751 return false;
752}
753
Keno Fischer34ca8312015-11-06 00:12:50 +0000754namespace {
755// Reduce the list of Named Metadata nodes. We keep this as a list of
756// names to avoid having to convert back and forth every time.
757class ReduceCrashingNamedMD : public ListReducer<std::string> {
758 BugDriver &BD;
Vedant Kumar08d829d2018-02-08 18:46:49 +0000759 BugTester TestFn;
Keno Fischer34ca8312015-11-06 00:12:50 +0000760
761public:
Vedant Kumar08d829d2018-02-08 18:46:49 +0000762 ReduceCrashingNamedMD(BugDriver &bd, BugTester testFn)
Keno Fischer34ca8312015-11-06 00:12:50 +0000763 : BD(bd), TestFn(testFn) {}
764
Justin Bogner1c039152016-09-06 17:18:22 +0000765 Expected<TestResult> doTest(std::vector<std::string> &Prefix,
766 std::vector<std::string> &Kept) override {
Keno Fischer34ca8312015-11-06 00:12:50 +0000767 if (!Kept.empty() && TestNamedMDs(Kept))
768 return KeepSuffix;
769 if (!Prefix.empty() && TestNamedMDs(Prefix))
770 return KeepPrefix;
771 return NoFailure;
772 }
773
774 bool TestNamedMDs(std::vector<std::string> &NamedMDs);
775};
776}
777
778bool ReduceCrashingNamedMD::TestNamedMDs(std::vector<std::string> &NamedMDs) {
779
780 ValueToValueMapTy VMap;
Rafael Espindola71867532018-02-14 19:50:40 +0000781 Module *M = CloneModule(*BD.getProgram(), VMap).release();
Keno Fischer34ca8312015-11-06 00:12:50 +0000782
783 outs() << "Checking for crash with only these named metadata nodes:";
784 unsigned NumPrint = std::min<size_t>(NamedMDs.size(), 10);
785 for (unsigned i = 0, e = NumPrint; i != e; ++i)
786 outs() << " " << NamedMDs[i];
787 if (NumPrint < NamedMDs.size())
788 outs() << "... <" << NamedMDs.size() << " total>";
789 outs() << ": ";
790
791 // Make a StringMap for faster lookup
792 StringSet<> Names;
793 for (const std::string &Name : NamedMDs)
794 Names.insert(Name);
795
796 // First collect all the metadata to delete in a vector, then
797 // delete them all at once to avoid invalidating the iterator
798 std::vector<NamedMDNode *> ToDelete;
799 ToDelete.reserve(M->named_metadata_size() - Names.size());
800 for (auto &NamedMD : M->named_metadata())
Adrian Prantlfaebbb02016-03-28 21:06:26 +0000801 // Always keep a nonempty llvm.dbg.cu because the Verifier would complain.
802 if (!Names.count(NamedMD.getName()) &&
803 (!(NamedMD.getName() == "llvm.dbg.cu" && NamedMD.getNumOperands() > 0)))
Keno Fischer34ca8312015-11-06 00:12:50 +0000804 ToDelete.push_back(&NamedMD);
805
806 for (auto *NamedMD : ToDelete)
807 NamedMD->eraseFromParent();
808
809 // Verify that this is still valid.
810 legacy::PassManager Passes;
Adrian Prantl919bdf12016-10-18 16:24:43 +0000811 Passes.add(createVerifierPass(/*FatalErrors=*/false));
Keno Fischer34ca8312015-11-06 00:12:50 +0000812 Passes.run(*M);
813
814 // Try running on the hacked up program...
815 if (TestFn(BD, M)) {
816 BD.setNewProgram(M); // It crashed, keep the trimmed version...
817 return true;
818 }
819 delete M; // It didn't crash, try something else.
820 return false;
821}
822
823namespace {
824// Reduce the list of operands to named metadata nodes
825class ReduceCrashingNamedMDOps : public ListReducer<const MDNode *> {
826 BugDriver &BD;
Vedant Kumar08d829d2018-02-08 18:46:49 +0000827 BugTester TestFn;
Keno Fischer34ca8312015-11-06 00:12:50 +0000828
829public:
Vedant Kumar08d829d2018-02-08 18:46:49 +0000830 ReduceCrashingNamedMDOps(BugDriver &bd, BugTester testFn)
Keno Fischer34ca8312015-11-06 00:12:50 +0000831 : BD(bd), TestFn(testFn) {}
832
Justin Bogner1c039152016-09-06 17:18:22 +0000833 Expected<TestResult> doTest(std::vector<const MDNode *> &Prefix,
834 std::vector<const MDNode *> &Kept) override {
Keno Fischer34ca8312015-11-06 00:12:50 +0000835 if (!Kept.empty() && TestNamedMDOps(Kept))
836 return KeepSuffix;
837 if (!Prefix.empty() && TestNamedMDOps(Prefix))
838 return KeepPrefix;
839 return NoFailure;
840 }
841
842 bool TestNamedMDOps(std::vector<const MDNode *> &NamedMDOps);
843};
844}
845
846bool ReduceCrashingNamedMDOps::TestNamedMDOps(
847 std::vector<const MDNode *> &NamedMDOps) {
848 // Convert list to set for fast lookup...
Matthias Braunb30f2f512016-01-30 01:24:31 +0000849 SmallPtrSet<const MDNode *, 32> OldMDNodeOps;
Keno Fischer34ca8312015-11-06 00:12:50 +0000850 for (unsigned i = 0, e = NamedMDOps.size(); i != e; ++i) {
851 OldMDNodeOps.insert(NamedMDOps[i]);
852 }
853
854 outs() << "Checking for crash with only " << OldMDNodeOps.size();
855 if (OldMDNodeOps.size() == 1)
856 outs() << " named metadata operand: ";
857 else
858 outs() << " named metadata operands: ";
859
860 ValueToValueMapTy VMap;
Rafael Espindola71867532018-02-14 19:50:40 +0000861 Module *M = CloneModule(*BD.getProgram(), VMap).release();
Keno Fischer34ca8312015-11-06 00:12:50 +0000862
863 // This is a little wasteful. In the future it might be good if we could have
864 // these dropped during cloning.
865 for (auto &NamedMD : BD.getProgram()->named_metadata()) {
866 // Drop the old one and create a new one
867 M->eraseNamedMetadata(M->getNamedMetadata(NamedMD.getName()));
868 NamedMDNode *NewNamedMDNode =
869 M->getOrInsertNamedMetadata(NamedMD.getName());
870 for (MDNode *op : NamedMD.operands())
871 if (OldMDNodeOps.count(op))
872 NewNamedMDNode->addOperand(cast<MDNode>(MapMetadata(op, VMap)));
873 }
874
875 // Verify that this is still valid.
876 legacy::PassManager Passes;
Adrian Prantl919bdf12016-10-18 16:24:43 +0000877 Passes.add(createVerifierPass(/*FatalErrors=*/false));
Keno Fischer34ca8312015-11-06 00:12:50 +0000878 Passes.run(*M);
879
880 // Try running on the hacked up program...
881 if (TestFn(BD, M)) {
882 // Make sure to use instruction pointers that point into the now-current
883 // module, and that they don't include any deleted blocks.
884 NamedMDOps.clear();
885 for (const MDNode *Node : OldMDNodeOps)
Duncan P. N. Exon Smithda4a56d2016-04-02 17:04:38 +0000886 NamedMDOps.push_back(cast<MDNode>(*VMap.getMappedMD(Node)));
Keno Fischer34ca8312015-11-06 00:12:50 +0000887
888 BD.setNewProgram(M); // It crashed, keep the trimmed version...
889 return true;
890 }
891 delete M; // It didn't crash, try something else.
892 return false;
893}
894
Vedant Kumar66e85e62018-02-08 20:27:09 +0000895/// Attempt to eliminate as many global initializers as possible.
Vedant Kumar08d829d2018-02-08 18:46:49 +0000896static Error ReduceGlobalInitializers(BugDriver &BD, BugTester TestFn) {
Vedant Kumar66e85e62018-02-08 20:27:09 +0000897 Module *OrigM = BD.getProgram();
898 if (OrigM->global_empty())
899 return Error::success();
Misha Brukman650ba8e2005-04-22 00:00:37 +0000900
Vedant Kumar66e85e62018-02-08 20:27:09 +0000901 // Now try to reduce the number of global variable initializers in the
902 // module to something small.
Rafael Espindola71867532018-02-14 19:50:40 +0000903 std::unique_ptr<Module> M = CloneModule(*OrigM);
Vedant Kumar66e85e62018-02-08 20:27:09 +0000904 bool DeletedInit = false;
Bill Wendling3f833432006-10-25 18:36:14 +0000905
Vedant Kumar66e85e62018-02-08 20:27:09 +0000906 for (GlobalVariable &GV : M->globals()) {
907 if (GV.hasInitializer()) {
908 DeleteGlobalInitializer(&GV);
909 GV.setLinkage(GlobalValue::ExternalLinkage);
910 GV.setComdat(nullptr);
911 DeletedInit = true;
Chris Lattner65e5f652003-04-25 00:53:05 +0000912 }
913 }
Vedant Kumar66e85e62018-02-08 20:27:09 +0000914
915 if (!DeletedInit)
916 return Error::success();
917
918 // See if the program still causes a crash...
919 outs() << "\nChecking to see if we can delete global inits: ";
920
921 if (TestFn(BD, M.get())) { // Still crashes?
922 BD.setNewProgram(M.release());
923 outs() << "\n*** Able to remove all global initializers!\n";
924 return Error::success();
925 }
926
927 // No longer crashes.
928 outs() << " - Removing all global inits hides problem!\n";
929
930 std::vector<GlobalVariable *> GVs;
931 for (GlobalVariable &GV : OrigM->globals())
932 if (GV.hasInitializer())
933 GVs.push_back(&GV);
934
935 if (GVs.size() > 1 && !BugpointIsInterrupted) {
936 outs() << "\n*** Attempting to reduce the number of global initializers "
937 << "in the testcase\n";
938
939 unsigned OldSize = GVs.size();
940 Expected<bool> Result =
941 ReduceCrashingGlobalInitializers(BD, TestFn).reduceList(GVs);
942 if (Error E = Result.takeError())
943 return E;
944
945 if (GVs.size() < OldSize)
946 BD.EmitProgressBitcode(BD.getProgram(), "reduced-global-variables");
947 }
Justin Bogner1c039152016-09-06 17:18:22 +0000948 return Error::success();
Philip Reames1c232f92016-06-29 00:43:18 +0000949}
950
Vedant Kumar08d829d2018-02-08 18:46:49 +0000951static Error ReduceInsts(BugDriver &BD, BugTester TestFn) {
Philip Reames1c232f92016-06-29 00:43:18 +0000952 // Attempt to delete instructions using bisection. This should help out nasty
953 // cases with large basic blocks where the problem is at one end.
954 if (!BugpointIsInterrupted) {
Justin Bogner8d0a0812016-09-02 01:21:37 +0000955 std::vector<const Instruction *> Insts;
Philip Reames1c232f92016-06-29 00:43:18 +0000956 for (const Function &F : *BD.getProgram())
957 for (const BasicBlock &BB : F)
958 for (const Instruction &I : BB)
959 if (!isa<TerminatorInst>(&I))
960 Insts.push_back(&I);
961
Justin Bogner1c039152016-09-06 17:18:22 +0000962 Expected<bool> Result =
963 ReduceCrashingInstructions(BD, TestFn).reduceList(Insts);
964 if (Error E = Result.takeError())
965 return E;
Philip Reames1c232f92016-06-29 00:43:18 +0000966 }
967
968 unsigned Simplification = 2;
969 do {
970 if (BugpointIsInterrupted)
Justin Bogner1c039152016-09-06 17:18:22 +0000971 // TODO: Should we distinguish this with an "interrupted error"?
972 return Error::success();
Philip Reames1c232f92016-06-29 00:43:18 +0000973 --Simplification;
974 outs() << "\n*** Attempting to reduce testcase by deleting instruc"
975 << "tions: Simplification Level #" << Simplification << '\n';
976
977 // Now that we have deleted the functions that are unnecessary for the
978 // program, try to remove instructions that are not necessary to cause the
979 // crash. To do this, we loop through all of the instructions in the
980 // remaining functions, deleting them (replacing any values produced with
981 // nulls), and then running ADCE and SimplifyCFG. If the transformed input
982 // still triggers failure, keep deleting until we cannot trigger failure
983 // anymore.
984 //
985 unsigned InstructionsToSkipBeforeDeleting = 0;
986 TryAgain:
987
988 // Loop over all of the (non-terminator) instructions remaining in the
989 // function, attempting to delete them.
990 unsigned CurInstructionNum = 0;
991 for (Module::const_iterator FI = BD.getProgram()->begin(),
Justin Bogner8d0a0812016-09-02 01:21:37 +0000992 E = BD.getProgram()->end();
993 FI != E; ++FI)
Philip Reames1c232f92016-06-29 00:43:18 +0000994 if (!FI->isDeclaration())
995 for (Function::const_iterator BI = FI->begin(), E = FI->end(); BI != E;
996 ++BI)
997 for (BasicBlock::const_iterator I = BI->begin(), E = --BI->end();
998 I != E; ++I, ++CurInstructionNum) {
999 if (InstructionsToSkipBeforeDeleting) {
1000 --InstructionsToSkipBeforeDeleting;
1001 } else {
1002 if (BugpointIsInterrupted)
Justin Bogner1c039152016-09-06 17:18:22 +00001003 // TODO: Should this be some kind of interrupted error?
1004 return Error::success();
Philip Reames1c232f92016-06-29 00:43:18 +00001005
Arnold Schwaighofera8f5a822017-03-07 20:28:59 +00001006 if (I->isEHPad() || I->getType()->isTokenTy() ||
1007 I->isSwiftError())
Philip Reames1c232f92016-06-29 00:43:18 +00001008 continue;
1009
1010 outs() << "Checking instruction: " << *I;
1011 std::unique_ptr<Module> M =
1012 BD.deleteInstructionFromProgram(&*I, Simplification);
1013
1014 // Find out if the pass still crashes on this pass...
1015 if (TestFn(BD, M.get())) {
1016 // Yup, it does, we delete the old module, and continue trying
1017 // to reduce the testcase...
1018 BD.setNewProgram(M.release());
1019 InstructionsToSkipBeforeDeleting = CurInstructionNum;
Justin Bogner8d0a0812016-09-02 01:21:37 +00001020 goto TryAgain; // I wish I had a multi-level break here!
Philip Reames1c232f92016-06-29 00:43:18 +00001021 }
1022 }
1023 }
1024
1025 if (InstructionsToSkipBeforeDeleting) {
1026 InstructionsToSkipBeforeDeleting = 0;
1027 goto TryAgain;
1028 }
1029
1030 } while (Simplification);
1031 BD.EmitProgressBitcode(BD.getProgram(), "reduced-instructions");
Justin Bogner1c039152016-09-06 17:18:22 +00001032 return Error::success();
Philip Reames1c232f92016-06-29 00:43:18 +00001033}
1034
Philip Reames1c232f92016-06-29 00:43:18 +00001035/// DebugACrash - Given a predicate that determines whether a component crashes
1036/// on a program, try to destructively reduce the program while still keeping
1037/// the predicate true.
Vedant Kumar08d829d2018-02-08 18:46:49 +00001038static Error DebugACrash(BugDriver &BD, BugTester TestFn) {
Philip Reames1c232f92016-06-29 00:43:18 +00001039 // See if we can get away with nuking some of the global variable initializers
1040 // in the program...
1041 if (!NoGlobalRM)
Justin Bogner1c039152016-09-06 17:18:22 +00001042 if (Error E = ReduceGlobalInitializers(BD, TestFn))
1043 return E;
Misha Brukman650ba8e2005-04-22 00:00:37 +00001044
Chris Lattner1d080f22003-04-24 22:24:58 +00001045 // Now try to reduce the number of functions in the module to something small.
Justin Bogner8d0a0812016-09-02 01:21:37 +00001046 std::vector<Function *> Functions;
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +00001047 for (Function &F : *BD.getProgram())
1048 if (!F.isDeclaration())
1049 Functions.push_back(&F);
Chris Lattner73a6bdd2002-11-20 22:28:10 +00001050
Chris Lattnerbeb01fa2005-08-02 02:16:17 +00001051 if (Functions.size() > 1 && !BugpointIsInterrupted) {
Dan Gohmanee051522009-07-16 15:30:09 +00001052 outs() << "\n*** Attempting to reduce the number of functions "
Justin Bogner8d0a0812016-09-02 01:21:37 +00001053 "in the testcase\n";
Chris Lattner73a6bdd2002-11-20 22:28:10 +00001054
Chris Lattner8bda4c42004-02-18 23:26:28 +00001055 unsigned OldSize = Functions.size();
Justin Bogner1c039152016-09-06 17:18:22 +00001056 Expected<bool> Result =
1057 ReduceCrashingFunctions(BD, TestFn).reduceList(Functions);
1058 if (Error E = Result.takeError())
1059 return E;
Chris Lattner73a6bdd2002-11-20 22:28:10 +00001060
Chris Lattnerbeb01fa2005-08-02 02:16:17 +00001061 if (Functions.size() < OldSize)
Rafael Espindola594994a2010-07-28 18:12:30 +00001062 BD.EmitProgressBitcode(BD.getProgram(), "reduced-function");
Chris Lattner73a6bdd2002-11-20 22:28:10 +00001063 }
1064
Daniel Berlin271ca402016-07-27 16:13:25 +00001065 // Attempt to change conditional branches into unconditional branches to
1066 // eliminate blocks.
1067 if (!DisableSimplifyCFG && !BugpointIsInterrupted) {
Justin Bogner8d0a0812016-09-02 01:21:37 +00001068 std::vector<const BasicBlock *> Blocks;
Daniel Berlin271ca402016-07-27 16:13:25 +00001069 for (Function &F : *BD.getProgram())
1070 for (BasicBlock &BB : F)
1071 Blocks.push_back(&BB);
1072 unsigned OldSize = Blocks.size();
Justin Bogner1c039152016-09-06 17:18:22 +00001073 Expected<bool> Result =
1074 ReduceCrashingConditionals(BD, TestFn, true).reduceList(Blocks);
1075 if (Error E = Result.takeError())
1076 return E;
1077 Result = ReduceCrashingConditionals(BD, TestFn, false).reduceList(Blocks);
1078 if (Error E = Result.takeError())
1079 return E;
Daniel Berlin271ca402016-07-27 16:13:25 +00001080 if (Blocks.size() < OldSize)
1081 BD.EmitProgressBitcode(BD.getProgram(), "reduced-conditionals");
1082 }
1083
Chris Lattnerf32939b2003-04-24 23:51:38 +00001084 // Attempt to delete entire basic blocks at a time to speed up
1085 // convergence... this actually works by setting the terminator of the blocks
1086 // to a return instruction then running simplifycfg, which can potentially
1087 // shrinks the code dramatically quickly
1088 //
Chris Lattnerbeb01fa2005-08-02 02:16:17 +00001089 if (!DisableSimplifyCFG && !BugpointIsInterrupted) {
Justin Bogner8d0a0812016-09-02 01:21:37 +00001090 std::vector<const BasicBlock *> Blocks;
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +00001091 for (Function &F : *BD.getProgram())
1092 for (BasicBlock &BB : F)
1093 Blocks.push_back(&BB);
Torok Edwin6ee6f732009-05-24 09:40:47 +00001094 unsigned OldSize = Blocks.size();
Justin Bogner1c039152016-09-06 17:18:22 +00001095 Expected<bool> Result = ReduceCrashingBlocks(BD, TestFn).reduceList(Blocks);
1096 if (Error E = Result.takeError())
1097 return E;
Torok Edwin6ee6f732009-05-24 09:40:47 +00001098 if (Blocks.size() < OldSize)
Rafael Espindola594994a2010-07-28 18:12:30 +00001099 BD.EmitProgressBitcode(BD.getProgram(), "reduced-blocks");
Chris Lattnerd1e2aae2003-08-05 15:51:05 +00001100 }
Chris Lattnerd4e04742002-12-23 23:49:59 +00001101
Simon Pilgrim0c559f62017-04-14 15:21:15 +00001102 if (!DisableSimplifyCFG && !BugpointIsInterrupted) {
Justin Bogner8d0a0812016-09-02 01:21:37 +00001103 std::vector<const BasicBlock *> Blocks;
Daniel Berlin60606262016-07-28 22:29:25 +00001104 for (Function &F : *BD.getProgram())
1105 for (BasicBlock &BB : F)
1106 Blocks.push_back(&BB);
1107 unsigned OldSize = Blocks.size();
Justin Bogner1c039152016-09-06 17:18:22 +00001108 Expected<bool> Result = ReduceSimplifyCFG(BD, TestFn).reduceList(Blocks);
1109 if (Error E = Result.takeError())
1110 return E;
Daniel Berlin60606262016-07-28 22:29:25 +00001111 if (Blocks.size() < OldSize)
1112 BD.EmitProgressBitcode(BD.getProgram(), "reduced-simplifycfg");
1113 }
Justin Bogner8d0a0812016-09-02 01:21:37 +00001114
Nick Lewycky6e090c92009-05-25 05:30:00 +00001115 // Attempt to delete instructions using bisection. This should help out nasty
1116 // cases with large basic blocks where the problem is at one end.
Philip Reames1c232f92016-06-29 00:43:18 +00001117 if (!BugpointIsInterrupted)
Justin Bogner1c039152016-09-06 17:18:22 +00001118 if (Error E = ReduceInsts(BD, TestFn))
1119 return E;
Keno Fischer34ca8312015-11-06 00:12:50 +00001120
Michael Ilsemane5428042016-10-25 18:44:13 +00001121 // Attempt to strip debug info metadata.
1122 auto stripMetadata = [&](std::function<bool(Module &)> strip) {
Rafael Espindola71867532018-02-14 19:50:40 +00001123 std::unique_ptr<Module> M = CloneModule(*BD.getProgram());
Michael Ilsemane5428042016-10-25 18:44:13 +00001124 strip(*M);
1125 if (TestFn(BD, M.get()))
1126 BD.setNewProgram(M.release());
1127 };
1128 if (!NoStripDebugInfo && !BugpointIsInterrupted) {
1129 outs() << "\n*** Attempting to strip the debug info: ";
1130 stripMetadata(StripDebugInfo);
1131 }
1132 if (!NoStripDebugTypeInfo && !BugpointIsInterrupted) {
1133 outs() << "\n*** Attempting to strip the debug type info: ";
1134 stripMetadata(stripNonLineTableDebugInfo);
1135 }
1136
Keno Fischer34ca8312015-11-06 00:12:50 +00001137 if (!NoNamedMDRM) {
Keno Fischer34ca8312015-11-06 00:12:50 +00001138 if (!BugpointIsInterrupted) {
1139 // Try to reduce the amount of global metadata (particularly debug info),
1140 // by dropping global named metadata that anchors them
1141 outs() << "\n*** Attempting to remove named metadata: ";
1142 std::vector<std::string> NamedMDNames;
1143 for (auto &NamedMD : BD.getProgram()->named_metadata())
1144 NamedMDNames.push_back(NamedMD.getName().str());
Justin Bogner1c039152016-09-06 17:18:22 +00001145 Expected<bool> Result =
1146 ReduceCrashingNamedMD(BD, TestFn).reduceList(NamedMDNames);
1147 if (Error E = Result.takeError())
1148 return E;
Keno Fischer34ca8312015-11-06 00:12:50 +00001149 }
1150
1151 if (!BugpointIsInterrupted) {
1152 // Now that we quickly dropped all the named metadata that doesn't
1153 // contribute to the crash, bisect the operands of the remaining ones
1154 std::vector<const MDNode *> NamedMDOps;
1155 for (auto &NamedMD : BD.getProgram()->named_metadata())
Keno Fischer256df862015-11-06 00:45:47 +00001156 for (auto op : NamedMD.operands())
1157 NamedMDOps.push_back(op);
Justin Bogner1c039152016-09-06 17:18:22 +00001158 Expected<bool> Result =
1159 ReduceCrashingNamedMDOps(BD, TestFn).reduceList(NamedMDOps);
1160 if (Error E = Result.takeError())
1161 return E;
Keno Fischer34ca8312015-11-06 00:12:50 +00001162 }
Philip Reamesac285cc2016-06-29 00:10:39 +00001163 BD.EmitProgressBitcode(BD.getProgram(), "reduced-named-md");
Keno Fischer34ca8312015-11-06 00:12:50 +00001164 }
1165
Chris Lattner514c02e2003-02-28 16:13:20 +00001166 // Try to clean up the testcase by running funcresolve and globaldce...
Chris Lattnerbeb01fa2005-08-02 02:16:17 +00001167 if (!BugpointIsInterrupted) {
Dan Gohmanee051522009-07-16 15:30:09 +00001168 outs() << "\n*** Attempting to perform final cleanups: ";
Rafael Espindola71867532018-02-14 19:50:40 +00001169 std::unique_ptr<Module> M = CloneModule(*BD.getProgram());
Vedant Kumare84e7672018-02-09 05:09:50 +00001170 M = BD.performFinalCleanups(M.release(), true);
Misha Brukman650ba8e2005-04-22 00:00:37 +00001171
Chris Lattnerbeb01fa2005-08-02 02:16:17 +00001172 // Find out if the pass still crashes on the cleaned up program...
Vedant Kumare84e7672018-02-09 05:09:50 +00001173 if (M && TestFn(BD, M.get()))
1174 BD.setNewProgram(M.release()); // Yup, it does, keep the reduced version...
Chris Lattner514c02e2003-02-28 16:13:20 +00001175 }
1176
Rafael Espindola594994a2010-07-28 18:12:30 +00001177 BD.EmitProgressBitcode(BD.getProgram(), "reduced-simplified");
Chris Lattner514c02e2003-02-28 16:13:20 +00001178
Justin Bogner1c039152016-09-06 17:18:22 +00001179 return Error::success();
Chris Lattner73a6bdd2002-11-20 22:28:10 +00001180}
Brian Gaeke960707c2003-11-11 22:41:34 +00001181
Rafael Espindolad1c7ef42010-08-05 03:00:22 +00001182static bool TestForOptimizerCrash(const BugDriver &BD, Module *M) {
Philip Reamese5b56022016-06-29 03:01:13 +00001183 return BD.runPasses(M, BD.getPassesToRun());
Chris Lattner8bda4c42004-02-18 23:26:28 +00001184}
Chris Lattneread1dff2004-02-18 21:02:04 +00001185
Chris Lattner8bda4c42004-02-18 23:26:28 +00001186/// debugOptimizerCrash - This method is called when some pass crashes on input.
1187/// It attempts to prune down the testcase to something reasonable, and figure
1188/// out exactly which pass is crashing.
1189///
Justin Bogner1c039152016-09-06 17:18:22 +00001190Error BugDriver::debugOptimizerCrash(const std::string &ID) {
Dan Gohmanee051522009-07-16 15:30:09 +00001191 outs() << "\n*** Debugging optimizer crash!\n";
Chris Lattner8bda4c42004-02-18 23:26:28 +00001192
1193 // Reduce the list of passes which causes the optimizer to crash...
Justin Bogner1c039152016-09-06 17:18:22 +00001194 if (!BugpointIsInterrupted && !DontReducePassList) {
1195 Expected<bool> Result = ReducePassList(*this).reduceList(PassesToRun);
1196 if (Error E = Result.takeError())
1197 return E;
1198 }
Chris Lattner8bda4c42004-02-18 23:26:28 +00001199
Dan Gohmanee051522009-07-16 15:30:09 +00001200 outs() << "\n*** Found crashing pass"
1201 << (PassesToRun.size() == 1 ? ": " : "es: ")
1202 << getPassesString(PassesToRun) << '\n';
Chris Lattner8bda4c42004-02-18 23:26:28 +00001203
Rafael Espindola594994a2010-07-28 18:12:30 +00001204 EmitProgressBitcode(Program, ID);
Chris Lattner8bda4c42004-02-18 23:26:28 +00001205
Justin Bogner1c039152016-09-06 17:18:22 +00001206 return DebugACrash(*this, TestForOptimizerCrash);
Chris Lattner8bda4c42004-02-18 23:26:28 +00001207}
1208
Rafael Espindolad1c7ef42010-08-05 03:00:22 +00001209static bool TestForCodeGenCrash(const BugDriver &BD, Module *M) {
Justin Bogner1c039152016-09-06 17:18:22 +00001210 if (Error E = BD.compileProgram(M)) {
Sebastian Pop8f7d0192016-07-15 23:15:06 +00001211 if (VerboseErrors)
Justin Bogner1c039152016-09-06 17:18:22 +00001212 errs() << toString(std::move(E)) << "\n";
1213 else {
1214 consumeError(std::move(E));
Sebastian Pop8f7d0192016-07-15 23:15:06 +00001215 errs() << "<crash>\n";
Justin Bogner1c039152016-09-06 17:18:22 +00001216 }
Justin Bogner8d0a0812016-09-02 01:21:37 +00001217 return true; // Tool is still crashing.
Chris Lattner8bda4c42004-02-18 23:26:28 +00001218 }
Nick Lewycky6ba630b2010-04-12 05:08:25 +00001219 errs() << '\n';
1220 return false;
Chris Lattner8bda4c42004-02-18 23:26:28 +00001221}
Chris Lattneread1dff2004-02-18 21:02:04 +00001222
1223/// debugCodeGeneratorCrash - This method is called when the code generator
1224/// crashes on an input. It attempts to reduce the input as much as possible
1225/// while still causing the code generator to crash.
Justin Bogner1c039152016-09-06 17:18:22 +00001226Error BugDriver::debugCodeGeneratorCrash() {
Dan Gohmand8db3762009-07-15 16:35:29 +00001227 errs() << "*** Debugging code generator crash!\n";
Chris Lattneread1dff2004-02-18 21:02:04 +00001228
Justin Bogner1c039152016-09-06 17:18:22 +00001229 return DebugACrash(*this, TestForCodeGenCrash);
Chris Lattneread1dff2004-02-18 21:02:04 +00001230}