blob: f6b35f5fd5322bded1326b06cc78ab11fbceb301 [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"
Daniel Berlin60606262016-07-28 22:29:25 +000017#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000018#include "llvm/ADT/SmallPtrSet.h"
Keno Fischer34ca8312015-11-06 00:12:50 +000019#include "llvm/ADT/StringSet.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"
22#include "llvm/IR/DerivedTypes.h"
23#include "llvm/IR/Instructions.h"
Chandler Carruth30d69c22015-02-13 10:01:29 +000024#include "llvm/IR/LegacyPassManager.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/Module.h"
26#include "llvm/IR/ValueSymbolTable.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000027#include "llvm/IR/Verifier.h"
Misha Brukman0c2305b2003-08-07 21:19:30 +000028#include "llvm/Pass.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000029#include "llvm/Support/CommandLine.h"
30#include "llvm/Support/FileUtilities.h"
Chris Lattnerf32939b2003-04-24 23:51:38 +000031#include "llvm/Transforms/Scalar.h"
Daniel Berlin271ca402016-07-27 16:13:25 +000032#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattner1d080f22003-04-24 22:24:58 +000033#include "llvm/Transforms/Utils/Cloning.h"
Daniel Berlin271ca402016-07-27 16:13:25 +000034#include "llvm/Transforms/Utils/Local.h"
Chris Lattner1d080f22003-04-24 22:24:58 +000035#include <set>
Chris Lattner2f1aa112004-01-14 03:38:37 +000036using namespace llvm;
Chris Lattner73a6bdd2002-11-20 22:28:10 +000037
Andrew Lenharthef9aa122006-03-05 22:21:36 +000038namespace {
39 cl::opt<bool>
40 KeepMain("keep-main",
41 cl::desc("Force function reduction to keep main"),
42 cl::init(false));
Torok Edwin5bd3f7b2009-05-24 09:31:04 +000043 cl::opt<bool>
44 NoGlobalRM ("disable-global-remove",
45 cl::desc("Do not remove global variables"),
46 cl::init(false));
JF Bastienf87e20d2015-04-20 23:42:22 +000047
48 cl::opt<bool>
49 ReplaceFuncsWithNull("replace-funcs-with-null",
50 cl::desc("When stubbing functions, replace all uses will null"),
51 cl::init(false));
52 cl::opt<bool>
53 DontReducePassList("disable-pass-list-reduction",
54 cl::desc("Skip pass list reduction steps"),
55 cl::init(false));
Keno Fischer34ca8312015-11-06 00:12:50 +000056
57 cl::opt<bool> NoNamedMDRM("disable-namedmd-remove",
58 cl::desc("Do not remove global named metadata"),
59 cl::init(false));
Sebastian Pop8f7d0192016-07-15 23:15:06 +000060 cl::opt<bool> VerboseErrors("verbose-errors",
61 cl::desc("Print the output of crashing program"),
62 cl::init(false));
Andrew Lenharthef9aa122006-03-05 22:21:36 +000063}
64
Brian Gaeke960707c2003-11-11 22:41:34 +000065namespace llvm {
Rafael Espindola33e81a82010-08-08 03:55:08 +000066 class ReducePassList : public ListReducer<std::string> {
Chris Lattner2f1aa112004-01-14 03:38:37 +000067 BugDriver &BD;
68 public:
Chris Lattner327019b2004-02-18 21:24:48 +000069 ReducePassList(BugDriver &bd) : BD(bd) {}
Misha Brukman650ba8e2005-04-22 00:00:37 +000070
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +000071 // doTest - Return true iff running the "removed" passes succeeds, and
Chris Lattner2f1aa112004-01-14 03:38:37 +000072 // running the "Kept" passes fail when run on the output of the "removed"
73 // passes. If we return true, we update the current module of bugpoint.
74 //
Craig Toppere56917c2014-03-08 08:27:28 +000075 TestResult doTest(std::vector<std::string> &Removed,
76 std::vector<std::string> &Kept,
77 std::string &Error) override;
Chris Lattner2f1aa112004-01-14 03:38:37 +000078 };
79}
Chris Lattner1d080f22003-04-24 22:24:58 +000080
Chris Lattner327019b2004-02-18 21:24:48 +000081ReducePassList::TestResult
Rafael Espindola33e81a82010-08-08 03:55:08 +000082ReducePassList::doTest(std::vector<std::string> &Prefix,
83 std::vector<std::string> &Suffix,
Nick Lewycky6ba630b2010-04-12 05:08:25 +000084 std::string &Error) {
Rafael Espindolabb876652013-06-17 19:33:18 +000085 std::string PrefixOutput;
Craig Toppere6cb63e2014-04-25 04:24:47 +000086 Module *OrigProgram = nullptr;
Chris Lattner1d080f22003-04-24 22:24:58 +000087 if (!Prefix.empty()) {
Dan Gohmanee051522009-07-16 15:30:09 +000088 outs() << "Checking to see if these passes crash: "
89 << getPassesString(Prefix) << ": ";
Rafael Espindolabb876652013-06-17 19:33:18 +000090 if (BD.runPasses(BD.getProgram(), Prefix, PrefixOutput))
Chris Lattner1d080f22003-04-24 22:24:58 +000091 return KeepPrefix;
Chris Lattnera9656312003-06-02 04:54:29 +000092
93 OrigProgram = BD.Program;
94
Rafael Espindola28b351a2014-08-26 17:19:03 +000095 BD.Program = parseInputFile(PrefixOutput, BD.getContext()).release();
Craig Toppere6cb63e2014-04-25 04:24:47 +000096 if (BD.Program == nullptr) {
Dan Gohmand8db3762009-07-15 16:35:29 +000097 errs() << BD.getToolName() << ": Error reading bitcode file '"
Rafael Espindolabb876652013-06-17 19:33:18 +000098 << PrefixOutput << "'!\n";
Chris Lattnera9656312003-06-02 04:54:29 +000099 exit(1);
100 }
Rafael Espindolabb876652013-06-17 19:33:18 +0000101 sys::fs::remove(PrefixOutput);
Chris Lattner1d080f22003-04-24 22:24:58 +0000102 }
103
Dan Gohmanee051522009-07-16 15:30:09 +0000104 outs() << "Checking to see if these passes crash: "
105 << getPassesString(Suffix) << ": ";
Misha Brukman650ba8e2005-04-22 00:00:37 +0000106
Rafael Espindola37302ea2010-08-05 02:16:32 +0000107 if (BD.runPasses(BD.getProgram(), Suffix)) {
Chris Lattner1d080f22003-04-24 22:24:58 +0000108 delete OrigProgram; // The suffix crashes alone...
109 return KeepSuffix;
110 }
111
112 // Nothing failed, restore state...
Chris Lattnera9656312003-06-02 04:54:29 +0000113 if (OrigProgram) {
114 delete BD.Program;
115 BD.Program = OrigProgram;
116 }
Chris Lattner1d080f22003-04-24 22:24:58 +0000117 return NoFailure;
118}
119
Bill Wendling3f833432006-10-25 18:36:14 +0000120namespace {
121 /// ReduceCrashingGlobalVariables - This works by removing the global
122 /// variable's initializer and seeing if the program still crashes. If it
123 /// does, then we keep that program and try again.
124 ///
125 class ReduceCrashingGlobalVariables : public ListReducer<GlobalVariable*> {
126 BugDriver &BD;
Rafael Espindolad1c7ef42010-08-05 03:00:22 +0000127 bool (*TestFn)(const BugDriver &, Module *);
Bill Wendling3f833432006-10-25 18:36:14 +0000128 public:
129 ReduceCrashingGlobalVariables(BugDriver &bd,
Rafael Espindolad1c7ef42010-08-05 03:00:22 +0000130 bool (*testFn)(const BugDriver &, Module *))
Bill Wendling3f833432006-10-25 18:36:14 +0000131 : BD(bd), TestFn(testFn) {}
132
Craig Toppere56917c2014-03-08 08:27:28 +0000133 TestResult doTest(std::vector<GlobalVariable*> &Prefix,
134 std::vector<GlobalVariable*> &Kept,
135 std::string &Error) override {
Bill Wendling3f833432006-10-25 18:36:14 +0000136 if (!Kept.empty() && TestGlobalVariables(Kept))
137 return KeepSuffix;
Bill Wendling3f833432006-10-25 18:36:14 +0000138 if (!Prefix.empty() && TestGlobalVariables(Prefix))
139 return KeepPrefix;
Bill Wendling3f833432006-10-25 18:36:14 +0000140 return NoFailure;
141 }
142
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000143 bool TestGlobalVariables(std::vector<GlobalVariable*> &GVs);
Bill Wendling3f833432006-10-25 18:36:14 +0000144 };
145}
146
147bool
148ReduceCrashingGlobalVariables::TestGlobalVariables(
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000149 std::vector<GlobalVariable*> &GVs) {
Bill Wendling3f833432006-10-25 18:36:14 +0000150 // Clone the program to try hacking it apart...
Rafael Espindola229e38f2010-10-13 01:36:30 +0000151 ValueToValueMapTy VMap;
Rafael Espindolacab951d2015-12-08 23:57:17 +0000152 Module *M = CloneModule(BD.getProgram(), VMap).release();
Bill Wendling3f833432006-10-25 18:36:14 +0000153
154 // Convert list to set for fast lookup...
155 std::set<GlobalVariable*> GVSet;
156
157 for (unsigned i = 0, e = GVs.size(); i != e; ++i) {
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000158 GlobalVariable* CMGV = cast<GlobalVariable>(VMap[GVs[i]]);
Bill Wendling3f833432006-10-25 18:36:14 +0000159 assert(CMGV && "Global Variable not in module?!");
160 GVSet.insert(CMGV);
161 }
162
Dan Gohmanee051522009-07-16 15:30:09 +0000163 outs() << "Checking for crash with only these global variables: ";
Bill Wendling3f833432006-10-25 18:36:14 +0000164 PrintGlobalVariableList(GVs);
Dan Gohmanee051522009-07-16 15:30:09 +0000165 outs() << ": ";
Bill Wendling3f833432006-10-25 18:36:14 +0000166
167 // Loop over and delete any global variables which we aren't supposed to be
168 // playing with...
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000169 for (GlobalVariable &I : M->globals())
170 if (I.hasInitializer() && !GVSet.count(&I)) {
Hal Finkel28ad2b42015-11-26 19:23:49 +0000171 DeleteGlobalInitializer(&I);
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000172 I.setLinkage(GlobalValue::ExternalLinkage);
Justin Lebar2a445cf2016-06-15 23:20:12 +0000173 I.setComdat(nullptr);
Bill Wendling3f833432006-10-25 18:36:14 +0000174 }
175
176 // Try running the hacked up program...
177 if (TestFn(BD, M)) {
178 BD.setNewProgram(M); // It crashed, keep the trimmed version...
179
180 // Make sure to use global variable pointers that point into the now-current
181 // module.
182 GVs.assign(GVSet.begin(), GVSet.end());
183 return true;
184 }
185
186 delete M;
187 return false;
188}
189
David Blaikiea379b1812011-12-20 02:50:00 +0000190namespace {
Bill Wendling3f833432006-10-25 18:36:14 +0000191 /// ReduceCrashingFunctions reducer - This works by removing functions and
192 /// seeing if the program still crashes. If it does, then keep the newer,
193 /// smaller program.
194 ///
Chris Lattnerfd72bed2004-03-14 20:50:42 +0000195 class ReduceCrashingFunctions : public ListReducer<Function*> {
Chris Lattner2f1aa112004-01-14 03:38:37 +0000196 BugDriver &BD;
Rafael Espindolad1c7ef42010-08-05 03:00:22 +0000197 bool (*TestFn)(const BugDriver &, Module *);
Chris Lattner2f1aa112004-01-14 03:38:37 +0000198 public:
Chris Lattner8bda4c42004-02-18 23:26:28 +0000199 ReduceCrashingFunctions(BugDriver &bd,
Rafael Espindolad1c7ef42010-08-05 03:00:22 +0000200 bool (*testFn)(const BugDriver &, Module *))
Chris Lattner8bda4c42004-02-18 23:26:28 +0000201 : BD(bd), TestFn(testFn) {}
Misha Brukman650ba8e2005-04-22 00:00:37 +0000202
Craig Toppere56917c2014-03-08 08:27:28 +0000203 TestResult doTest(std::vector<Function*> &Prefix,
204 std::vector<Function*> &Kept,
205 std::string &Error) override {
Chris Lattner2f1aa112004-01-14 03:38:37 +0000206 if (!Kept.empty() && TestFuncs(Kept))
207 return KeepSuffix;
208 if (!Prefix.empty() && TestFuncs(Prefix))
209 return KeepPrefix;
210 return NoFailure;
211 }
Misha Brukman650ba8e2005-04-22 00:00:37 +0000212
Chris Lattnerfd72bed2004-03-14 20:50:42 +0000213 bool TestFuncs(std::vector<Function*> &Prefix);
Chris Lattner2f1aa112004-01-14 03:38:37 +0000214 };
215}
Chris Lattner1d080f22003-04-24 22:24:58 +0000216
JF Bastienf87e20d2015-04-20 23:42:22 +0000217static void RemoveFunctionReferences(Module *M, const char* Name) {
218 auto *UsedVar = M->getGlobalVariable(Name, true);
219 if (!UsedVar || !UsedVar->hasInitializer()) return;
220 if (isa<ConstantAggregateZero>(UsedVar->getInitializer())) {
221 assert(UsedVar->use_empty());
222 UsedVar->eraseFromParent();
223 return;
224 }
225 auto *OldUsedVal = cast<ConstantArray>(UsedVar->getInitializer());
226 std::vector<Constant*> Used;
227 for(Value *V : OldUsedVal->operand_values()) {
228 Constant *Op = cast<Constant>(V->stripPointerCasts());
229 if(!Op->isNullValue()) {
230 Used.push_back(cast<Constant>(V));
231 }
232 }
233 auto *NewValElemTy = OldUsedVal->getType()->getElementType();
234 auto *NewValTy = ArrayType::get(NewValElemTy, Used.size());
235 auto *NewUsedVal = ConstantArray::get(NewValTy, Used);
236 UsedVar->mutateType(NewUsedVal->getType()->getPointerTo());
237 UsedVar->setInitializer(NewUsedVal);
238}
239
Chris Lattnerfd72bed2004-03-14 20:50:42 +0000240bool ReduceCrashingFunctions::TestFuncs(std::vector<Function*> &Funcs) {
Dmitri Gribenko6e0520e2013-09-02 01:18:56 +0000241 // If main isn't present, claim there is no problem.
David Majnemer0d955d02016-08-11 22:21:41 +0000242 if (KeepMain && !is_contained(Funcs, BD.getProgram()->getFunction("main")))
Andrew Lenharthef9aa122006-03-05 22:21:36 +0000243 return false;
244
Misha Brukman8b2bd4e2003-10-10 17:57:28 +0000245 // Clone the program to try hacking it apart...
Rafael Espindola229e38f2010-10-13 01:36:30 +0000246 ValueToValueMapTy VMap;
Rafael Espindolacab951d2015-12-08 23:57:17 +0000247 Module *M = CloneModule(BD.getProgram(), VMap).release();
Misha Brukman650ba8e2005-04-22 00:00:37 +0000248
Chris Lattner1d080f22003-04-24 22:24:58 +0000249 // Convert list to set for fast lookup...
250 std::set<Function*> Functions;
251 for (unsigned i = 0, e = Funcs.size(); i != e; ++i) {
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000252 Function *CMF = cast<Function>(VMap[Funcs[i]]);
Chris Lattner1d080f22003-04-24 22:24:58 +0000253 assert(CMF && "Function not in module?!");
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000254 assert(CMF->getFunctionType() == Funcs[i]->getFunctionType() && "wrong ty");
Dan Gohmanbcad7182009-03-06 02:16:23 +0000255 assert(CMF->getName() == Funcs[i]->getName() && "wrong name");
Chris Lattnerde39f2b2003-04-24 22:54:06 +0000256 Functions.insert(CMF);
Chris Lattner1d080f22003-04-24 22:24:58 +0000257 }
258
Dan Gohmanee051522009-07-16 15:30:09 +0000259 outs() << "Checking for crash with only these functions: ";
Chris Lattnerfd72bed2004-03-14 20:50:42 +0000260 PrintFunctionList(Funcs);
Dan Gohmanee051522009-07-16 15:30:09 +0000261 outs() << ": ";
JF Bastienf87e20d2015-04-20 23:42:22 +0000262 if (!ReplaceFuncsWithNull) {
263 // Loop over and delete any functions which we aren't supposed to be playing
264 // with...
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000265 for (Function &I : *M)
266 if (!I.isDeclaration() && !Functions.count(&I))
267 DeleteFunctionBody(&I);
JF Bastienf87e20d2015-04-20 23:42:22 +0000268 } else {
269 std::vector<GlobalValue*> ToRemove;
270 // First, remove aliases to functions we're about to purge.
271 for (GlobalAlias &Alias : M->aliases()) {
David Majnemer95549492016-05-04 00:20:48 +0000272 GlobalObject *Root = Alias.getBaseObject();
273 Function *F = dyn_cast_or_null<Function>(Root);
JF Bastienf87e20d2015-04-20 23:42:22 +0000274 if (F) {
275 if (Functions.count(F))
276 // We're keeping this function.
277 continue;
278 } else if (Root->isNullValue()) {
279 // This referenced a globalalias that we've already replaced,
280 // so we still need to replace this alias.
281 } else if (!F) {
282 // Not a function, therefore not something we mess with.
283 continue;
284 }
Chris Lattner1d080f22003-04-24 22:24:58 +0000285
JF Bastienf87e20d2015-04-20 23:42:22 +0000286 PointerType *Ty = cast<PointerType>(Alias.getType());
287 Constant *Replacement = ConstantPointerNull::get(Ty);
288 Alias.replaceAllUsesWith(Replacement);
289 ToRemove.push_back(&Alias);
290 }
Chris Lattner1d080f22003-04-24 22:24:58 +0000291
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000292 for (Function &I : *M) {
293 if (!I.isDeclaration() && !Functions.count(&I)) {
294 PointerType *Ty = cast<PointerType>(I.getType());
JF Bastienf87e20d2015-04-20 23:42:22 +0000295 Constant *Replacement = ConstantPointerNull::get(Ty);
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000296 I.replaceAllUsesWith(Replacement);
297 ToRemove.push_back(&I);
JF Bastienf87e20d2015-04-20 23:42:22 +0000298 }
299 }
300
301 for (auto *F : ToRemove) {
302 F->eraseFromParent();
303 }
304
305 // Finally, remove any null members from any global intrinsic.
306 RemoveFunctionReferences(M, "llvm.used");
307 RemoveFunctionReferences(M, "llvm.compiler.used");
308 }
Chris Lattner1d080f22003-04-24 22:24:58 +0000309 // Try running the hacked up program...
Chris Lattner8bda4c42004-02-18 23:26:28 +0000310 if (TestFn(BD, M)) {
Chris Lattner327019b2004-02-18 21:24:48 +0000311 BD.setNewProgram(M); // It crashed, keep the trimmed version...
Chris Lattner1d080f22003-04-24 22:24:58 +0000312
313 // Make sure to use function pointers that point into the now-current
314 // module.
315 Funcs.assign(Functions.begin(), Functions.end());
316 return true;
317 }
Chris Lattner327019b2004-02-18 21:24:48 +0000318 delete M;
Chris Lattner1d080f22003-04-24 22:24:58 +0000319 return false;
320}
321
Chris Lattner1942f982004-02-18 21:29:46 +0000322namespace {
Daniel Berlin60606262016-07-28 22:29:25 +0000323/// Simplify the CFG without completely destroying it.
324/// This is not well defined, but basically comes down to "try to eliminate
325/// unreachable blocks and constant fold terminators without deciding that
326/// certain undefined behavior cuts off the program at the legs".
327void simpleSimplifyCfg(Function &F, SmallVectorImpl<BasicBlock *> &BBs) {
328 if (F.empty())
329 return;
330
331 for (auto *BB : BBs) {
332 ConstantFoldTerminator(BB);
333 MergeBlockIntoPredecessor(BB);
334 }
335
336 // Remove unreachable blocks
337 // removeUnreachableBlocks can't be used here, it will turn various
338 // undefined behavior into unreachables, but bugpoint was the thing that
339 // generated the undefined behavior, and we don't want it to kill the entire
340 // program.
341 SmallPtrSet<BasicBlock *, 16> Visited;
342 for (auto *BB : depth_first(&F.getEntryBlock()))
343 Visited.insert(BB);
344
345 SmallVector<BasicBlock *, 16> Unreachable;
346 for (auto &BB : F)
347 if (!Visited.count(&BB))
348 Unreachable.push_back(&BB);
349
350 // The dead BB's may be in a dead cycle or otherwise have references to each
351 // other. Because of this, we have to drop all references first, then delete
352 // them all at once.
353 for (auto *BB : Unreachable) {
354 for (BasicBlock *Successor : successors(&*BB))
355 if (Visited.count(Successor))
356 Successor->removePredecessor(&*BB);
357 BB->dropAllReferences();
358 }
359 for (auto *BB : Unreachable)
360 BB->eraseFromParent();
361}
Chris Lattner2f1aa112004-01-14 03:38:37 +0000362 /// ReduceCrashingBlocks reducer - This works by setting the terminators of
363 /// all terminators except the specified basic blocks to a 'ret' instruction,
364 /// then running the simplify-cfg pass. This has the effect of chopping up
365 /// the CFG really fast which can reduce large functions quickly.
366 ///
Chris Lattner8bda4c42004-02-18 23:26:28 +0000367 class ReduceCrashingBlocks : public ListReducer<const BasicBlock*> {
Chris Lattner2f1aa112004-01-14 03:38:37 +0000368 BugDriver &BD;
Rafael Espindolad1c7ef42010-08-05 03:00:22 +0000369 bool (*TestFn)(const BugDriver &, Module *);
Chris Lattner2f1aa112004-01-14 03:38:37 +0000370 public:
Daniel Berlin60606262016-07-28 22:29:25 +0000371 ReduceCrashingBlocks(BugDriver &BD,
Rafael Espindolad1c7ef42010-08-05 03:00:22 +0000372 bool (*testFn)(const BugDriver &, Module *))
Daniel Berlin60606262016-07-28 22:29:25 +0000373 : BD(BD), TestFn(testFn) {}
Misha Brukman650ba8e2005-04-22 00:00:37 +0000374
Craig Toppere56917c2014-03-08 08:27:28 +0000375 TestResult doTest(std::vector<const BasicBlock*> &Prefix,
376 std::vector<const BasicBlock*> &Kept,
377 std::string &Error) override {
Chris Lattner2f1aa112004-01-14 03:38:37 +0000378 if (!Kept.empty() && TestBlocks(Kept))
379 return KeepSuffix;
380 if (!Prefix.empty() && TestBlocks(Prefix))
381 return KeepPrefix;
382 return NoFailure;
383 }
Misha Brukman650ba8e2005-04-22 00:00:37 +0000384
Chris Lattner8bda4c42004-02-18 23:26:28 +0000385 bool TestBlocks(std::vector<const BasicBlock*> &Prefix);
Chris Lattner2f1aa112004-01-14 03:38:37 +0000386 };
387}
Chris Lattnerf32939b2003-04-24 23:51:38 +0000388
Chris Lattner8bda4c42004-02-18 23:26:28 +0000389bool ReduceCrashingBlocks::TestBlocks(std::vector<const BasicBlock*> &BBs) {
Misha Brukman8b2bd4e2003-10-10 17:57:28 +0000390 // Clone the program to try hacking it apart...
Rafael Espindola229e38f2010-10-13 01:36:30 +0000391 ValueToValueMapTy VMap;
Rafael Espindolacab951d2015-12-08 23:57:17 +0000392 Module *M = CloneModule(BD.getProgram(), VMap).release();
Misha Brukman650ba8e2005-04-22 00:00:37 +0000393
Chris Lattnerf32939b2003-04-24 23:51:38 +0000394 // Convert list to set for fast lookup...
Nick Lewyckyb294e312009-04-04 09:39:23 +0000395 SmallPtrSet<BasicBlock*, 8> Blocks;
396 for (unsigned i = 0, e = BBs.size(); i != e; ++i)
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000397 Blocks.insert(cast<BasicBlock>(VMap[BBs[i]]));
Chris Lattnerf32939b2003-04-24 23:51:38 +0000398
Dan Gohmanee051522009-07-16 15:30:09 +0000399 outs() << "Checking for crash with only these blocks:";
Chris Lattner4f50ebd2003-10-27 04:44:59 +0000400 unsigned NumPrint = Blocks.size();
401 if (NumPrint > 10) NumPrint = 10;
402 for (unsigned i = 0, e = NumPrint; i != e; ++i)
Dan Gohmanee051522009-07-16 15:30:09 +0000403 outs() << " " << BBs[i]->getName();
Chris Lattner4f50ebd2003-10-27 04:44:59 +0000404 if (NumPrint < Blocks.size())
Dan Gohmanee051522009-07-16 15:30:09 +0000405 outs() << "... <" << Blocks.size() << " total>";
406 outs() << ": ";
Chris Lattnerf32939b2003-04-24 23:51:38 +0000407
408 // Loop over and delete any hack up any blocks that are not listed...
409 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
410 for (Function::iterator BB = I->begin(), E = I->end(); BB != E; ++BB)
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000411 if (!Blocks.count(&*BB) && BB->getTerminator()->getNumSuccessors()) {
Chris Lattnerf32939b2003-04-24 23:51:38 +0000412 // Loop over all of the successors of this block, deleting any PHI nodes
413 // that might include it.
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000414 for (succ_iterator SI = succ_begin(&*BB), E = succ_end(&*BB); SI != E;
415 ++SI)
416 (*SI)->removePredecessor(&*BB);
Chris Lattnerf32939b2003-04-24 23:51:38 +0000417
Chris Lattner7855a5c2008-04-28 00:04:58 +0000418 TerminatorInst *BBTerm = BB->getTerminator();
Philip Reames29e641c2016-06-29 00:15:35 +0000419 if (BBTerm->isEHPad() || BBTerm->getType()->isTokenTy())
David Majnemer189d7da2015-11-08 04:16:12 +0000420 continue;
Philip Reames29e641c2016-06-29 00:15:35 +0000421 if (!BBTerm->getType()->isVoidTy())
Owen Anderson5a1acd92009-07-31 20:28:14 +0000422 BBTerm->replaceAllUsesWith(Constant::getNullValue(BBTerm->getType()));
Chris Lattner7b233af2003-11-22 02:10:38 +0000423
Chris Lattner7855a5c2008-04-28 00:04:58 +0000424 // Replace the old terminator instruction.
Chris Lattnerf32939b2003-04-24 23:51:38 +0000425 BB->getInstList().pop_back();
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000426 new UnreachableInst(BB->getContext(), &*BB);
Chris Lattnerf32939b2003-04-24 23:51:38 +0000427 }
428
429 // The CFG Simplifier pass may delete one of the basic blocks we are
430 // interested in. If it does we need to take the block out of the list. Make
431 // a "persistent mapping" by turning basic blocks into <function, name> pairs.
432 // This won't work well if blocks are unnamed, but that is just the risk we
433 // have to take.
Rafael Espindolad1e241a2010-08-10 15:46:11 +0000434 std::vector<std::pair<std::string, std::string> > BlockInfo;
Chris Lattnerf32939b2003-04-24 23:51:38 +0000435
Craig Topper46276792014-08-24 23:23:06 +0000436 for (BasicBlock *BB : Blocks)
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000437 BlockInfo.emplace_back(BB->getParent()->getName(), BB->getName());
Daniel Berlin60606262016-07-28 22:29:25 +0000438
439 SmallVector<BasicBlock *, 16> ToProcess;
440 for (auto &F :*M) {
441 for (auto &BB : F)
442 if (!Blocks.count(&BB))
443 ToProcess.push_back(&BB);
444 simpleSimplifyCfg(F, ToProcess);
445 ToProcess.clear();
446 }
447 // Verify we didn't break anything
Rafael Espindolad1e241a2010-08-10 15:46:11 +0000448 std::vector<std::string> Passes;
Rafael Espindolad1e241a2010-08-10 15:46:11 +0000449 Passes.push_back("verify");
Rafael Espindola28b351a2014-08-26 17:19:03 +0000450 std::unique_ptr<Module> New = BD.runPassesOn(M, Passes);
Rafael Espindolad1e241a2010-08-10 15:46:11 +0000451 delete M;
452 if (!New) {
Daniel Berlin60606262016-07-28 22:29:25 +0000453 errs() << "verify failed!\n";
Rafael Espindolad1e241a2010-08-10 15:46:11 +0000454 exit(1);
455 }
Rafael Espindola28b351a2014-08-26 17:19:03 +0000456 M = New.release();
Daniel Berlin60606262016-07-28 22:29:25 +0000457
Chris Lattnerf32939b2003-04-24 23:51:38 +0000458 // Try running on the hacked up program...
Chris Lattner8bda4c42004-02-18 23:26:28 +0000459 if (TestFn(BD, M)) {
Chris Lattner327019b2004-02-18 21:24:48 +0000460 BD.setNewProgram(M); // It crashed, keep the trimmed version...
Chris Lattnerf32939b2003-04-24 23:51:38 +0000461
462 // Make sure to use basic block pointers that point into the now-current
463 // module, and that they don't include any deleted blocks.
464 BBs.clear();
Rafael Espindolad1e241a2010-08-10 15:46:11 +0000465 const ValueSymbolTable &GST = M->getValueSymbolTable();
Chris Lattnerf32939b2003-04-24 23:51:38 +0000466 for (unsigned i = 0, e = BlockInfo.size(); i != e; ++i) {
Rafael Espindolad1e241a2010-08-10 15:46:11 +0000467 Function *F = cast<Function>(GST.lookup(BlockInfo[i].first));
468 ValueSymbolTable &ST = F->getValueSymbolTable();
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000469 Value* V = ST.lookup(BlockInfo[i].second);
Owen Anderson55f1c092009-08-13 21:58:54 +0000470 if (V && V->getType() == Type::getLabelTy(V->getContext()))
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000471 BBs.push_back(cast<BasicBlock>(V));
Chris Lattnerf32939b2003-04-24 23:51:38 +0000472 }
473 return true;
474 }
Chris Lattner327019b2004-02-18 21:24:48 +0000475 delete M; // It didn't crash, try something else.
Chris Lattnerf32939b2003-04-24 23:51:38 +0000476 return false;
477}
478
Nick Lewycky6e090c92009-05-25 05:30:00 +0000479namespace {
Daniel Berlin271ca402016-07-27 16:13:25 +0000480/// ReduceCrashingConditionals reducer - This works by changing
481/// conditional branches to unconditional ones, then simplifying the CFG
482/// This has the effect of chopping up the CFG really fast which can reduce
483/// large functions quickly.
484///
485class ReduceCrashingConditionals : public ListReducer<const BasicBlock *> {
486 BugDriver &BD;
487 bool (*TestFn)(const BugDriver &, Module *);
488 bool Direction;
489
490public:
491 ReduceCrashingConditionals(BugDriver &bd,
492 bool (*testFn)(const BugDriver &, Module *),
493 bool Direction)
494 : BD(bd), TestFn(testFn), Direction(Direction) {}
495
496 TestResult doTest(std::vector<const BasicBlock *> &Prefix,
497 std::vector<const BasicBlock *> &Kept,
498 std::string &Error) override {
499 if (!Kept.empty() && TestBlocks(Kept))
500 return KeepSuffix;
501 if (!Prefix.empty() && TestBlocks(Prefix))
502 return KeepPrefix;
503 return NoFailure;
504 }
505
506 bool TestBlocks(std::vector<const BasicBlock *> &Prefix);
507};
508}
509
510bool ReduceCrashingConditionals::TestBlocks(
511 std::vector<const BasicBlock *> &BBs) {
512 // Clone the program to try hacking it apart...
513 ValueToValueMapTy VMap;
514 Module *M = CloneModule(BD.getProgram(), VMap).release();
515
516 // Convert list to set for fast lookup...
517 SmallPtrSet<const BasicBlock *, 8> Blocks;
518 for (const auto *BB: BBs)
519 Blocks.insert(cast<BasicBlock>(VMap[BB]));
520
521 outs() << "Checking for crash with changing conditionals to always jump to "
522 << (Direction ? "true" : "false") << ":";
523 unsigned NumPrint = Blocks.size();
524 if (NumPrint > 10)
525 NumPrint = 10;
526 for (unsigned i = 0, e = NumPrint; i != e; ++i)
527 outs() << " " << BBs[i]->getName();
528 if (NumPrint < Blocks.size())
529 outs() << "... <" << Blocks.size() << " total>";
530 outs() << ": ";
531
532 // Loop over and delete any hack up any blocks that are not listed...
533 for (auto &F: *M)
534 for (auto &BB : F)
535 if (!Blocks.count(&BB)) {
536 auto *BR = dyn_cast<BranchInst>(BB.getTerminator());
537 if (!BR || !BR->isConditional())
538 continue;
539 if (Direction)
540 BR->setCondition(ConstantInt::getTrue(BR->getContext()));
541 else
542 BR->setCondition(ConstantInt::getFalse(BR->getContext()));
543 }
544
545 // The following may destroy some blocks, so we save them first
546 std::vector<std::pair<std::string, std::string>> BlockInfo;
547
548 for (const BasicBlock *BB : Blocks)
549 BlockInfo.emplace_back(BB->getParent()->getName(), BB->getName());
550
551 SmallVector<BasicBlock *, 16> ToProcess;
552 for (auto &F :*M) {
553 for (auto &BB : F)
554 if (!Blocks.count(&BB))
555 ToProcess.push_back(&BB);
556 simpleSimplifyCfg(F, ToProcess);
557 ToProcess.clear();
558 }
559 // Verify we didn't break anything
560 std::vector<std::string> Passes;
561 Passes.push_back("verify");
562 std::unique_ptr<Module> New = BD.runPassesOn(M, Passes);
563 delete M;
564 if (!New) {
565 errs() << "verify failed!\n";
566 exit(1);
567 }
568 M = New.release();
569
570 // Try running on the hacked up program...
571 if (TestFn(BD, M)) {
572 BD.setNewProgram(M); // It crashed, keep the trimmed version...
573
574 // Make sure to use basic block pointers that point into the now-current
575 // module, and that they don't include any deleted blocks.
576 BBs.clear();
577 const ValueSymbolTable &GST = M->getValueSymbolTable();
578 for (auto &BI : BlockInfo) {
579 auto *F = cast<Function>(GST.lookup(BI.first));
580 ValueSymbolTable &ST = F->getValueSymbolTable();
581 Value *V = ST.lookup(BI.second);
582 if (V && V->getType() == Type::getLabelTy(V->getContext()))
583 BBs.push_back(cast<BasicBlock>(V));
584 }
585 return true;
586 }
587 delete M; // It didn't crash, try something else.
588 return false;
589}
590
591namespace {
Daniel Berlin60606262016-07-28 22:29:25 +0000592/// SimplifyCFG reducer - This works by calling SimplifyCFG on each basic block
593/// in the program.
594
595class ReduceSimplifyCFG : public ListReducer<const BasicBlock *> {
596 BugDriver &BD;
597 bool (*TestFn)(const BugDriver &, Module *);
598 TargetTransformInfo TTI;
599
600public:
601 ReduceSimplifyCFG(BugDriver &bd,
602 bool (*testFn)(const BugDriver &, Module *))
603 : BD(bd), TestFn(testFn), TTI(bd.getProgram()->getDataLayout())
604 {}
605
606 TestResult doTest(std::vector<const BasicBlock *> &Prefix,
607 std::vector<const BasicBlock *> &Kept,
608 std::string &Error) override {
609 if (!Kept.empty() && TestBlocks(Kept))
610 return KeepSuffix;
611 if (!Prefix.empty() && TestBlocks(Prefix))
612 return KeepPrefix;
613 return NoFailure;
614 }
615
616 bool TestBlocks(std::vector<const BasicBlock *> &Prefix);
617};
618}
619
620bool ReduceSimplifyCFG::TestBlocks(
621 std::vector<const BasicBlock *> &BBs) {
622 // Clone the program to try hacking it apart...
623 ValueToValueMapTy VMap;
624 Module *M = CloneModule(BD.getProgram(), VMap).release();
625
626 // Convert list to set for fast lookup...
627 SmallPtrSet<const BasicBlock *, 8> Blocks;
628 for (const auto *BB: BBs)
629 Blocks.insert(cast<BasicBlock>(VMap[BB]));
630
631 outs() << "Checking for crash with CFG simplifying:";
632 unsigned NumPrint = Blocks.size();
633 if (NumPrint > 10)
634 NumPrint = 10;
635 for (unsigned i = 0, e = NumPrint; i != e; ++i)
636 outs() << " " << BBs[i]->getName();
637 if (NumPrint < Blocks.size())
638 outs() << "... <" << Blocks.size() << " total>";
639 outs() << ": ";
640
641 // The following may destroy some blocks, so we save them first
642 std::vector<std::pair<std::string, std::string>> BlockInfo;
643
644 for (const BasicBlock *BB : Blocks)
645 BlockInfo.emplace_back(BB->getParent()->getName(), BB->getName());
646
647
648 // Loop over and delete any hack up any blocks that are not listed...
649 for (auto &F: *M)
650 // Loop over all of the basic blocks and remove them if they are unneeded.
651 for (Function::iterator BBIt = F.begin(); BBIt != F.end(); ) {
652 if (!Blocks.count(&*BBIt)) {
653 ++BBIt;
654 continue;
655 }
656 SimplifyCFG(&*BBIt++, TTI, 1);
657 }
658 // Verify we didn't break anything
659 std::vector<std::string> Passes;
660 Passes.push_back("verify");
661 std::unique_ptr<Module> New = BD.runPassesOn(M, Passes);
662 delete M;
663 if (!New) {
664 errs() << "verify failed!\n";
665 exit(1);
666 }
667 M = New.release();
668
669 // Try running on the hacked up program...
670 if (TestFn(BD, M)) {
671 BD.setNewProgram(M); // It crashed, keep the trimmed version...
672
673 // Make sure to use basic block pointers that point into the now-current
674 // module, and that they don't include any deleted blocks.
675 BBs.clear();
676 const ValueSymbolTable &GST = M->getValueSymbolTable();
677 for (auto &BI : BlockInfo){
678 auto *F = cast<Function>(GST.lookup(BI.first));
679 ValueSymbolTable &ST = F->getValueSymbolTable();
680 Value *V = ST.lookup(BI.second);
681 if (V && V->getType() == Type::getLabelTy(V->getContext()))
682 BBs.push_back(cast<BasicBlock>(V));
683 }
684 return true;
685 }
686 delete M; // It didn't crash, try something else.
687 return false;
688}
689
690namespace {
Nick Lewycky6e090c92009-05-25 05:30:00 +0000691 /// ReduceCrashingInstructions reducer - This works by removing the specified
692 /// non-terminator instructions and replacing them with undef.
693 ///
694 class ReduceCrashingInstructions : public ListReducer<const Instruction*> {
695 BugDriver &BD;
Rafael Espindolad1c7ef42010-08-05 03:00:22 +0000696 bool (*TestFn)(const BugDriver &, Module *);
Nick Lewycky6e090c92009-05-25 05:30:00 +0000697 public:
Rafael Espindolad1c7ef42010-08-05 03:00:22 +0000698 ReduceCrashingInstructions(BugDriver &bd,
699 bool (*testFn)(const BugDriver &, Module *))
Nick Lewycky6e090c92009-05-25 05:30:00 +0000700 : BD(bd), TestFn(testFn) {}
701
Craig Toppere56917c2014-03-08 08:27:28 +0000702 TestResult doTest(std::vector<const Instruction*> &Prefix,
703 std::vector<const Instruction*> &Kept,
704 std::string &Error) override {
Nick Lewycky6e090c92009-05-25 05:30:00 +0000705 if (!Kept.empty() && TestInsts(Kept))
706 return KeepSuffix;
707 if (!Prefix.empty() && TestInsts(Prefix))
708 return KeepPrefix;
709 return NoFailure;
710 }
711
712 bool TestInsts(std::vector<const Instruction*> &Prefix);
713 };
714}
715
716bool ReduceCrashingInstructions::TestInsts(std::vector<const Instruction*>
717 &Insts) {
718 // Clone the program to try hacking it apart...
Rafael Espindola229e38f2010-10-13 01:36:30 +0000719 ValueToValueMapTy VMap;
Rafael Espindolacab951d2015-12-08 23:57:17 +0000720 Module *M = CloneModule(BD.getProgram(), VMap).release();
Nick Lewycky6e090c92009-05-25 05:30:00 +0000721
722 // Convert list to set for fast lookup...
Matthias Braunb30f2f512016-01-30 01:24:31 +0000723 SmallPtrSet<Instruction*, 32> Instructions;
Nick Lewycky6e090c92009-05-25 05:30:00 +0000724 for (unsigned i = 0, e = Insts.size(); i != e; ++i) {
725 assert(!isa<TerminatorInst>(Insts[i]));
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000726 Instructions.insert(cast<Instruction>(VMap[Insts[i]]));
Nick Lewycky6e090c92009-05-25 05:30:00 +0000727 }
728
Dan Gohmanee051522009-07-16 15:30:09 +0000729 outs() << "Checking for crash with only " << Instructions.size();
Nick Lewycky6e090c92009-05-25 05:30:00 +0000730 if (Instructions.size() == 1)
Dan Gohmanee051522009-07-16 15:30:09 +0000731 outs() << " instruction: ";
Nick Lewycky6e090c92009-05-25 05:30:00 +0000732 else
Dan Gohmanee051522009-07-16 15:30:09 +0000733 outs() << " instructions: ";
Nick Lewycky6e090c92009-05-25 05:30:00 +0000734
735 for (Module::iterator MI = M->begin(), ME = M->end(); MI != ME; ++MI)
736 for (Function::iterator FI = MI->begin(), FE = MI->end(); FI != FE; ++FI)
737 for (BasicBlock::iterator I = FI->begin(), E = FI->end(); I != E;) {
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000738 Instruction *Inst = &*I++;
Eli Friedmand4e02a52011-11-01 04:40:56 +0000739 if (!Instructions.count(Inst) && !isa<TerminatorInst>(Inst) &&
Philip Reames29e641c2016-06-29 00:15:35 +0000740 !Inst->isEHPad() && !Inst->getType()->isTokenTy()) {
741 if (!Inst->getType()->isVoidTy())
Nick Lewycky6e090c92009-05-25 05:30:00 +0000742 Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
743 Inst->eraseFromParent();
744 }
745 }
746
747 // Verify that this is still valid.
Chandler Carruth30d69c22015-02-13 10:01:29 +0000748 legacy::PassManager Passes;
Nick Lewycky6e090c92009-05-25 05:30:00 +0000749 Passes.add(createVerifierPass());
750 Passes.run(*M);
751
752 // Try running on the hacked up program...
753 if (TestFn(BD, M)) {
754 BD.setNewProgram(M); // It crashed, keep the trimmed version...
755
756 // Make sure to use instruction pointers that point into the now-current
757 // module, and that they don't include any deleted blocks.
758 Insts.clear();
Craig Topper46276792014-08-24 23:23:06 +0000759 for (Instruction *Inst : Instructions)
760 Insts.push_back(Inst);
Nick Lewycky6e090c92009-05-25 05:30:00 +0000761 return true;
762 }
763 delete M; // It didn't crash, try something else.
764 return false;
765}
766
Keno Fischer34ca8312015-11-06 00:12:50 +0000767namespace {
768// Reduce the list of Named Metadata nodes. We keep this as a list of
769// names to avoid having to convert back and forth every time.
770class ReduceCrashingNamedMD : public ListReducer<std::string> {
771 BugDriver &BD;
772 bool (*TestFn)(const BugDriver &, Module *);
773
774public:
775 ReduceCrashingNamedMD(BugDriver &bd,
776 bool (*testFn)(const BugDriver &, Module *))
777 : BD(bd), TestFn(testFn) {}
778
779 TestResult doTest(std::vector<std::string> &Prefix,
780 std::vector<std::string> &Kept,
781 std::string &Error) override {
782 if (!Kept.empty() && TestNamedMDs(Kept))
783 return KeepSuffix;
784 if (!Prefix.empty() && TestNamedMDs(Prefix))
785 return KeepPrefix;
786 return NoFailure;
787 }
788
789 bool TestNamedMDs(std::vector<std::string> &NamedMDs);
790};
791}
792
793bool ReduceCrashingNamedMD::TestNamedMDs(std::vector<std::string> &NamedMDs) {
794
795 ValueToValueMapTy VMap;
Rafael Espindolacab951d2015-12-08 23:57:17 +0000796 Module *M = CloneModule(BD.getProgram(), VMap).release();
Keno Fischer34ca8312015-11-06 00:12:50 +0000797
798 outs() << "Checking for crash with only these named metadata nodes:";
799 unsigned NumPrint = std::min<size_t>(NamedMDs.size(), 10);
800 for (unsigned i = 0, e = NumPrint; i != e; ++i)
801 outs() << " " << NamedMDs[i];
802 if (NumPrint < NamedMDs.size())
803 outs() << "... <" << NamedMDs.size() << " total>";
804 outs() << ": ";
805
806 // Make a StringMap for faster lookup
807 StringSet<> Names;
808 for (const std::string &Name : NamedMDs)
809 Names.insert(Name);
810
811 // First collect all the metadata to delete in a vector, then
812 // delete them all at once to avoid invalidating the iterator
813 std::vector<NamedMDNode *> ToDelete;
814 ToDelete.reserve(M->named_metadata_size() - Names.size());
815 for (auto &NamedMD : M->named_metadata())
Adrian Prantlfaebbb02016-03-28 21:06:26 +0000816 // Always keep a nonempty llvm.dbg.cu because the Verifier would complain.
817 if (!Names.count(NamedMD.getName()) &&
818 (!(NamedMD.getName() == "llvm.dbg.cu" && NamedMD.getNumOperands() > 0)))
Keno Fischer34ca8312015-11-06 00:12:50 +0000819 ToDelete.push_back(&NamedMD);
820
821 for (auto *NamedMD : ToDelete)
822 NamedMD->eraseFromParent();
823
824 // Verify that this is still valid.
825 legacy::PassManager Passes;
826 Passes.add(createVerifierPass());
827 Passes.run(*M);
828
829 // Try running on the hacked up program...
830 if (TestFn(BD, M)) {
831 BD.setNewProgram(M); // It crashed, keep the trimmed version...
832 return true;
833 }
834 delete M; // It didn't crash, try something else.
835 return false;
836}
837
838namespace {
839// Reduce the list of operands to named metadata nodes
840class ReduceCrashingNamedMDOps : public ListReducer<const MDNode *> {
841 BugDriver &BD;
842 bool (*TestFn)(const BugDriver &, Module *);
843
844public:
845 ReduceCrashingNamedMDOps(BugDriver &bd,
846 bool (*testFn)(const BugDriver &, Module *))
847 : BD(bd), TestFn(testFn) {}
848
849 TestResult doTest(std::vector<const MDNode *> &Prefix,
850 std::vector<const MDNode *> &Kept,
851 std::string &Error) override {
852 if (!Kept.empty() && TestNamedMDOps(Kept))
853 return KeepSuffix;
854 if (!Prefix.empty() && TestNamedMDOps(Prefix))
855 return KeepPrefix;
856 return NoFailure;
857 }
858
859 bool TestNamedMDOps(std::vector<const MDNode *> &NamedMDOps);
860};
861}
862
863bool ReduceCrashingNamedMDOps::TestNamedMDOps(
864 std::vector<const MDNode *> &NamedMDOps) {
865 // Convert list to set for fast lookup...
Matthias Braunb30f2f512016-01-30 01:24:31 +0000866 SmallPtrSet<const MDNode *, 32> OldMDNodeOps;
Keno Fischer34ca8312015-11-06 00:12:50 +0000867 for (unsigned i = 0, e = NamedMDOps.size(); i != e; ++i) {
868 OldMDNodeOps.insert(NamedMDOps[i]);
869 }
870
871 outs() << "Checking for crash with only " << OldMDNodeOps.size();
872 if (OldMDNodeOps.size() == 1)
873 outs() << " named metadata operand: ";
874 else
875 outs() << " named metadata operands: ";
876
877 ValueToValueMapTy VMap;
Rafael Espindolacab951d2015-12-08 23:57:17 +0000878 Module *M = CloneModule(BD.getProgram(), VMap).release();
Keno Fischer34ca8312015-11-06 00:12:50 +0000879
880 // This is a little wasteful. In the future it might be good if we could have
881 // these dropped during cloning.
882 for (auto &NamedMD : BD.getProgram()->named_metadata()) {
883 // Drop the old one and create a new one
884 M->eraseNamedMetadata(M->getNamedMetadata(NamedMD.getName()));
885 NamedMDNode *NewNamedMDNode =
886 M->getOrInsertNamedMetadata(NamedMD.getName());
887 for (MDNode *op : NamedMD.operands())
888 if (OldMDNodeOps.count(op))
889 NewNamedMDNode->addOperand(cast<MDNode>(MapMetadata(op, VMap)));
890 }
891
892 // Verify that this is still valid.
893 legacy::PassManager Passes;
894 Passes.add(createVerifierPass());
895 Passes.run(*M);
896
897 // Try running on the hacked up program...
898 if (TestFn(BD, M)) {
899 // Make sure to use instruction pointers that point into the now-current
900 // module, and that they don't include any deleted blocks.
901 NamedMDOps.clear();
902 for (const MDNode *Node : OldMDNodeOps)
Duncan P. N. Exon Smithda4a56d2016-04-02 17:04:38 +0000903 NamedMDOps.push_back(cast<MDNode>(*VMap.getMappedMD(Node)));
Keno Fischer34ca8312015-11-06 00:12:50 +0000904
905 BD.setNewProgram(M); // It crashed, keep the trimmed version...
906 return true;
907 }
908 delete M; // It didn't crash, try something else.
909 return false;
910}
911
Philip Reames1c232f92016-06-29 00:43:18 +0000912static void ReduceGlobalInitializers(BugDriver &BD,
913 bool (*TestFn)(const BugDriver &, Module *),
914 std::string &Error) {
915 if (BD.getProgram()->global_begin() != BD.getProgram()->global_end()) {
Bill Wendling3f833432006-10-25 18:36:14 +0000916 // Now try to reduce the number of global variable initializers in the
917 // module to something small.
Rafael Espindolacab951d2015-12-08 23:57:17 +0000918 Module *M = CloneModule(BD.getProgram()).release();
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000919 bool DeletedInit = false;
Misha Brukman650ba8e2005-04-22 00:00:37 +0000920
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000921 for (Module::global_iterator I = M->global_begin(), E = M->global_end();
922 I != E; ++I)
923 if (I->hasInitializer()) {
Hal Finkel28ad2b42015-11-26 19:23:49 +0000924 DeleteGlobalInitializer(&*I);
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000925 I->setLinkage(GlobalValue::ExternalLinkage);
Justin Lebar2a445cf2016-06-15 23:20:12 +0000926 I->setComdat(nullptr);
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000927 DeletedInit = true;
928 }
Bill Wendling3f833432006-10-25 18:36:14 +0000929
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000930 if (!DeletedInit) {
931 delete M; // No change made...
932 } else {
933 // See if the program still causes a crash...
Dan Gohmanee051522009-07-16 15:30:09 +0000934 outs() << "\nChecking to see if we can delete global inits: ";
Bill Wendling3f833432006-10-25 18:36:14 +0000935
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000936 if (TestFn(BD, M)) { // Still crashes?
937 BD.setNewProgram(M);
Dan Gohmanee051522009-07-16 15:30:09 +0000938 outs() << "\n*** Able to remove all global initializers!\n";
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000939 } else { // No longer crashes?
Dan Gohmanee051522009-07-16 15:30:09 +0000940 outs() << " - Removing all global inits hides problem!\n";
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000941 delete M;
Bill Wendling3f833432006-10-25 18:36:14 +0000942
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000943 std::vector<GlobalVariable*> GVs;
944
945 for (Module::global_iterator I = BD.getProgram()->global_begin(),
946 E = BD.getProgram()->global_end(); I != E; ++I)
947 if (I->hasInitializer())
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000948 GVs.push_back(&*I);
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000949
950 if (GVs.size() > 1 && !BugpointIsInterrupted) {
Dan Gohmanee051522009-07-16 15:30:09 +0000951 outs() << "\n*** Attempting to reduce the number of global "
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000952 << "variables in the testcase\n";
953
954 unsigned OldSize = GVs.size();
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000955 ReduceCrashingGlobalVariables(BD, TestFn).reduceList(GVs, Error);
Philip Reames1c232f92016-06-29 00:43:18 +0000956 assert(!Error.empty());
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000957
958 if (GVs.size() < OldSize)
Rafael Espindola594994a2010-07-28 18:12:30 +0000959 BD.EmitProgressBitcode(BD.getProgram(), "reduced-global-variables");
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000960 }
Bill Wendlingce3afd62006-10-27 20:22:04 +0000961 }
Chris Lattner65e5f652003-04-25 00:53:05 +0000962 }
963 }
Philip Reames1c232f92016-06-29 00:43:18 +0000964}
965
966static void ReduceInsts(BugDriver &BD,
967 bool (*TestFn)(const BugDriver &, Module *),
968 std::string &Error) {
969 // Attempt to delete instructions using bisection. This should help out nasty
970 // cases with large basic blocks where the problem is at one end.
971 if (!BugpointIsInterrupted) {
972 std::vector<const Instruction*> Insts;
973 for (const Function &F : *BD.getProgram())
974 for (const BasicBlock &BB : F)
975 for (const Instruction &I : BB)
976 if (!isa<TerminatorInst>(&I))
977 Insts.push_back(&I);
978
979 ReduceCrashingInstructions(BD, TestFn).reduceList(Insts, Error);
980 }
981
982 unsigned Simplification = 2;
983 do {
984 if (BugpointIsInterrupted)
985 return;
986 --Simplification;
987 outs() << "\n*** Attempting to reduce testcase by deleting instruc"
988 << "tions: Simplification Level #" << Simplification << '\n';
989
990 // Now that we have deleted the functions that are unnecessary for the
991 // program, try to remove instructions that are not necessary to cause the
992 // crash. To do this, we loop through all of the instructions in the
993 // remaining functions, deleting them (replacing any values produced with
994 // nulls), and then running ADCE and SimplifyCFG. If the transformed input
995 // still triggers failure, keep deleting until we cannot trigger failure
996 // anymore.
997 //
998 unsigned InstructionsToSkipBeforeDeleting = 0;
999 TryAgain:
1000
1001 // Loop over all of the (non-terminator) instructions remaining in the
1002 // function, attempting to delete them.
1003 unsigned CurInstructionNum = 0;
1004 for (Module::const_iterator FI = BD.getProgram()->begin(),
1005 E = BD.getProgram()->end(); FI != E; ++FI)
1006 if (!FI->isDeclaration())
1007 for (Function::const_iterator BI = FI->begin(), E = FI->end(); BI != E;
1008 ++BI)
1009 for (BasicBlock::const_iterator I = BI->begin(), E = --BI->end();
1010 I != E; ++I, ++CurInstructionNum) {
1011 if (InstructionsToSkipBeforeDeleting) {
1012 --InstructionsToSkipBeforeDeleting;
1013 } else {
1014 if (BugpointIsInterrupted)
1015 return;
1016
1017 if (I->isEHPad() || I->getType()->isTokenTy())
1018 continue;
1019
1020 outs() << "Checking instruction: " << *I;
1021 std::unique_ptr<Module> M =
1022 BD.deleteInstructionFromProgram(&*I, Simplification);
1023
1024 // Find out if the pass still crashes on this pass...
1025 if (TestFn(BD, M.get())) {
1026 // Yup, it does, we delete the old module, and continue trying
1027 // to reduce the testcase...
1028 BD.setNewProgram(M.release());
1029 InstructionsToSkipBeforeDeleting = CurInstructionNum;
1030 goto TryAgain; // I wish I had a multi-level break here!
1031 }
1032 }
1033 }
1034
1035 if (InstructionsToSkipBeforeDeleting) {
1036 InstructionsToSkipBeforeDeleting = 0;
1037 goto TryAgain;
1038 }
1039
1040 } while (Simplification);
1041 BD.EmitProgressBitcode(BD.getProgram(), "reduced-instructions");
1042}
1043
1044
1045/// DebugACrash - Given a predicate that determines whether a component crashes
1046/// on a program, try to destructively reduce the program while still keeping
1047/// the predicate true.
1048static bool DebugACrash(BugDriver &BD,
1049 bool (*TestFn)(const BugDriver &, Module *),
1050 std::string &Error) {
1051 // See if we can get away with nuking some of the global variable initializers
1052 // in the program...
1053 if (!NoGlobalRM)
1054 ReduceGlobalInitializers(BD, TestFn, Error);
Misha Brukman650ba8e2005-04-22 00:00:37 +00001055
Chris Lattner1d080f22003-04-24 22:24:58 +00001056 // Now try to reduce the number of functions in the module to something small.
Chris Lattnerfd72bed2004-03-14 20:50:42 +00001057 std::vector<Function*> Functions;
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +00001058 for (Function &F : *BD.getProgram())
1059 if (!F.isDeclaration())
1060 Functions.push_back(&F);
Chris Lattner73a6bdd2002-11-20 22:28:10 +00001061
Chris Lattnerbeb01fa2005-08-02 02:16:17 +00001062 if (Functions.size() > 1 && !BugpointIsInterrupted) {
Dan Gohmanee051522009-07-16 15:30:09 +00001063 outs() << "\n*** Attempting to reduce the number of functions "
Chris Lattner1d080f22003-04-24 22:24:58 +00001064 "in the testcase\n";
Chris Lattner73a6bdd2002-11-20 22:28:10 +00001065
Chris Lattner8bda4c42004-02-18 23:26:28 +00001066 unsigned OldSize = Functions.size();
Nick Lewycky6ba630b2010-04-12 05:08:25 +00001067 ReduceCrashingFunctions(BD, TestFn).reduceList(Functions, Error);
Chris Lattner73a6bdd2002-11-20 22:28:10 +00001068
Chris Lattnerbeb01fa2005-08-02 02:16:17 +00001069 if (Functions.size() < OldSize)
Rafael Espindola594994a2010-07-28 18:12:30 +00001070 BD.EmitProgressBitcode(BD.getProgram(), "reduced-function");
Chris Lattner73a6bdd2002-11-20 22:28:10 +00001071 }
1072
Daniel Berlin271ca402016-07-27 16:13:25 +00001073 // Attempt to change conditional branches into unconditional branches to
1074 // eliminate blocks.
1075 if (!DisableSimplifyCFG && !BugpointIsInterrupted) {
1076 std::vector<const BasicBlock*> Blocks;
1077 for (Function &F : *BD.getProgram())
1078 for (BasicBlock &BB : F)
1079 Blocks.push_back(&BB);
1080 unsigned OldSize = Blocks.size();
1081 ReduceCrashingConditionals(BD, TestFn, true).reduceList(Blocks, Error);
1082 ReduceCrashingConditionals(BD, TestFn, false).reduceList(Blocks, Error);
1083 if (Blocks.size() < OldSize)
1084 BD.EmitProgressBitcode(BD.getProgram(), "reduced-conditionals");
1085 }
1086
Chris Lattnerf32939b2003-04-24 23:51:38 +00001087 // Attempt to delete entire basic blocks at a time to speed up
1088 // convergence... this actually works by setting the terminator of the blocks
1089 // to a return instruction then running simplifycfg, which can potentially
1090 // shrinks the code dramatically quickly
1091 //
Chris Lattnerbeb01fa2005-08-02 02:16:17 +00001092 if (!DisableSimplifyCFG && !BugpointIsInterrupted) {
Chris Lattner8bda4c42004-02-18 23:26:28 +00001093 std::vector<const BasicBlock*> Blocks;
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +00001094 for (Function &F : *BD.getProgram())
1095 for (BasicBlock &BB : F)
1096 Blocks.push_back(&BB);
Torok Edwin6ee6f732009-05-24 09:40:47 +00001097 unsigned OldSize = Blocks.size();
Nick Lewycky6ba630b2010-04-12 05:08:25 +00001098 ReduceCrashingBlocks(BD, TestFn).reduceList(Blocks, Error);
Torok Edwin6ee6f732009-05-24 09:40:47 +00001099 if (Blocks.size() < OldSize)
Rafael Espindola594994a2010-07-28 18:12:30 +00001100 BD.EmitProgressBitcode(BD.getProgram(), "reduced-blocks");
Chris Lattnerd1e2aae2003-08-05 15:51:05 +00001101 }
Chris Lattnerd4e04742002-12-23 23:49:59 +00001102
Daniel Berlin60606262016-07-28 22:29:25 +00001103 if (!DisableSimplifyCFG & !BugpointIsInterrupted) {
1104 std::vector<const BasicBlock*> Blocks;
1105 for (Function &F : *BD.getProgram())
1106 for (BasicBlock &BB : F)
1107 Blocks.push_back(&BB);
1108 unsigned OldSize = Blocks.size();
1109 ReduceSimplifyCFG(BD, TestFn).reduceList(Blocks, Error);
1110 if (Blocks.size() < OldSize)
1111 BD.EmitProgressBitcode(BD.getProgram(), "reduced-simplifycfg");
1112 }
1113
Nick Lewycky6e090c92009-05-25 05:30:00 +00001114 // Attempt to delete instructions using bisection. This should help out nasty
1115 // cases with large basic blocks where the problem is at one end.
Philip Reames1c232f92016-06-29 00:43:18 +00001116 if (!BugpointIsInterrupted)
1117 ReduceInsts(BD, TestFn, Error);
Keno Fischer34ca8312015-11-06 00:12:50 +00001118
1119 if (!NoNamedMDRM) {
Keno Fischer34ca8312015-11-06 00:12:50 +00001120 if (!BugpointIsInterrupted) {
1121 // Try to reduce the amount of global metadata (particularly debug info),
1122 // by dropping global named metadata that anchors them
1123 outs() << "\n*** Attempting to remove named metadata: ";
1124 std::vector<std::string> NamedMDNames;
1125 for (auto &NamedMD : BD.getProgram()->named_metadata())
1126 NamedMDNames.push_back(NamedMD.getName().str());
1127 ReduceCrashingNamedMD(BD, TestFn).reduceList(NamedMDNames, Error);
1128 }
1129
1130 if (!BugpointIsInterrupted) {
1131 // Now that we quickly dropped all the named metadata that doesn't
1132 // contribute to the crash, bisect the operands of the remaining ones
1133 std::vector<const MDNode *> NamedMDOps;
1134 for (auto &NamedMD : BD.getProgram()->named_metadata())
Keno Fischer256df862015-11-06 00:45:47 +00001135 for (auto op : NamedMD.operands())
1136 NamedMDOps.push_back(op);
Keno Fischer34ca8312015-11-06 00:12:50 +00001137 ReduceCrashingNamedMDOps(BD, TestFn).reduceList(NamedMDOps, Error);
1138 }
Philip Reamesac285cc2016-06-29 00:10:39 +00001139 BD.EmitProgressBitcode(BD.getProgram(), "reduced-named-md");
Keno Fischer34ca8312015-11-06 00:12:50 +00001140 }
1141
Chris Lattner514c02e2003-02-28 16:13:20 +00001142 // Try to clean up the testcase by running funcresolve and globaldce...
Chris Lattnerbeb01fa2005-08-02 02:16:17 +00001143 if (!BugpointIsInterrupted) {
Dan Gohmanee051522009-07-16 15:30:09 +00001144 outs() << "\n*** Attempting to perform final cleanups: ";
Rafael Espindolacab951d2015-12-08 23:57:17 +00001145 Module *M = CloneModule(BD.getProgram()).release();
Rafael Espindola28b351a2014-08-26 17:19:03 +00001146 M = BD.performFinalCleanups(M, true).release();
Misha Brukman650ba8e2005-04-22 00:00:37 +00001147
Chris Lattnerbeb01fa2005-08-02 02:16:17 +00001148 // Find out if the pass still crashes on the cleaned up program...
1149 if (TestFn(BD, M)) {
1150 BD.setNewProgram(M); // Yup, it does, keep the reduced version...
1151 } else {
1152 delete M;
1153 }
Chris Lattner514c02e2003-02-28 16:13:20 +00001154 }
1155
Rafael Espindola594994a2010-07-28 18:12:30 +00001156 BD.EmitProgressBitcode(BD.getProgram(), "reduced-simplified");
Chris Lattner514c02e2003-02-28 16:13:20 +00001157
Misha Brukman650ba8e2005-04-22 00:00:37 +00001158 return false;
Chris Lattner73a6bdd2002-11-20 22:28:10 +00001159}
Brian Gaeke960707c2003-11-11 22:41:34 +00001160
Rafael Espindolad1c7ef42010-08-05 03:00:22 +00001161static bool TestForOptimizerCrash(const BugDriver &BD, Module *M) {
Philip Reamese5b56022016-06-29 03:01:13 +00001162 return BD.runPasses(M, BD.getPassesToRun());
Chris Lattner8bda4c42004-02-18 23:26:28 +00001163}
Chris Lattneread1dff2004-02-18 21:02:04 +00001164
Chris Lattner8bda4c42004-02-18 23:26:28 +00001165/// debugOptimizerCrash - This method is called when some pass crashes on input.
1166/// It attempts to prune down the testcase to something reasonable, and figure
1167/// out exactly which pass is crashing.
1168///
Patrick Jenkinsc46c0382006-08-15 16:40:49 +00001169bool BugDriver::debugOptimizerCrash(const std::string &ID) {
Dan Gohmanee051522009-07-16 15:30:09 +00001170 outs() << "\n*** Debugging optimizer crash!\n";
Chris Lattner8bda4c42004-02-18 23:26:28 +00001171
Nick Lewycky6ba630b2010-04-12 05:08:25 +00001172 std::string Error;
Chris Lattner8bda4c42004-02-18 23:26:28 +00001173 // Reduce the list of passes which causes the optimizer to crash...
JF Bastienf87e20d2015-04-20 23:42:22 +00001174 if (!BugpointIsInterrupted && !DontReducePassList)
Nick Lewycky6ba630b2010-04-12 05:08:25 +00001175 ReducePassList(*this).reduceList(PassesToRun, Error);
1176 assert(Error.empty());
Chris Lattner8bda4c42004-02-18 23:26:28 +00001177
Dan Gohmanee051522009-07-16 15:30:09 +00001178 outs() << "\n*** Found crashing pass"
1179 << (PassesToRun.size() == 1 ? ": " : "es: ")
1180 << getPassesString(PassesToRun) << '\n';
Chris Lattner8bda4c42004-02-18 23:26:28 +00001181
Rafael Espindola594994a2010-07-28 18:12:30 +00001182 EmitProgressBitcode(Program, ID);
Chris Lattner8bda4c42004-02-18 23:26:28 +00001183
Nick Lewycky6ba630b2010-04-12 05:08:25 +00001184 bool Success = DebugACrash(*this, TestForOptimizerCrash, Error);
1185 assert(Error.empty());
1186 return Success;
Chris Lattner8bda4c42004-02-18 23:26:28 +00001187}
1188
Rafael Espindolad1c7ef42010-08-05 03:00:22 +00001189static bool TestForCodeGenCrash(const BugDriver &BD, Module *M) {
Nick Lewycky6ba630b2010-04-12 05:08:25 +00001190 std::string Error;
1191 BD.compileProgram(M, &Error);
1192 if (!Error.empty()) {
Sebastian Pop8f7d0192016-07-15 23:15:06 +00001193 if (VerboseErrors)
1194 errs() << Error << "\n";
1195 else
1196 errs() << "<crash>\n";
Chris Lattner8bda4c42004-02-18 23:26:28 +00001197 return true; // Tool is still crashing.
1198 }
Nick Lewycky6ba630b2010-04-12 05:08:25 +00001199 errs() << '\n';
1200 return false;
Chris Lattner8bda4c42004-02-18 23:26:28 +00001201}
Chris Lattneread1dff2004-02-18 21:02:04 +00001202
1203/// debugCodeGeneratorCrash - This method is called when the code generator
1204/// crashes on an input. It attempts to reduce the input as much as possible
1205/// while still causing the code generator to crash.
Nick Lewycky6ba630b2010-04-12 05:08:25 +00001206bool BugDriver::debugCodeGeneratorCrash(std::string &Error) {
Dan Gohmand8db3762009-07-15 16:35:29 +00001207 errs() << "*** Debugging code generator crash!\n";
Chris Lattneread1dff2004-02-18 21:02:04 +00001208
Nick Lewycky6ba630b2010-04-12 05:08:25 +00001209 return DebugACrash(*this, TestForCodeGenCrash, Error);
Chris Lattneread1dff2004-02-18 21:02:04 +00001210}