blob: a5c8f294d4be812de4000c24605e117c0b4f152c [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;
Rafael Espindola2c8bcab2018-02-14 19:58:41 +000088 std::unique_ptr<Module> OrigProgram;
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
Rafael Espindola2c8bcab2018-02-14 19:58:41 +000095 OrigProgram.reset(BD.Program);
Chris Lattnera9656312003-06-02 04:54:29 +000096
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 Espindola2c8bcab2018-02-14 19:58:41 +0000109 if (BD.runPasses(BD.getProgram(), Suffix))
110 return KeepSuffix; // The suffix crashes alone...
Chris Lattner1d080f22003-04-24 22:24:58 +0000111
112 // Nothing failed, restore state...
Chris Lattnera9656312003-06-02 04:54:29 +0000113 if (OrigProgram) {
114 delete BD.Program;
Rafael Espindola2c8bcab2018-02-14 19:58:41 +0000115 BD.Program = OrigProgram.release();
Chris Lattnera9656312003-06-02 04:54:29 +0000116 }
Chris Lattner1d080f22003-04-24 22:24:58 +0000117 return NoFailure;
118}
119
Vedant Kumar08d829d2018-02-08 18:46:49 +0000120using BugTester = bool (*)(const BugDriver &, Module *);
121
Bill Wendling3f833432006-10-25 18:36:14 +0000122namespace {
Vedant Kumar66e85e62018-02-08 20:27:09 +0000123/// ReduceCrashingGlobalInitializers - This works by removing global variable
124/// initializers and seeing if the program still crashes. If it does, then we
125/// keep that program and try again.
126class ReduceCrashingGlobalInitializers : public ListReducer<GlobalVariable *> {
Justin Bogner8d0a0812016-09-02 01:21:37 +0000127 BugDriver &BD;
Vedant Kumar08d829d2018-02-08 18:46:49 +0000128 BugTester TestFn;
Justin Bogner8d0a0812016-09-02 01:21:37 +0000129
130public:
Vedant Kumar66e85e62018-02-08 20:27:09 +0000131 ReduceCrashingGlobalInitializers(BugDriver &bd, BugTester testFn)
Bill Wendling3f833432006-10-25 18:36:14 +0000132 : BD(bd), TestFn(testFn) {}
133
Justin Bogner1c039152016-09-06 17:18:22 +0000134 Expected<TestResult> doTest(std::vector<GlobalVariable *> &Prefix,
135 std::vector<GlobalVariable *> &Kept) override {
Justin Bogner8d0a0812016-09-02 01:21:37 +0000136 if (!Kept.empty() && TestGlobalVariables(Kept))
137 return KeepSuffix;
138 if (!Prefix.empty() && TestGlobalVariables(Prefix))
139 return KeepPrefix;
140 return NoFailure;
141 }
Bill Wendling3f833432006-10-25 18:36:14 +0000142
Justin Bogner8d0a0812016-09-02 01:21:37 +0000143 bool TestGlobalVariables(std::vector<GlobalVariable *> &GVs);
144};
Bill Wendling3f833432006-10-25 18:36:14 +0000145}
146
Vedant Kumar66e85e62018-02-08 20:27:09 +0000147bool ReduceCrashingGlobalInitializers::TestGlobalVariables(
Justin Bogner8d0a0812016-09-02 01:21:37 +0000148 std::vector<GlobalVariable *> &GVs) {
Bill Wendling3f833432006-10-25 18:36:14 +0000149 // Clone the program to try hacking it apart...
Rafael Espindola229e38f2010-10-13 01:36:30 +0000150 ValueToValueMapTy VMap;
Rafael Espindola71867532018-02-14 19:50:40 +0000151 std::unique_ptr<Module> M = CloneModule(*BD.getProgram(), VMap);
Bill Wendling3f833432006-10-25 18:36:14 +0000152
153 // Convert list to set for fast lookup...
Justin Bogner8d0a0812016-09-02 01:21:37 +0000154 std::set<GlobalVariable *> GVSet;
Bill Wendling3f833432006-10-25 18:36:14 +0000155
156 for (unsigned i = 0, e = GVs.size(); i != e; ++i) {
Justin Bogner8d0a0812016-09-02 01:21:37 +0000157 GlobalVariable *CMGV = cast<GlobalVariable>(VMap[GVs[i]]);
Bill Wendling3f833432006-10-25 18:36:14 +0000158 assert(CMGV && "Global Variable not in module?!");
159 GVSet.insert(CMGV);
160 }
161
Dan Gohmanee051522009-07-16 15:30:09 +0000162 outs() << "Checking for crash with only these global variables: ";
Bill Wendling3f833432006-10-25 18:36:14 +0000163 PrintGlobalVariableList(GVs);
Dan Gohmanee051522009-07-16 15:30:09 +0000164 outs() << ": ";
Bill Wendling3f833432006-10-25 18:36:14 +0000165
166 // Loop over and delete any global variables which we aren't supposed to be
167 // playing with...
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000168 for (GlobalVariable &I : M->globals())
169 if (I.hasInitializer() && !GVSet.count(&I)) {
Hal Finkel28ad2b42015-11-26 19:23:49 +0000170 DeleteGlobalInitializer(&I);
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000171 I.setLinkage(GlobalValue::ExternalLinkage);
Justin Lebar2a445cf2016-06-15 23:20:12 +0000172 I.setComdat(nullptr);
Bill Wendling3f833432006-10-25 18:36:14 +0000173 }
174
175 // Try running the hacked up program...
Vedant Kumar66e85e62018-02-08 20:27:09 +0000176 if (TestFn(BD, M.get())) {
177 BD.setNewProgram(M.release()); // It crashed, keep the trimmed version...
Bill Wendling3f833432006-10-25 18:36:14 +0000178
179 // Make sure to use global variable pointers that point into the now-current
180 // module.
181 GVs.assign(GVSet.begin(), GVSet.end());
182 return true;
183 }
184
Bill Wendling3f833432006-10-25 18:36:14 +0000185 return false;
186}
187
David Blaikiea379b1812011-12-20 02:50:00 +0000188namespace {
Justin Bogner8d0a0812016-09-02 01:21:37 +0000189/// ReduceCrashingFunctions reducer - This works by removing functions and
190/// seeing if the program still crashes. If it does, then keep the newer,
191/// smaller program.
192///
193class ReduceCrashingFunctions : public ListReducer<Function *> {
194 BugDriver &BD;
Vedant Kumar08d829d2018-02-08 18:46:49 +0000195 BugTester TestFn;
Justin Bogner8d0a0812016-09-02 01:21:37 +0000196
197public:
Vedant Kumar08d829d2018-02-08 18:46:49 +0000198 ReduceCrashingFunctions(BugDriver &bd, BugTester testFn)
Chris Lattner8bda4c42004-02-18 23:26:28 +0000199 : BD(bd), TestFn(testFn) {}
Misha Brukman650ba8e2005-04-22 00:00:37 +0000200
Justin Bogner1c039152016-09-06 17:18:22 +0000201 Expected<TestResult> doTest(std::vector<Function *> &Prefix,
202 std::vector<Function *> &Kept) override {
Justin Bogner8d0a0812016-09-02 01:21:37 +0000203 if (!Kept.empty() && TestFuncs(Kept))
204 return KeepSuffix;
205 if (!Prefix.empty() && TestFuncs(Prefix))
206 return KeepPrefix;
207 return NoFailure;
208 }
Misha Brukman650ba8e2005-04-22 00:00:37 +0000209
Justin Bogner8d0a0812016-09-02 01:21:37 +0000210 bool TestFuncs(std::vector<Function *> &Prefix);
211};
Chris Lattner2f1aa112004-01-14 03:38:37 +0000212}
Chris Lattner1d080f22003-04-24 22:24:58 +0000213
Justin Bogner8d0a0812016-09-02 01:21:37 +0000214static void RemoveFunctionReferences(Module *M, const char *Name) {
JF Bastienf87e20d2015-04-20 23:42:22 +0000215 auto *UsedVar = M->getGlobalVariable(Name, true);
Justin Bogner8d0a0812016-09-02 01:21:37 +0000216 if (!UsedVar || !UsedVar->hasInitializer())
217 return;
JF Bastienf87e20d2015-04-20 23:42:22 +0000218 if (isa<ConstantAggregateZero>(UsedVar->getInitializer())) {
219 assert(UsedVar->use_empty());
220 UsedVar->eraseFromParent();
221 return;
222 }
223 auto *OldUsedVal = cast<ConstantArray>(UsedVar->getInitializer());
Justin Bogner8d0a0812016-09-02 01:21:37 +0000224 std::vector<Constant *> Used;
225 for (Value *V : OldUsedVal->operand_values()) {
JF Bastienf87e20d2015-04-20 23:42:22 +0000226 Constant *Op = cast<Constant>(V->stripPointerCasts());
Justin Bogner8d0a0812016-09-02 01:21:37 +0000227 if (!Op->isNullValue()) {
JF Bastienf87e20d2015-04-20 23:42:22 +0000228 Used.push_back(cast<Constant>(V));
229 }
230 }
231 auto *NewValElemTy = OldUsedVal->getType()->getElementType();
232 auto *NewValTy = ArrayType::get(NewValElemTy, Used.size());
233 auto *NewUsedVal = ConstantArray::get(NewValTy, Used);
234 UsedVar->mutateType(NewUsedVal->getType()->getPointerTo());
235 UsedVar->setInitializer(NewUsedVal);
236}
237
Justin Bogner8d0a0812016-09-02 01:21:37 +0000238bool ReduceCrashingFunctions::TestFuncs(std::vector<Function *> &Funcs) {
Dmitri Gribenko6e0520e2013-09-02 01:18:56 +0000239 // If main isn't present, claim there is no problem.
David Majnemer0d955d02016-08-11 22:21:41 +0000240 if (KeepMain && !is_contained(Funcs, BD.getProgram()->getFunction("main")))
Andrew Lenharthef9aa122006-03-05 22:21:36 +0000241 return false;
242
Misha Brukman8b2bd4e2003-10-10 17:57:28 +0000243 // Clone the program to try hacking it apart...
Rafael Espindola229e38f2010-10-13 01:36:30 +0000244 ValueToValueMapTy VMap;
Rafael Espindola15647b72018-02-14 20:21:20 +0000245 std::unique_ptr<Module> M = CloneModule(*BD.getProgram(), VMap);
Misha Brukman650ba8e2005-04-22 00:00:37 +0000246
Chris Lattner1d080f22003-04-24 22:24:58 +0000247 // Convert list to set for fast lookup...
Justin Bogner8d0a0812016-09-02 01:21:37 +0000248 std::set<Function *> Functions;
Chris Lattner1d080f22003-04-24 22:24:58 +0000249 for (unsigned i = 0, e = Funcs.size(); i != e; ++i) {
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000250 Function *CMF = cast<Function>(VMap[Funcs[i]]);
Chris Lattner1d080f22003-04-24 22:24:58 +0000251 assert(CMF && "Function not in module?!");
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000252 assert(CMF->getFunctionType() == Funcs[i]->getFunctionType() && "wrong ty");
Dan Gohmanbcad7182009-03-06 02:16:23 +0000253 assert(CMF->getName() == Funcs[i]->getName() && "wrong name");
Chris Lattnerde39f2b2003-04-24 22:54:06 +0000254 Functions.insert(CMF);
Chris Lattner1d080f22003-04-24 22:24:58 +0000255 }
256
Dan Gohmanee051522009-07-16 15:30:09 +0000257 outs() << "Checking for crash with only these functions: ";
Chris Lattnerfd72bed2004-03-14 20:50:42 +0000258 PrintFunctionList(Funcs);
Dan Gohmanee051522009-07-16 15:30:09 +0000259 outs() << ": ";
JF Bastienf87e20d2015-04-20 23:42:22 +0000260 if (!ReplaceFuncsWithNull) {
261 // Loop over and delete any functions which we aren't supposed to be playing
262 // with...
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000263 for (Function &I : *M)
264 if (!I.isDeclaration() && !Functions.count(&I))
265 DeleteFunctionBody(&I);
JF Bastienf87e20d2015-04-20 23:42:22 +0000266 } else {
Justin Bogner8d0a0812016-09-02 01:21:37 +0000267 std::vector<GlobalValue *> ToRemove;
JF Bastienf87e20d2015-04-20 23:42:22 +0000268 // First, remove aliases to functions we're about to purge.
269 for (GlobalAlias &Alias : M->aliases()) {
David Majnemer95549492016-05-04 00:20:48 +0000270 GlobalObject *Root = Alias.getBaseObject();
271 Function *F = dyn_cast_or_null<Function>(Root);
JF Bastienf87e20d2015-04-20 23:42:22 +0000272 if (F) {
273 if (Functions.count(F))
274 // We're keeping this function.
275 continue;
276 } else if (Root->isNullValue()) {
277 // This referenced a globalalias that we've already replaced,
278 // so we still need to replace this alias.
279 } else if (!F) {
280 // Not a function, therefore not something we mess with.
281 continue;
282 }
Chris Lattner1d080f22003-04-24 22:24:58 +0000283
JF Bastienf87e20d2015-04-20 23:42:22 +0000284 PointerType *Ty = cast<PointerType>(Alias.getType());
285 Constant *Replacement = ConstantPointerNull::get(Ty);
286 Alias.replaceAllUsesWith(Replacement);
287 ToRemove.push_back(&Alias);
288 }
Chris Lattner1d080f22003-04-24 22:24:58 +0000289
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000290 for (Function &I : *M) {
291 if (!I.isDeclaration() && !Functions.count(&I)) {
292 PointerType *Ty = cast<PointerType>(I.getType());
JF Bastienf87e20d2015-04-20 23:42:22 +0000293 Constant *Replacement = ConstantPointerNull::get(Ty);
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000294 I.replaceAllUsesWith(Replacement);
295 ToRemove.push_back(&I);
JF Bastienf87e20d2015-04-20 23:42:22 +0000296 }
297 }
298
299 for (auto *F : ToRemove) {
300 F->eraseFromParent();
301 }
302
303 // Finally, remove any null members from any global intrinsic.
Rafael Espindola15647b72018-02-14 20:21:20 +0000304 RemoveFunctionReferences(M.get(), "llvm.used");
305 RemoveFunctionReferences(M.get(), "llvm.compiler.used");
JF Bastienf87e20d2015-04-20 23:42:22 +0000306 }
Chris Lattner1d080f22003-04-24 22:24:58 +0000307 // Try running the hacked up program...
Rafael Espindola15647b72018-02-14 20:21:20 +0000308 if (TestFn(BD, M.get())) {
309 BD.setNewProgram(M.release()); // It crashed, keep the trimmed version...
Chris Lattner1d080f22003-04-24 22:24:58 +0000310
311 // Make sure to use function pointers that point into the now-current
312 // module.
313 Funcs.assign(Functions.begin(), Functions.end());
314 return true;
315 }
Chris Lattner1d080f22003-04-24 22:24:58 +0000316 return false;
317}
318
Chris Lattner1942f982004-02-18 21:29:46 +0000319namespace {
Daniel Berlin60606262016-07-28 22:29:25 +0000320/// Simplify the CFG without completely destroying it.
321/// This is not well defined, but basically comes down to "try to eliminate
322/// unreachable blocks and constant fold terminators without deciding that
323/// certain undefined behavior cuts off the program at the legs".
324void simpleSimplifyCfg(Function &F, SmallVectorImpl<BasicBlock *> &BBs) {
325 if (F.empty())
326 return;
327
328 for (auto *BB : BBs) {
329 ConstantFoldTerminator(BB);
330 MergeBlockIntoPredecessor(BB);
331 }
332
333 // Remove unreachable blocks
334 // removeUnreachableBlocks can't be used here, it will turn various
335 // undefined behavior into unreachables, but bugpoint was the thing that
336 // generated the undefined behavior, and we don't want it to kill the entire
337 // program.
338 SmallPtrSet<BasicBlock *, 16> Visited;
339 for (auto *BB : depth_first(&F.getEntryBlock()))
340 Visited.insert(BB);
341
342 SmallVector<BasicBlock *, 16> Unreachable;
343 for (auto &BB : F)
344 if (!Visited.count(&BB))
345 Unreachable.push_back(&BB);
346
347 // The dead BB's may be in a dead cycle or otherwise have references to each
348 // other. Because of this, we have to drop all references first, then delete
349 // them all at once.
Justin Bogner8d0a0812016-09-02 01:21:37 +0000350 for (auto *BB : Unreachable) {
Daniel Berlin60606262016-07-28 22:29:25 +0000351 for (BasicBlock *Successor : successors(&*BB))
352 if (Visited.count(Successor))
353 Successor->removePredecessor(&*BB);
354 BB->dropAllReferences();
355 }
356 for (auto *BB : Unreachable)
357 BB->eraseFromParent();
358}
Justin Bogner8d0a0812016-09-02 01:21:37 +0000359/// ReduceCrashingBlocks reducer - This works by setting the terminators of
360/// all terminators except the specified basic blocks to a 'ret' instruction,
361/// then running the simplify-cfg pass. This has the effect of chopping up
362/// the CFG really fast which can reduce large functions quickly.
363///
364class ReduceCrashingBlocks : public ListReducer<const BasicBlock *> {
365 BugDriver &BD;
Vedant Kumar08d829d2018-02-08 18:46:49 +0000366 BugTester TestFn;
Justin Bogner8d0a0812016-09-02 01:21:37 +0000367
368public:
Vedant Kumar08d829d2018-02-08 18:46:49 +0000369 ReduceCrashingBlocks(BugDriver &BD, BugTester testFn)
Daniel Berlin60606262016-07-28 22:29:25 +0000370 : BD(BD), TestFn(testFn) {}
Misha Brukman650ba8e2005-04-22 00:00:37 +0000371
Justin Bogner1c039152016-09-06 17:18:22 +0000372 Expected<TestResult> doTest(std::vector<const BasicBlock *> &Prefix,
373 std::vector<const BasicBlock *> &Kept) override {
Justin Bogner8d0a0812016-09-02 01:21:37 +0000374 if (!Kept.empty() && TestBlocks(Kept))
375 return KeepSuffix;
376 if (!Prefix.empty() && TestBlocks(Prefix))
377 return KeepPrefix;
378 return NoFailure;
379 }
Misha Brukman650ba8e2005-04-22 00:00:37 +0000380
Justin Bogner8d0a0812016-09-02 01:21:37 +0000381 bool TestBlocks(std::vector<const BasicBlock *> &Prefix);
382};
Chris Lattner2f1aa112004-01-14 03:38:37 +0000383}
Chris Lattnerf32939b2003-04-24 23:51:38 +0000384
Justin Bogner8d0a0812016-09-02 01:21:37 +0000385bool ReduceCrashingBlocks::TestBlocks(std::vector<const BasicBlock *> &BBs) {
Misha Brukman8b2bd4e2003-10-10 17:57:28 +0000386 // Clone the program to try hacking it apart...
Rafael Espindola229e38f2010-10-13 01:36:30 +0000387 ValueToValueMapTy VMap;
Rafael Espindola71867532018-02-14 19:50:40 +0000388 std::unique_ptr<Module> M = CloneModule(*BD.getProgram(), VMap);
Misha Brukman650ba8e2005-04-22 00:00:37 +0000389
Chris Lattnerf32939b2003-04-24 23:51:38 +0000390 // Convert list to set for fast lookup...
Justin Bogner8d0a0812016-09-02 01:21:37 +0000391 SmallPtrSet<BasicBlock *, 8> Blocks;
Nick Lewyckyb294e312009-04-04 09:39:23 +0000392 for (unsigned i = 0, e = BBs.size(); i != e; ++i)
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000393 Blocks.insert(cast<BasicBlock>(VMap[BBs[i]]));
Chris Lattnerf32939b2003-04-24 23:51:38 +0000394
Dan Gohmanee051522009-07-16 15:30:09 +0000395 outs() << "Checking for crash with only these blocks:";
Chris Lattner4f50ebd2003-10-27 04:44:59 +0000396 unsigned NumPrint = Blocks.size();
Justin Bogner8d0a0812016-09-02 01:21:37 +0000397 if (NumPrint > 10)
398 NumPrint = 10;
Chris Lattner4f50ebd2003-10-27 04:44:59 +0000399 for (unsigned i = 0, e = NumPrint; i != e; ++i)
Dan Gohmanee051522009-07-16 15:30:09 +0000400 outs() << " " << BBs[i]->getName();
Chris Lattner4f50ebd2003-10-27 04:44:59 +0000401 if (NumPrint < Blocks.size())
Dan Gohmanee051522009-07-16 15:30:09 +0000402 outs() << "... <" << Blocks.size() << " total>";
403 outs() << ": ";
Chris Lattnerf32939b2003-04-24 23:51:38 +0000404
405 // Loop over and delete any hack up any blocks that are not listed...
Vedant Kumare84e7672018-02-09 05:09:50 +0000406 for (Function &F : M->functions()) {
407 for (BasicBlock &BB : F) {
408 if (!Blocks.count(&BB) && BB.getTerminator()->getNumSuccessors()) {
Chris Lattnerf32939b2003-04-24 23:51:38 +0000409 // Loop over all of the successors of this block, deleting any PHI nodes
410 // that might include it.
Vedant Kumare84e7672018-02-09 05:09:50 +0000411 for (BasicBlock *Succ : successors(&BB))
412 Succ->removePredecessor(&BB);
Chris Lattnerf32939b2003-04-24 23:51:38 +0000413
Vedant Kumare84e7672018-02-09 05:09:50 +0000414 TerminatorInst *BBTerm = BB.getTerminator();
Philip Reames29e641c2016-06-29 00:15:35 +0000415 if (BBTerm->isEHPad() || BBTerm->getType()->isTokenTy())
David Majnemer189d7da2015-11-08 04:16:12 +0000416 continue;
Philip Reames29e641c2016-06-29 00:15:35 +0000417 if (!BBTerm->getType()->isVoidTy())
Owen Anderson5a1acd92009-07-31 20:28:14 +0000418 BBTerm->replaceAllUsesWith(Constant::getNullValue(BBTerm->getType()));
Chris Lattner7b233af2003-11-22 02:10:38 +0000419
Chris Lattner7855a5c2008-04-28 00:04:58 +0000420 // Replace the old terminator instruction.
Vedant Kumare84e7672018-02-09 05:09:50 +0000421 BB.getInstList().pop_back();
422 new UnreachableInst(BB.getContext(), &BB);
Chris Lattnerf32939b2003-04-24 23:51:38 +0000423 }
Vedant Kumare84e7672018-02-09 05:09:50 +0000424 }
425 }
Chris Lattnerf32939b2003-04-24 23:51:38 +0000426
427 // The CFG Simplifier pass may delete one of the basic blocks we are
428 // interested in. If it does we need to take the block out of the list. Make
429 // a "persistent mapping" by turning basic blocks into <function, name> pairs.
430 // This won't work well if blocks are unnamed, but that is just the risk we
Vedant Kumare84e7672018-02-09 05:09:50 +0000431 // have to take. FIXME: Can we just name the blocks?
Justin Bogner8d0a0812016-09-02 01:21:37 +0000432 std::vector<std::pair<std::string, std::string>> BlockInfo;
Chris Lattnerf32939b2003-04-24 23:51:38 +0000433
Craig Topper46276792014-08-24 23:23:06 +0000434 for (BasicBlock *BB : Blocks)
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000435 BlockInfo.emplace_back(BB->getParent()->getName(), BB->getName());
Justin Bogner8d0a0812016-09-02 01:21:37 +0000436
Daniel Berlin60606262016-07-28 22:29:25 +0000437 SmallVector<BasicBlock *, 16> ToProcess;
Justin Bogner8d0a0812016-09-02 01:21:37 +0000438 for (auto &F : *M) {
Daniel Berlin60606262016-07-28 22:29:25 +0000439 for (auto &BB : F)
440 if (!Blocks.count(&BB))
441 ToProcess.push_back(&BB);
442 simpleSimplifyCfg(F, ToProcess);
443 ToProcess.clear();
444 }
445 // Verify we didn't break anything
Rafael Espindolad1e241a2010-08-10 15:46:11 +0000446 std::vector<std::string> Passes;
Rafael Espindolad1e241a2010-08-10 15:46:11 +0000447 Passes.push_back("verify");
Vedant Kumare84e7672018-02-09 05:09:50 +0000448 std::unique_ptr<Module> New = BD.runPassesOn(M.get(), Passes);
Rafael Espindolad1e241a2010-08-10 15:46:11 +0000449 if (!New) {
Daniel Berlin60606262016-07-28 22:29:25 +0000450 errs() << "verify failed!\n";
Rafael Espindolad1e241a2010-08-10 15:46:11 +0000451 exit(1);
452 }
Vedant Kumare84e7672018-02-09 05:09:50 +0000453 M = std::move(New);
Justin Bogner8d0a0812016-09-02 01:21:37 +0000454
Chris Lattnerf32939b2003-04-24 23:51:38 +0000455 // Try running on the hacked up program...
Vedant Kumare84e7672018-02-09 05:09:50 +0000456 if (TestFn(BD, M.get())) {
457 BD.setNewProgram(M.release()); // It crashed, keep the trimmed version...
Chris Lattnerf32939b2003-04-24 23:51:38 +0000458
459 // Make sure to use basic block pointers that point into the now-current
460 // module, and that they don't include any deleted blocks.
461 BBs.clear();
Vedant Kumare84e7672018-02-09 05:09:50 +0000462 const ValueSymbolTable &GST = BD.getProgram()->getValueSymbolTable();
463 for (const auto &BI : BlockInfo) {
464 Function *F = cast<Function>(GST.lookup(BI.first));
465 Value *V = F->getValueSymbolTable()->lookup(BI.second);
Owen Anderson55f1c092009-08-13 21:58:54 +0000466 if (V && V->getType() == Type::getLabelTy(V->getContext()))
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000467 BBs.push_back(cast<BasicBlock>(V));
Chris Lattnerf32939b2003-04-24 23:51:38 +0000468 }
469 return true;
470 }
Vedant Kumare84e7672018-02-09 05:09:50 +0000471 // It didn't crash, try something else.
Chris Lattnerf32939b2003-04-24 23:51:38 +0000472 return false;
473}
474
Nick Lewycky6e090c92009-05-25 05:30:00 +0000475namespace {
Daniel Berlin271ca402016-07-27 16:13:25 +0000476/// ReduceCrashingConditionals reducer - This works by changing
477/// conditional branches to unconditional ones, then simplifying the CFG
478/// This has the effect of chopping up the CFG really fast which can reduce
479/// large functions quickly.
480///
481class ReduceCrashingConditionals : public ListReducer<const BasicBlock *> {
482 BugDriver &BD;
Vedant Kumar08d829d2018-02-08 18:46:49 +0000483 BugTester TestFn;
Daniel Berlin271ca402016-07-27 16:13:25 +0000484 bool Direction;
485
486public:
Vedant Kumar08d829d2018-02-08 18:46:49 +0000487 ReduceCrashingConditionals(BugDriver &bd, BugTester testFn, bool Direction)
Daniel Berlin271ca402016-07-27 16:13:25 +0000488 : BD(bd), TestFn(testFn), Direction(Direction) {}
489
Justin Bogner1c039152016-09-06 17:18:22 +0000490 Expected<TestResult> doTest(std::vector<const BasicBlock *> &Prefix,
491 std::vector<const BasicBlock *> &Kept) override {
Daniel Berlin271ca402016-07-27 16:13:25 +0000492 if (!Kept.empty() && TestBlocks(Kept))
493 return KeepSuffix;
494 if (!Prefix.empty() && TestBlocks(Prefix))
495 return KeepPrefix;
496 return NoFailure;
497 }
498
499 bool TestBlocks(std::vector<const BasicBlock *> &Prefix);
500};
501}
502
503bool ReduceCrashingConditionals::TestBlocks(
504 std::vector<const BasicBlock *> &BBs) {
505 // Clone the program to try hacking it apart...
506 ValueToValueMapTy VMap;
Rafael Espindola71867532018-02-14 19:50:40 +0000507 std::unique_ptr<Module> M = CloneModule(*BD.getProgram(), VMap);
Daniel Berlin271ca402016-07-27 16:13:25 +0000508
509 // Convert list to set for fast lookup...
510 SmallPtrSet<const BasicBlock *, 8> Blocks;
Justin Bogner8d0a0812016-09-02 01:21:37 +0000511 for (const auto *BB : BBs)
Daniel Berlin271ca402016-07-27 16:13:25 +0000512 Blocks.insert(cast<BasicBlock>(VMap[BB]));
513
514 outs() << "Checking for crash with changing conditionals to always jump to "
515 << (Direction ? "true" : "false") << ":";
516 unsigned NumPrint = Blocks.size();
517 if (NumPrint > 10)
518 NumPrint = 10;
519 for (unsigned i = 0, e = NumPrint; i != e; ++i)
520 outs() << " " << BBs[i]->getName();
521 if (NumPrint < Blocks.size())
522 outs() << "... <" << Blocks.size() << " total>";
523 outs() << ": ";
524
525 // Loop over and delete any hack up any blocks that are not listed...
Justin Bogner8d0a0812016-09-02 01:21:37 +0000526 for (auto &F : *M)
Daniel Berlin271ca402016-07-27 16:13:25 +0000527 for (auto &BB : F)
528 if (!Blocks.count(&BB)) {
529 auto *BR = dyn_cast<BranchInst>(BB.getTerminator());
530 if (!BR || !BR->isConditional())
531 continue;
532 if (Direction)
533 BR->setCondition(ConstantInt::getTrue(BR->getContext()));
534 else
535 BR->setCondition(ConstantInt::getFalse(BR->getContext()));
536 }
537
538 // The following may destroy some blocks, so we save them first
539 std::vector<std::pair<std::string, std::string>> BlockInfo;
540
541 for (const BasicBlock *BB : Blocks)
542 BlockInfo.emplace_back(BB->getParent()->getName(), BB->getName());
543
544 SmallVector<BasicBlock *, 16> ToProcess;
Justin Bogner8d0a0812016-09-02 01:21:37 +0000545 for (auto &F : *M) {
Daniel Berlin271ca402016-07-27 16:13:25 +0000546 for (auto &BB : F)
547 if (!Blocks.count(&BB))
548 ToProcess.push_back(&BB);
549 simpleSimplifyCfg(F, ToProcess);
550 ToProcess.clear();
551 }
552 // Verify we didn't break anything
553 std::vector<std::string> Passes;
554 Passes.push_back("verify");
Vedant Kumare84e7672018-02-09 05:09:50 +0000555 std::unique_ptr<Module> New = BD.runPassesOn(M.get(), Passes);
Daniel Berlin271ca402016-07-27 16:13:25 +0000556 if (!New) {
557 errs() << "verify failed!\n";
558 exit(1);
559 }
Vedant Kumare84e7672018-02-09 05:09:50 +0000560 M = std::move(New);
Daniel Berlin271ca402016-07-27 16:13:25 +0000561
562 // Try running on the hacked up program...
Vedant Kumare84e7672018-02-09 05:09:50 +0000563 if (TestFn(BD, M.get())) {
564 BD.setNewProgram(M.release()); // It crashed, keep the trimmed version...
Daniel Berlin271ca402016-07-27 16:13:25 +0000565
566 // Make sure to use basic block pointers that point into the now-current
567 // module, and that they don't include any deleted blocks.
568 BBs.clear();
Vedant Kumare84e7672018-02-09 05:09:50 +0000569 const ValueSymbolTable &GST = BD.getProgram()->getValueSymbolTable();
Daniel Berlin271ca402016-07-27 16:13:25 +0000570 for (auto &BI : BlockInfo) {
571 auto *F = cast<Function>(GST.lookup(BI.first));
Mehdi Aminia53d49e2016-09-17 06:00:02 +0000572 Value *V = F->getValueSymbolTable()->lookup(BI.second);
Daniel Berlin271ca402016-07-27 16:13:25 +0000573 if (V && V->getType() == Type::getLabelTy(V->getContext()))
574 BBs.push_back(cast<BasicBlock>(V));
575 }
576 return true;
577 }
Vedant Kumare84e7672018-02-09 05:09:50 +0000578 // It didn't crash, try something else.
Daniel Berlin271ca402016-07-27 16:13:25 +0000579 return false;
580}
581
582namespace {
Daniel Berlin60606262016-07-28 22:29:25 +0000583/// SimplifyCFG reducer - This works by calling SimplifyCFG on each basic block
584/// in the program.
585
586class ReduceSimplifyCFG : public ListReducer<const BasicBlock *> {
587 BugDriver &BD;
Vedant Kumar08d829d2018-02-08 18:46:49 +0000588 BugTester TestFn;
Daniel Berlin60606262016-07-28 22:29:25 +0000589 TargetTransformInfo TTI;
Justin Bogner8d0a0812016-09-02 01:21:37 +0000590
Daniel Berlin60606262016-07-28 22:29:25 +0000591public:
Vedant Kumar08d829d2018-02-08 18:46:49 +0000592 ReduceSimplifyCFG(BugDriver &bd, BugTester testFn)
Justin Bogner8d0a0812016-09-02 01:21:37 +0000593 : BD(bd), TestFn(testFn), TTI(bd.getProgram()->getDataLayout()) {}
Daniel Berlin60606262016-07-28 22:29:25 +0000594
Justin Bogner1c039152016-09-06 17:18:22 +0000595 Expected<TestResult> doTest(std::vector<const BasicBlock *> &Prefix,
596 std::vector<const BasicBlock *> &Kept) override {
Daniel Berlin60606262016-07-28 22:29:25 +0000597 if (!Kept.empty() && TestBlocks(Kept))
598 return KeepSuffix;
599 if (!Prefix.empty() && TestBlocks(Prefix))
600 return KeepPrefix;
601 return NoFailure;
602 }
603
604 bool TestBlocks(std::vector<const BasicBlock *> &Prefix);
605};
606}
607
Justin Bogner8d0a0812016-09-02 01:21:37 +0000608bool ReduceSimplifyCFG::TestBlocks(std::vector<const BasicBlock *> &BBs) {
Daniel Berlin60606262016-07-28 22:29:25 +0000609 // Clone the program to try hacking it apart...
610 ValueToValueMapTy VMap;
Rafael Espindola71867532018-02-14 19:50:40 +0000611 std::unique_ptr<Module> M = CloneModule(*BD.getProgram(), VMap);
Daniel Berlin60606262016-07-28 22:29:25 +0000612
613 // Convert list to set for fast lookup...
614 SmallPtrSet<const BasicBlock *, 8> Blocks;
Justin Bogner8d0a0812016-09-02 01:21:37 +0000615 for (const auto *BB : BBs)
Daniel Berlin60606262016-07-28 22:29:25 +0000616 Blocks.insert(cast<BasicBlock>(VMap[BB]));
617
618 outs() << "Checking for crash with CFG simplifying:";
619 unsigned NumPrint = Blocks.size();
620 if (NumPrint > 10)
621 NumPrint = 10;
622 for (unsigned i = 0, e = NumPrint; i != e; ++i)
623 outs() << " " << BBs[i]->getName();
624 if (NumPrint < Blocks.size())
625 outs() << "... <" << Blocks.size() << " total>";
626 outs() << ": ";
627
Justin Bogner8d0a0812016-09-02 01:21:37 +0000628 // The following may destroy some blocks, so we save them first
Daniel Berlin60606262016-07-28 22:29:25 +0000629 std::vector<std::pair<std::string, std::string>> BlockInfo;
630
631 for (const BasicBlock *BB : Blocks)
632 BlockInfo.emplace_back(BB->getParent()->getName(), BB->getName());
633
Daniel Berlin60606262016-07-28 22:29:25 +0000634 // Loop over and delete any hack up any blocks that are not listed...
Justin Bogner8d0a0812016-09-02 01:21:37 +0000635 for (auto &F : *M)
636 // Loop over all of the basic blocks and remove them if they are unneeded.
637 for (Function::iterator BBIt = F.begin(); BBIt != F.end();) {
638 if (!Blocks.count(&*BBIt)) {
639 ++BBIt;
640 continue;
641 }
Sanjay Patel4c33d522017-10-04 20:26:25 +0000642 simplifyCFG(&*BBIt++, TTI);
Justin Bogner8d0a0812016-09-02 01:21:37 +0000643 }
Daniel Berlin60606262016-07-28 22:29:25 +0000644 // Verify we didn't break anything
645 std::vector<std::string> Passes;
646 Passes.push_back("verify");
Vedant Kumare84e7672018-02-09 05:09:50 +0000647 std::unique_ptr<Module> New = BD.runPassesOn(M.get(), Passes);
Daniel Berlin60606262016-07-28 22:29:25 +0000648 if (!New) {
649 errs() << "verify failed!\n";
650 exit(1);
651 }
Vedant Kumare84e7672018-02-09 05:09:50 +0000652 M = std::move(New);
Daniel Berlin60606262016-07-28 22:29:25 +0000653
654 // Try running on the hacked up program...
Vedant Kumare84e7672018-02-09 05:09:50 +0000655 if (TestFn(BD, M.get())) {
656 BD.setNewProgram(M.release()); // It crashed, keep the trimmed version...
Daniel Berlin60606262016-07-28 22:29:25 +0000657
658 // Make sure to use basic block pointers that point into the now-current
659 // module, and that they don't include any deleted blocks.
660 BBs.clear();
Vedant Kumare84e7672018-02-09 05:09:50 +0000661 const ValueSymbolTable &GST = BD.getProgram()->getValueSymbolTable();
Justin Bogner8d0a0812016-09-02 01:21:37 +0000662 for (auto &BI : BlockInfo) {
Daniel Berlin60606262016-07-28 22:29:25 +0000663 auto *F = cast<Function>(GST.lookup(BI.first));
Mehdi Aminia53d49e2016-09-17 06:00:02 +0000664 Value *V = F->getValueSymbolTable()->lookup(BI.second);
Daniel Berlin60606262016-07-28 22:29:25 +0000665 if (V && V->getType() == Type::getLabelTy(V->getContext()))
666 BBs.push_back(cast<BasicBlock>(V));
667 }
668 return true;
669 }
Vedant Kumare84e7672018-02-09 05:09:50 +0000670 // It didn't crash, try something else.
Daniel Berlin60606262016-07-28 22:29:25 +0000671 return false;
672}
673
674namespace {
Justin Bogner8d0a0812016-09-02 01:21:37 +0000675/// ReduceCrashingInstructions reducer - This works by removing the specified
676/// non-terminator instructions and replacing them with undef.
677///
678class ReduceCrashingInstructions : public ListReducer<const Instruction *> {
679 BugDriver &BD;
Vedant Kumar08d829d2018-02-08 18:46:49 +0000680 BugTester TestFn;
Justin Bogner8d0a0812016-09-02 01:21:37 +0000681
682public:
Vedant Kumar08d829d2018-02-08 18:46:49 +0000683 ReduceCrashingInstructions(BugDriver &bd, BugTester testFn)
Nick Lewycky6e090c92009-05-25 05:30:00 +0000684 : BD(bd), TestFn(testFn) {}
685
Justin Bogner1c039152016-09-06 17:18:22 +0000686 Expected<TestResult> doTest(std::vector<const Instruction *> &Prefix,
687 std::vector<const Instruction *> &Kept) override {
Justin Bogner8d0a0812016-09-02 01:21:37 +0000688 if (!Kept.empty() && TestInsts(Kept))
689 return KeepSuffix;
690 if (!Prefix.empty() && TestInsts(Prefix))
691 return KeepPrefix;
692 return NoFailure;
693 }
Nick Lewycky6e090c92009-05-25 05:30:00 +0000694
Justin Bogner8d0a0812016-09-02 01:21:37 +0000695 bool TestInsts(std::vector<const Instruction *> &Prefix);
696};
Nick Lewycky6e090c92009-05-25 05:30:00 +0000697}
698
Justin Bogner8d0a0812016-09-02 01:21:37 +0000699bool ReduceCrashingInstructions::TestInsts(
700 std::vector<const Instruction *> &Insts) {
Nick Lewycky6e090c92009-05-25 05:30:00 +0000701 // Clone the program to try hacking it apart...
Rafael Espindola229e38f2010-10-13 01:36:30 +0000702 ValueToValueMapTy VMap;
Rafael Espindola19d86552018-02-14 20:25:18 +0000703 std::unique_ptr<Module> M = CloneModule(*BD.getProgram(), VMap);
Nick Lewycky6e090c92009-05-25 05:30:00 +0000704
705 // Convert list to set for fast lookup...
Justin Bogner8d0a0812016-09-02 01:21:37 +0000706 SmallPtrSet<Instruction *, 32> Instructions;
Nick Lewycky6e090c92009-05-25 05:30:00 +0000707 for (unsigned i = 0, e = Insts.size(); i != e; ++i) {
708 assert(!isa<TerminatorInst>(Insts[i]));
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000709 Instructions.insert(cast<Instruction>(VMap[Insts[i]]));
Nick Lewycky6e090c92009-05-25 05:30:00 +0000710 }
711
Dan Gohmanee051522009-07-16 15:30:09 +0000712 outs() << "Checking for crash with only " << Instructions.size();
Nick Lewycky6e090c92009-05-25 05:30:00 +0000713 if (Instructions.size() == 1)
Dan Gohmanee051522009-07-16 15:30:09 +0000714 outs() << " instruction: ";
Nick Lewycky6e090c92009-05-25 05:30:00 +0000715 else
Dan Gohmanee051522009-07-16 15:30:09 +0000716 outs() << " instructions: ";
Nick Lewycky6e090c92009-05-25 05:30:00 +0000717
718 for (Module::iterator MI = M->begin(), ME = M->end(); MI != ME; ++MI)
719 for (Function::iterator FI = MI->begin(), FE = MI->end(); FI != FE; ++FI)
720 for (BasicBlock::iterator I = FI->begin(), E = FI->end(); I != E;) {
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000721 Instruction *Inst = &*I++;
Eli Friedmand4e02a52011-11-01 04:40:56 +0000722 if (!Instructions.count(Inst) && !isa<TerminatorInst>(Inst) &&
Arnold Schwaighofera8f5a822017-03-07 20:28:59 +0000723 !Inst->isEHPad() && !Inst->getType()->isTokenTy() &&
724 !Inst->isSwiftError()) {
Philip Reames29e641c2016-06-29 00:15:35 +0000725 if (!Inst->getType()->isVoidTy())
Nick Lewycky6e090c92009-05-25 05:30:00 +0000726 Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
727 Inst->eraseFromParent();
728 }
729 }
730
731 // Verify that this is still valid.
Chandler Carruth30d69c22015-02-13 10:01:29 +0000732 legacy::PassManager Passes;
Adrian Prantl919bdf12016-10-18 16:24:43 +0000733 Passes.add(createVerifierPass(/*FatalErrors=*/false));
Nick Lewycky6e090c92009-05-25 05:30:00 +0000734 Passes.run(*M);
735
736 // Try running on the hacked up program...
Rafael Espindola19d86552018-02-14 20:25:18 +0000737 if (TestFn(BD, M.get())) {
738 BD.setNewProgram(M.release()); // It crashed, keep the trimmed version...
Nick Lewycky6e090c92009-05-25 05:30:00 +0000739
740 // Make sure to use instruction pointers that point into the now-current
741 // module, and that they don't include any deleted blocks.
742 Insts.clear();
Craig Topper46276792014-08-24 23:23:06 +0000743 for (Instruction *Inst : Instructions)
744 Insts.push_back(Inst);
Nick Lewycky6e090c92009-05-25 05:30:00 +0000745 return true;
746 }
Rafael Espindola19d86552018-02-14 20:25:18 +0000747 // It didn't crash, try something else.
Nick Lewycky6e090c92009-05-25 05:30:00 +0000748 return false;
749}
750
Keno Fischer34ca8312015-11-06 00:12:50 +0000751namespace {
752// Reduce the list of Named Metadata nodes. We keep this as a list of
753// names to avoid having to convert back and forth every time.
754class ReduceCrashingNamedMD : public ListReducer<std::string> {
755 BugDriver &BD;
Vedant Kumar08d829d2018-02-08 18:46:49 +0000756 BugTester TestFn;
Keno Fischer34ca8312015-11-06 00:12:50 +0000757
758public:
Vedant Kumar08d829d2018-02-08 18:46:49 +0000759 ReduceCrashingNamedMD(BugDriver &bd, BugTester testFn)
Keno Fischer34ca8312015-11-06 00:12:50 +0000760 : BD(bd), TestFn(testFn) {}
761
Justin Bogner1c039152016-09-06 17:18:22 +0000762 Expected<TestResult> doTest(std::vector<std::string> &Prefix,
763 std::vector<std::string> &Kept) override {
Keno Fischer34ca8312015-11-06 00:12:50 +0000764 if (!Kept.empty() && TestNamedMDs(Kept))
765 return KeepSuffix;
766 if (!Prefix.empty() && TestNamedMDs(Prefix))
767 return KeepPrefix;
768 return NoFailure;
769 }
770
771 bool TestNamedMDs(std::vector<std::string> &NamedMDs);
772};
773}
774
775bool ReduceCrashingNamedMD::TestNamedMDs(std::vector<std::string> &NamedMDs) {
776
777 ValueToValueMapTy VMap;
Rafael Espindola29118412018-02-14 20:53:38 +0000778 std::unique_ptr<Module> M = CloneModule(*BD.getProgram(), VMap);
Keno Fischer34ca8312015-11-06 00:12:50 +0000779
780 outs() << "Checking for crash with only these named metadata nodes:";
781 unsigned NumPrint = std::min<size_t>(NamedMDs.size(), 10);
782 for (unsigned i = 0, e = NumPrint; i != e; ++i)
783 outs() << " " << NamedMDs[i];
784 if (NumPrint < NamedMDs.size())
785 outs() << "... <" << NamedMDs.size() << " total>";
786 outs() << ": ";
787
788 // Make a StringMap for faster lookup
789 StringSet<> Names;
790 for (const std::string &Name : NamedMDs)
791 Names.insert(Name);
792
793 // First collect all the metadata to delete in a vector, then
794 // delete them all at once to avoid invalidating the iterator
795 std::vector<NamedMDNode *> ToDelete;
796 ToDelete.reserve(M->named_metadata_size() - Names.size());
797 for (auto &NamedMD : M->named_metadata())
Adrian Prantlfaebbb02016-03-28 21:06:26 +0000798 // Always keep a nonempty llvm.dbg.cu because the Verifier would complain.
799 if (!Names.count(NamedMD.getName()) &&
800 (!(NamedMD.getName() == "llvm.dbg.cu" && NamedMD.getNumOperands() > 0)))
Keno Fischer34ca8312015-11-06 00:12:50 +0000801 ToDelete.push_back(&NamedMD);
802
803 for (auto *NamedMD : ToDelete)
804 NamedMD->eraseFromParent();
805
806 // Verify that this is still valid.
807 legacy::PassManager Passes;
Adrian Prantl919bdf12016-10-18 16:24:43 +0000808 Passes.add(createVerifierPass(/*FatalErrors=*/false));
Keno Fischer34ca8312015-11-06 00:12:50 +0000809 Passes.run(*M);
810
811 // Try running on the hacked up program...
Rafael Espindola29118412018-02-14 20:53:38 +0000812 if (TestFn(BD, M.get())) {
813 BD.setNewProgram(M.release()); // It crashed, keep the trimmed version...
Keno Fischer34ca8312015-11-06 00:12:50 +0000814 return true;
815 }
Keno Fischer34ca8312015-11-06 00:12:50 +0000816 return false;
817}
818
819namespace {
820// Reduce the list of operands to named metadata nodes
821class ReduceCrashingNamedMDOps : public ListReducer<const MDNode *> {
822 BugDriver &BD;
Vedant Kumar08d829d2018-02-08 18:46:49 +0000823 BugTester TestFn;
Keno Fischer34ca8312015-11-06 00:12:50 +0000824
825public:
Vedant Kumar08d829d2018-02-08 18:46:49 +0000826 ReduceCrashingNamedMDOps(BugDriver &bd, BugTester testFn)
Keno Fischer34ca8312015-11-06 00:12:50 +0000827 : BD(bd), TestFn(testFn) {}
828
Justin Bogner1c039152016-09-06 17:18:22 +0000829 Expected<TestResult> doTest(std::vector<const MDNode *> &Prefix,
830 std::vector<const MDNode *> &Kept) override {
Keno Fischer34ca8312015-11-06 00:12:50 +0000831 if (!Kept.empty() && TestNamedMDOps(Kept))
832 return KeepSuffix;
833 if (!Prefix.empty() && TestNamedMDOps(Prefix))
834 return KeepPrefix;
835 return NoFailure;
836 }
837
838 bool TestNamedMDOps(std::vector<const MDNode *> &NamedMDOps);
839};
840}
841
842bool ReduceCrashingNamedMDOps::TestNamedMDOps(
843 std::vector<const MDNode *> &NamedMDOps) {
844 // Convert list to set for fast lookup...
Matthias Braunb30f2f512016-01-30 01:24:31 +0000845 SmallPtrSet<const MDNode *, 32> OldMDNodeOps;
Keno Fischer34ca8312015-11-06 00:12:50 +0000846 for (unsigned i = 0, e = NamedMDOps.size(); i != e; ++i) {
847 OldMDNodeOps.insert(NamedMDOps[i]);
848 }
849
850 outs() << "Checking for crash with only " << OldMDNodeOps.size();
851 if (OldMDNodeOps.size() == 1)
852 outs() << " named metadata operand: ";
853 else
854 outs() << " named metadata operands: ";
855
856 ValueToValueMapTy VMap;
Rafael Espindola71867532018-02-14 19:50:40 +0000857 Module *M = CloneModule(*BD.getProgram(), VMap).release();
Keno Fischer34ca8312015-11-06 00:12:50 +0000858
859 // This is a little wasteful. In the future it might be good if we could have
860 // these dropped during cloning.
861 for (auto &NamedMD : BD.getProgram()->named_metadata()) {
862 // Drop the old one and create a new one
863 M->eraseNamedMetadata(M->getNamedMetadata(NamedMD.getName()));
864 NamedMDNode *NewNamedMDNode =
865 M->getOrInsertNamedMetadata(NamedMD.getName());
866 for (MDNode *op : NamedMD.operands())
867 if (OldMDNodeOps.count(op))
868 NewNamedMDNode->addOperand(cast<MDNode>(MapMetadata(op, VMap)));
869 }
870
871 // Verify that this is still valid.
872 legacy::PassManager Passes;
Adrian Prantl919bdf12016-10-18 16:24:43 +0000873 Passes.add(createVerifierPass(/*FatalErrors=*/false));
Keno Fischer34ca8312015-11-06 00:12:50 +0000874 Passes.run(*M);
875
876 // Try running on the hacked up program...
877 if (TestFn(BD, M)) {
878 // Make sure to use instruction pointers that point into the now-current
879 // module, and that they don't include any deleted blocks.
880 NamedMDOps.clear();
881 for (const MDNode *Node : OldMDNodeOps)
Duncan P. N. Exon Smithda4a56d2016-04-02 17:04:38 +0000882 NamedMDOps.push_back(cast<MDNode>(*VMap.getMappedMD(Node)));
Keno Fischer34ca8312015-11-06 00:12:50 +0000883
884 BD.setNewProgram(M); // It crashed, keep the trimmed version...
885 return true;
886 }
887 delete M; // It didn't crash, try something else.
888 return false;
889}
890
Vedant Kumar66e85e62018-02-08 20:27:09 +0000891/// Attempt to eliminate as many global initializers as possible.
Vedant Kumar08d829d2018-02-08 18:46:49 +0000892static Error ReduceGlobalInitializers(BugDriver &BD, BugTester TestFn) {
Vedant Kumar66e85e62018-02-08 20:27:09 +0000893 Module *OrigM = BD.getProgram();
894 if (OrigM->global_empty())
895 return Error::success();
Misha Brukman650ba8e2005-04-22 00:00:37 +0000896
Vedant Kumar66e85e62018-02-08 20:27:09 +0000897 // Now try to reduce the number of global variable initializers in the
898 // module to something small.
Rafael Espindola71867532018-02-14 19:50:40 +0000899 std::unique_ptr<Module> M = CloneModule(*OrigM);
Vedant Kumar66e85e62018-02-08 20:27:09 +0000900 bool DeletedInit = false;
Bill Wendling3f833432006-10-25 18:36:14 +0000901
Vedant Kumar66e85e62018-02-08 20:27:09 +0000902 for (GlobalVariable &GV : M->globals()) {
903 if (GV.hasInitializer()) {
904 DeleteGlobalInitializer(&GV);
905 GV.setLinkage(GlobalValue::ExternalLinkage);
906 GV.setComdat(nullptr);
907 DeletedInit = true;
Chris Lattner65e5f652003-04-25 00:53:05 +0000908 }
909 }
Vedant Kumar66e85e62018-02-08 20:27:09 +0000910
911 if (!DeletedInit)
912 return Error::success();
913
914 // See if the program still causes a crash...
915 outs() << "\nChecking to see if we can delete global inits: ";
916
917 if (TestFn(BD, M.get())) { // Still crashes?
918 BD.setNewProgram(M.release());
919 outs() << "\n*** Able to remove all global initializers!\n";
920 return Error::success();
921 }
922
923 // No longer crashes.
924 outs() << " - Removing all global inits hides problem!\n";
925
926 std::vector<GlobalVariable *> GVs;
927 for (GlobalVariable &GV : OrigM->globals())
928 if (GV.hasInitializer())
929 GVs.push_back(&GV);
930
931 if (GVs.size() > 1 && !BugpointIsInterrupted) {
932 outs() << "\n*** Attempting to reduce the number of global initializers "
933 << "in the testcase\n";
934
935 unsigned OldSize = GVs.size();
936 Expected<bool> Result =
937 ReduceCrashingGlobalInitializers(BD, TestFn).reduceList(GVs);
938 if (Error E = Result.takeError())
939 return E;
940
941 if (GVs.size() < OldSize)
942 BD.EmitProgressBitcode(BD.getProgram(), "reduced-global-variables");
943 }
Justin Bogner1c039152016-09-06 17:18:22 +0000944 return Error::success();
Philip Reames1c232f92016-06-29 00:43:18 +0000945}
946
Vedant Kumar08d829d2018-02-08 18:46:49 +0000947static Error ReduceInsts(BugDriver &BD, BugTester TestFn) {
Philip Reames1c232f92016-06-29 00:43:18 +0000948 // Attempt to delete instructions using bisection. This should help out nasty
949 // cases with large basic blocks where the problem is at one end.
950 if (!BugpointIsInterrupted) {
Justin Bogner8d0a0812016-09-02 01:21:37 +0000951 std::vector<const Instruction *> Insts;
Philip Reames1c232f92016-06-29 00:43:18 +0000952 for (const Function &F : *BD.getProgram())
953 for (const BasicBlock &BB : F)
954 for (const Instruction &I : BB)
955 if (!isa<TerminatorInst>(&I))
956 Insts.push_back(&I);
957
Justin Bogner1c039152016-09-06 17:18:22 +0000958 Expected<bool> Result =
959 ReduceCrashingInstructions(BD, TestFn).reduceList(Insts);
960 if (Error E = Result.takeError())
961 return E;
Philip Reames1c232f92016-06-29 00:43:18 +0000962 }
963
964 unsigned Simplification = 2;
965 do {
966 if (BugpointIsInterrupted)
Justin Bogner1c039152016-09-06 17:18:22 +0000967 // TODO: Should we distinguish this with an "interrupted error"?
968 return Error::success();
Philip Reames1c232f92016-06-29 00:43:18 +0000969 --Simplification;
970 outs() << "\n*** Attempting to reduce testcase by deleting instruc"
971 << "tions: Simplification Level #" << Simplification << '\n';
972
973 // Now that we have deleted the functions that are unnecessary for the
974 // program, try to remove instructions that are not necessary to cause the
975 // crash. To do this, we loop through all of the instructions in the
976 // remaining functions, deleting them (replacing any values produced with
977 // nulls), and then running ADCE and SimplifyCFG. If the transformed input
978 // still triggers failure, keep deleting until we cannot trigger failure
979 // anymore.
980 //
981 unsigned InstructionsToSkipBeforeDeleting = 0;
982 TryAgain:
983
984 // Loop over all of the (non-terminator) instructions remaining in the
985 // function, attempting to delete them.
986 unsigned CurInstructionNum = 0;
987 for (Module::const_iterator FI = BD.getProgram()->begin(),
Justin Bogner8d0a0812016-09-02 01:21:37 +0000988 E = BD.getProgram()->end();
989 FI != E; ++FI)
Philip Reames1c232f92016-06-29 00:43:18 +0000990 if (!FI->isDeclaration())
991 for (Function::const_iterator BI = FI->begin(), E = FI->end(); BI != E;
992 ++BI)
993 for (BasicBlock::const_iterator I = BI->begin(), E = --BI->end();
994 I != E; ++I, ++CurInstructionNum) {
995 if (InstructionsToSkipBeforeDeleting) {
996 --InstructionsToSkipBeforeDeleting;
997 } else {
998 if (BugpointIsInterrupted)
Justin Bogner1c039152016-09-06 17:18:22 +0000999 // TODO: Should this be some kind of interrupted error?
1000 return Error::success();
Philip Reames1c232f92016-06-29 00:43:18 +00001001
Arnold Schwaighofera8f5a822017-03-07 20:28:59 +00001002 if (I->isEHPad() || I->getType()->isTokenTy() ||
1003 I->isSwiftError())
Philip Reames1c232f92016-06-29 00:43:18 +00001004 continue;
1005
1006 outs() << "Checking instruction: " << *I;
1007 std::unique_ptr<Module> M =
1008 BD.deleteInstructionFromProgram(&*I, Simplification);
1009
1010 // Find out if the pass still crashes on this pass...
1011 if (TestFn(BD, M.get())) {
1012 // Yup, it does, we delete the old module, and continue trying
1013 // to reduce the testcase...
1014 BD.setNewProgram(M.release());
1015 InstructionsToSkipBeforeDeleting = CurInstructionNum;
Justin Bogner8d0a0812016-09-02 01:21:37 +00001016 goto TryAgain; // I wish I had a multi-level break here!
Philip Reames1c232f92016-06-29 00:43:18 +00001017 }
1018 }
1019 }
1020
1021 if (InstructionsToSkipBeforeDeleting) {
1022 InstructionsToSkipBeforeDeleting = 0;
1023 goto TryAgain;
1024 }
1025
1026 } while (Simplification);
1027 BD.EmitProgressBitcode(BD.getProgram(), "reduced-instructions");
Justin Bogner1c039152016-09-06 17:18:22 +00001028 return Error::success();
Philip Reames1c232f92016-06-29 00:43:18 +00001029}
1030
Philip Reames1c232f92016-06-29 00:43:18 +00001031/// DebugACrash - Given a predicate that determines whether a component crashes
1032/// on a program, try to destructively reduce the program while still keeping
1033/// the predicate true.
Vedant Kumar08d829d2018-02-08 18:46:49 +00001034static Error DebugACrash(BugDriver &BD, BugTester TestFn) {
Philip Reames1c232f92016-06-29 00:43:18 +00001035 // See if we can get away with nuking some of the global variable initializers
1036 // in the program...
1037 if (!NoGlobalRM)
Justin Bogner1c039152016-09-06 17:18:22 +00001038 if (Error E = ReduceGlobalInitializers(BD, TestFn))
1039 return E;
Misha Brukman650ba8e2005-04-22 00:00:37 +00001040
Chris Lattner1d080f22003-04-24 22:24:58 +00001041 // Now try to reduce the number of functions in the module to something small.
Justin Bogner8d0a0812016-09-02 01:21:37 +00001042 std::vector<Function *> Functions;
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +00001043 for (Function &F : *BD.getProgram())
1044 if (!F.isDeclaration())
1045 Functions.push_back(&F);
Chris Lattner73a6bdd2002-11-20 22:28:10 +00001046
Chris Lattnerbeb01fa2005-08-02 02:16:17 +00001047 if (Functions.size() > 1 && !BugpointIsInterrupted) {
Dan Gohmanee051522009-07-16 15:30:09 +00001048 outs() << "\n*** Attempting to reduce the number of functions "
Justin Bogner8d0a0812016-09-02 01:21:37 +00001049 "in the testcase\n";
Chris Lattner73a6bdd2002-11-20 22:28:10 +00001050
Chris Lattner8bda4c42004-02-18 23:26:28 +00001051 unsigned OldSize = Functions.size();
Justin Bogner1c039152016-09-06 17:18:22 +00001052 Expected<bool> Result =
1053 ReduceCrashingFunctions(BD, TestFn).reduceList(Functions);
1054 if (Error E = Result.takeError())
1055 return E;
Chris Lattner73a6bdd2002-11-20 22:28:10 +00001056
Chris Lattnerbeb01fa2005-08-02 02:16:17 +00001057 if (Functions.size() < OldSize)
Rafael Espindola594994a2010-07-28 18:12:30 +00001058 BD.EmitProgressBitcode(BD.getProgram(), "reduced-function");
Chris Lattner73a6bdd2002-11-20 22:28:10 +00001059 }
1060
Daniel Berlin271ca402016-07-27 16:13:25 +00001061 // Attempt to change conditional branches into unconditional branches to
1062 // eliminate blocks.
1063 if (!DisableSimplifyCFG && !BugpointIsInterrupted) {
Justin Bogner8d0a0812016-09-02 01:21:37 +00001064 std::vector<const BasicBlock *> Blocks;
Daniel Berlin271ca402016-07-27 16:13:25 +00001065 for (Function &F : *BD.getProgram())
1066 for (BasicBlock &BB : F)
1067 Blocks.push_back(&BB);
1068 unsigned OldSize = Blocks.size();
Justin Bogner1c039152016-09-06 17:18:22 +00001069 Expected<bool> Result =
1070 ReduceCrashingConditionals(BD, TestFn, true).reduceList(Blocks);
1071 if (Error E = Result.takeError())
1072 return E;
1073 Result = ReduceCrashingConditionals(BD, TestFn, false).reduceList(Blocks);
1074 if (Error E = Result.takeError())
1075 return E;
Daniel Berlin271ca402016-07-27 16:13:25 +00001076 if (Blocks.size() < OldSize)
1077 BD.EmitProgressBitcode(BD.getProgram(), "reduced-conditionals");
1078 }
1079
Chris Lattnerf32939b2003-04-24 23:51:38 +00001080 // Attempt to delete entire basic blocks at a time to speed up
1081 // convergence... this actually works by setting the terminator of the blocks
1082 // to a return instruction then running simplifycfg, which can potentially
1083 // shrinks the code dramatically quickly
1084 //
Chris Lattnerbeb01fa2005-08-02 02:16:17 +00001085 if (!DisableSimplifyCFG && !BugpointIsInterrupted) {
Justin Bogner8d0a0812016-09-02 01:21:37 +00001086 std::vector<const BasicBlock *> Blocks;
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +00001087 for (Function &F : *BD.getProgram())
1088 for (BasicBlock &BB : F)
1089 Blocks.push_back(&BB);
Torok Edwin6ee6f732009-05-24 09:40:47 +00001090 unsigned OldSize = Blocks.size();
Justin Bogner1c039152016-09-06 17:18:22 +00001091 Expected<bool> Result = ReduceCrashingBlocks(BD, TestFn).reduceList(Blocks);
1092 if (Error E = Result.takeError())
1093 return E;
Torok Edwin6ee6f732009-05-24 09:40:47 +00001094 if (Blocks.size() < OldSize)
Rafael Espindola594994a2010-07-28 18:12:30 +00001095 BD.EmitProgressBitcode(BD.getProgram(), "reduced-blocks");
Chris Lattnerd1e2aae2003-08-05 15:51:05 +00001096 }
Chris Lattnerd4e04742002-12-23 23:49:59 +00001097
Simon Pilgrim0c559f62017-04-14 15:21:15 +00001098 if (!DisableSimplifyCFG && !BugpointIsInterrupted) {
Justin Bogner8d0a0812016-09-02 01:21:37 +00001099 std::vector<const BasicBlock *> Blocks;
Daniel Berlin60606262016-07-28 22:29:25 +00001100 for (Function &F : *BD.getProgram())
1101 for (BasicBlock &BB : F)
1102 Blocks.push_back(&BB);
1103 unsigned OldSize = Blocks.size();
Justin Bogner1c039152016-09-06 17:18:22 +00001104 Expected<bool> Result = ReduceSimplifyCFG(BD, TestFn).reduceList(Blocks);
1105 if (Error E = Result.takeError())
1106 return E;
Daniel Berlin60606262016-07-28 22:29:25 +00001107 if (Blocks.size() < OldSize)
1108 BD.EmitProgressBitcode(BD.getProgram(), "reduced-simplifycfg");
1109 }
Justin Bogner8d0a0812016-09-02 01:21:37 +00001110
Nick Lewycky6e090c92009-05-25 05:30:00 +00001111 // Attempt to delete instructions using bisection. This should help out nasty
1112 // cases with large basic blocks where the problem is at one end.
Philip Reames1c232f92016-06-29 00:43:18 +00001113 if (!BugpointIsInterrupted)
Justin Bogner1c039152016-09-06 17:18:22 +00001114 if (Error E = ReduceInsts(BD, TestFn))
1115 return E;
Keno Fischer34ca8312015-11-06 00:12:50 +00001116
Michael Ilsemane5428042016-10-25 18:44:13 +00001117 // Attempt to strip debug info metadata.
1118 auto stripMetadata = [&](std::function<bool(Module &)> strip) {
Rafael Espindola71867532018-02-14 19:50:40 +00001119 std::unique_ptr<Module> M = CloneModule(*BD.getProgram());
Michael Ilsemane5428042016-10-25 18:44:13 +00001120 strip(*M);
1121 if (TestFn(BD, M.get()))
1122 BD.setNewProgram(M.release());
1123 };
1124 if (!NoStripDebugInfo && !BugpointIsInterrupted) {
1125 outs() << "\n*** Attempting to strip the debug info: ";
1126 stripMetadata(StripDebugInfo);
1127 }
1128 if (!NoStripDebugTypeInfo && !BugpointIsInterrupted) {
1129 outs() << "\n*** Attempting to strip the debug type info: ";
1130 stripMetadata(stripNonLineTableDebugInfo);
1131 }
1132
Keno Fischer34ca8312015-11-06 00:12:50 +00001133 if (!NoNamedMDRM) {
Keno Fischer34ca8312015-11-06 00:12:50 +00001134 if (!BugpointIsInterrupted) {
1135 // Try to reduce the amount of global metadata (particularly debug info),
1136 // by dropping global named metadata that anchors them
1137 outs() << "\n*** Attempting to remove named metadata: ";
1138 std::vector<std::string> NamedMDNames;
1139 for (auto &NamedMD : BD.getProgram()->named_metadata())
1140 NamedMDNames.push_back(NamedMD.getName().str());
Justin Bogner1c039152016-09-06 17:18:22 +00001141 Expected<bool> Result =
1142 ReduceCrashingNamedMD(BD, TestFn).reduceList(NamedMDNames);
1143 if (Error E = Result.takeError())
1144 return E;
Keno Fischer34ca8312015-11-06 00:12:50 +00001145 }
1146
1147 if (!BugpointIsInterrupted) {
1148 // Now that we quickly dropped all the named metadata that doesn't
1149 // contribute to the crash, bisect the operands of the remaining ones
1150 std::vector<const MDNode *> NamedMDOps;
1151 for (auto &NamedMD : BD.getProgram()->named_metadata())
Keno Fischer256df862015-11-06 00:45:47 +00001152 for (auto op : NamedMD.operands())
1153 NamedMDOps.push_back(op);
Justin Bogner1c039152016-09-06 17:18:22 +00001154 Expected<bool> Result =
1155 ReduceCrashingNamedMDOps(BD, TestFn).reduceList(NamedMDOps);
1156 if (Error E = Result.takeError())
1157 return E;
Keno Fischer34ca8312015-11-06 00:12:50 +00001158 }
Philip Reamesac285cc2016-06-29 00:10:39 +00001159 BD.EmitProgressBitcode(BD.getProgram(), "reduced-named-md");
Keno Fischer34ca8312015-11-06 00:12:50 +00001160 }
1161
Chris Lattner514c02e2003-02-28 16:13:20 +00001162 // Try to clean up the testcase by running funcresolve and globaldce...
Chris Lattnerbeb01fa2005-08-02 02:16:17 +00001163 if (!BugpointIsInterrupted) {
Dan Gohmanee051522009-07-16 15:30:09 +00001164 outs() << "\n*** Attempting to perform final cleanups: ";
Rafael Espindola71867532018-02-14 19:50:40 +00001165 std::unique_ptr<Module> M = CloneModule(*BD.getProgram());
Vedant Kumare84e7672018-02-09 05:09:50 +00001166 M = BD.performFinalCleanups(M.release(), true);
Misha Brukman650ba8e2005-04-22 00:00:37 +00001167
Chris Lattnerbeb01fa2005-08-02 02:16:17 +00001168 // Find out if the pass still crashes on the cleaned up program...
Vedant Kumare84e7672018-02-09 05:09:50 +00001169 if (M && TestFn(BD, M.get()))
1170 BD.setNewProgram(M.release()); // Yup, it does, keep the reduced version...
Chris Lattner514c02e2003-02-28 16:13:20 +00001171 }
1172
Rafael Espindola594994a2010-07-28 18:12:30 +00001173 BD.EmitProgressBitcode(BD.getProgram(), "reduced-simplified");
Chris Lattner514c02e2003-02-28 16:13:20 +00001174
Justin Bogner1c039152016-09-06 17:18:22 +00001175 return Error::success();
Chris Lattner73a6bdd2002-11-20 22:28:10 +00001176}
Brian Gaeke960707c2003-11-11 22:41:34 +00001177
Rafael Espindolad1c7ef42010-08-05 03:00:22 +00001178static bool TestForOptimizerCrash(const BugDriver &BD, Module *M) {
Philip Reamese5b56022016-06-29 03:01:13 +00001179 return BD.runPasses(M, BD.getPassesToRun());
Chris Lattner8bda4c42004-02-18 23:26:28 +00001180}
Chris Lattneread1dff2004-02-18 21:02:04 +00001181
Chris Lattner8bda4c42004-02-18 23:26:28 +00001182/// debugOptimizerCrash - This method is called when some pass crashes on input.
1183/// It attempts to prune down the testcase to something reasonable, and figure
1184/// out exactly which pass is crashing.
1185///
Justin Bogner1c039152016-09-06 17:18:22 +00001186Error BugDriver::debugOptimizerCrash(const std::string &ID) {
Dan Gohmanee051522009-07-16 15:30:09 +00001187 outs() << "\n*** Debugging optimizer crash!\n";
Chris Lattner8bda4c42004-02-18 23:26:28 +00001188
1189 // Reduce the list of passes which causes the optimizer to crash...
Justin Bogner1c039152016-09-06 17:18:22 +00001190 if (!BugpointIsInterrupted && !DontReducePassList) {
1191 Expected<bool> Result = ReducePassList(*this).reduceList(PassesToRun);
1192 if (Error E = Result.takeError())
1193 return E;
1194 }
Chris Lattner8bda4c42004-02-18 23:26:28 +00001195
Dan Gohmanee051522009-07-16 15:30:09 +00001196 outs() << "\n*** Found crashing pass"
1197 << (PassesToRun.size() == 1 ? ": " : "es: ")
1198 << getPassesString(PassesToRun) << '\n';
Chris Lattner8bda4c42004-02-18 23:26:28 +00001199
Rafael Espindola594994a2010-07-28 18:12:30 +00001200 EmitProgressBitcode(Program, ID);
Chris Lattner8bda4c42004-02-18 23:26:28 +00001201
Justin Bogner1c039152016-09-06 17:18:22 +00001202 return DebugACrash(*this, TestForOptimizerCrash);
Chris Lattner8bda4c42004-02-18 23:26:28 +00001203}
1204
Rafael Espindolad1c7ef42010-08-05 03:00:22 +00001205static bool TestForCodeGenCrash(const BugDriver &BD, Module *M) {
Justin Bogner1c039152016-09-06 17:18:22 +00001206 if (Error E = BD.compileProgram(M)) {
Sebastian Pop8f7d0192016-07-15 23:15:06 +00001207 if (VerboseErrors)
Justin Bogner1c039152016-09-06 17:18:22 +00001208 errs() << toString(std::move(E)) << "\n";
1209 else {
1210 consumeError(std::move(E));
Sebastian Pop8f7d0192016-07-15 23:15:06 +00001211 errs() << "<crash>\n";
Justin Bogner1c039152016-09-06 17:18:22 +00001212 }
Justin Bogner8d0a0812016-09-02 01:21:37 +00001213 return true; // Tool is still crashing.
Chris Lattner8bda4c42004-02-18 23:26:28 +00001214 }
Nick Lewycky6ba630b2010-04-12 05:08:25 +00001215 errs() << '\n';
1216 return false;
Chris Lattner8bda4c42004-02-18 23:26:28 +00001217}
Chris Lattneread1dff2004-02-18 21:02:04 +00001218
1219/// debugCodeGeneratorCrash - This method is called when the code generator
1220/// crashes on an input. It attempts to reduce the input as much as possible
1221/// while still causing the code generator to crash.
Justin Bogner1c039152016-09-06 17:18:22 +00001222Error BugDriver::debugCodeGeneratorCrash() {
Dan Gohmand8db3762009-07-15 16:35:29 +00001223 errs() << "*** Debugging code generator crash!\n";
Chris Lattneread1dff2004-02-18 21:02:04 +00001224
Justin Bogner1c039152016-09-06 17:18:22 +00001225 return DebugACrash(*this, TestForCodeGenCrash);
Chris Lattneread1dff2004-02-18 21:02:04 +00001226}