blob: c5ceba6f5a67c791db7b4b5351a8be9f0adfa59d [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.
242 if (KeepMain && std::find(Funcs.begin(), Funcs.end(),
243 BD.getProgram()->getFunction("main")) ==
244 Funcs.end())
Andrew Lenharthef9aa122006-03-05 22:21:36 +0000245 return false;
246
Misha Brukman8b2bd4e2003-10-10 17:57:28 +0000247 // Clone the program to try hacking it apart...
Rafael Espindola229e38f2010-10-13 01:36:30 +0000248 ValueToValueMapTy VMap;
Rafael Espindolacab951d2015-12-08 23:57:17 +0000249 Module *M = CloneModule(BD.getProgram(), VMap).release();
Misha Brukman650ba8e2005-04-22 00:00:37 +0000250
Chris Lattner1d080f22003-04-24 22:24:58 +0000251 // Convert list to set for fast lookup...
252 std::set<Function*> Functions;
253 for (unsigned i = 0, e = Funcs.size(); i != e; ++i) {
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000254 Function *CMF = cast<Function>(VMap[Funcs[i]]);
Chris Lattner1d080f22003-04-24 22:24:58 +0000255 assert(CMF && "Function not in module?!");
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000256 assert(CMF->getFunctionType() == Funcs[i]->getFunctionType() && "wrong ty");
Dan Gohmanbcad7182009-03-06 02:16:23 +0000257 assert(CMF->getName() == Funcs[i]->getName() && "wrong name");
Chris Lattnerde39f2b2003-04-24 22:54:06 +0000258 Functions.insert(CMF);
Chris Lattner1d080f22003-04-24 22:24:58 +0000259 }
260
Dan Gohmanee051522009-07-16 15:30:09 +0000261 outs() << "Checking for crash with only these functions: ";
Chris Lattnerfd72bed2004-03-14 20:50:42 +0000262 PrintFunctionList(Funcs);
Dan Gohmanee051522009-07-16 15:30:09 +0000263 outs() << ": ";
JF Bastienf87e20d2015-04-20 23:42:22 +0000264 if (!ReplaceFuncsWithNull) {
265 // Loop over and delete any functions which we aren't supposed to be playing
266 // with...
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000267 for (Function &I : *M)
268 if (!I.isDeclaration() && !Functions.count(&I))
269 DeleteFunctionBody(&I);
JF Bastienf87e20d2015-04-20 23:42:22 +0000270 } else {
271 std::vector<GlobalValue*> ToRemove;
272 // First, remove aliases to functions we're about to purge.
273 for (GlobalAlias &Alias : M->aliases()) {
David Majnemer95549492016-05-04 00:20:48 +0000274 GlobalObject *Root = Alias.getBaseObject();
275 Function *F = dyn_cast_or_null<Function>(Root);
JF Bastienf87e20d2015-04-20 23:42:22 +0000276 if (F) {
277 if (Functions.count(F))
278 // We're keeping this function.
279 continue;
280 } else if (Root->isNullValue()) {
281 // This referenced a globalalias that we've already replaced,
282 // so we still need to replace this alias.
283 } else if (!F) {
284 // Not a function, therefore not something we mess with.
285 continue;
286 }
Chris Lattner1d080f22003-04-24 22:24:58 +0000287
JF Bastienf87e20d2015-04-20 23:42:22 +0000288 PointerType *Ty = cast<PointerType>(Alias.getType());
289 Constant *Replacement = ConstantPointerNull::get(Ty);
290 Alias.replaceAllUsesWith(Replacement);
291 ToRemove.push_back(&Alias);
292 }
Chris Lattner1d080f22003-04-24 22:24:58 +0000293
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000294 for (Function &I : *M) {
295 if (!I.isDeclaration() && !Functions.count(&I)) {
296 PointerType *Ty = cast<PointerType>(I.getType());
JF Bastienf87e20d2015-04-20 23:42:22 +0000297 Constant *Replacement = ConstantPointerNull::get(Ty);
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000298 I.replaceAllUsesWith(Replacement);
299 ToRemove.push_back(&I);
JF Bastienf87e20d2015-04-20 23:42:22 +0000300 }
301 }
302
303 for (auto *F : ToRemove) {
304 F->eraseFromParent();
305 }
306
307 // Finally, remove any null members from any global intrinsic.
308 RemoveFunctionReferences(M, "llvm.used");
309 RemoveFunctionReferences(M, "llvm.compiler.used");
310 }
Chris Lattner1d080f22003-04-24 22:24:58 +0000311 // Try running the hacked up program...
Chris Lattner8bda4c42004-02-18 23:26:28 +0000312 if (TestFn(BD, M)) {
Chris Lattner327019b2004-02-18 21:24:48 +0000313 BD.setNewProgram(M); // It crashed, keep the trimmed version...
Chris Lattner1d080f22003-04-24 22:24:58 +0000314
315 // Make sure to use function pointers that point into the now-current
316 // module.
317 Funcs.assign(Functions.begin(), Functions.end());
318 return true;
319 }
Chris Lattner327019b2004-02-18 21:24:48 +0000320 delete M;
Chris Lattner1d080f22003-04-24 22:24:58 +0000321 return false;
322}
323
Chris Lattner1942f982004-02-18 21:29:46 +0000324namespace {
Daniel Berlin60606262016-07-28 22:29:25 +0000325/// Simplify the CFG without completely destroying it.
326/// This is not well defined, but basically comes down to "try to eliminate
327/// unreachable blocks and constant fold terminators without deciding that
328/// certain undefined behavior cuts off the program at the legs".
329void simpleSimplifyCfg(Function &F, SmallVectorImpl<BasicBlock *> &BBs) {
330 if (F.empty())
331 return;
332
333 for (auto *BB : BBs) {
334 ConstantFoldTerminator(BB);
335 MergeBlockIntoPredecessor(BB);
336 }
337
338 // Remove unreachable blocks
339 // removeUnreachableBlocks can't be used here, it will turn various
340 // undefined behavior into unreachables, but bugpoint was the thing that
341 // generated the undefined behavior, and we don't want it to kill the entire
342 // program.
343 SmallPtrSet<BasicBlock *, 16> Visited;
344 for (auto *BB : depth_first(&F.getEntryBlock()))
345 Visited.insert(BB);
346
347 SmallVector<BasicBlock *, 16> Unreachable;
348 for (auto &BB : F)
349 if (!Visited.count(&BB))
350 Unreachable.push_back(&BB);
351
352 // The dead BB's may be in a dead cycle or otherwise have references to each
353 // other. Because of this, we have to drop all references first, then delete
354 // them all at once.
355 for (auto *BB : Unreachable) {
356 for (BasicBlock *Successor : successors(&*BB))
357 if (Visited.count(Successor))
358 Successor->removePredecessor(&*BB);
359 BB->dropAllReferences();
360 }
361 for (auto *BB : Unreachable)
362 BB->eraseFromParent();
363}
Chris Lattner2f1aa112004-01-14 03:38:37 +0000364 /// ReduceCrashingBlocks reducer - This works by setting the terminators of
365 /// all terminators except the specified basic blocks to a 'ret' instruction,
366 /// then running the simplify-cfg pass. This has the effect of chopping up
367 /// the CFG really fast which can reduce large functions quickly.
368 ///
Chris Lattner8bda4c42004-02-18 23:26:28 +0000369 class ReduceCrashingBlocks : public ListReducer<const BasicBlock*> {
Chris Lattner2f1aa112004-01-14 03:38:37 +0000370 BugDriver &BD;
Rafael Espindolad1c7ef42010-08-05 03:00:22 +0000371 bool (*TestFn)(const BugDriver &, Module *);
Chris Lattner2f1aa112004-01-14 03:38:37 +0000372 public:
Daniel Berlin60606262016-07-28 22:29:25 +0000373 ReduceCrashingBlocks(BugDriver &BD,
Rafael Espindolad1c7ef42010-08-05 03:00:22 +0000374 bool (*testFn)(const BugDriver &, Module *))
Daniel Berlin60606262016-07-28 22:29:25 +0000375 : BD(BD), TestFn(testFn) {}
Misha Brukman650ba8e2005-04-22 00:00:37 +0000376
Craig Toppere56917c2014-03-08 08:27:28 +0000377 TestResult doTest(std::vector<const BasicBlock*> &Prefix,
378 std::vector<const BasicBlock*> &Kept,
379 std::string &Error) override {
Chris Lattner2f1aa112004-01-14 03:38:37 +0000380 if (!Kept.empty() && TestBlocks(Kept))
381 return KeepSuffix;
382 if (!Prefix.empty() && TestBlocks(Prefix))
383 return KeepPrefix;
384 return NoFailure;
385 }
Misha Brukman650ba8e2005-04-22 00:00:37 +0000386
Chris Lattner8bda4c42004-02-18 23:26:28 +0000387 bool TestBlocks(std::vector<const BasicBlock*> &Prefix);
Chris Lattner2f1aa112004-01-14 03:38:37 +0000388 };
389}
Chris Lattnerf32939b2003-04-24 23:51:38 +0000390
Chris Lattner8bda4c42004-02-18 23:26:28 +0000391bool ReduceCrashingBlocks::TestBlocks(std::vector<const BasicBlock*> &BBs) {
Misha Brukman8b2bd4e2003-10-10 17:57:28 +0000392 // Clone the program to try hacking it apart...
Rafael Espindola229e38f2010-10-13 01:36:30 +0000393 ValueToValueMapTy VMap;
Rafael Espindolacab951d2015-12-08 23:57:17 +0000394 Module *M = CloneModule(BD.getProgram(), VMap).release();
Misha Brukman650ba8e2005-04-22 00:00:37 +0000395
Chris Lattnerf32939b2003-04-24 23:51:38 +0000396 // Convert list to set for fast lookup...
Nick Lewyckyb294e312009-04-04 09:39:23 +0000397 SmallPtrSet<BasicBlock*, 8> Blocks;
398 for (unsigned i = 0, e = BBs.size(); i != e; ++i)
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000399 Blocks.insert(cast<BasicBlock>(VMap[BBs[i]]));
Chris Lattnerf32939b2003-04-24 23:51:38 +0000400
Dan Gohmanee051522009-07-16 15:30:09 +0000401 outs() << "Checking for crash with only these blocks:";
Chris Lattner4f50ebd2003-10-27 04:44:59 +0000402 unsigned NumPrint = Blocks.size();
403 if (NumPrint > 10) NumPrint = 10;
404 for (unsigned i = 0, e = NumPrint; i != e; ++i)
Dan Gohmanee051522009-07-16 15:30:09 +0000405 outs() << " " << BBs[i]->getName();
Chris Lattner4f50ebd2003-10-27 04:44:59 +0000406 if (NumPrint < Blocks.size())
Dan Gohmanee051522009-07-16 15:30:09 +0000407 outs() << "... <" << Blocks.size() << " total>";
408 outs() << ": ";
Chris Lattnerf32939b2003-04-24 23:51:38 +0000409
410 // Loop over and delete any hack up any blocks that are not listed...
411 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
412 for (Function::iterator BB = I->begin(), E = I->end(); BB != E; ++BB)
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000413 if (!Blocks.count(&*BB) && BB->getTerminator()->getNumSuccessors()) {
Chris Lattnerf32939b2003-04-24 23:51:38 +0000414 // Loop over all of the successors of this block, deleting any PHI nodes
415 // that might include it.
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000416 for (succ_iterator SI = succ_begin(&*BB), E = succ_end(&*BB); SI != E;
417 ++SI)
418 (*SI)->removePredecessor(&*BB);
Chris Lattnerf32939b2003-04-24 23:51:38 +0000419
Chris Lattner7855a5c2008-04-28 00:04:58 +0000420 TerminatorInst *BBTerm = BB->getTerminator();
Philip Reames29e641c2016-06-29 00:15:35 +0000421 if (BBTerm->isEHPad() || BBTerm->getType()->isTokenTy())
David Majnemer189d7da2015-11-08 04:16:12 +0000422 continue;
Philip Reames29e641c2016-06-29 00:15:35 +0000423 if (!BBTerm->getType()->isVoidTy())
Owen Anderson5a1acd92009-07-31 20:28:14 +0000424 BBTerm->replaceAllUsesWith(Constant::getNullValue(BBTerm->getType()));
Chris Lattner7b233af2003-11-22 02:10:38 +0000425
Chris Lattner7855a5c2008-04-28 00:04:58 +0000426 // Replace the old terminator instruction.
Chris Lattnerf32939b2003-04-24 23:51:38 +0000427 BB->getInstList().pop_back();
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000428 new UnreachableInst(BB->getContext(), &*BB);
Chris Lattnerf32939b2003-04-24 23:51:38 +0000429 }
430
431 // The CFG Simplifier pass may delete one of the basic blocks we are
432 // interested in. If it does we need to take the block out of the list. Make
433 // a "persistent mapping" by turning basic blocks into <function, name> pairs.
434 // This won't work well if blocks are unnamed, but that is just the risk we
435 // have to take.
Rafael Espindolad1e241a2010-08-10 15:46:11 +0000436 std::vector<std::pair<std::string, std::string> > BlockInfo;
Chris Lattnerf32939b2003-04-24 23:51:38 +0000437
Craig Topper46276792014-08-24 23:23:06 +0000438 for (BasicBlock *BB : Blocks)
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000439 BlockInfo.emplace_back(BB->getParent()->getName(), BB->getName());
Daniel Berlin60606262016-07-28 22:29:25 +0000440
441 SmallVector<BasicBlock *, 16> ToProcess;
442 for (auto &F :*M) {
443 for (auto &BB : F)
444 if (!Blocks.count(&BB))
445 ToProcess.push_back(&BB);
446 simpleSimplifyCfg(F, ToProcess);
447 ToProcess.clear();
448 }
449 // Verify we didn't break anything
Rafael Espindolad1e241a2010-08-10 15:46:11 +0000450 std::vector<std::string> Passes;
Rafael Espindolad1e241a2010-08-10 15:46:11 +0000451 Passes.push_back("verify");
Rafael Espindola28b351a2014-08-26 17:19:03 +0000452 std::unique_ptr<Module> New = BD.runPassesOn(M, Passes);
Rafael Espindolad1e241a2010-08-10 15:46:11 +0000453 delete M;
454 if (!New) {
Daniel Berlin60606262016-07-28 22:29:25 +0000455 errs() << "verify failed!\n";
Rafael Espindolad1e241a2010-08-10 15:46:11 +0000456 exit(1);
457 }
Rafael Espindola28b351a2014-08-26 17:19:03 +0000458 M = New.release();
Daniel Berlin60606262016-07-28 22:29:25 +0000459
Chris Lattnerf32939b2003-04-24 23:51:38 +0000460 // Try running on the hacked up program...
Chris Lattner8bda4c42004-02-18 23:26:28 +0000461 if (TestFn(BD, M)) {
Chris Lattner327019b2004-02-18 21:24:48 +0000462 BD.setNewProgram(M); // It crashed, keep the trimmed version...
Chris Lattnerf32939b2003-04-24 23:51:38 +0000463
464 // Make sure to use basic block pointers that point into the now-current
465 // module, and that they don't include any deleted blocks.
466 BBs.clear();
Rafael Espindolad1e241a2010-08-10 15:46:11 +0000467 const ValueSymbolTable &GST = M->getValueSymbolTable();
Chris Lattnerf32939b2003-04-24 23:51:38 +0000468 for (unsigned i = 0, e = BlockInfo.size(); i != e; ++i) {
Rafael Espindolad1e241a2010-08-10 15:46:11 +0000469 Function *F = cast<Function>(GST.lookup(BlockInfo[i].first));
470 ValueSymbolTable &ST = F->getValueSymbolTable();
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000471 Value* V = ST.lookup(BlockInfo[i].second);
Owen Anderson55f1c092009-08-13 21:58:54 +0000472 if (V && V->getType() == Type::getLabelTy(V->getContext()))
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000473 BBs.push_back(cast<BasicBlock>(V));
Chris Lattnerf32939b2003-04-24 23:51:38 +0000474 }
475 return true;
476 }
Chris Lattner327019b2004-02-18 21:24:48 +0000477 delete M; // It didn't crash, try something else.
Chris Lattnerf32939b2003-04-24 23:51:38 +0000478 return false;
479}
480
Nick Lewycky6e090c92009-05-25 05:30:00 +0000481namespace {
Daniel Berlin271ca402016-07-27 16:13:25 +0000482/// ReduceCrashingConditionals reducer - This works by changing
483/// conditional branches to unconditional ones, then simplifying the CFG
484/// This has the effect of chopping up the CFG really fast which can reduce
485/// large functions quickly.
486///
487class ReduceCrashingConditionals : public ListReducer<const BasicBlock *> {
488 BugDriver &BD;
489 bool (*TestFn)(const BugDriver &, Module *);
490 bool Direction;
491
492public:
493 ReduceCrashingConditionals(BugDriver &bd,
494 bool (*testFn)(const BugDriver &, Module *),
495 bool Direction)
496 : BD(bd), TestFn(testFn), Direction(Direction) {}
497
498 TestResult doTest(std::vector<const BasicBlock *> &Prefix,
499 std::vector<const BasicBlock *> &Kept,
500 std::string &Error) override {
501 if (!Kept.empty() && TestBlocks(Kept))
502 return KeepSuffix;
503 if (!Prefix.empty() && TestBlocks(Prefix))
504 return KeepPrefix;
505 return NoFailure;
506 }
507
508 bool TestBlocks(std::vector<const BasicBlock *> &Prefix);
509};
510}
511
512bool ReduceCrashingConditionals::TestBlocks(
513 std::vector<const BasicBlock *> &BBs) {
514 // Clone the program to try hacking it apart...
515 ValueToValueMapTy VMap;
516 Module *M = CloneModule(BD.getProgram(), VMap).release();
517
518 // Convert list to set for fast lookup...
519 SmallPtrSet<const BasicBlock *, 8> Blocks;
520 for (const auto *BB: BBs)
521 Blocks.insert(cast<BasicBlock>(VMap[BB]));
522
523 outs() << "Checking for crash with changing conditionals to always jump to "
524 << (Direction ? "true" : "false") << ":";
525 unsigned NumPrint = Blocks.size();
526 if (NumPrint > 10)
527 NumPrint = 10;
528 for (unsigned i = 0, e = NumPrint; i != e; ++i)
529 outs() << " " << BBs[i]->getName();
530 if (NumPrint < Blocks.size())
531 outs() << "... <" << Blocks.size() << " total>";
532 outs() << ": ";
533
534 // Loop over and delete any hack up any blocks that are not listed...
535 for (auto &F: *M)
536 for (auto &BB : F)
537 if (!Blocks.count(&BB)) {
538 auto *BR = dyn_cast<BranchInst>(BB.getTerminator());
539 if (!BR || !BR->isConditional())
540 continue;
541 if (Direction)
542 BR->setCondition(ConstantInt::getTrue(BR->getContext()));
543 else
544 BR->setCondition(ConstantInt::getFalse(BR->getContext()));
545 }
546
547 // The following may destroy some blocks, so we save them first
548 std::vector<std::pair<std::string, std::string>> BlockInfo;
549
550 for (const BasicBlock *BB : Blocks)
551 BlockInfo.emplace_back(BB->getParent()->getName(), BB->getName());
552
553 SmallVector<BasicBlock *, 16> ToProcess;
554 for (auto &F :*M) {
555 for (auto &BB : F)
556 if (!Blocks.count(&BB))
557 ToProcess.push_back(&BB);
558 simpleSimplifyCfg(F, ToProcess);
559 ToProcess.clear();
560 }
561 // Verify we didn't break anything
562 std::vector<std::string> Passes;
563 Passes.push_back("verify");
564 std::unique_ptr<Module> New = BD.runPassesOn(M, Passes);
565 delete M;
566 if (!New) {
567 errs() << "verify failed!\n";
568 exit(1);
569 }
570 M = New.release();
571
572 // Try running on the hacked up program...
573 if (TestFn(BD, M)) {
574 BD.setNewProgram(M); // It crashed, keep the trimmed version...
575
576 // Make sure to use basic block pointers that point into the now-current
577 // module, and that they don't include any deleted blocks.
578 BBs.clear();
579 const ValueSymbolTable &GST = M->getValueSymbolTable();
580 for (auto &BI : BlockInfo) {
581 auto *F = cast<Function>(GST.lookup(BI.first));
582 ValueSymbolTable &ST = F->getValueSymbolTable();
583 Value *V = ST.lookup(BI.second);
584 if (V && V->getType() == Type::getLabelTy(V->getContext()))
585 BBs.push_back(cast<BasicBlock>(V));
586 }
587 return true;
588 }
589 delete M; // It didn't crash, try something else.
590 return false;
591}
592
593namespace {
Daniel Berlin60606262016-07-28 22:29:25 +0000594/// SimplifyCFG reducer - This works by calling SimplifyCFG on each basic block
595/// in the program.
596
597class ReduceSimplifyCFG : public ListReducer<const BasicBlock *> {
598 BugDriver &BD;
599 bool (*TestFn)(const BugDriver &, Module *);
600 TargetTransformInfo TTI;
601
602public:
603 ReduceSimplifyCFG(BugDriver &bd,
604 bool (*testFn)(const BugDriver &, Module *))
605 : BD(bd), TestFn(testFn), TTI(bd.getProgram()->getDataLayout())
606 {}
607
608 TestResult doTest(std::vector<const BasicBlock *> &Prefix,
609 std::vector<const BasicBlock *> &Kept,
610 std::string &Error) override {
611 if (!Kept.empty() && TestBlocks(Kept))
612 return KeepSuffix;
613 if (!Prefix.empty() && TestBlocks(Prefix))
614 return KeepPrefix;
615 return NoFailure;
616 }
617
618 bool TestBlocks(std::vector<const BasicBlock *> &Prefix);
619};
620}
621
622bool ReduceSimplifyCFG::TestBlocks(
623 std::vector<const BasicBlock *> &BBs) {
624 // Clone the program to try hacking it apart...
625 ValueToValueMapTy VMap;
626 Module *M = CloneModule(BD.getProgram(), VMap).release();
627
628 // Convert list to set for fast lookup...
629 SmallPtrSet<const BasicBlock *, 8> Blocks;
630 for (const auto *BB: BBs)
631 Blocks.insert(cast<BasicBlock>(VMap[BB]));
632
633 outs() << "Checking for crash with CFG simplifying:";
634 unsigned NumPrint = Blocks.size();
635 if (NumPrint > 10)
636 NumPrint = 10;
637 for (unsigned i = 0, e = NumPrint; i != e; ++i)
638 outs() << " " << BBs[i]->getName();
639 if (NumPrint < Blocks.size())
640 outs() << "... <" << Blocks.size() << " total>";
641 outs() << ": ";
642
643 // The following may destroy some blocks, so we save them first
644 std::vector<std::pair<std::string, std::string>> BlockInfo;
645
646 for (const BasicBlock *BB : Blocks)
647 BlockInfo.emplace_back(BB->getParent()->getName(), BB->getName());
648
649
650 // Loop over and delete any hack up any blocks that are not listed...
651 for (auto &F: *M)
652 // Loop over all of the basic blocks and remove them if they are unneeded.
653 for (Function::iterator BBIt = F.begin(); BBIt != F.end(); ) {
654 if (!Blocks.count(&*BBIt)) {
655 ++BBIt;
656 continue;
657 }
658 SimplifyCFG(&*BBIt++, TTI, 1);
659 }
660 // Verify we didn't break anything
661 std::vector<std::string> Passes;
662 Passes.push_back("verify");
663 std::unique_ptr<Module> New = BD.runPassesOn(M, Passes);
664 delete M;
665 if (!New) {
666 errs() << "verify failed!\n";
667 exit(1);
668 }
669 M = New.release();
670
671 // Try running on the hacked up program...
672 if (TestFn(BD, M)) {
673 BD.setNewProgram(M); // It crashed, keep the trimmed version...
674
675 // Make sure to use basic block pointers that point into the now-current
676 // module, and that they don't include any deleted blocks.
677 BBs.clear();
678 const ValueSymbolTable &GST = M->getValueSymbolTable();
679 for (auto &BI : BlockInfo){
680 auto *F = cast<Function>(GST.lookup(BI.first));
681 ValueSymbolTable &ST = F->getValueSymbolTable();
682 Value *V = ST.lookup(BI.second);
683 if (V && V->getType() == Type::getLabelTy(V->getContext()))
684 BBs.push_back(cast<BasicBlock>(V));
685 }
686 return true;
687 }
688 delete M; // It didn't crash, try something else.
689 return false;
690}
691
692namespace {
Nick Lewycky6e090c92009-05-25 05:30:00 +0000693 /// ReduceCrashingInstructions reducer - This works by removing the specified
694 /// non-terminator instructions and replacing them with undef.
695 ///
696 class ReduceCrashingInstructions : public ListReducer<const Instruction*> {
697 BugDriver &BD;
Rafael Espindolad1c7ef42010-08-05 03:00:22 +0000698 bool (*TestFn)(const BugDriver &, Module *);
Nick Lewycky6e090c92009-05-25 05:30:00 +0000699 public:
Rafael Espindolad1c7ef42010-08-05 03:00:22 +0000700 ReduceCrashingInstructions(BugDriver &bd,
701 bool (*testFn)(const BugDriver &, Module *))
Nick Lewycky6e090c92009-05-25 05:30:00 +0000702 : BD(bd), TestFn(testFn) {}
703
Craig Toppere56917c2014-03-08 08:27:28 +0000704 TestResult doTest(std::vector<const Instruction*> &Prefix,
705 std::vector<const Instruction*> &Kept,
706 std::string &Error) override {
Nick Lewycky6e090c92009-05-25 05:30:00 +0000707 if (!Kept.empty() && TestInsts(Kept))
708 return KeepSuffix;
709 if (!Prefix.empty() && TestInsts(Prefix))
710 return KeepPrefix;
711 return NoFailure;
712 }
713
714 bool TestInsts(std::vector<const Instruction*> &Prefix);
715 };
716}
717
718bool ReduceCrashingInstructions::TestInsts(std::vector<const Instruction*>
719 &Insts) {
720 // Clone the program to try hacking it apart...
Rafael Espindola229e38f2010-10-13 01:36:30 +0000721 ValueToValueMapTy VMap;
Rafael Espindolacab951d2015-12-08 23:57:17 +0000722 Module *M = CloneModule(BD.getProgram(), VMap).release();
Nick Lewycky6e090c92009-05-25 05:30:00 +0000723
724 // Convert list to set for fast lookup...
Matthias Braunb30f2f512016-01-30 01:24:31 +0000725 SmallPtrSet<Instruction*, 32> Instructions;
Nick Lewycky6e090c92009-05-25 05:30:00 +0000726 for (unsigned i = 0, e = Insts.size(); i != e; ++i) {
727 assert(!isa<TerminatorInst>(Insts[i]));
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000728 Instructions.insert(cast<Instruction>(VMap[Insts[i]]));
Nick Lewycky6e090c92009-05-25 05:30:00 +0000729 }
730
Dan Gohmanee051522009-07-16 15:30:09 +0000731 outs() << "Checking for crash with only " << Instructions.size();
Nick Lewycky6e090c92009-05-25 05:30:00 +0000732 if (Instructions.size() == 1)
Dan Gohmanee051522009-07-16 15:30:09 +0000733 outs() << " instruction: ";
Nick Lewycky6e090c92009-05-25 05:30:00 +0000734 else
Dan Gohmanee051522009-07-16 15:30:09 +0000735 outs() << " instructions: ";
Nick Lewycky6e090c92009-05-25 05:30:00 +0000736
737 for (Module::iterator MI = M->begin(), ME = M->end(); MI != ME; ++MI)
738 for (Function::iterator FI = MI->begin(), FE = MI->end(); FI != FE; ++FI)
739 for (BasicBlock::iterator I = FI->begin(), E = FI->end(); I != E;) {
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000740 Instruction *Inst = &*I++;
Eli Friedmand4e02a52011-11-01 04:40:56 +0000741 if (!Instructions.count(Inst) && !isa<TerminatorInst>(Inst) &&
Philip Reames29e641c2016-06-29 00:15:35 +0000742 !Inst->isEHPad() && !Inst->getType()->isTokenTy()) {
743 if (!Inst->getType()->isVoidTy())
Nick Lewycky6e090c92009-05-25 05:30:00 +0000744 Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
745 Inst->eraseFromParent();
746 }
747 }
748
749 // Verify that this is still valid.
Chandler Carruth30d69c22015-02-13 10:01:29 +0000750 legacy::PassManager Passes;
Nick Lewycky6e090c92009-05-25 05:30:00 +0000751 Passes.add(createVerifierPass());
752 Passes.run(*M);
753
754 // Try running on the hacked up program...
755 if (TestFn(BD, M)) {
756 BD.setNewProgram(M); // It crashed, keep the trimmed version...
757
758 // Make sure to use instruction pointers that point into the now-current
759 // module, and that they don't include any deleted blocks.
760 Insts.clear();
Craig Topper46276792014-08-24 23:23:06 +0000761 for (Instruction *Inst : Instructions)
762 Insts.push_back(Inst);
Nick Lewycky6e090c92009-05-25 05:30:00 +0000763 return true;
764 }
765 delete M; // It didn't crash, try something else.
766 return false;
767}
768
Keno Fischer34ca8312015-11-06 00:12:50 +0000769namespace {
770// Reduce the list of Named Metadata nodes. We keep this as a list of
771// names to avoid having to convert back and forth every time.
772class ReduceCrashingNamedMD : public ListReducer<std::string> {
773 BugDriver &BD;
774 bool (*TestFn)(const BugDriver &, Module *);
775
776public:
777 ReduceCrashingNamedMD(BugDriver &bd,
778 bool (*testFn)(const BugDriver &, Module *))
779 : BD(bd), TestFn(testFn) {}
780
781 TestResult doTest(std::vector<std::string> &Prefix,
782 std::vector<std::string> &Kept,
783 std::string &Error) override {
784 if (!Kept.empty() && TestNamedMDs(Kept))
785 return KeepSuffix;
786 if (!Prefix.empty() && TestNamedMDs(Prefix))
787 return KeepPrefix;
788 return NoFailure;
789 }
790
791 bool TestNamedMDs(std::vector<std::string> &NamedMDs);
792};
793}
794
795bool ReduceCrashingNamedMD::TestNamedMDs(std::vector<std::string> &NamedMDs) {
796
797 ValueToValueMapTy VMap;
Rafael Espindolacab951d2015-12-08 23:57:17 +0000798 Module *M = CloneModule(BD.getProgram(), VMap).release();
Keno Fischer34ca8312015-11-06 00:12:50 +0000799
800 outs() << "Checking for crash with only these named metadata nodes:";
801 unsigned NumPrint = std::min<size_t>(NamedMDs.size(), 10);
802 for (unsigned i = 0, e = NumPrint; i != e; ++i)
803 outs() << " " << NamedMDs[i];
804 if (NumPrint < NamedMDs.size())
805 outs() << "... <" << NamedMDs.size() << " total>";
806 outs() << ": ";
807
808 // Make a StringMap for faster lookup
809 StringSet<> Names;
810 for (const std::string &Name : NamedMDs)
811 Names.insert(Name);
812
813 // First collect all the metadata to delete in a vector, then
814 // delete them all at once to avoid invalidating the iterator
815 std::vector<NamedMDNode *> ToDelete;
816 ToDelete.reserve(M->named_metadata_size() - Names.size());
817 for (auto &NamedMD : M->named_metadata())
Adrian Prantlfaebbb02016-03-28 21:06:26 +0000818 // Always keep a nonempty llvm.dbg.cu because the Verifier would complain.
819 if (!Names.count(NamedMD.getName()) &&
820 (!(NamedMD.getName() == "llvm.dbg.cu" && NamedMD.getNumOperands() > 0)))
Keno Fischer34ca8312015-11-06 00:12:50 +0000821 ToDelete.push_back(&NamedMD);
822
823 for (auto *NamedMD : ToDelete)
824 NamedMD->eraseFromParent();
825
826 // Verify that this is still valid.
827 legacy::PassManager Passes;
828 Passes.add(createVerifierPass());
829 Passes.run(*M);
830
831 // Try running on the hacked up program...
832 if (TestFn(BD, M)) {
833 BD.setNewProgram(M); // It crashed, keep the trimmed version...
834 return true;
835 }
836 delete M; // It didn't crash, try something else.
837 return false;
838}
839
840namespace {
841// Reduce the list of operands to named metadata nodes
842class ReduceCrashingNamedMDOps : public ListReducer<const MDNode *> {
843 BugDriver &BD;
844 bool (*TestFn)(const BugDriver &, Module *);
845
846public:
847 ReduceCrashingNamedMDOps(BugDriver &bd,
848 bool (*testFn)(const BugDriver &, Module *))
849 : BD(bd), TestFn(testFn) {}
850
851 TestResult doTest(std::vector<const MDNode *> &Prefix,
852 std::vector<const MDNode *> &Kept,
853 std::string &Error) override {
854 if (!Kept.empty() && TestNamedMDOps(Kept))
855 return KeepSuffix;
856 if (!Prefix.empty() && TestNamedMDOps(Prefix))
857 return KeepPrefix;
858 return NoFailure;
859 }
860
861 bool TestNamedMDOps(std::vector<const MDNode *> &NamedMDOps);
862};
863}
864
865bool ReduceCrashingNamedMDOps::TestNamedMDOps(
866 std::vector<const MDNode *> &NamedMDOps) {
867 // Convert list to set for fast lookup...
Matthias Braunb30f2f512016-01-30 01:24:31 +0000868 SmallPtrSet<const MDNode *, 32> OldMDNodeOps;
Keno Fischer34ca8312015-11-06 00:12:50 +0000869 for (unsigned i = 0, e = NamedMDOps.size(); i != e; ++i) {
870 OldMDNodeOps.insert(NamedMDOps[i]);
871 }
872
873 outs() << "Checking for crash with only " << OldMDNodeOps.size();
874 if (OldMDNodeOps.size() == 1)
875 outs() << " named metadata operand: ";
876 else
877 outs() << " named metadata operands: ";
878
879 ValueToValueMapTy VMap;
Rafael Espindolacab951d2015-12-08 23:57:17 +0000880 Module *M = CloneModule(BD.getProgram(), VMap).release();
Keno Fischer34ca8312015-11-06 00:12:50 +0000881
882 // This is a little wasteful. In the future it might be good if we could have
883 // these dropped during cloning.
884 for (auto &NamedMD : BD.getProgram()->named_metadata()) {
885 // Drop the old one and create a new one
886 M->eraseNamedMetadata(M->getNamedMetadata(NamedMD.getName()));
887 NamedMDNode *NewNamedMDNode =
888 M->getOrInsertNamedMetadata(NamedMD.getName());
889 for (MDNode *op : NamedMD.operands())
890 if (OldMDNodeOps.count(op))
891 NewNamedMDNode->addOperand(cast<MDNode>(MapMetadata(op, VMap)));
892 }
893
894 // Verify that this is still valid.
895 legacy::PassManager Passes;
896 Passes.add(createVerifierPass());
897 Passes.run(*M);
898
899 // Try running on the hacked up program...
900 if (TestFn(BD, M)) {
901 // Make sure to use instruction pointers that point into the now-current
902 // module, and that they don't include any deleted blocks.
903 NamedMDOps.clear();
904 for (const MDNode *Node : OldMDNodeOps)
Duncan P. N. Exon Smithda4a56d2016-04-02 17:04:38 +0000905 NamedMDOps.push_back(cast<MDNode>(*VMap.getMappedMD(Node)));
Keno Fischer34ca8312015-11-06 00:12:50 +0000906
907 BD.setNewProgram(M); // It crashed, keep the trimmed version...
908 return true;
909 }
910 delete M; // It didn't crash, try something else.
911 return false;
912}
913
Philip Reames1c232f92016-06-29 00:43:18 +0000914static void ReduceGlobalInitializers(BugDriver &BD,
915 bool (*TestFn)(const BugDriver &, Module *),
916 std::string &Error) {
917 if (BD.getProgram()->global_begin() != BD.getProgram()->global_end()) {
Bill Wendling3f833432006-10-25 18:36:14 +0000918 // Now try to reduce the number of global variable initializers in the
919 // module to something small.
Rafael Espindolacab951d2015-12-08 23:57:17 +0000920 Module *M = CloneModule(BD.getProgram()).release();
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000921 bool DeletedInit = false;
Misha Brukman650ba8e2005-04-22 00:00:37 +0000922
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000923 for (Module::global_iterator I = M->global_begin(), E = M->global_end();
924 I != E; ++I)
925 if (I->hasInitializer()) {
Hal Finkel28ad2b42015-11-26 19:23:49 +0000926 DeleteGlobalInitializer(&*I);
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000927 I->setLinkage(GlobalValue::ExternalLinkage);
Justin Lebar2a445cf2016-06-15 23:20:12 +0000928 I->setComdat(nullptr);
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000929 DeletedInit = true;
930 }
Bill Wendling3f833432006-10-25 18:36:14 +0000931
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000932 if (!DeletedInit) {
933 delete M; // No change made...
934 } else {
935 // See if the program still causes a crash...
Dan Gohmanee051522009-07-16 15:30:09 +0000936 outs() << "\nChecking to see if we can delete global inits: ";
Bill Wendling3f833432006-10-25 18:36:14 +0000937
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000938 if (TestFn(BD, M)) { // Still crashes?
939 BD.setNewProgram(M);
Dan Gohmanee051522009-07-16 15:30:09 +0000940 outs() << "\n*** Able to remove all global initializers!\n";
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000941 } else { // No longer crashes?
Dan Gohmanee051522009-07-16 15:30:09 +0000942 outs() << " - Removing all global inits hides problem!\n";
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000943 delete M;
Bill Wendling3f833432006-10-25 18:36:14 +0000944
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000945 std::vector<GlobalVariable*> GVs;
946
947 for (Module::global_iterator I = BD.getProgram()->global_begin(),
948 E = BD.getProgram()->global_end(); I != E; ++I)
949 if (I->hasInitializer())
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000950 GVs.push_back(&*I);
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000951
952 if (GVs.size() > 1 && !BugpointIsInterrupted) {
Dan Gohmanee051522009-07-16 15:30:09 +0000953 outs() << "\n*** Attempting to reduce the number of global "
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000954 << "variables in the testcase\n";
955
956 unsigned OldSize = GVs.size();
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000957 ReduceCrashingGlobalVariables(BD, TestFn).reduceList(GVs, Error);
Philip Reames1c232f92016-06-29 00:43:18 +0000958 assert(!Error.empty());
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000959
960 if (GVs.size() < OldSize)
Rafael Espindola594994a2010-07-28 18:12:30 +0000961 BD.EmitProgressBitcode(BD.getProgram(), "reduced-global-variables");
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000962 }
Bill Wendlingce3afd62006-10-27 20:22:04 +0000963 }
Chris Lattner65e5f652003-04-25 00:53:05 +0000964 }
965 }
Philip Reames1c232f92016-06-29 00:43:18 +0000966}
967
968static void ReduceInsts(BugDriver &BD,
969 bool (*TestFn)(const BugDriver &, Module *),
970 std::string &Error) {
971 // Attempt to delete instructions using bisection. This should help out nasty
972 // cases with large basic blocks where the problem is at one end.
973 if (!BugpointIsInterrupted) {
974 std::vector<const Instruction*> Insts;
975 for (const Function &F : *BD.getProgram())
976 for (const BasicBlock &BB : F)
977 for (const Instruction &I : BB)
978 if (!isa<TerminatorInst>(&I))
979 Insts.push_back(&I);
980
981 ReduceCrashingInstructions(BD, TestFn).reduceList(Insts, Error);
982 }
983
984 unsigned Simplification = 2;
985 do {
986 if (BugpointIsInterrupted)
987 return;
988 --Simplification;
989 outs() << "\n*** Attempting to reduce testcase by deleting instruc"
990 << "tions: Simplification Level #" << Simplification << '\n';
991
992 // Now that we have deleted the functions that are unnecessary for the
993 // program, try to remove instructions that are not necessary to cause the
994 // crash. To do this, we loop through all of the instructions in the
995 // remaining functions, deleting them (replacing any values produced with
996 // nulls), and then running ADCE and SimplifyCFG. If the transformed input
997 // still triggers failure, keep deleting until we cannot trigger failure
998 // anymore.
999 //
1000 unsigned InstructionsToSkipBeforeDeleting = 0;
1001 TryAgain:
1002
1003 // Loop over all of the (non-terminator) instructions remaining in the
1004 // function, attempting to delete them.
1005 unsigned CurInstructionNum = 0;
1006 for (Module::const_iterator FI = BD.getProgram()->begin(),
1007 E = BD.getProgram()->end(); FI != E; ++FI)
1008 if (!FI->isDeclaration())
1009 for (Function::const_iterator BI = FI->begin(), E = FI->end(); BI != E;
1010 ++BI)
1011 for (BasicBlock::const_iterator I = BI->begin(), E = --BI->end();
1012 I != E; ++I, ++CurInstructionNum) {
1013 if (InstructionsToSkipBeforeDeleting) {
1014 --InstructionsToSkipBeforeDeleting;
1015 } else {
1016 if (BugpointIsInterrupted)
1017 return;
1018
1019 if (I->isEHPad() || I->getType()->isTokenTy())
1020 continue;
1021
1022 outs() << "Checking instruction: " << *I;
1023 std::unique_ptr<Module> M =
1024 BD.deleteInstructionFromProgram(&*I, Simplification);
1025
1026 // Find out if the pass still crashes on this pass...
1027 if (TestFn(BD, M.get())) {
1028 // Yup, it does, we delete the old module, and continue trying
1029 // to reduce the testcase...
1030 BD.setNewProgram(M.release());
1031 InstructionsToSkipBeforeDeleting = CurInstructionNum;
1032 goto TryAgain; // I wish I had a multi-level break here!
1033 }
1034 }
1035 }
1036
1037 if (InstructionsToSkipBeforeDeleting) {
1038 InstructionsToSkipBeforeDeleting = 0;
1039 goto TryAgain;
1040 }
1041
1042 } while (Simplification);
1043 BD.EmitProgressBitcode(BD.getProgram(), "reduced-instructions");
1044}
1045
1046
1047/// DebugACrash - Given a predicate that determines whether a component crashes
1048/// on a program, try to destructively reduce the program while still keeping
1049/// the predicate true.
1050static bool DebugACrash(BugDriver &BD,
1051 bool (*TestFn)(const BugDriver &, Module *),
1052 std::string &Error) {
1053 // See if we can get away with nuking some of the global variable initializers
1054 // in the program...
1055 if (!NoGlobalRM)
1056 ReduceGlobalInitializers(BD, TestFn, Error);
Misha Brukman650ba8e2005-04-22 00:00:37 +00001057
Chris Lattner1d080f22003-04-24 22:24:58 +00001058 // Now try to reduce the number of functions in the module to something small.
Chris Lattnerfd72bed2004-03-14 20:50:42 +00001059 std::vector<Function*> Functions;
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +00001060 for (Function &F : *BD.getProgram())
1061 if (!F.isDeclaration())
1062 Functions.push_back(&F);
Chris Lattner73a6bdd2002-11-20 22:28:10 +00001063
Chris Lattnerbeb01fa2005-08-02 02:16:17 +00001064 if (Functions.size() > 1 && !BugpointIsInterrupted) {
Dan Gohmanee051522009-07-16 15:30:09 +00001065 outs() << "\n*** Attempting to reduce the number of functions "
Chris Lattner1d080f22003-04-24 22:24:58 +00001066 "in the testcase\n";
Chris Lattner73a6bdd2002-11-20 22:28:10 +00001067
Chris Lattner8bda4c42004-02-18 23:26:28 +00001068 unsigned OldSize = Functions.size();
Nick Lewycky6ba630b2010-04-12 05:08:25 +00001069 ReduceCrashingFunctions(BD, TestFn).reduceList(Functions, Error);
Chris Lattner73a6bdd2002-11-20 22:28:10 +00001070
Chris Lattnerbeb01fa2005-08-02 02:16:17 +00001071 if (Functions.size() < OldSize)
Rafael Espindola594994a2010-07-28 18:12:30 +00001072 BD.EmitProgressBitcode(BD.getProgram(), "reduced-function");
Chris Lattner73a6bdd2002-11-20 22:28:10 +00001073 }
1074
Daniel Berlin271ca402016-07-27 16:13:25 +00001075 // Attempt to change conditional branches into unconditional branches to
1076 // eliminate blocks.
1077 if (!DisableSimplifyCFG && !BugpointIsInterrupted) {
1078 std::vector<const BasicBlock*> Blocks;
1079 for (Function &F : *BD.getProgram())
1080 for (BasicBlock &BB : F)
1081 Blocks.push_back(&BB);
1082 unsigned OldSize = Blocks.size();
1083 ReduceCrashingConditionals(BD, TestFn, true).reduceList(Blocks, Error);
1084 ReduceCrashingConditionals(BD, TestFn, false).reduceList(Blocks, Error);
1085 if (Blocks.size() < OldSize)
1086 BD.EmitProgressBitcode(BD.getProgram(), "reduced-conditionals");
1087 }
1088
Chris Lattnerf32939b2003-04-24 23:51:38 +00001089 // Attempt to delete entire basic blocks at a time to speed up
1090 // convergence... this actually works by setting the terminator of the blocks
1091 // to a return instruction then running simplifycfg, which can potentially
1092 // shrinks the code dramatically quickly
1093 //
Chris Lattnerbeb01fa2005-08-02 02:16:17 +00001094 if (!DisableSimplifyCFG && !BugpointIsInterrupted) {
Chris Lattner8bda4c42004-02-18 23:26:28 +00001095 std::vector<const BasicBlock*> Blocks;
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +00001096 for (Function &F : *BD.getProgram())
1097 for (BasicBlock &BB : F)
1098 Blocks.push_back(&BB);
Torok Edwin6ee6f732009-05-24 09:40:47 +00001099 unsigned OldSize = Blocks.size();
Nick Lewycky6ba630b2010-04-12 05:08:25 +00001100 ReduceCrashingBlocks(BD, TestFn).reduceList(Blocks, Error);
Torok Edwin6ee6f732009-05-24 09:40:47 +00001101 if (Blocks.size() < OldSize)
Rafael Espindola594994a2010-07-28 18:12:30 +00001102 BD.EmitProgressBitcode(BD.getProgram(), "reduced-blocks");
Chris Lattnerd1e2aae2003-08-05 15:51:05 +00001103 }
Chris Lattnerd4e04742002-12-23 23:49:59 +00001104
Daniel Berlin60606262016-07-28 22:29:25 +00001105 if (!DisableSimplifyCFG & !BugpointIsInterrupted) {
1106 std::vector<const BasicBlock*> Blocks;
1107 for (Function &F : *BD.getProgram())
1108 for (BasicBlock &BB : F)
1109 Blocks.push_back(&BB);
1110 unsigned OldSize = Blocks.size();
1111 ReduceSimplifyCFG(BD, TestFn).reduceList(Blocks, Error);
1112 if (Blocks.size() < OldSize)
1113 BD.EmitProgressBitcode(BD.getProgram(), "reduced-simplifycfg");
1114 }
1115
Nick Lewycky6e090c92009-05-25 05:30:00 +00001116 // Attempt to delete instructions using bisection. This should help out nasty
1117 // cases with large basic blocks where the problem is at one end.
Philip Reames1c232f92016-06-29 00:43:18 +00001118 if (!BugpointIsInterrupted)
1119 ReduceInsts(BD, TestFn, Error);
Keno Fischer34ca8312015-11-06 00:12:50 +00001120
1121 if (!NoNamedMDRM) {
Keno Fischer34ca8312015-11-06 00:12:50 +00001122 if (!BugpointIsInterrupted) {
1123 // Try to reduce the amount of global metadata (particularly debug info),
1124 // by dropping global named metadata that anchors them
1125 outs() << "\n*** Attempting to remove named metadata: ";
1126 std::vector<std::string> NamedMDNames;
1127 for (auto &NamedMD : BD.getProgram()->named_metadata())
1128 NamedMDNames.push_back(NamedMD.getName().str());
1129 ReduceCrashingNamedMD(BD, TestFn).reduceList(NamedMDNames, Error);
1130 }
1131
1132 if (!BugpointIsInterrupted) {
1133 // Now that we quickly dropped all the named metadata that doesn't
1134 // contribute to the crash, bisect the operands of the remaining ones
1135 std::vector<const MDNode *> NamedMDOps;
1136 for (auto &NamedMD : BD.getProgram()->named_metadata())
Keno Fischer256df862015-11-06 00:45:47 +00001137 for (auto op : NamedMD.operands())
1138 NamedMDOps.push_back(op);
Keno Fischer34ca8312015-11-06 00:12:50 +00001139 ReduceCrashingNamedMDOps(BD, TestFn).reduceList(NamedMDOps, Error);
1140 }
Philip Reamesac285cc2016-06-29 00:10:39 +00001141 BD.EmitProgressBitcode(BD.getProgram(), "reduced-named-md");
Keno Fischer34ca8312015-11-06 00:12:50 +00001142 }
1143
Chris Lattner514c02e2003-02-28 16:13:20 +00001144 // Try to clean up the testcase by running funcresolve and globaldce...
Chris Lattnerbeb01fa2005-08-02 02:16:17 +00001145 if (!BugpointIsInterrupted) {
Dan Gohmanee051522009-07-16 15:30:09 +00001146 outs() << "\n*** Attempting to perform final cleanups: ";
Rafael Espindolacab951d2015-12-08 23:57:17 +00001147 Module *M = CloneModule(BD.getProgram()).release();
Rafael Espindola28b351a2014-08-26 17:19:03 +00001148 M = BD.performFinalCleanups(M, true).release();
Misha Brukman650ba8e2005-04-22 00:00:37 +00001149
Chris Lattnerbeb01fa2005-08-02 02:16:17 +00001150 // Find out if the pass still crashes on the cleaned up program...
1151 if (TestFn(BD, M)) {
1152 BD.setNewProgram(M); // Yup, it does, keep the reduced version...
1153 } else {
1154 delete M;
1155 }
Chris Lattner514c02e2003-02-28 16:13:20 +00001156 }
1157
Rafael Espindola594994a2010-07-28 18:12:30 +00001158 BD.EmitProgressBitcode(BD.getProgram(), "reduced-simplified");
Chris Lattner514c02e2003-02-28 16:13:20 +00001159
Misha Brukman650ba8e2005-04-22 00:00:37 +00001160 return false;
Chris Lattner73a6bdd2002-11-20 22:28:10 +00001161}
Brian Gaeke960707c2003-11-11 22:41:34 +00001162
Rafael Espindolad1c7ef42010-08-05 03:00:22 +00001163static bool TestForOptimizerCrash(const BugDriver &BD, Module *M) {
Philip Reamese5b56022016-06-29 03:01:13 +00001164 return BD.runPasses(M, BD.getPassesToRun());
Chris Lattner8bda4c42004-02-18 23:26:28 +00001165}
Chris Lattneread1dff2004-02-18 21:02:04 +00001166
Chris Lattner8bda4c42004-02-18 23:26:28 +00001167/// debugOptimizerCrash - This method is called when some pass crashes on input.
1168/// It attempts to prune down the testcase to something reasonable, and figure
1169/// out exactly which pass is crashing.
1170///
Patrick Jenkinsc46c0382006-08-15 16:40:49 +00001171bool BugDriver::debugOptimizerCrash(const std::string &ID) {
Dan Gohmanee051522009-07-16 15:30:09 +00001172 outs() << "\n*** Debugging optimizer crash!\n";
Chris Lattner8bda4c42004-02-18 23:26:28 +00001173
Nick Lewycky6ba630b2010-04-12 05:08:25 +00001174 std::string Error;
Chris Lattner8bda4c42004-02-18 23:26:28 +00001175 // Reduce the list of passes which causes the optimizer to crash...
JF Bastienf87e20d2015-04-20 23:42:22 +00001176 if (!BugpointIsInterrupted && !DontReducePassList)
Nick Lewycky6ba630b2010-04-12 05:08:25 +00001177 ReducePassList(*this).reduceList(PassesToRun, Error);
1178 assert(Error.empty());
Chris Lattner8bda4c42004-02-18 23:26:28 +00001179
Dan Gohmanee051522009-07-16 15:30:09 +00001180 outs() << "\n*** Found crashing pass"
1181 << (PassesToRun.size() == 1 ? ": " : "es: ")
1182 << getPassesString(PassesToRun) << '\n';
Chris Lattner8bda4c42004-02-18 23:26:28 +00001183
Rafael Espindola594994a2010-07-28 18:12:30 +00001184 EmitProgressBitcode(Program, ID);
Chris Lattner8bda4c42004-02-18 23:26:28 +00001185
Nick Lewycky6ba630b2010-04-12 05:08:25 +00001186 bool Success = DebugACrash(*this, TestForOptimizerCrash, Error);
1187 assert(Error.empty());
1188 return Success;
Chris Lattner8bda4c42004-02-18 23:26:28 +00001189}
1190
Rafael Espindolad1c7ef42010-08-05 03:00:22 +00001191static bool TestForCodeGenCrash(const BugDriver &BD, Module *M) {
Nick Lewycky6ba630b2010-04-12 05:08:25 +00001192 std::string Error;
1193 BD.compileProgram(M, &Error);
1194 if (!Error.empty()) {
Sebastian Pop8f7d0192016-07-15 23:15:06 +00001195 if (VerboseErrors)
1196 errs() << Error << "\n";
1197 else
1198 errs() << "<crash>\n";
Chris Lattner8bda4c42004-02-18 23:26:28 +00001199 return true; // Tool is still crashing.
1200 }
Nick Lewycky6ba630b2010-04-12 05:08:25 +00001201 errs() << '\n';
1202 return false;
Chris Lattner8bda4c42004-02-18 23:26:28 +00001203}
Chris Lattneread1dff2004-02-18 21:02:04 +00001204
1205/// debugCodeGeneratorCrash - This method is called when the code generator
1206/// crashes on an input. It attempts to reduce the input as much as possible
1207/// while still causing the code generator to crash.
Nick Lewycky6ba630b2010-04-12 05:08:25 +00001208bool BugDriver::debugCodeGeneratorCrash(std::string &Error) {
Dan Gohmand8db3762009-07-15 16:35:29 +00001209 errs() << "*** Debugging code generator crash!\n";
Chris Lattneread1dff2004-02-18 21:02:04 +00001210
Nick Lewycky6ba630b2010-04-12 05:08:25 +00001211 return DebugACrash(*this, TestForCodeGenCrash, Error);
Chris Lattneread1dff2004-02-18 21:02:04 +00001212}