blob: 4b6e6df102839d7cd691800d07cef34164dcec16 [file] [log] [blame]
Chris Lattner73a6bdd2002-11-20 22:28:10 +00001//===- CrashDebugger.cpp - Debug compilation crashes ----------------------===//
Misha Brukman650ba8e2005-04-22 00:00:37 +00002//
John Criswell09344dc2003-10-20 17:47:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner345353d2007-12-29 20:44:31 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman650ba8e2005-04-22 00:00:37 +00007//
John Criswell09344dc2003-10-20 17:47:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner73a6bdd2002-11-20 22:28:10 +00009//
10// This file defines the bugpoint internals that narrow down compilation crashes
11//
12//===----------------------------------------------------------------------===//
13
14#include "BugDriver.h"
Chris Lattner1d080f22003-04-24 22:24:58 +000015#include "ListReducer.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000016#include "ToolRunner.h"
17#include "llvm/ADT/SmallPtrSet.h"
Keno Fischer34ca8312015-11-06 00:12:50 +000018#include "llvm/ADT/StringSet.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000019#include "llvm/IR/CFG.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000020#include "llvm/IR/Constants.h"
21#include "llvm/IR/DerivedTypes.h"
22#include "llvm/IR/Instructions.h"
Chandler Carruth30d69c22015-02-13 10:01:29 +000023#include "llvm/IR/LegacyPassManager.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/Module.h"
25#include "llvm/IR/ValueSymbolTable.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000026#include "llvm/IR/Verifier.h"
Misha Brukman0c2305b2003-08-07 21:19:30 +000027#include "llvm/Pass.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000028#include "llvm/Support/CommandLine.h"
29#include "llvm/Support/FileUtilities.h"
Chris Lattnerf32939b2003-04-24 23:51:38 +000030#include "llvm/Transforms/Scalar.h"
Chris Lattner1d080f22003-04-24 22:24:58 +000031#include "llvm/Transforms/Utils/Cloning.h"
Chris Lattner1d080f22003-04-24 22:24:58 +000032#include <set>
Chris Lattner2f1aa112004-01-14 03:38:37 +000033using namespace llvm;
Chris Lattner73a6bdd2002-11-20 22:28:10 +000034
Andrew Lenharthef9aa122006-03-05 22:21:36 +000035namespace {
36 cl::opt<bool>
37 KeepMain("keep-main",
38 cl::desc("Force function reduction to keep main"),
39 cl::init(false));
Torok Edwin5bd3f7b2009-05-24 09:31:04 +000040 cl::opt<bool>
41 NoGlobalRM ("disable-global-remove",
42 cl::desc("Do not remove global variables"),
43 cl::init(false));
JF Bastienf87e20d2015-04-20 23:42:22 +000044
45 cl::opt<bool>
46 ReplaceFuncsWithNull("replace-funcs-with-null",
47 cl::desc("When stubbing functions, replace all uses will null"),
48 cl::init(false));
49 cl::opt<bool>
50 DontReducePassList("disable-pass-list-reduction",
51 cl::desc("Skip pass list reduction steps"),
52 cl::init(false));
Keno Fischer34ca8312015-11-06 00:12:50 +000053
54 cl::opt<bool> NoNamedMDRM("disable-namedmd-remove",
55 cl::desc("Do not remove global named metadata"),
56 cl::init(false));
Andrew Lenharthef9aa122006-03-05 22:21:36 +000057}
58
Brian Gaeke960707c2003-11-11 22:41:34 +000059namespace llvm {
Rafael Espindola33e81a82010-08-08 03:55:08 +000060 class ReducePassList : public ListReducer<std::string> {
Chris Lattner2f1aa112004-01-14 03:38:37 +000061 BugDriver &BD;
62 public:
Chris Lattner327019b2004-02-18 21:24:48 +000063 ReducePassList(BugDriver &bd) : BD(bd) {}
Misha Brukman650ba8e2005-04-22 00:00:37 +000064
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +000065 // doTest - Return true iff running the "removed" passes succeeds, and
Chris Lattner2f1aa112004-01-14 03:38:37 +000066 // running the "Kept" passes fail when run on the output of the "removed"
67 // passes. If we return true, we update the current module of bugpoint.
68 //
Craig Toppere56917c2014-03-08 08:27:28 +000069 TestResult doTest(std::vector<std::string> &Removed,
70 std::vector<std::string> &Kept,
71 std::string &Error) override;
Chris Lattner2f1aa112004-01-14 03:38:37 +000072 };
73}
Chris Lattner1d080f22003-04-24 22:24:58 +000074
Chris Lattner327019b2004-02-18 21:24:48 +000075ReducePassList::TestResult
Rafael Espindola33e81a82010-08-08 03:55:08 +000076ReducePassList::doTest(std::vector<std::string> &Prefix,
77 std::vector<std::string> &Suffix,
Nick Lewycky6ba630b2010-04-12 05:08:25 +000078 std::string &Error) {
Rafael Espindolabb876652013-06-17 19:33:18 +000079 std::string PrefixOutput;
Craig Toppere6cb63e2014-04-25 04:24:47 +000080 Module *OrigProgram = nullptr;
Chris Lattner1d080f22003-04-24 22:24:58 +000081 if (!Prefix.empty()) {
Dan Gohmanee051522009-07-16 15:30:09 +000082 outs() << "Checking to see if these passes crash: "
83 << getPassesString(Prefix) << ": ";
Rafael Espindolabb876652013-06-17 19:33:18 +000084 if (BD.runPasses(BD.getProgram(), Prefix, PrefixOutput))
Chris Lattner1d080f22003-04-24 22:24:58 +000085 return KeepPrefix;
Chris Lattnera9656312003-06-02 04:54:29 +000086
87 OrigProgram = BD.Program;
88
Rafael Espindola28b351a2014-08-26 17:19:03 +000089 BD.Program = parseInputFile(PrefixOutput, BD.getContext()).release();
Craig Toppere6cb63e2014-04-25 04:24:47 +000090 if (BD.Program == nullptr) {
Dan Gohmand8db3762009-07-15 16:35:29 +000091 errs() << BD.getToolName() << ": Error reading bitcode file '"
Rafael Espindolabb876652013-06-17 19:33:18 +000092 << PrefixOutput << "'!\n";
Chris Lattnera9656312003-06-02 04:54:29 +000093 exit(1);
94 }
Rafael Espindolabb876652013-06-17 19:33:18 +000095 sys::fs::remove(PrefixOutput);
Chris Lattner1d080f22003-04-24 22:24:58 +000096 }
97
Dan Gohmanee051522009-07-16 15:30:09 +000098 outs() << "Checking to see if these passes crash: "
99 << getPassesString(Suffix) << ": ";
Misha Brukman650ba8e2005-04-22 00:00:37 +0000100
Rafael Espindola37302ea2010-08-05 02:16:32 +0000101 if (BD.runPasses(BD.getProgram(), Suffix)) {
Chris Lattner1d080f22003-04-24 22:24:58 +0000102 delete OrigProgram; // The suffix crashes alone...
103 return KeepSuffix;
104 }
105
106 // Nothing failed, restore state...
Chris Lattnera9656312003-06-02 04:54:29 +0000107 if (OrigProgram) {
108 delete BD.Program;
109 BD.Program = OrigProgram;
110 }
Chris Lattner1d080f22003-04-24 22:24:58 +0000111 return NoFailure;
112}
113
Bill Wendling3f833432006-10-25 18:36:14 +0000114namespace {
115 /// ReduceCrashingGlobalVariables - This works by removing the global
116 /// variable's initializer and seeing if the program still crashes. If it
117 /// does, then we keep that program and try again.
118 ///
119 class ReduceCrashingGlobalVariables : public ListReducer<GlobalVariable*> {
120 BugDriver &BD;
Rafael Espindolad1c7ef42010-08-05 03:00:22 +0000121 bool (*TestFn)(const BugDriver &, Module *);
Bill Wendling3f833432006-10-25 18:36:14 +0000122 public:
123 ReduceCrashingGlobalVariables(BugDriver &bd,
Rafael Espindolad1c7ef42010-08-05 03:00:22 +0000124 bool (*testFn)(const BugDriver &, Module *))
Bill Wendling3f833432006-10-25 18:36:14 +0000125 : BD(bd), TestFn(testFn) {}
126
Craig Toppere56917c2014-03-08 08:27:28 +0000127 TestResult doTest(std::vector<GlobalVariable*> &Prefix,
128 std::vector<GlobalVariable*> &Kept,
129 std::string &Error) override {
Bill Wendling3f833432006-10-25 18:36:14 +0000130 if (!Kept.empty() && TestGlobalVariables(Kept))
131 return KeepSuffix;
Bill Wendling3f833432006-10-25 18:36:14 +0000132 if (!Prefix.empty() && TestGlobalVariables(Prefix))
133 return KeepPrefix;
Bill Wendling3f833432006-10-25 18:36:14 +0000134 return NoFailure;
135 }
136
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000137 bool TestGlobalVariables(std::vector<GlobalVariable*> &GVs);
Bill Wendling3f833432006-10-25 18:36:14 +0000138 };
139}
140
141bool
142ReduceCrashingGlobalVariables::TestGlobalVariables(
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000143 std::vector<GlobalVariable*> &GVs) {
Bill Wendling3f833432006-10-25 18:36:14 +0000144 // Clone the program to try hacking it apart...
Rafael Espindola229e38f2010-10-13 01:36:30 +0000145 ValueToValueMapTy VMap;
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000146 Module *M = CloneModule(BD.getProgram(), VMap);
Bill Wendling3f833432006-10-25 18:36:14 +0000147
148 // Convert list to set for fast lookup...
149 std::set<GlobalVariable*> GVSet;
150
151 for (unsigned i = 0, e = GVs.size(); i != e; ++i) {
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000152 GlobalVariable* CMGV = cast<GlobalVariable>(VMap[GVs[i]]);
Bill Wendling3f833432006-10-25 18:36:14 +0000153 assert(CMGV && "Global Variable not in module?!");
154 GVSet.insert(CMGV);
155 }
156
Dan Gohmanee051522009-07-16 15:30:09 +0000157 outs() << "Checking for crash with only these global variables: ";
Bill Wendling3f833432006-10-25 18:36:14 +0000158 PrintGlobalVariableList(GVs);
Dan Gohmanee051522009-07-16 15:30:09 +0000159 outs() << ": ";
Bill Wendling3f833432006-10-25 18:36:14 +0000160
161 // Loop over and delete any global variables which we aren't supposed to be
162 // playing with...
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000163 for (GlobalVariable &I : M->globals())
164 if (I.hasInitializer() && !GVSet.count(&I)) {
165 I.setInitializer(nullptr);
166 I.setLinkage(GlobalValue::ExternalLinkage);
Bill Wendling3f833432006-10-25 18:36:14 +0000167 }
168
169 // Try running the hacked up program...
170 if (TestFn(BD, M)) {
171 BD.setNewProgram(M); // It crashed, keep the trimmed version...
172
173 // Make sure to use global variable pointers that point into the now-current
174 // module.
175 GVs.assign(GVSet.begin(), GVSet.end());
176 return true;
177 }
178
179 delete M;
180 return false;
181}
182
David Blaikiea379b1812011-12-20 02:50:00 +0000183namespace {
Bill Wendling3f833432006-10-25 18:36:14 +0000184 /// ReduceCrashingFunctions reducer - This works by removing functions and
185 /// seeing if the program still crashes. If it does, then keep the newer,
186 /// smaller program.
187 ///
Chris Lattnerfd72bed2004-03-14 20:50:42 +0000188 class ReduceCrashingFunctions : public ListReducer<Function*> {
Chris Lattner2f1aa112004-01-14 03:38:37 +0000189 BugDriver &BD;
Rafael Espindolad1c7ef42010-08-05 03:00:22 +0000190 bool (*TestFn)(const BugDriver &, Module *);
Chris Lattner2f1aa112004-01-14 03:38:37 +0000191 public:
Chris Lattner8bda4c42004-02-18 23:26:28 +0000192 ReduceCrashingFunctions(BugDriver &bd,
Rafael Espindolad1c7ef42010-08-05 03:00:22 +0000193 bool (*testFn)(const BugDriver &, Module *))
Chris Lattner8bda4c42004-02-18 23:26:28 +0000194 : BD(bd), TestFn(testFn) {}
Misha Brukman650ba8e2005-04-22 00:00:37 +0000195
Craig Toppere56917c2014-03-08 08:27:28 +0000196 TestResult doTest(std::vector<Function*> &Prefix,
197 std::vector<Function*> &Kept,
198 std::string &Error) override {
Chris Lattner2f1aa112004-01-14 03:38:37 +0000199 if (!Kept.empty() && TestFuncs(Kept))
200 return KeepSuffix;
201 if (!Prefix.empty() && TestFuncs(Prefix))
202 return KeepPrefix;
203 return NoFailure;
204 }
Misha Brukman650ba8e2005-04-22 00:00:37 +0000205
Chris Lattnerfd72bed2004-03-14 20:50:42 +0000206 bool TestFuncs(std::vector<Function*> &Prefix);
Chris Lattner2f1aa112004-01-14 03:38:37 +0000207 };
208}
Chris Lattner1d080f22003-04-24 22:24:58 +0000209
JF Bastienf87e20d2015-04-20 23:42:22 +0000210static void RemoveFunctionReferences(Module *M, const char* Name) {
211 auto *UsedVar = M->getGlobalVariable(Name, true);
212 if (!UsedVar || !UsedVar->hasInitializer()) return;
213 if (isa<ConstantAggregateZero>(UsedVar->getInitializer())) {
214 assert(UsedVar->use_empty());
215 UsedVar->eraseFromParent();
216 return;
217 }
218 auto *OldUsedVal = cast<ConstantArray>(UsedVar->getInitializer());
219 std::vector<Constant*> Used;
220 for(Value *V : OldUsedVal->operand_values()) {
221 Constant *Op = cast<Constant>(V->stripPointerCasts());
222 if(!Op->isNullValue()) {
223 Used.push_back(cast<Constant>(V));
224 }
225 }
226 auto *NewValElemTy = OldUsedVal->getType()->getElementType();
227 auto *NewValTy = ArrayType::get(NewValElemTy, Used.size());
228 auto *NewUsedVal = ConstantArray::get(NewValTy, Used);
229 UsedVar->mutateType(NewUsedVal->getType()->getPointerTo());
230 UsedVar->setInitializer(NewUsedVal);
231}
232
Chris Lattnerfd72bed2004-03-14 20:50:42 +0000233bool ReduceCrashingFunctions::TestFuncs(std::vector<Function*> &Funcs) {
Dmitri Gribenko6e0520e2013-09-02 01:18:56 +0000234 // If main isn't present, claim there is no problem.
235 if (KeepMain && std::find(Funcs.begin(), Funcs.end(),
236 BD.getProgram()->getFunction("main")) ==
237 Funcs.end())
Andrew Lenharthef9aa122006-03-05 22:21:36 +0000238 return false;
239
Misha Brukman8b2bd4e2003-10-10 17:57:28 +0000240 // Clone the program to try hacking it apart...
Rafael Espindola229e38f2010-10-13 01:36:30 +0000241 ValueToValueMapTy VMap;
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000242 Module *M = CloneModule(BD.getProgram(), VMap);
Misha Brukman650ba8e2005-04-22 00:00:37 +0000243
Chris Lattner1d080f22003-04-24 22:24:58 +0000244 // Convert list to set for fast lookup...
245 std::set<Function*> Functions;
246 for (unsigned i = 0, e = Funcs.size(); i != e; ++i) {
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000247 Function *CMF = cast<Function>(VMap[Funcs[i]]);
Chris Lattner1d080f22003-04-24 22:24:58 +0000248 assert(CMF && "Function not in module?!");
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000249 assert(CMF->getFunctionType() == Funcs[i]->getFunctionType() && "wrong ty");
Dan Gohmanbcad7182009-03-06 02:16:23 +0000250 assert(CMF->getName() == Funcs[i]->getName() && "wrong name");
Chris Lattnerde39f2b2003-04-24 22:54:06 +0000251 Functions.insert(CMF);
Chris Lattner1d080f22003-04-24 22:24:58 +0000252 }
253
Dan Gohmanee051522009-07-16 15:30:09 +0000254 outs() << "Checking for crash with only these functions: ";
Chris Lattnerfd72bed2004-03-14 20:50:42 +0000255 PrintFunctionList(Funcs);
Dan Gohmanee051522009-07-16 15:30:09 +0000256 outs() << ": ";
JF Bastienf87e20d2015-04-20 23:42:22 +0000257 if (!ReplaceFuncsWithNull) {
258 // Loop over and delete any functions which we aren't supposed to be playing
259 // with...
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000260 for (Function &I : *M)
261 if (!I.isDeclaration() && !Functions.count(&I))
262 DeleteFunctionBody(&I);
JF Bastienf87e20d2015-04-20 23:42:22 +0000263 } else {
264 std::vector<GlobalValue*> ToRemove;
265 // First, remove aliases to functions we're about to purge.
266 for (GlobalAlias &Alias : M->aliases()) {
267 Constant *Root = Alias.getAliasee()->stripPointerCasts();
268 Function *F = dyn_cast<Function>(Root);
269 if (F) {
270 if (Functions.count(F))
271 // We're keeping this function.
272 continue;
273 } else if (Root->isNullValue()) {
274 // This referenced a globalalias that we've already replaced,
275 // so we still need to replace this alias.
276 } else if (!F) {
277 // Not a function, therefore not something we mess with.
278 continue;
279 }
Chris Lattner1d080f22003-04-24 22:24:58 +0000280
JF Bastienf87e20d2015-04-20 23:42:22 +0000281 PointerType *Ty = cast<PointerType>(Alias.getType());
282 Constant *Replacement = ConstantPointerNull::get(Ty);
283 Alias.replaceAllUsesWith(Replacement);
284 ToRemove.push_back(&Alias);
285 }
Chris Lattner1d080f22003-04-24 22:24:58 +0000286
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000287 for (Function &I : *M) {
288 if (!I.isDeclaration() && !Functions.count(&I)) {
289 PointerType *Ty = cast<PointerType>(I.getType());
JF Bastienf87e20d2015-04-20 23:42:22 +0000290 Constant *Replacement = ConstantPointerNull::get(Ty);
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000291 I.replaceAllUsesWith(Replacement);
292 ToRemove.push_back(&I);
JF Bastienf87e20d2015-04-20 23:42:22 +0000293 }
294 }
295
296 for (auto *F : ToRemove) {
297 F->eraseFromParent();
298 }
299
300 // Finally, remove any null members from any global intrinsic.
301 RemoveFunctionReferences(M, "llvm.used");
302 RemoveFunctionReferences(M, "llvm.compiler.used");
303 }
Chris Lattner1d080f22003-04-24 22:24:58 +0000304 // Try running the hacked up program...
Chris Lattner8bda4c42004-02-18 23:26:28 +0000305 if (TestFn(BD, M)) {
Chris Lattner327019b2004-02-18 21:24:48 +0000306 BD.setNewProgram(M); // It crashed, keep the trimmed version...
Chris Lattner1d080f22003-04-24 22:24:58 +0000307
308 // Make sure to use function pointers that point into the now-current
309 // module.
310 Funcs.assign(Functions.begin(), Functions.end());
311 return true;
312 }
Chris Lattner327019b2004-02-18 21:24:48 +0000313 delete M;
Chris Lattner1d080f22003-04-24 22:24:58 +0000314 return false;
315}
316
Chris Lattner16a41312003-04-24 17:02:17 +0000317
Chris Lattner1942f982004-02-18 21:29:46 +0000318namespace {
Chris Lattner2f1aa112004-01-14 03:38:37 +0000319 /// ReduceCrashingBlocks reducer - This works by setting the terminators of
320 /// all terminators except the specified basic blocks to a 'ret' instruction,
321 /// then running the simplify-cfg pass. This has the effect of chopping up
322 /// the CFG really fast which can reduce large functions quickly.
323 ///
Chris Lattner8bda4c42004-02-18 23:26:28 +0000324 class ReduceCrashingBlocks : public ListReducer<const BasicBlock*> {
Chris Lattner2f1aa112004-01-14 03:38:37 +0000325 BugDriver &BD;
Rafael Espindolad1c7ef42010-08-05 03:00:22 +0000326 bool (*TestFn)(const BugDriver &, Module *);
Chris Lattner2f1aa112004-01-14 03:38:37 +0000327 public:
Rafael Espindolad1c7ef42010-08-05 03:00:22 +0000328 ReduceCrashingBlocks(BugDriver &bd,
329 bool (*testFn)(const BugDriver &, Module *))
Chris Lattner8bda4c42004-02-18 23:26:28 +0000330 : BD(bd), TestFn(testFn) {}
Misha Brukman650ba8e2005-04-22 00:00:37 +0000331
Craig Toppere56917c2014-03-08 08:27:28 +0000332 TestResult doTest(std::vector<const BasicBlock*> &Prefix,
333 std::vector<const BasicBlock*> &Kept,
334 std::string &Error) override {
Chris Lattner2f1aa112004-01-14 03:38:37 +0000335 if (!Kept.empty() && TestBlocks(Kept))
336 return KeepSuffix;
337 if (!Prefix.empty() && TestBlocks(Prefix))
338 return KeepPrefix;
339 return NoFailure;
340 }
Misha Brukman650ba8e2005-04-22 00:00:37 +0000341
Chris Lattner8bda4c42004-02-18 23:26:28 +0000342 bool TestBlocks(std::vector<const BasicBlock*> &Prefix);
Chris Lattner2f1aa112004-01-14 03:38:37 +0000343 };
344}
Chris Lattnerf32939b2003-04-24 23:51:38 +0000345
Chris Lattner8bda4c42004-02-18 23:26:28 +0000346bool ReduceCrashingBlocks::TestBlocks(std::vector<const BasicBlock*> &BBs) {
Misha Brukman8b2bd4e2003-10-10 17:57:28 +0000347 // Clone the program to try hacking it apart...
Rafael Espindola229e38f2010-10-13 01:36:30 +0000348 ValueToValueMapTy VMap;
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000349 Module *M = CloneModule(BD.getProgram(), VMap);
Misha Brukman650ba8e2005-04-22 00:00:37 +0000350
Chris Lattnerf32939b2003-04-24 23:51:38 +0000351 // Convert list to set for fast lookup...
Nick Lewyckyb294e312009-04-04 09:39:23 +0000352 SmallPtrSet<BasicBlock*, 8> Blocks;
353 for (unsigned i = 0, e = BBs.size(); i != e; ++i)
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000354 Blocks.insert(cast<BasicBlock>(VMap[BBs[i]]));
Chris Lattnerf32939b2003-04-24 23:51:38 +0000355
Dan Gohmanee051522009-07-16 15:30:09 +0000356 outs() << "Checking for crash with only these blocks:";
Chris Lattner4f50ebd2003-10-27 04:44:59 +0000357 unsigned NumPrint = Blocks.size();
358 if (NumPrint > 10) NumPrint = 10;
359 for (unsigned i = 0, e = NumPrint; i != e; ++i)
Dan Gohmanee051522009-07-16 15:30:09 +0000360 outs() << " " << BBs[i]->getName();
Chris Lattner4f50ebd2003-10-27 04:44:59 +0000361 if (NumPrint < Blocks.size())
Dan Gohmanee051522009-07-16 15:30:09 +0000362 outs() << "... <" << Blocks.size() << " total>";
363 outs() << ": ";
Chris Lattnerf32939b2003-04-24 23:51:38 +0000364
365 // Loop over and delete any hack up any blocks that are not listed...
366 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
367 for (Function::iterator BB = I->begin(), E = I->end(); BB != E; ++BB)
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000368 if (!Blocks.count(&*BB) && BB->getTerminator()->getNumSuccessors()) {
Chris Lattnerf32939b2003-04-24 23:51:38 +0000369 // Loop over all of the successors of this block, deleting any PHI nodes
370 // that might include it.
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000371 for (succ_iterator SI = succ_begin(&*BB), E = succ_end(&*BB); SI != E;
372 ++SI)
373 (*SI)->removePredecessor(&*BB);
Chris Lattnerf32939b2003-04-24 23:51:38 +0000374
Chris Lattner7855a5c2008-04-28 00:04:58 +0000375 TerminatorInst *BBTerm = BB->getTerminator();
JF Bastienf87e20d2015-04-20 23:42:22 +0000376
Dan Gohman34a22492010-06-07 20:19:26 +0000377 if (!BB->getTerminator()->getType()->isVoidTy())
Owen Anderson5a1acd92009-07-31 20:28:14 +0000378 BBTerm->replaceAllUsesWith(Constant::getNullValue(BBTerm->getType()));
Chris Lattner7b233af2003-11-22 02:10:38 +0000379
Chris Lattner7855a5c2008-04-28 00:04:58 +0000380 // Replace the old terminator instruction.
Chris Lattnerf32939b2003-04-24 23:51:38 +0000381 BB->getInstList().pop_back();
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000382 new UnreachableInst(BB->getContext(), &*BB);
Chris Lattnerf32939b2003-04-24 23:51:38 +0000383 }
384
385 // The CFG Simplifier pass may delete one of the basic blocks we are
386 // interested in. If it does we need to take the block out of the list. Make
387 // a "persistent mapping" by turning basic blocks into <function, name> pairs.
388 // This won't work well if blocks are unnamed, but that is just the risk we
389 // have to take.
Rafael Espindolad1e241a2010-08-10 15:46:11 +0000390 std::vector<std::pair<std::string, std::string> > BlockInfo;
Chris Lattnerf32939b2003-04-24 23:51:38 +0000391
Craig Topper46276792014-08-24 23:23:06 +0000392 for (BasicBlock *BB : Blocks)
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000393 BlockInfo.emplace_back(BB->getParent()->getName(), BB->getName());
Chris Lattnerf32939b2003-04-24 23:51:38 +0000394
395 // Now run the CFG simplify pass on the function...
Rafael Espindolad1e241a2010-08-10 15:46:11 +0000396 std::vector<std::string> Passes;
397 Passes.push_back("simplifycfg");
398 Passes.push_back("verify");
Rafael Espindola28b351a2014-08-26 17:19:03 +0000399 std::unique_ptr<Module> New = BD.runPassesOn(M, Passes);
Rafael Espindolad1e241a2010-08-10 15:46:11 +0000400 delete M;
401 if (!New) {
402 errs() << "simplifycfg failed!\n";
403 exit(1);
404 }
Rafael Espindola28b351a2014-08-26 17:19:03 +0000405 M = New.release();
Chris Lattnerf32939b2003-04-24 23:51:38 +0000406
407 // Try running on the hacked up program...
Chris Lattner8bda4c42004-02-18 23:26:28 +0000408 if (TestFn(BD, M)) {
Chris Lattner327019b2004-02-18 21:24:48 +0000409 BD.setNewProgram(M); // It crashed, keep the trimmed version...
Chris Lattnerf32939b2003-04-24 23:51:38 +0000410
411 // Make sure to use basic block pointers that point into the now-current
412 // module, and that they don't include any deleted blocks.
413 BBs.clear();
Rafael Espindolad1e241a2010-08-10 15:46:11 +0000414 const ValueSymbolTable &GST = M->getValueSymbolTable();
Chris Lattnerf32939b2003-04-24 23:51:38 +0000415 for (unsigned i = 0, e = BlockInfo.size(); i != e; ++i) {
Rafael Espindolad1e241a2010-08-10 15:46:11 +0000416 Function *F = cast<Function>(GST.lookup(BlockInfo[i].first));
417 ValueSymbolTable &ST = F->getValueSymbolTable();
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000418 Value* V = ST.lookup(BlockInfo[i].second);
Owen Anderson55f1c092009-08-13 21:58:54 +0000419 if (V && V->getType() == Type::getLabelTy(V->getContext()))
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000420 BBs.push_back(cast<BasicBlock>(V));
Chris Lattnerf32939b2003-04-24 23:51:38 +0000421 }
422 return true;
423 }
Chris Lattner327019b2004-02-18 21:24:48 +0000424 delete M; // It didn't crash, try something else.
Chris Lattnerf32939b2003-04-24 23:51:38 +0000425 return false;
426}
427
Nick Lewycky6e090c92009-05-25 05:30:00 +0000428namespace {
429 /// ReduceCrashingInstructions reducer - This works by removing the specified
430 /// non-terminator instructions and replacing them with undef.
431 ///
432 class ReduceCrashingInstructions : public ListReducer<const Instruction*> {
433 BugDriver &BD;
Rafael Espindolad1c7ef42010-08-05 03:00:22 +0000434 bool (*TestFn)(const BugDriver &, Module *);
Nick Lewycky6e090c92009-05-25 05:30:00 +0000435 public:
Rafael Espindolad1c7ef42010-08-05 03:00:22 +0000436 ReduceCrashingInstructions(BugDriver &bd,
437 bool (*testFn)(const BugDriver &, Module *))
Nick Lewycky6e090c92009-05-25 05:30:00 +0000438 : BD(bd), TestFn(testFn) {}
439
Craig Toppere56917c2014-03-08 08:27:28 +0000440 TestResult doTest(std::vector<const Instruction*> &Prefix,
441 std::vector<const Instruction*> &Kept,
442 std::string &Error) override {
Nick Lewycky6e090c92009-05-25 05:30:00 +0000443 if (!Kept.empty() && TestInsts(Kept))
444 return KeepSuffix;
445 if (!Prefix.empty() && TestInsts(Prefix))
446 return KeepPrefix;
447 return NoFailure;
448 }
449
450 bool TestInsts(std::vector<const Instruction*> &Prefix);
451 };
452}
453
454bool ReduceCrashingInstructions::TestInsts(std::vector<const Instruction*>
455 &Insts) {
456 // Clone the program to try hacking it apart...
Rafael Espindola229e38f2010-10-13 01:36:30 +0000457 ValueToValueMapTy VMap;
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000458 Module *M = CloneModule(BD.getProgram(), VMap);
Nick Lewycky6e090c92009-05-25 05:30:00 +0000459
460 // Convert list to set for fast lookup...
461 SmallPtrSet<Instruction*, 64> Instructions;
462 for (unsigned i = 0, e = Insts.size(); i != e; ++i) {
463 assert(!isa<TerminatorInst>(Insts[i]));
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000464 Instructions.insert(cast<Instruction>(VMap[Insts[i]]));
Nick Lewycky6e090c92009-05-25 05:30:00 +0000465 }
466
Dan Gohmanee051522009-07-16 15:30:09 +0000467 outs() << "Checking for crash with only " << Instructions.size();
Nick Lewycky6e090c92009-05-25 05:30:00 +0000468 if (Instructions.size() == 1)
Dan Gohmanee051522009-07-16 15:30:09 +0000469 outs() << " instruction: ";
Nick Lewycky6e090c92009-05-25 05:30:00 +0000470 else
Dan Gohmanee051522009-07-16 15:30:09 +0000471 outs() << " instructions: ";
Nick Lewycky6e090c92009-05-25 05:30:00 +0000472
473 for (Module::iterator MI = M->begin(), ME = M->end(); MI != ME; ++MI)
474 for (Function::iterator FI = MI->begin(), FE = MI->end(); FI != FE; ++FI)
475 for (BasicBlock::iterator I = FI->begin(), E = FI->end(); I != E;) {
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000476 Instruction *Inst = &*I++;
Eli Friedmand4e02a52011-11-01 04:40:56 +0000477 if (!Instructions.count(Inst) && !isa<TerminatorInst>(Inst) &&
David Majnemerba275f92015-08-19 19:54:02 +0000478 !Inst->isEHPad()) {
Dan Gohman34a22492010-06-07 20:19:26 +0000479 if (!Inst->getType()->isVoidTy())
Nick Lewycky6e090c92009-05-25 05:30:00 +0000480 Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
481 Inst->eraseFromParent();
482 }
483 }
484
485 // Verify that this is still valid.
Chandler Carruth30d69c22015-02-13 10:01:29 +0000486 legacy::PassManager Passes;
Nick Lewycky6e090c92009-05-25 05:30:00 +0000487 Passes.add(createVerifierPass());
488 Passes.run(*M);
489
490 // Try running on the hacked up program...
491 if (TestFn(BD, M)) {
492 BD.setNewProgram(M); // It crashed, keep the trimmed version...
493
494 // Make sure to use instruction pointers that point into the now-current
495 // module, and that they don't include any deleted blocks.
496 Insts.clear();
Craig Topper46276792014-08-24 23:23:06 +0000497 for (Instruction *Inst : Instructions)
498 Insts.push_back(Inst);
Nick Lewycky6e090c92009-05-25 05:30:00 +0000499 return true;
500 }
501 delete M; // It didn't crash, try something else.
502 return false;
503}
504
Keno Fischer34ca8312015-11-06 00:12:50 +0000505namespace {
506// Reduce the list of Named Metadata nodes. We keep this as a list of
507// names to avoid having to convert back and forth every time.
508class ReduceCrashingNamedMD : public ListReducer<std::string> {
509 BugDriver &BD;
510 bool (*TestFn)(const BugDriver &, Module *);
511
512public:
513 ReduceCrashingNamedMD(BugDriver &bd,
514 bool (*testFn)(const BugDriver &, Module *))
515 : BD(bd), TestFn(testFn) {}
516
517 TestResult doTest(std::vector<std::string> &Prefix,
518 std::vector<std::string> &Kept,
519 std::string &Error) override {
520 if (!Kept.empty() && TestNamedMDs(Kept))
521 return KeepSuffix;
522 if (!Prefix.empty() && TestNamedMDs(Prefix))
523 return KeepPrefix;
524 return NoFailure;
525 }
526
527 bool TestNamedMDs(std::vector<std::string> &NamedMDs);
528};
529}
530
531bool ReduceCrashingNamedMD::TestNamedMDs(std::vector<std::string> &NamedMDs) {
532
533 ValueToValueMapTy VMap;
534 Module *M = CloneModule(BD.getProgram(), VMap);
535
536 outs() << "Checking for crash with only these named metadata nodes:";
537 unsigned NumPrint = std::min<size_t>(NamedMDs.size(), 10);
538 for (unsigned i = 0, e = NumPrint; i != e; ++i)
539 outs() << " " << NamedMDs[i];
540 if (NumPrint < NamedMDs.size())
541 outs() << "... <" << NamedMDs.size() << " total>";
542 outs() << ": ";
543
544 // Make a StringMap for faster lookup
545 StringSet<> Names;
546 for (const std::string &Name : NamedMDs)
547 Names.insert(Name);
548
549 // First collect all the metadata to delete in a vector, then
550 // delete them all at once to avoid invalidating the iterator
551 std::vector<NamedMDNode *> ToDelete;
552 ToDelete.reserve(M->named_metadata_size() - Names.size());
553 for (auto &NamedMD : M->named_metadata())
554 if (!Names.count(NamedMD.getName()))
555 ToDelete.push_back(&NamedMD);
556
557 for (auto *NamedMD : ToDelete)
558 NamedMD->eraseFromParent();
559
560 // Verify that this is still valid.
561 legacy::PassManager Passes;
562 Passes.add(createVerifierPass());
563 Passes.run(*M);
564
565 // Try running on the hacked up program...
566 if (TestFn(BD, M)) {
567 BD.setNewProgram(M); // It crashed, keep the trimmed version...
568 return true;
569 }
570 delete M; // It didn't crash, try something else.
571 return false;
572}
573
574namespace {
575// Reduce the list of operands to named metadata nodes
576class ReduceCrashingNamedMDOps : public ListReducer<const MDNode *> {
577 BugDriver &BD;
578 bool (*TestFn)(const BugDriver &, Module *);
579
580public:
581 ReduceCrashingNamedMDOps(BugDriver &bd,
582 bool (*testFn)(const BugDriver &, Module *))
583 : BD(bd), TestFn(testFn) {}
584
585 TestResult doTest(std::vector<const MDNode *> &Prefix,
586 std::vector<const MDNode *> &Kept,
587 std::string &Error) override {
588 if (!Kept.empty() && TestNamedMDOps(Kept))
589 return KeepSuffix;
590 if (!Prefix.empty() && TestNamedMDOps(Prefix))
591 return KeepPrefix;
592 return NoFailure;
593 }
594
595 bool TestNamedMDOps(std::vector<const MDNode *> &NamedMDOps);
596};
597}
598
599bool ReduceCrashingNamedMDOps::TestNamedMDOps(
600 std::vector<const MDNode *> &NamedMDOps) {
601 // Convert list to set for fast lookup...
602 SmallPtrSet<const MDNode *, 64> OldMDNodeOps;
603 for (unsigned i = 0, e = NamedMDOps.size(); i != e; ++i) {
604 OldMDNodeOps.insert(NamedMDOps[i]);
605 }
606
607 outs() << "Checking for crash with only " << OldMDNodeOps.size();
608 if (OldMDNodeOps.size() == 1)
609 outs() << " named metadata operand: ";
610 else
611 outs() << " named metadata operands: ";
612
613 ValueToValueMapTy VMap;
614 Module *M = CloneModule(BD.getProgram(), VMap);
615
616 // This is a little wasteful. In the future it might be good if we could have
617 // these dropped during cloning.
618 for (auto &NamedMD : BD.getProgram()->named_metadata()) {
619 // Drop the old one and create a new one
620 M->eraseNamedMetadata(M->getNamedMetadata(NamedMD.getName()));
621 NamedMDNode *NewNamedMDNode =
622 M->getOrInsertNamedMetadata(NamedMD.getName());
623 for (MDNode *op : NamedMD.operands())
624 if (OldMDNodeOps.count(op))
625 NewNamedMDNode->addOperand(cast<MDNode>(MapMetadata(op, VMap)));
626 }
627
628 // Verify that this is still valid.
629 legacy::PassManager Passes;
630 Passes.add(createVerifierPass());
631 Passes.run(*M);
632
633 // Try running on the hacked up program...
634 if (TestFn(BD, M)) {
635 // Make sure to use instruction pointers that point into the now-current
636 // module, and that they don't include any deleted blocks.
637 NamedMDOps.clear();
638 for (const MDNode *Node : OldMDNodeOps)
639 NamedMDOps.push_back(cast<MDNode>(VMap.MD()[Node].get()));
640
641 BD.setNewProgram(M); // It crashed, keep the trimmed version...
642 return true;
643 }
644 delete M; // It didn't crash, try something else.
645 return false;
646}
647
Chris Lattner8bda4c42004-02-18 23:26:28 +0000648/// DebugACrash - Given a predicate that determines whether a component crashes
649/// on a program, try to destructively reduce the program while still keeping
650/// the predicate true.
Rafael Espindolad1c7ef42010-08-05 03:00:22 +0000651static bool DebugACrash(BugDriver &BD,
652 bool (*TestFn)(const BugDriver &, Module *),
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000653 std::string &Error) {
Bill Wendling3f833432006-10-25 18:36:14 +0000654 // See if we can get away with nuking some of the global variable initializers
Chris Lattner65e5f652003-04-25 00:53:05 +0000655 // in the program...
Torok Edwin5bd3f7b2009-05-24 09:31:04 +0000656 if (!NoGlobalRM &&
657 BD.getProgram()->global_begin() != BD.getProgram()->global_end()) {
Bill Wendling3f833432006-10-25 18:36:14 +0000658 // Now try to reduce the number of global variable initializers in the
659 // module to something small.
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000660 Module *M = CloneModule(BD.getProgram());
661 bool DeletedInit = false;
Misha Brukman650ba8e2005-04-22 00:00:37 +0000662
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000663 for (Module::global_iterator I = M->global_begin(), E = M->global_end();
664 I != E; ++I)
665 if (I->hasInitializer()) {
Craig Toppere6cb63e2014-04-25 04:24:47 +0000666 I->setInitializer(nullptr);
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000667 I->setLinkage(GlobalValue::ExternalLinkage);
668 DeletedInit = true;
669 }
Bill Wendling3f833432006-10-25 18:36:14 +0000670
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000671 if (!DeletedInit) {
672 delete M; // No change made...
673 } else {
674 // See if the program still causes a crash...
Dan Gohmanee051522009-07-16 15:30:09 +0000675 outs() << "\nChecking to see if we can delete global inits: ";
Bill Wendling3f833432006-10-25 18:36:14 +0000676
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000677 if (TestFn(BD, M)) { // Still crashes?
678 BD.setNewProgram(M);
Dan Gohmanee051522009-07-16 15:30:09 +0000679 outs() << "\n*** Able to remove all global initializers!\n";
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000680 } else { // No longer crashes?
Dan Gohmanee051522009-07-16 15:30:09 +0000681 outs() << " - Removing all global inits hides problem!\n";
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000682 delete M;
Bill Wendling3f833432006-10-25 18:36:14 +0000683
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000684 std::vector<GlobalVariable*> GVs;
685
686 for (Module::global_iterator I = BD.getProgram()->global_begin(),
687 E = BD.getProgram()->global_end(); I != E; ++I)
688 if (I->hasInitializer())
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000689 GVs.push_back(&*I);
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000690
691 if (GVs.size() > 1 && !BugpointIsInterrupted) {
Dan Gohmanee051522009-07-16 15:30:09 +0000692 outs() << "\n*** Attempting to reduce the number of global "
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000693 << "variables in the testcase\n";
694
695 unsigned OldSize = GVs.size();
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000696 ReduceCrashingGlobalVariables(BD, TestFn).reduceList(GVs, Error);
697 if (!Error.empty())
698 return true;
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000699
700 if (GVs.size() < OldSize)
Rafael Espindola594994a2010-07-28 18:12:30 +0000701 BD.EmitProgressBitcode(BD.getProgram(), "reduced-global-variables");
Bill Wendling74a4a2a2006-10-27 20:18:06 +0000702 }
Bill Wendlingce3afd62006-10-27 20:22:04 +0000703 }
Chris Lattner65e5f652003-04-25 00:53:05 +0000704 }
705 }
Misha Brukman650ba8e2005-04-22 00:00:37 +0000706
Chris Lattner1d080f22003-04-24 22:24:58 +0000707 // Now try to reduce the number of functions in the module to something small.
Chris Lattnerfd72bed2004-03-14 20:50:42 +0000708 std::vector<Function*> Functions;
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000709 for (Function &F : *BD.getProgram())
710 if (!F.isDeclaration())
711 Functions.push_back(&F);
Chris Lattner73a6bdd2002-11-20 22:28:10 +0000712
Chris Lattnerbeb01fa2005-08-02 02:16:17 +0000713 if (Functions.size() > 1 && !BugpointIsInterrupted) {
Dan Gohmanee051522009-07-16 15:30:09 +0000714 outs() << "\n*** Attempting to reduce the number of functions "
Chris Lattner1d080f22003-04-24 22:24:58 +0000715 "in the testcase\n";
Chris Lattner73a6bdd2002-11-20 22:28:10 +0000716
Chris Lattner8bda4c42004-02-18 23:26:28 +0000717 unsigned OldSize = Functions.size();
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000718 ReduceCrashingFunctions(BD, TestFn).reduceList(Functions, Error);
Chris Lattner73a6bdd2002-11-20 22:28:10 +0000719
Chris Lattnerbeb01fa2005-08-02 02:16:17 +0000720 if (Functions.size() < OldSize)
Rafael Espindola594994a2010-07-28 18:12:30 +0000721 BD.EmitProgressBitcode(BD.getProgram(), "reduced-function");
Chris Lattner73a6bdd2002-11-20 22:28:10 +0000722 }
723
Chris Lattnerf32939b2003-04-24 23:51:38 +0000724 // Attempt to delete entire basic blocks at a time to speed up
725 // convergence... this actually works by setting the terminator of the blocks
726 // to a return instruction then running simplifycfg, which can potentially
727 // shrinks the code dramatically quickly
728 //
Chris Lattnerbeb01fa2005-08-02 02:16:17 +0000729 if (!DisableSimplifyCFG && !BugpointIsInterrupted) {
Chris Lattner8bda4c42004-02-18 23:26:28 +0000730 std::vector<const BasicBlock*> Blocks;
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000731 for (Function &F : *BD.getProgram())
732 for (BasicBlock &BB : F)
733 Blocks.push_back(&BB);
Torok Edwin6ee6f732009-05-24 09:40:47 +0000734 unsigned OldSize = Blocks.size();
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000735 ReduceCrashingBlocks(BD, TestFn).reduceList(Blocks, Error);
Torok Edwin6ee6f732009-05-24 09:40:47 +0000736 if (Blocks.size() < OldSize)
Rafael Espindola594994a2010-07-28 18:12:30 +0000737 BD.EmitProgressBitcode(BD.getProgram(), "reduced-blocks");
Chris Lattnerd1e2aae2003-08-05 15:51:05 +0000738 }
Chris Lattnerd4e04742002-12-23 23:49:59 +0000739
Nick Lewycky6e090c92009-05-25 05:30:00 +0000740 // Attempt to delete instructions using bisection. This should help out nasty
741 // cases with large basic blocks where the problem is at one end.
742 if (!BugpointIsInterrupted) {
743 std::vector<const Instruction*> Insts;
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000744 for (const Function &F : *BD.getProgram())
745 for (const BasicBlock &BB : F)
746 for (const Instruction &I : BB)
747 if (!isa<TerminatorInst>(&I))
748 Insts.push_back(&I);
Nick Lewycky6e090c92009-05-25 05:30:00 +0000749
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000750 ReduceCrashingInstructions(BD, TestFn).reduceList(Insts, Error);
Nick Lewycky6e090c92009-05-25 05:30:00 +0000751 }
752
Chris Lattner1d080f22003-04-24 22:24:58 +0000753 // FIXME: This should use the list reducer to converge faster by deleting
754 // larger chunks of instructions at a time!
Chris Lattner0ee372c2004-03-13 19:35:54 +0000755 unsigned Simplification = 2;
Chris Lattner0eb5ce92003-01-23 02:48:33 +0000756 do {
Chris Lattnerbeb01fa2005-08-02 02:16:17 +0000757 if (BugpointIsInterrupted) break;
Chris Lattner0eb5ce92003-01-23 02:48:33 +0000758 --Simplification;
Dan Gohmanee051522009-07-16 15:30:09 +0000759 outs() << "\n*** Attempting to reduce testcase by deleting instruc"
760 << "tions: Simplification Level #" << Simplification << '\n';
Chris Lattner0eb5ce92003-01-23 02:48:33 +0000761
Misha Brukman7eb05a12003-08-18 14:43:39 +0000762 // Now that we have deleted the functions that are unnecessary for the
763 // program, try to remove instructions that are not necessary to cause the
Chris Lattner0eb5ce92003-01-23 02:48:33 +0000764 // crash. To do this, we loop through all of the instructions in the
765 // remaining functions, deleting them (replacing any values produced with
766 // nulls), and then running ADCE and SimplifyCFG. If the transformed input
767 // still triggers failure, keep deleting until we cannot trigger failure
768 // anymore.
769 //
Chris Lattner94b2bfb2004-02-18 23:59:11 +0000770 unsigned InstructionsToSkipBeforeDeleting = 0;
Chris Lattner0eb5ce92003-01-23 02:48:33 +0000771 TryAgain:
Misha Brukman650ba8e2005-04-22 00:00:37 +0000772
Chris Lattner0eb5ce92003-01-23 02:48:33 +0000773 // Loop over all of the (non-terminator) instructions remaining in the
774 // function, attempting to delete them.
Chris Lattner94b2bfb2004-02-18 23:59:11 +0000775 unsigned CurInstructionNum = 0;
Chris Lattner8bda4c42004-02-18 23:26:28 +0000776 for (Module::const_iterator FI = BD.getProgram()->begin(),
777 E = BD.getProgram()->end(); FI != E; ++FI)
Reid Spencer5301e7c2007-01-30 20:08:39 +0000778 if (!FI->isDeclaration())
Chris Lattner8bda4c42004-02-18 23:26:28 +0000779 for (Function::const_iterator BI = FI->begin(), E = FI->end(); BI != E;
780 ++BI)
781 for (BasicBlock::const_iterator I = BI->begin(), E = --BI->end();
Bill Wendling2990ec62011-12-25 06:56:22 +0000782 I != E; ++I, ++CurInstructionNum) {
Chris Lattner94b2bfb2004-02-18 23:59:11 +0000783 if (InstructionsToSkipBeforeDeleting) {
784 --InstructionsToSkipBeforeDeleting;
785 } else {
Chris Lattnerbeb01fa2005-08-02 02:16:17 +0000786 if (BugpointIsInterrupted) goto ExitLoops;
787
Eli Friedmand4e02a52011-11-01 04:40:56 +0000788 if (isa<LandingPadInst>(I))
789 continue;
790
Dan Gohmanee051522009-07-16 15:30:09 +0000791 outs() << "Checking instruction: " << *I;
Rafael Espindola28b351a2014-08-26 17:19:03 +0000792 std::unique_ptr<Module> M =
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000793 BD.deleteInstructionFromProgram(&*I, Simplification);
Misha Brukman650ba8e2005-04-22 00:00:37 +0000794
Chris Lattner94b2bfb2004-02-18 23:59:11 +0000795 // Find out if the pass still crashes on this pass...
Rafael Espindola28b351a2014-08-26 17:19:03 +0000796 if (TestFn(BD, M.get())) {
Chris Lattner94b2bfb2004-02-18 23:59:11 +0000797 // Yup, it does, we delete the old module, and continue trying
798 // to reduce the testcase...
Rafael Espindola28b351a2014-08-26 17:19:03 +0000799 BD.setNewProgram(M.release());
Chris Lattner94b2bfb2004-02-18 23:59:11 +0000800 InstructionsToSkipBeforeDeleting = CurInstructionNum;
801 goto TryAgain; // I wish I had a multi-level break here!
802 }
Chris Lattner0eb5ce92003-01-23 02:48:33 +0000803 }
Bill Wendling2990ec62011-12-25 06:56:22 +0000804 }
Chris Lattner94b2bfb2004-02-18 23:59:11 +0000805
806 if (InstructionsToSkipBeforeDeleting) {
807 InstructionsToSkipBeforeDeleting = 0;
808 goto TryAgain;
809 }
Misha Brukman650ba8e2005-04-22 00:00:37 +0000810
Chris Lattner0eb5ce92003-01-23 02:48:33 +0000811 } while (Simplification);
Keno Fischer34ca8312015-11-06 00:12:50 +0000812
813 if (!NoNamedMDRM) {
814 BD.EmitProgressBitcode(BD.getProgram(), "reduced-instructions");
815
816 if (!BugpointIsInterrupted) {
817 // Try to reduce the amount of global metadata (particularly debug info),
818 // by dropping global named metadata that anchors them
819 outs() << "\n*** Attempting to remove named metadata: ";
820 std::vector<std::string> NamedMDNames;
821 for (auto &NamedMD : BD.getProgram()->named_metadata())
822 NamedMDNames.push_back(NamedMD.getName().str());
823 ReduceCrashingNamedMD(BD, TestFn).reduceList(NamedMDNames, Error);
824 }
825
826 if (!BugpointIsInterrupted) {
827 // Now that we quickly dropped all the named metadata that doesn't
828 // contribute to the crash, bisect the operands of the remaining ones
829 std::vector<const MDNode *> NamedMDOps;
830 for (auto &NamedMD : BD.getProgram()->named_metadata())
831 NamedMDOps.insert(NamedMDOps.end(), NamedMD.op_begin(),
832 NamedMD.op_end());
833 ReduceCrashingNamedMDOps(BD, TestFn).reduceList(NamedMDOps, Error);
834 }
835 }
836
Chris Lattnerbeb01fa2005-08-02 02:16:17 +0000837ExitLoops:
Chris Lattner514c02e2003-02-28 16:13:20 +0000838
839 // Try to clean up the testcase by running funcresolve and globaldce...
Chris Lattnerbeb01fa2005-08-02 02:16:17 +0000840 if (!BugpointIsInterrupted) {
Dan Gohmanee051522009-07-16 15:30:09 +0000841 outs() << "\n*** Attempting to perform final cleanups: ";
Chris Lattnerbeb01fa2005-08-02 02:16:17 +0000842 Module *M = CloneModule(BD.getProgram());
Rafael Espindola28b351a2014-08-26 17:19:03 +0000843 M = BD.performFinalCleanups(M, true).release();
Misha Brukman650ba8e2005-04-22 00:00:37 +0000844
Chris Lattnerbeb01fa2005-08-02 02:16:17 +0000845 // Find out if the pass still crashes on the cleaned up program...
846 if (TestFn(BD, M)) {
847 BD.setNewProgram(M); // Yup, it does, keep the reduced version...
848 } else {
849 delete M;
850 }
Chris Lattner514c02e2003-02-28 16:13:20 +0000851 }
852
Rafael Espindola594994a2010-07-28 18:12:30 +0000853 BD.EmitProgressBitcode(BD.getProgram(), "reduced-simplified");
Chris Lattner514c02e2003-02-28 16:13:20 +0000854
Misha Brukman650ba8e2005-04-22 00:00:37 +0000855 return false;
Chris Lattner73a6bdd2002-11-20 22:28:10 +0000856}
Brian Gaeke960707c2003-11-11 22:41:34 +0000857
Rafael Espindolad1c7ef42010-08-05 03:00:22 +0000858static bool TestForOptimizerCrash(const BugDriver &BD, Module *M) {
Chris Lattner8bda4c42004-02-18 23:26:28 +0000859 return BD.runPasses(M);
860}
Chris Lattneread1dff2004-02-18 21:02:04 +0000861
Chris Lattner8bda4c42004-02-18 23:26:28 +0000862/// debugOptimizerCrash - This method is called when some pass crashes on input.
863/// It attempts to prune down the testcase to something reasonable, and figure
864/// out exactly which pass is crashing.
865///
Patrick Jenkinsc46c0382006-08-15 16:40:49 +0000866bool BugDriver::debugOptimizerCrash(const std::string &ID) {
Dan Gohmanee051522009-07-16 15:30:09 +0000867 outs() << "\n*** Debugging optimizer crash!\n";
Chris Lattner8bda4c42004-02-18 23:26:28 +0000868
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000869 std::string Error;
Chris Lattner8bda4c42004-02-18 23:26:28 +0000870 // Reduce the list of passes which causes the optimizer to crash...
JF Bastienf87e20d2015-04-20 23:42:22 +0000871 if (!BugpointIsInterrupted && !DontReducePassList)
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000872 ReducePassList(*this).reduceList(PassesToRun, Error);
873 assert(Error.empty());
Chris Lattner8bda4c42004-02-18 23:26:28 +0000874
Dan Gohmanee051522009-07-16 15:30:09 +0000875 outs() << "\n*** Found crashing pass"
876 << (PassesToRun.size() == 1 ? ": " : "es: ")
877 << getPassesString(PassesToRun) << '\n';
Chris Lattner8bda4c42004-02-18 23:26:28 +0000878
Rafael Espindola594994a2010-07-28 18:12:30 +0000879 EmitProgressBitcode(Program, ID);
Chris Lattner8bda4c42004-02-18 23:26:28 +0000880
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000881 bool Success = DebugACrash(*this, TestForOptimizerCrash, Error);
882 assert(Error.empty());
883 return Success;
Chris Lattner8bda4c42004-02-18 23:26:28 +0000884}
885
Rafael Espindolad1c7ef42010-08-05 03:00:22 +0000886static bool TestForCodeGenCrash(const BugDriver &BD, Module *M) {
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000887 std::string Error;
888 BD.compileProgram(M, &Error);
889 if (!Error.empty()) {
Dan Gohmand8db3762009-07-15 16:35:29 +0000890 errs() << "<crash>\n";
Chris Lattner8bda4c42004-02-18 23:26:28 +0000891 return true; // Tool is still crashing.
892 }
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000893 errs() << '\n';
894 return false;
Chris Lattner8bda4c42004-02-18 23:26:28 +0000895}
Chris Lattneread1dff2004-02-18 21:02:04 +0000896
897/// debugCodeGeneratorCrash - This method is called when the code generator
898/// crashes on an input. It attempts to reduce the input as much as possible
899/// while still causing the code generator to crash.
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000900bool BugDriver::debugCodeGeneratorCrash(std::string &Error) {
Dan Gohmand8db3762009-07-15 16:35:29 +0000901 errs() << "*** Debugging code generator crash!\n";
Chris Lattneread1dff2004-02-18 21:02:04 +0000902
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000903 return DebugACrash(*this, TestForCodeGenCrash, Error);
Chris Lattneread1dff2004-02-18 21:02:04 +0000904}