blob: bd542aa0ca7e4496e53a623a458819d1b12a625f [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 Espindola71867532018-02-14 19:50:40 +0000703 Module *M = CloneModule(*BD.getProgram(), VMap).release();
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...
737 if (TestFn(BD, M)) {
Justin Bogner8d0a0812016-09-02 01:21:37 +0000738 BD.setNewProgram(M); // 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 }
Justin Bogner8d0a0812016-09-02 01:21:37 +0000747 delete M; // 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 Espindola71867532018-02-14 19:50:40 +0000778 Module *M = CloneModule(*BD.getProgram(), VMap).release();
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...
812 if (TestFn(BD, M)) {
813 BD.setNewProgram(M); // It crashed, keep the trimmed version...
814 return true;
815 }
816 delete M; // It didn't crash, try something else.
817 return false;
818}
819
820namespace {
821// Reduce the list of operands to named metadata nodes
822class ReduceCrashingNamedMDOps : public ListReducer<const MDNode *> {
823 BugDriver &BD;
Vedant Kumar08d829d2018-02-08 18:46:49 +0000824 BugTester TestFn;
Keno Fischer34ca8312015-11-06 00:12:50 +0000825
826public:
Vedant Kumar08d829d2018-02-08 18:46:49 +0000827 ReduceCrashingNamedMDOps(BugDriver &bd, BugTester testFn)
Keno Fischer34ca8312015-11-06 00:12:50 +0000828 : BD(bd), TestFn(testFn) {}
829
Justin Bogner1c039152016-09-06 17:18:22 +0000830 Expected<TestResult> doTest(std::vector<const MDNode *> &Prefix,
831 std::vector<const MDNode *> &Kept) override {
Keno Fischer34ca8312015-11-06 00:12:50 +0000832 if (!Kept.empty() && TestNamedMDOps(Kept))
833 return KeepSuffix;
834 if (!Prefix.empty() && TestNamedMDOps(Prefix))
835 return KeepPrefix;
836 return NoFailure;
837 }
838
839 bool TestNamedMDOps(std::vector<const MDNode *> &NamedMDOps);
840};
841}
842
843bool ReduceCrashingNamedMDOps::TestNamedMDOps(
844 std::vector<const MDNode *> &NamedMDOps) {
845 // Convert list to set for fast lookup...
Matthias Braunb30f2f512016-01-30 01:24:31 +0000846 SmallPtrSet<const MDNode *, 32> OldMDNodeOps;
Keno Fischer34ca8312015-11-06 00:12:50 +0000847 for (unsigned i = 0, e = NamedMDOps.size(); i != e; ++i) {
848 OldMDNodeOps.insert(NamedMDOps[i]);
849 }
850
851 outs() << "Checking for crash with only " << OldMDNodeOps.size();
852 if (OldMDNodeOps.size() == 1)
853 outs() << " named metadata operand: ";
854 else
855 outs() << " named metadata operands: ";
856
857 ValueToValueMapTy VMap;
Rafael Espindola71867532018-02-14 19:50:40 +0000858 Module *M = CloneModule(*BD.getProgram(), VMap).release();
Keno Fischer34ca8312015-11-06 00:12:50 +0000859
860 // This is a little wasteful. In the future it might be good if we could have
861 // these dropped during cloning.
862 for (auto &NamedMD : BD.getProgram()->named_metadata()) {
863 // Drop the old one and create a new one
864 M->eraseNamedMetadata(M->getNamedMetadata(NamedMD.getName()));
865 NamedMDNode *NewNamedMDNode =
866 M->getOrInsertNamedMetadata(NamedMD.getName());
867 for (MDNode *op : NamedMD.operands())
868 if (OldMDNodeOps.count(op))
869 NewNamedMDNode->addOperand(cast<MDNode>(MapMetadata(op, VMap)));
870 }
871
872 // Verify that this is still valid.
873 legacy::PassManager Passes;
Adrian Prantl919bdf12016-10-18 16:24:43 +0000874 Passes.add(createVerifierPass(/*FatalErrors=*/false));
Keno Fischer34ca8312015-11-06 00:12:50 +0000875 Passes.run(*M);
876
877 // Try running on the hacked up program...
878 if (TestFn(BD, M)) {
879 // Make sure to use instruction pointers that point into the now-current
880 // module, and that they don't include any deleted blocks.
881 NamedMDOps.clear();
882 for (const MDNode *Node : OldMDNodeOps)
Duncan P. N. Exon Smithda4a56d2016-04-02 17:04:38 +0000883 NamedMDOps.push_back(cast<MDNode>(*VMap.getMappedMD(Node)));
Keno Fischer34ca8312015-11-06 00:12:50 +0000884
885 BD.setNewProgram(M); // It crashed, keep the trimmed version...
886 return true;
887 }
888 delete M; // It didn't crash, try something else.
889 return false;
890}
891
Vedant Kumar66e85e62018-02-08 20:27:09 +0000892/// Attempt to eliminate as many global initializers as possible.
Vedant Kumar08d829d2018-02-08 18:46:49 +0000893static Error ReduceGlobalInitializers(BugDriver &BD, BugTester TestFn) {
Vedant Kumar66e85e62018-02-08 20:27:09 +0000894 Module *OrigM = BD.getProgram();
895 if (OrigM->global_empty())
896 return Error::success();
Misha Brukman650ba8e2005-04-22 00:00:37 +0000897
Vedant Kumar66e85e62018-02-08 20:27:09 +0000898 // Now try to reduce the number of global variable initializers in the
899 // module to something small.
Rafael Espindola71867532018-02-14 19:50:40 +0000900 std::unique_ptr<Module> M = CloneModule(*OrigM);
Vedant Kumar66e85e62018-02-08 20:27:09 +0000901 bool DeletedInit = false;
Bill Wendling3f833432006-10-25 18:36:14 +0000902
Vedant Kumar66e85e62018-02-08 20:27:09 +0000903 for (GlobalVariable &GV : M->globals()) {
904 if (GV.hasInitializer()) {
905 DeleteGlobalInitializer(&GV);
906 GV.setLinkage(GlobalValue::ExternalLinkage);
907 GV.setComdat(nullptr);
908 DeletedInit = true;
Chris Lattner65e5f652003-04-25 00:53:05 +0000909 }
910 }
Vedant Kumar66e85e62018-02-08 20:27:09 +0000911
912 if (!DeletedInit)
913 return Error::success();
914
915 // See if the program still causes a crash...
916 outs() << "\nChecking to see if we can delete global inits: ";
917
918 if (TestFn(BD, M.get())) { // Still crashes?
919 BD.setNewProgram(M.release());
920 outs() << "\n*** Able to remove all global initializers!\n";
921 return Error::success();
922 }
923
924 // No longer crashes.
925 outs() << " - Removing all global inits hides problem!\n";
926
927 std::vector<GlobalVariable *> GVs;
928 for (GlobalVariable &GV : OrigM->globals())
929 if (GV.hasInitializer())
930 GVs.push_back(&GV);
931
932 if (GVs.size() > 1 && !BugpointIsInterrupted) {
933 outs() << "\n*** Attempting to reduce the number of global initializers "
934 << "in the testcase\n";
935
936 unsigned OldSize = GVs.size();
937 Expected<bool> Result =
938 ReduceCrashingGlobalInitializers(BD, TestFn).reduceList(GVs);
939 if (Error E = Result.takeError())
940 return E;
941
942 if (GVs.size() < OldSize)
943 BD.EmitProgressBitcode(BD.getProgram(), "reduced-global-variables");
944 }
Justin Bogner1c039152016-09-06 17:18:22 +0000945 return Error::success();
Philip Reames1c232f92016-06-29 00:43:18 +0000946}
947
Vedant Kumar08d829d2018-02-08 18:46:49 +0000948static Error ReduceInsts(BugDriver &BD, BugTester TestFn) {
Philip Reames1c232f92016-06-29 00:43:18 +0000949 // Attempt to delete instructions using bisection. This should help out nasty
950 // cases with large basic blocks where the problem is at one end.
951 if (!BugpointIsInterrupted) {
Justin Bogner8d0a0812016-09-02 01:21:37 +0000952 std::vector<const Instruction *> Insts;
Philip Reames1c232f92016-06-29 00:43:18 +0000953 for (const Function &F : *BD.getProgram())
954 for (const BasicBlock &BB : F)
955 for (const Instruction &I : BB)
956 if (!isa<TerminatorInst>(&I))
957 Insts.push_back(&I);
958
Justin Bogner1c039152016-09-06 17:18:22 +0000959 Expected<bool> Result =
960 ReduceCrashingInstructions(BD, TestFn).reduceList(Insts);
961 if (Error E = Result.takeError())
962 return E;
Philip Reames1c232f92016-06-29 00:43:18 +0000963 }
964
965 unsigned Simplification = 2;
966 do {
967 if (BugpointIsInterrupted)
Justin Bogner1c039152016-09-06 17:18:22 +0000968 // TODO: Should we distinguish this with an "interrupted error"?
969 return Error::success();
Philip Reames1c232f92016-06-29 00:43:18 +0000970 --Simplification;
971 outs() << "\n*** Attempting to reduce testcase by deleting instruc"
972 << "tions: Simplification Level #" << Simplification << '\n';
973
974 // Now that we have deleted the functions that are unnecessary for the
975 // program, try to remove instructions that are not necessary to cause the
976 // crash. To do this, we loop through all of the instructions in the
977 // remaining functions, deleting them (replacing any values produced with
978 // nulls), and then running ADCE and SimplifyCFG. If the transformed input
979 // still triggers failure, keep deleting until we cannot trigger failure
980 // anymore.
981 //
982 unsigned InstructionsToSkipBeforeDeleting = 0;
983 TryAgain:
984
985 // Loop over all of the (non-terminator) instructions remaining in the
986 // function, attempting to delete them.
987 unsigned CurInstructionNum = 0;
988 for (Module::const_iterator FI = BD.getProgram()->begin(),
Justin Bogner8d0a0812016-09-02 01:21:37 +0000989 E = BD.getProgram()->end();
990 FI != E; ++FI)
Philip Reames1c232f92016-06-29 00:43:18 +0000991 if (!FI->isDeclaration())
992 for (Function::const_iterator BI = FI->begin(), E = FI->end(); BI != E;
993 ++BI)
994 for (BasicBlock::const_iterator I = BI->begin(), E = --BI->end();
995 I != E; ++I, ++CurInstructionNum) {
996 if (InstructionsToSkipBeforeDeleting) {
997 --InstructionsToSkipBeforeDeleting;
998 } else {
999 if (BugpointIsInterrupted)
Justin Bogner1c039152016-09-06 17:18:22 +00001000 // TODO: Should this be some kind of interrupted error?
1001 return Error::success();
Philip Reames1c232f92016-06-29 00:43:18 +00001002
Arnold Schwaighofera8f5a822017-03-07 20:28:59 +00001003 if (I->isEHPad() || I->getType()->isTokenTy() ||
1004 I->isSwiftError())
Philip Reames1c232f92016-06-29 00:43:18 +00001005 continue;
1006
1007 outs() << "Checking instruction: " << *I;
1008 std::unique_ptr<Module> M =
1009 BD.deleteInstructionFromProgram(&*I, Simplification);
1010
1011 // Find out if the pass still crashes on this pass...
1012 if (TestFn(BD, M.get())) {
1013 // Yup, it does, we delete the old module, and continue trying
1014 // to reduce the testcase...
1015 BD.setNewProgram(M.release());
1016 InstructionsToSkipBeforeDeleting = CurInstructionNum;
Justin Bogner8d0a0812016-09-02 01:21:37 +00001017 goto TryAgain; // I wish I had a multi-level break here!
Philip Reames1c232f92016-06-29 00:43:18 +00001018 }
1019 }
1020 }
1021
1022 if (InstructionsToSkipBeforeDeleting) {
1023 InstructionsToSkipBeforeDeleting = 0;
1024 goto TryAgain;
1025 }
1026
1027 } while (Simplification);
1028 BD.EmitProgressBitcode(BD.getProgram(), "reduced-instructions");
Justin Bogner1c039152016-09-06 17:18:22 +00001029 return Error::success();
Philip Reames1c232f92016-06-29 00:43:18 +00001030}
1031
Philip Reames1c232f92016-06-29 00:43:18 +00001032/// DebugACrash - Given a predicate that determines whether a component crashes
1033/// on a program, try to destructively reduce the program while still keeping
1034/// the predicate true.
Vedant Kumar08d829d2018-02-08 18:46:49 +00001035static Error DebugACrash(BugDriver &BD, BugTester TestFn) {
Philip Reames1c232f92016-06-29 00:43:18 +00001036 // See if we can get away with nuking some of the global variable initializers
1037 // in the program...
1038 if (!NoGlobalRM)
Justin Bogner1c039152016-09-06 17:18:22 +00001039 if (Error E = ReduceGlobalInitializers(BD, TestFn))
1040 return E;
Misha Brukman650ba8e2005-04-22 00:00:37 +00001041
Chris Lattner1d080f22003-04-24 22:24:58 +00001042 // Now try to reduce the number of functions in the module to something small.
Justin Bogner8d0a0812016-09-02 01:21:37 +00001043 std::vector<Function *> Functions;
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +00001044 for (Function &F : *BD.getProgram())
1045 if (!F.isDeclaration())
1046 Functions.push_back(&F);
Chris Lattner73a6bdd2002-11-20 22:28:10 +00001047
Chris Lattnerbeb01fa2005-08-02 02:16:17 +00001048 if (Functions.size() > 1 && !BugpointIsInterrupted) {
Dan Gohmanee051522009-07-16 15:30:09 +00001049 outs() << "\n*** Attempting to reduce the number of functions "
Justin Bogner8d0a0812016-09-02 01:21:37 +00001050 "in the testcase\n";
Chris Lattner73a6bdd2002-11-20 22:28:10 +00001051
Chris Lattner8bda4c42004-02-18 23:26:28 +00001052 unsigned OldSize = Functions.size();
Justin Bogner1c039152016-09-06 17:18:22 +00001053 Expected<bool> Result =
1054 ReduceCrashingFunctions(BD, TestFn).reduceList(Functions);
1055 if (Error E = Result.takeError())
1056 return E;
Chris Lattner73a6bdd2002-11-20 22:28:10 +00001057
Chris Lattnerbeb01fa2005-08-02 02:16:17 +00001058 if (Functions.size() < OldSize)
Rafael Espindola594994a2010-07-28 18:12:30 +00001059 BD.EmitProgressBitcode(BD.getProgram(), "reduced-function");
Chris Lattner73a6bdd2002-11-20 22:28:10 +00001060 }
1061
Daniel Berlin271ca402016-07-27 16:13:25 +00001062 // Attempt to change conditional branches into unconditional branches to
1063 // eliminate blocks.
1064 if (!DisableSimplifyCFG && !BugpointIsInterrupted) {
Justin Bogner8d0a0812016-09-02 01:21:37 +00001065 std::vector<const BasicBlock *> Blocks;
Daniel Berlin271ca402016-07-27 16:13:25 +00001066 for (Function &F : *BD.getProgram())
1067 for (BasicBlock &BB : F)
1068 Blocks.push_back(&BB);
1069 unsigned OldSize = Blocks.size();
Justin Bogner1c039152016-09-06 17:18:22 +00001070 Expected<bool> Result =
1071 ReduceCrashingConditionals(BD, TestFn, true).reduceList(Blocks);
1072 if (Error E = Result.takeError())
1073 return E;
1074 Result = ReduceCrashingConditionals(BD, TestFn, false).reduceList(Blocks);
1075 if (Error E = Result.takeError())
1076 return E;
Daniel Berlin271ca402016-07-27 16:13:25 +00001077 if (Blocks.size() < OldSize)
1078 BD.EmitProgressBitcode(BD.getProgram(), "reduced-conditionals");
1079 }
1080
Chris Lattnerf32939b2003-04-24 23:51:38 +00001081 // Attempt to delete entire basic blocks at a time to speed up
1082 // convergence... this actually works by setting the terminator of the blocks
1083 // to a return instruction then running simplifycfg, which can potentially
1084 // shrinks the code dramatically quickly
1085 //
Chris Lattnerbeb01fa2005-08-02 02:16:17 +00001086 if (!DisableSimplifyCFG && !BugpointIsInterrupted) {
Justin Bogner8d0a0812016-09-02 01:21:37 +00001087 std::vector<const BasicBlock *> Blocks;
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +00001088 for (Function &F : *BD.getProgram())
1089 for (BasicBlock &BB : F)
1090 Blocks.push_back(&BB);
Torok Edwin6ee6f732009-05-24 09:40:47 +00001091 unsigned OldSize = Blocks.size();
Justin Bogner1c039152016-09-06 17:18:22 +00001092 Expected<bool> Result = ReduceCrashingBlocks(BD, TestFn).reduceList(Blocks);
1093 if (Error E = Result.takeError())
1094 return E;
Torok Edwin6ee6f732009-05-24 09:40:47 +00001095 if (Blocks.size() < OldSize)
Rafael Espindola594994a2010-07-28 18:12:30 +00001096 BD.EmitProgressBitcode(BD.getProgram(), "reduced-blocks");
Chris Lattnerd1e2aae2003-08-05 15:51:05 +00001097 }
Chris Lattnerd4e04742002-12-23 23:49:59 +00001098
Simon Pilgrim0c559f62017-04-14 15:21:15 +00001099 if (!DisableSimplifyCFG && !BugpointIsInterrupted) {
Justin Bogner8d0a0812016-09-02 01:21:37 +00001100 std::vector<const BasicBlock *> Blocks;
Daniel Berlin60606262016-07-28 22:29:25 +00001101 for (Function &F : *BD.getProgram())
1102 for (BasicBlock &BB : F)
1103 Blocks.push_back(&BB);
1104 unsigned OldSize = Blocks.size();
Justin Bogner1c039152016-09-06 17:18:22 +00001105 Expected<bool> Result = ReduceSimplifyCFG(BD, TestFn).reduceList(Blocks);
1106 if (Error E = Result.takeError())
1107 return E;
Daniel Berlin60606262016-07-28 22:29:25 +00001108 if (Blocks.size() < OldSize)
1109 BD.EmitProgressBitcode(BD.getProgram(), "reduced-simplifycfg");
1110 }
Justin Bogner8d0a0812016-09-02 01:21:37 +00001111
Nick Lewycky6e090c92009-05-25 05:30:00 +00001112 // Attempt to delete instructions using bisection. This should help out nasty
1113 // cases with large basic blocks where the problem is at one end.
Philip Reames1c232f92016-06-29 00:43:18 +00001114 if (!BugpointIsInterrupted)
Justin Bogner1c039152016-09-06 17:18:22 +00001115 if (Error E = ReduceInsts(BD, TestFn))
1116 return E;
Keno Fischer34ca8312015-11-06 00:12:50 +00001117
Michael Ilsemane5428042016-10-25 18:44:13 +00001118 // Attempt to strip debug info metadata.
1119 auto stripMetadata = [&](std::function<bool(Module &)> strip) {
Rafael Espindola71867532018-02-14 19:50:40 +00001120 std::unique_ptr<Module> M = CloneModule(*BD.getProgram());
Michael Ilsemane5428042016-10-25 18:44:13 +00001121 strip(*M);
1122 if (TestFn(BD, M.get()))
1123 BD.setNewProgram(M.release());
1124 };
1125 if (!NoStripDebugInfo && !BugpointIsInterrupted) {
1126 outs() << "\n*** Attempting to strip the debug info: ";
1127 stripMetadata(StripDebugInfo);
1128 }
1129 if (!NoStripDebugTypeInfo && !BugpointIsInterrupted) {
1130 outs() << "\n*** Attempting to strip the debug type info: ";
1131 stripMetadata(stripNonLineTableDebugInfo);
1132 }
1133
Keno Fischer34ca8312015-11-06 00:12:50 +00001134 if (!NoNamedMDRM) {
Keno Fischer34ca8312015-11-06 00:12:50 +00001135 if (!BugpointIsInterrupted) {
1136 // Try to reduce the amount of global metadata (particularly debug info),
1137 // by dropping global named metadata that anchors them
1138 outs() << "\n*** Attempting to remove named metadata: ";
1139 std::vector<std::string> NamedMDNames;
1140 for (auto &NamedMD : BD.getProgram()->named_metadata())
1141 NamedMDNames.push_back(NamedMD.getName().str());
Justin Bogner1c039152016-09-06 17:18:22 +00001142 Expected<bool> Result =
1143 ReduceCrashingNamedMD(BD, TestFn).reduceList(NamedMDNames);
1144 if (Error E = Result.takeError())
1145 return E;
Keno Fischer34ca8312015-11-06 00:12:50 +00001146 }
1147
1148 if (!BugpointIsInterrupted) {
1149 // Now that we quickly dropped all the named metadata that doesn't
1150 // contribute to the crash, bisect the operands of the remaining ones
1151 std::vector<const MDNode *> NamedMDOps;
1152 for (auto &NamedMD : BD.getProgram()->named_metadata())
Keno Fischer256df862015-11-06 00:45:47 +00001153 for (auto op : NamedMD.operands())
1154 NamedMDOps.push_back(op);
Justin Bogner1c039152016-09-06 17:18:22 +00001155 Expected<bool> Result =
1156 ReduceCrashingNamedMDOps(BD, TestFn).reduceList(NamedMDOps);
1157 if (Error E = Result.takeError())
1158 return E;
Keno Fischer34ca8312015-11-06 00:12:50 +00001159 }
Philip Reamesac285cc2016-06-29 00:10:39 +00001160 BD.EmitProgressBitcode(BD.getProgram(), "reduced-named-md");
Keno Fischer34ca8312015-11-06 00:12:50 +00001161 }
1162
Chris Lattner514c02e2003-02-28 16:13:20 +00001163 // Try to clean up the testcase by running funcresolve and globaldce...
Chris Lattnerbeb01fa2005-08-02 02:16:17 +00001164 if (!BugpointIsInterrupted) {
Dan Gohmanee051522009-07-16 15:30:09 +00001165 outs() << "\n*** Attempting to perform final cleanups: ";
Rafael Espindola71867532018-02-14 19:50:40 +00001166 std::unique_ptr<Module> M = CloneModule(*BD.getProgram());
Vedant Kumare84e7672018-02-09 05:09:50 +00001167 M = BD.performFinalCleanups(M.release(), true);
Misha Brukman650ba8e2005-04-22 00:00:37 +00001168
Chris Lattnerbeb01fa2005-08-02 02:16:17 +00001169 // Find out if the pass still crashes on the cleaned up program...
Vedant Kumare84e7672018-02-09 05:09:50 +00001170 if (M && TestFn(BD, M.get()))
1171 BD.setNewProgram(M.release()); // Yup, it does, keep the reduced version...
Chris Lattner514c02e2003-02-28 16:13:20 +00001172 }
1173
Rafael Espindola594994a2010-07-28 18:12:30 +00001174 BD.EmitProgressBitcode(BD.getProgram(), "reduced-simplified");
Chris Lattner514c02e2003-02-28 16:13:20 +00001175
Justin Bogner1c039152016-09-06 17:18:22 +00001176 return Error::success();
Chris Lattner73a6bdd2002-11-20 22:28:10 +00001177}
Brian Gaeke960707c2003-11-11 22:41:34 +00001178
Rafael Espindolad1c7ef42010-08-05 03:00:22 +00001179static bool TestForOptimizerCrash(const BugDriver &BD, Module *M) {
Philip Reamese5b56022016-06-29 03:01:13 +00001180 return BD.runPasses(M, BD.getPassesToRun());
Chris Lattner8bda4c42004-02-18 23:26:28 +00001181}
Chris Lattneread1dff2004-02-18 21:02:04 +00001182
Chris Lattner8bda4c42004-02-18 23:26:28 +00001183/// debugOptimizerCrash - This method is called when some pass crashes on input.
1184/// It attempts to prune down the testcase to something reasonable, and figure
1185/// out exactly which pass is crashing.
1186///
Justin Bogner1c039152016-09-06 17:18:22 +00001187Error BugDriver::debugOptimizerCrash(const std::string &ID) {
Dan Gohmanee051522009-07-16 15:30:09 +00001188 outs() << "\n*** Debugging optimizer crash!\n";
Chris Lattner8bda4c42004-02-18 23:26:28 +00001189
1190 // Reduce the list of passes which causes the optimizer to crash...
Justin Bogner1c039152016-09-06 17:18:22 +00001191 if (!BugpointIsInterrupted && !DontReducePassList) {
1192 Expected<bool> Result = ReducePassList(*this).reduceList(PassesToRun);
1193 if (Error E = Result.takeError())
1194 return E;
1195 }
Chris Lattner8bda4c42004-02-18 23:26:28 +00001196
Dan Gohmanee051522009-07-16 15:30:09 +00001197 outs() << "\n*** Found crashing pass"
1198 << (PassesToRun.size() == 1 ? ": " : "es: ")
1199 << getPassesString(PassesToRun) << '\n';
Chris Lattner8bda4c42004-02-18 23:26:28 +00001200
Rafael Espindola594994a2010-07-28 18:12:30 +00001201 EmitProgressBitcode(Program, ID);
Chris Lattner8bda4c42004-02-18 23:26:28 +00001202
Justin Bogner1c039152016-09-06 17:18:22 +00001203 return DebugACrash(*this, TestForOptimizerCrash);
Chris Lattner8bda4c42004-02-18 23:26:28 +00001204}
1205
Rafael Espindolad1c7ef42010-08-05 03:00:22 +00001206static bool TestForCodeGenCrash(const BugDriver &BD, Module *M) {
Justin Bogner1c039152016-09-06 17:18:22 +00001207 if (Error E = BD.compileProgram(M)) {
Sebastian Pop8f7d0192016-07-15 23:15:06 +00001208 if (VerboseErrors)
Justin Bogner1c039152016-09-06 17:18:22 +00001209 errs() << toString(std::move(E)) << "\n";
1210 else {
1211 consumeError(std::move(E));
Sebastian Pop8f7d0192016-07-15 23:15:06 +00001212 errs() << "<crash>\n";
Justin Bogner1c039152016-09-06 17:18:22 +00001213 }
Justin Bogner8d0a0812016-09-02 01:21:37 +00001214 return true; // Tool is still crashing.
Chris Lattner8bda4c42004-02-18 23:26:28 +00001215 }
Nick Lewycky6ba630b2010-04-12 05:08:25 +00001216 errs() << '\n';
1217 return false;
Chris Lattner8bda4c42004-02-18 23:26:28 +00001218}
Chris Lattneread1dff2004-02-18 21:02:04 +00001219
1220/// debugCodeGeneratorCrash - This method is called when the code generator
1221/// crashes on an input. It attempts to reduce the input as much as possible
1222/// while still causing the code generator to crash.
Justin Bogner1c039152016-09-06 17:18:22 +00001223Error BugDriver::debugCodeGeneratorCrash() {
Dan Gohmand8db3762009-07-15 16:35:29 +00001224 errs() << "*** Debugging code generator crash!\n";
Chris Lattneread1dff2004-02-18 21:02:04 +00001225
Justin Bogner1c039152016-09-06 17:18:22 +00001226 return DebugACrash(*this, TestForCodeGenCrash);
Chris Lattneread1dff2004-02-18 21:02:04 +00001227}