blob: ef6a214fde2054a5a84138c39beb4f9dad92d1b5 [file] [log] [blame]
Chris Lattnerafade922002-11-20 22:28:10 +00001//===- CrashDebugger.cpp - Debug compilation crashes ----------------------===//
Misha Brukman3da94ae2005-04-22 00:00:37 +00002//
John Criswell7c0e0222003-10-20 17:47:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner21c62da2007-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 Brukman3da94ae2005-04-22 00:00:37 +00007//
John Criswell7c0e0222003-10-20 17:47:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerafade922002-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 Lattneraae33f92003-04-24 22:24:58 +000015#include "ListReducer.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000016#include "ToolRunner.h"
17#include "llvm/ADT/SmallPtrSet.h"
Keno Fischer11e0c312015-11-06 00:12:50 +000018#include "llvm/ADT/StringSet.h"
Justin Bogner388e8b92016-09-02 01:21:37 +000019#include "llvm/Analysis/TargetTransformInfo.h"
David Blaikie8325fb22018-06-04 21:23:21 +000020#include "llvm/Transforms/Utils/Local.h"
Chandler Carruth03e36d72014-03-04 11:45:46 +000021#include "llvm/IR/CFG.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000022#include "llvm/IR/Constants.h"
Michael Ilseman5bd98bf2016-10-25 18:44:13 +000023#include "llvm/IR/DebugInfo.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000024#include "llvm/IR/DerivedTypes.h"
25#include "llvm/IR/Instructions.h"
Chandler Carruth417c5c12015-02-13 10:01:29 +000026#include "llvm/IR/LegacyPassManager.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000027#include "llvm/IR/Module.h"
28#include "llvm/IR/ValueSymbolTable.h"
Chandler Carruth56e13942014-01-13 09:26:24 +000029#include "llvm/IR/Verifier.h"
Misha Brukmane49603d2003-08-07 21:19:30 +000030#include "llvm/Pass.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000031#include "llvm/Support/CommandLine.h"
32#include "llvm/Support/FileUtilities.h"
Chris Lattner286921e2003-04-24 23:51:38 +000033#include "llvm/Transforms/Scalar.h"
Daniel Berlin41bc5c22016-07-27 16:13:25 +000034#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattneraae33f92003-04-24 22:24:58 +000035#include "llvm/Transforms/Utils/Cloning.h"
Chris Lattneraae33f92003-04-24 22:24:58 +000036#include <set>
Chris Lattnerfa761832004-01-14 03:38:37 +000037using namespace llvm;
Chris Lattnerafade922002-11-20 22:28:10 +000038
Andrew Lenharth7c0a9372006-03-05 22:21:36 +000039namespace {
Justin Bogner388e8b92016-09-02 01:21:37 +000040cl::opt<bool> KeepMain("keep-main",
41 cl::desc("Force function reduction to keep main"),
42 cl::init(false));
43cl::opt<bool> NoGlobalRM("disable-global-remove",
44 cl::desc("Do not remove global variables"),
45 cl::init(false));
JF Bastien7b862ec2015-04-20 23:42:22 +000046
Justin Bogner388e8b92016-09-02 01:21:37 +000047cl::opt<bool> ReplaceFuncsWithNull(
48 "replace-funcs-with-null",
49 cl::desc("When stubbing functions, replace all uses will null"),
50 cl::init(false));
51cl::opt<bool> DontReducePassList("disable-pass-list-reduction",
52 cl::desc("Skip pass list reduction steps"),
53 cl::init(false));
Keno Fischer11e0c312015-11-06 00:12:50 +000054
Justin Bogner388e8b92016-09-02 01:21:37 +000055cl::opt<bool> NoNamedMDRM("disable-namedmd-remove",
56 cl::desc("Do not remove global named metadata"),
57 cl::init(false));
Michael Ilseman5bd98bf2016-10-25 18:44:13 +000058cl::opt<bool> NoStripDebugInfo("disable-strip-debuginfo",
59 cl::desc("Do not strip debug info metadata"),
60 cl::init(false));
61cl::opt<bool> NoStripDebugTypeInfo("disable-strip-debug-types",
62 cl::desc("Do not strip debug type info metadata"),
63 cl::init(false));
Justin Bogner388e8b92016-09-02 01:21:37 +000064cl::opt<bool> VerboseErrors("verbose-errors",
Sebastian Pop91aa2f62016-07-15 23:15:06 +000065 cl::desc("Print the output of crashing program"),
66 cl::init(false));
Andrew Lenharth7c0a9372006-03-05 22:21:36 +000067}
68
Brian Gaeked0fde302003-11-11 22:41:34 +000069namespace llvm {
Justin Bogner388e8b92016-09-02 01:21:37 +000070class ReducePassList : public ListReducer<std::string> {
71 BugDriver &BD;
Misha Brukman3da94ae2005-04-22 00:00:37 +000072
Justin Bogner388e8b92016-09-02 01:21:37 +000073public:
74 ReducePassList(BugDriver &bd) : BD(bd) {}
75
Justin Bognerd8090ae2016-09-06 17:18:22 +000076 // Return true iff running the "removed" passes succeeds, and running the
77 // "Kept" passes fail when run on the output of the "removed" passes. If we
78 // return true, we update the current module of bugpoint.
79 Expected<TestResult> doTest(std::vector<std::string> &Removed,
80 std::vector<std::string> &Kept) override;
Justin Bogner388e8b92016-09-02 01:21:37 +000081};
Chris Lattnerfa761832004-01-14 03:38:37 +000082}
Chris Lattneraae33f92003-04-24 22:24:58 +000083
Justin Bognerd8090ae2016-09-06 17:18:22 +000084Expected<ReducePassList::TestResult>
Rafael Espindola8261dfe2010-08-08 03:55:08 +000085ReducePassList::doTest(std::vector<std::string> &Prefix,
Justin Bognerd8090ae2016-09-06 17:18:22 +000086 std::vector<std::string> &Suffix) {
Rafael Espindola11db6df2013-06-17 19:33:18 +000087 std::string PrefixOutput;
Rafael Espindola8b96d7c2018-02-14 19:58:41 +000088 std::unique_ptr<Module> OrigProgram;
Chris Lattneraae33f92003-04-24 22:24:58 +000089 if (!Prefix.empty()) {
Dan Gohmanac95cc72009-07-16 15:30:09 +000090 outs() << "Checking to see if these passes crash: "
91 << getPassesString(Prefix) << ": ";
Rafael Espindola11db6df2013-06-17 19:33:18 +000092 if (BD.runPasses(BD.getProgram(), Prefix, PrefixOutput))
Chris Lattneraae33f92003-04-24 22:24:58 +000093 return KeepPrefix;
Chris Lattnerb417c792003-06-02 04:54:29 +000094
Rafael Espindolacdac12c2018-02-14 21:44:34 +000095 OrigProgram = std::move(BD.Program);
Chris Lattnerb417c792003-06-02 04:54:29 +000096
Rafael Espindolacdac12c2018-02-14 21:44:34 +000097 BD.Program = parseInputFile(PrefixOutput, BD.getContext());
Craig Topper573faec2014-04-25 04:24:47 +000098 if (BD.Program == nullptr) {
Dan Gohman65f57c22009-07-15 16:35:29 +000099 errs() << BD.getToolName() << ": Error reading bitcode file '"
Rafael Espindola11db6df2013-06-17 19:33:18 +0000100 << PrefixOutput << "'!\n";
Chris Lattnerb417c792003-06-02 04:54:29 +0000101 exit(1);
102 }
Rafael Espindola11db6df2013-06-17 19:33:18 +0000103 sys::fs::remove(PrefixOutput);
Chris Lattneraae33f92003-04-24 22:24:58 +0000104 }
105
Justin Bogner388e8b92016-09-02 01:21:37 +0000106 outs() << "Checking to see if these passes crash: " << getPassesString(Suffix)
107 << ": ";
Misha Brukman3da94ae2005-04-22 00:00:37 +0000108
Rafael Espindola8b96d7c2018-02-14 19:58:41 +0000109 if (BD.runPasses(BD.getProgram(), Suffix))
110 return KeepSuffix; // The suffix crashes alone...
Chris Lattneraae33f92003-04-24 22:24:58 +0000111
112 // Nothing failed, restore state...
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000113 if (OrigProgram)
114 BD.Program = std::move(OrigProgram);
Chris Lattneraae33f92003-04-24 22:24:58 +0000115 return NoFailure;
116}
117
Vedant Kumar26757892018-02-08 18:46:49 +0000118using BugTester = bool (*)(const BugDriver &, Module *);
119
Bill Wendling4e3be892006-10-25 18:36:14 +0000120namespace {
Vedant Kumar0f1e6f82018-02-08 20:27:09 +0000121/// ReduceCrashingGlobalInitializers - This works by removing global variable
122/// initializers and seeing if the program still crashes. If it does, then we
123/// keep that program and try again.
124class ReduceCrashingGlobalInitializers : public ListReducer<GlobalVariable *> {
Justin Bogner388e8b92016-09-02 01:21:37 +0000125 BugDriver &BD;
Vedant Kumar26757892018-02-08 18:46:49 +0000126 BugTester TestFn;
Justin Bogner388e8b92016-09-02 01:21:37 +0000127
128public:
Vedant Kumar0f1e6f82018-02-08 20:27:09 +0000129 ReduceCrashingGlobalInitializers(BugDriver &bd, BugTester testFn)
Bill Wendling4e3be892006-10-25 18:36:14 +0000130 : BD(bd), TestFn(testFn) {}
131
Justin Bognerd8090ae2016-09-06 17:18:22 +0000132 Expected<TestResult> doTest(std::vector<GlobalVariable *> &Prefix,
133 std::vector<GlobalVariable *> &Kept) override {
Justin Bogner388e8b92016-09-02 01:21:37 +0000134 if (!Kept.empty() && TestGlobalVariables(Kept))
135 return KeepSuffix;
136 if (!Prefix.empty() && TestGlobalVariables(Prefix))
137 return KeepPrefix;
138 return NoFailure;
139 }
Bill Wendling4e3be892006-10-25 18:36:14 +0000140
Justin Bogner388e8b92016-09-02 01:21:37 +0000141 bool TestGlobalVariables(std::vector<GlobalVariable *> &GVs);
142};
Bill Wendling4e3be892006-10-25 18:36:14 +0000143}
144
Vedant Kumar0f1e6f82018-02-08 20:27:09 +0000145bool ReduceCrashingGlobalInitializers::TestGlobalVariables(
Justin Bogner388e8b92016-09-02 01:21:37 +0000146 std::vector<GlobalVariable *> &GVs) {
Bill Wendling4e3be892006-10-25 18:36:14 +0000147 // Clone the program to try hacking it apart...
Rafael Espindola1ed219a2010-10-13 01:36:30 +0000148 ValueToValueMapTy VMap;
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000149 std::unique_ptr<Module> M = CloneModule(BD.getProgram(), VMap);
Bill Wendling4e3be892006-10-25 18:36:14 +0000150
151 // Convert list to set for fast lookup...
Justin Bogner388e8b92016-09-02 01:21:37 +0000152 std::set<GlobalVariable *> GVSet;
Bill Wendling4e3be892006-10-25 18:36:14 +0000153
154 for (unsigned i = 0, e = GVs.size(); i != e; ++i) {
Justin Bogner388e8b92016-09-02 01:21:37 +0000155 GlobalVariable *CMGV = cast<GlobalVariable>(VMap[GVs[i]]);
Bill Wendling4e3be892006-10-25 18:36:14 +0000156 assert(CMGV && "Global Variable not in module?!");
157 GVSet.insert(CMGV);
158 }
159
Dan Gohmanac95cc72009-07-16 15:30:09 +0000160 outs() << "Checking for crash with only these global variables: ";
Bill Wendling4e3be892006-10-25 18:36:14 +0000161 PrintGlobalVariableList(GVs);
Dan Gohmanac95cc72009-07-16 15:30:09 +0000162 outs() << ": ";
Bill Wendling4e3be892006-10-25 18:36:14 +0000163
164 // Loop over and delete any global variables which we aren't supposed to be
165 // playing with...
Duncan P. N. Exon Smith1e221d52015-10-20 19:36:39 +0000166 for (GlobalVariable &I : M->globals())
167 if (I.hasInitializer() && !GVSet.count(&I)) {
Hal Finkelc818be02015-11-26 19:23:49 +0000168 DeleteGlobalInitializer(&I);
Duncan P. N. Exon Smith1e221d52015-10-20 19:36:39 +0000169 I.setLinkage(GlobalValue::ExternalLinkage);
Justin Lebarb570d712016-06-15 23:20:12 +0000170 I.setComdat(nullptr);
Bill Wendling4e3be892006-10-25 18:36:14 +0000171 }
172
173 // Try running the hacked up program...
Vedant Kumar0f1e6f82018-02-08 20:27:09 +0000174 if (TestFn(BD, M.get())) {
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000175 BD.setNewProgram(std::move(M)); // It crashed, keep the trimmed version...
Bill Wendling4e3be892006-10-25 18:36:14 +0000176
177 // Make sure to use global variable pointers that point into the now-current
178 // module.
179 GVs.assign(GVSet.begin(), GVSet.end());
180 return true;
181 }
182
Bill Wendling4e3be892006-10-25 18:36:14 +0000183 return false;
184}
185
David Blaikie2d24e2a2011-12-20 02:50:00 +0000186namespace {
Justin Bogner388e8b92016-09-02 01:21:37 +0000187/// ReduceCrashingFunctions reducer - This works by removing functions and
188/// seeing if the program still crashes. If it does, then keep the newer,
189/// smaller program.
190///
191class ReduceCrashingFunctions : public ListReducer<Function *> {
192 BugDriver &BD;
Vedant Kumar26757892018-02-08 18:46:49 +0000193 BugTester TestFn;
Justin Bogner388e8b92016-09-02 01:21:37 +0000194
195public:
Vedant Kumar26757892018-02-08 18:46:49 +0000196 ReduceCrashingFunctions(BugDriver &bd, BugTester testFn)
Chris Lattner8b189272004-02-18 23:26:28 +0000197 : BD(bd), TestFn(testFn) {}
Misha Brukman3da94ae2005-04-22 00:00:37 +0000198
Justin Bognerd8090ae2016-09-06 17:18:22 +0000199 Expected<TestResult> doTest(std::vector<Function *> &Prefix,
200 std::vector<Function *> &Kept) override {
Justin Bogner388e8b92016-09-02 01:21:37 +0000201 if (!Kept.empty() && TestFuncs(Kept))
202 return KeepSuffix;
203 if (!Prefix.empty() && TestFuncs(Prefix))
204 return KeepPrefix;
205 return NoFailure;
206 }
Misha Brukman3da94ae2005-04-22 00:00:37 +0000207
Justin Bogner388e8b92016-09-02 01:21:37 +0000208 bool TestFuncs(std::vector<Function *> &Prefix);
209};
Chris Lattnerfa761832004-01-14 03:38:37 +0000210}
Chris Lattneraae33f92003-04-24 22:24:58 +0000211
Justin Bogner388e8b92016-09-02 01:21:37 +0000212static void RemoveFunctionReferences(Module *M, const char *Name) {
JF Bastien7b862ec2015-04-20 23:42:22 +0000213 auto *UsedVar = M->getGlobalVariable(Name, true);
Justin Bogner388e8b92016-09-02 01:21:37 +0000214 if (!UsedVar || !UsedVar->hasInitializer())
215 return;
JF Bastien7b862ec2015-04-20 23:42:22 +0000216 if (isa<ConstantAggregateZero>(UsedVar->getInitializer())) {
217 assert(UsedVar->use_empty());
218 UsedVar->eraseFromParent();
219 return;
220 }
221 auto *OldUsedVal = cast<ConstantArray>(UsedVar->getInitializer());
Justin Bogner388e8b92016-09-02 01:21:37 +0000222 std::vector<Constant *> Used;
223 for (Value *V : OldUsedVal->operand_values()) {
JF Bastien7b862ec2015-04-20 23:42:22 +0000224 Constant *Op = cast<Constant>(V->stripPointerCasts());
Justin Bogner388e8b92016-09-02 01:21:37 +0000225 if (!Op->isNullValue()) {
JF Bastien7b862ec2015-04-20 23:42:22 +0000226 Used.push_back(cast<Constant>(V));
227 }
228 }
229 auto *NewValElemTy = OldUsedVal->getType()->getElementType();
230 auto *NewValTy = ArrayType::get(NewValElemTy, Used.size());
231 auto *NewUsedVal = ConstantArray::get(NewValTy, Used);
232 UsedVar->mutateType(NewUsedVal->getType()->getPointerTo());
233 UsedVar->setInitializer(NewUsedVal);
234}
235
Justin Bogner388e8b92016-09-02 01:21:37 +0000236bool ReduceCrashingFunctions::TestFuncs(std::vector<Function *> &Funcs) {
Dmitri Gribenkobf2f2702013-09-02 01:18:56 +0000237 // If main isn't present, claim there is no problem.
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000238 if (KeepMain && !is_contained(Funcs, BD.getProgram().getFunction("main")))
Andrew Lenharth7c0a9372006-03-05 22:21:36 +0000239 return false;
240
Misha Brukmancf00c4a2003-10-10 17:57:28 +0000241 // Clone the program to try hacking it apart...
Rafael Espindola1ed219a2010-10-13 01:36:30 +0000242 ValueToValueMapTy VMap;
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000243 std::unique_ptr<Module> M = CloneModule(BD.getProgram(), VMap);
Misha Brukman3da94ae2005-04-22 00:00:37 +0000244
Chris Lattneraae33f92003-04-24 22:24:58 +0000245 // Convert list to set for fast lookup...
Justin Bogner388e8b92016-09-02 01:21:37 +0000246 std::set<Function *> Functions;
Chris Lattneraae33f92003-04-24 22:24:58 +0000247 for (unsigned i = 0, e = Funcs.size(); i != e; ++i) {
Devang Patele9916a32010-06-24 00:33:28 +0000248 Function *CMF = cast<Function>(VMap[Funcs[i]]);
Chris Lattneraae33f92003-04-24 22:24:58 +0000249 assert(CMF && "Function not in module?!");
Reid Spenceref9b9a72007-02-05 20:47:22 +0000250 assert(CMF->getFunctionType() == Funcs[i]->getFunctionType() && "wrong ty");
Dan Gohmanf6dd0eb2009-03-06 02:16:23 +0000251 assert(CMF->getName() == Funcs[i]->getName() && "wrong name");
Chris Lattnerf607b792003-04-24 22:54:06 +0000252 Functions.insert(CMF);
Chris Lattneraae33f92003-04-24 22:24:58 +0000253 }
254
Dan Gohmanac95cc72009-07-16 15:30:09 +0000255 outs() << "Checking for crash with only these functions: ";
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000256 PrintFunctionList(Funcs);
Dan Gohmanac95cc72009-07-16 15:30:09 +0000257 outs() << ": ";
JF Bastien7b862ec2015-04-20 23:42:22 +0000258 if (!ReplaceFuncsWithNull) {
259 // Loop over and delete any functions which we aren't supposed to be playing
260 // with...
Duncan P. N. Exon Smith1e221d52015-10-20 19:36:39 +0000261 for (Function &I : *M)
262 if (!I.isDeclaration() && !Functions.count(&I))
263 DeleteFunctionBody(&I);
JF Bastien7b862ec2015-04-20 23:42:22 +0000264 } else {
Justin Bogner388e8b92016-09-02 01:21:37 +0000265 std::vector<GlobalValue *> ToRemove;
JF Bastien7b862ec2015-04-20 23:42:22 +0000266 // First, remove aliases to functions we're about to purge.
267 for (GlobalAlias &Alias : M->aliases()) {
David Majnemerfea3ecb2016-05-04 00:20:48 +0000268 GlobalObject *Root = Alias.getBaseObject();
269 Function *F = dyn_cast_or_null<Function>(Root);
JF Bastien7b862ec2015-04-20 23:42:22 +0000270 if (F) {
271 if (Functions.count(F))
272 // We're keeping this function.
273 continue;
274 } else if (Root->isNullValue()) {
275 // This referenced a globalalias that we've already replaced,
276 // so we still need to replace this alias.
277 } else if (!F) {
278 // Not a function, therefore not something we mess with.
279 continue;
280 }
Chris Lattneraae33f92003-04-24 22:24:58 +0000281
JF Bastien7b862ec2015-04-20 23:42:22 +0000282 PointerType *Ty = cast<PointerType>(Alias.getType());
283 Constant *Replacement = ConstantPointerNull::get(Ty);
284 Alias.replaceAllUsesWith(Replacement);
285 ToRemove.push_back(&Alias);
286 }
Chris Lattneraae33f92003-04-24 22:24:58 +0000287
Duncan P. N. Exon Smith1e221d52015-10-20 19:36:39 +0000288 for (Function &I : *M) {
289 if (!I.isDeclaration() && !Functions.count(&I)) {
290 PointerType *Ty = cast<PointerType>(I.getType());
JF Bastien7b862ec2015-04-20 23:42:22 +0000291 Constant *Replacement = ConstantPointerNull::get(Ty);
Duncan P. N. Exon Smith1e221d52015-10-20 19:36:39 +0000292 I.replaceAllUsesWith(Replacement);
293 ToRemove.push_back(&I);
JF Bastien7b862ec2015-04-20 23:42:22 +0000294 }
295 }
296
297 for (auto *F : ToRemove) {
298 F->eraseFromParent();
299 }
300
301 // Finally, remove any null members from any global intrinsic.
Rafael Espindola16b4c292018-02-14 20:21:20 +0000302 RemoveFunctionReferences(M.get(), "llvm.used");
303 RemoveFunctionReferences(M.get(), "llvm.compiler.used");
JF Bastien7b862ec2015-04-20 23:42:22 +0000304 }
Chris Lattneraae33f92003-04-24 22:24:58 +0000305 // Try running the hacked up program...
Rafael Espindola16b4c292018-02-14 20:21:20 +0000306 if (TestFn(BD, M.get())) {
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000307 BD.setNewProgram(std::move(M)); // It crashed, keep the trimmed version...
Chris Lattneraae33f92003-04-24 22:24:58 +0000308
309 // Make sure to use function pointers that point into the now-current
310 // module.
311 Funcs.assign(Functions.begin(), Functions.end());
312 return true;
313 }
Chris Lattneraae33f92003-04-24 22:24:58 +0000314 return false;
315}
316
Chris Lattnerf913f402004-02-18 21:29:46 +0000317namespace {
Brian Gesiak79550f62018-12-19 03:42:19 +0000318/// ReduceCrashingFunctionAttributes reducer - This works by removing
319/// attributes on a particular function and seeing if the program still crashes.
320/// If it does, then keep the newer, smaller program.
321///
322class ReduceCrashingFunctionAttributes : public ListReducer<Attribute> {
323 BugDriver &BD;
324 std::string FnName;
325 BugTester TestFn;
326
327public:
328 ReduceCrashingFunctionAttributes(BugDriver &bd, const std::string &FnName,
329 BugTester testFn)
330 : BD(bd), FnName(FnName), TestFn(testFn) {}
331
332 Expected<TestResult> doTest(std::vector<Attribute> &Prefix,
333 std::vector<Attribute> &Kept) override {
334 if (!Kept.empty() && TestFuncAttrs(Kept))
335 return KeepSuffix;
336 if (!Prefix.empty() && TestFuncAttrs(Prefix))
337 return KeepPrefix;
338 return NoFailure;
339 }
340
341 bool TestFuncAttrs(std::vector<Attribute> &Attrs);
342};
343}
344
345bool ReduceCrashingFunctionAttributes::TestFuncAttrs(
346 std::vector<Attribute> &Attrs) {
347 // Clone the program to try hacking it apart...
348 std::unique_ptr<Module> M = CloneModule(BD.getProgram());
349 Function *F = M->getFunction(FnName);
350
351 // Build up an AttributeList from the attributes we've been given by the
352 // reducer.
353 AttrBuilder AB;
354 for (auto A : Attrs)
355 AB.addAttribute(A);
356 AttributeList NewAttrs;
357 NewAttrs =
358 NewAttrs.addAttributes(BD.getContext(), AttributeList::FunctionIndex, AB);
359
360 // Set this new list of attributes on the function.
361 F->setAttributes(NewAttrs);
362
363 // Try running on the hacked up program...
364 if (TestFn(BD, M.get())) {
365 BD.setNewProgram(std::move(M)); // It crashed, keep the trimmed version...
366
367 // Pass along the set of attributes that caused the crash.
368 Attrs.clear();
369 for (Attribute A : NewAttrs.getFnAttributes()) {
370 Attrs.push_back(A);
371 }
372 return true;
373 }
374 return false;
375}
376
377namespace {
Daniel Berlinad0220c2016-07-28 22:29:25 +0000378/// Simplify the CFG without completely destroying it.
379/// This is not well defined, but basically comes down to "try to eliminate
380/// unreachable blocks and constant fold terminators without deciding that
381/// certain undefined behavior cuts off the program at the legs".
382void simpleSimplifyCfg(Function &F, SmallVectorImpl<BasicBlock *> &BBs) {
383 if (F.empty())
384 return;
385
386 for (auto *BB : BBs) {
387 ConstantFoldTerminator(BB);
388 MergeBlockIntoPredecessor(BB);
389 }
390
391 // Remove unreachable blocks
392 // removeUnreachableBlocks can't be used here, it will turn various
393 // undefined behavior into unreachables, but bugpoint was the thing that
394 // generated the undefined behavior, and we don't want it to kill the entire
395 // program.
396 SmallPtrSet<BasicBlock *, 16> Visited;
397 for (auto *BB : depth_first(&F.getEntryBlock()))
398 Visited.insert(BB);
399
400 SmallVector<BasicBlock *, 16> Unreachable;
401 for (auto &BB : F)
402 if (!Visited.count(&BB))
403 Unreachable.push_back(&BB);
404
405 // The dead BB's may be in a dead cycle or otherwise have references to each
406 // other. Because of this, we have to drop all references first, then delete
407 // them all at once.
Justin Bogner388e8b92016-09-02 01:21:37 +0000408 for (auto *BB : Unreachable) {
Daniel Berlinad0220c2016-07-28 22:29:25 +0000409 for (BasicBlock *Successor : successors(&*BB))
410 if (Visited.count(Successor))
411 Successor->removePredecessor(&*BB);
412 BB->dropAllReferences();
413 }
414 for (auto *BB : Unreachable)
415 BB->eraseFromParent();
416}
Justin Bogner388e8b92016-09-02 01:21:37 +0000417/// ReduceCrashingBlocks reducer - This works by setting the terminators of
418/// all terminators except the specified basic blocks to a 'ret' instruction,
419/// then running the simplify-cfg pass. This has the effect of chopping up
420/// the CFG really fast which can reduce large functions quickly.
421///
422class ReduceCrashingBlocks : public ListReducer<const BasicBlock *> {
423 BugDriver &BD;
Vedant Kumar26757892018-02-08 18:46:49 +0000424 BugTester TestFn;
Justin Bogner388e8b92016-09-02 01:21:37 +0000425
426public:
Vedant Kumar26757892018-02-08 18:46:49 +0000427 ReduceCrashingBlocks(BugDriver &BD, BugTester testFn)
Daniel Berlinad0220c2016-07-28 22:29:25 +0000428 : BD(BD), TestFn(testFn) {}
Misha Brukman3da94ae2005-04-22 00:00:37 +0000429
Justin Bognerd8090ae2016-09-06 17:18:22 +0000430 Expected<TestResult> doTest(std::vector<const BasicBlock *> &Prefix,
431 std::vector<const BasicBlock *> &Kept) override {
Justin Bogner388e8b92016-09-02 01:21:37 +0000432 if (!Kept.empty() && TestBlocks(Kept))
433 return KeepSuffix;
434 if (!Prefix.empty() && TestBlocks(Prefix))
435 return KeepPrefix;
436 return NoFailure;
437 }
Misha Brukman3da94ae2005-04-22 00:00:37 +0000438
Justin Bogner388e8b92016-09-02 01:21:37 +0000439 bool TestBlocks(std::vector<const BasicBlock *> &Prefix);
440};
Chris Lattnerfa761832004-01-14 03:38:37 +0000441}
Chris Lattner286921e2003-04-24 23:51:38 +0000442
Justin Bogner388e8b92016-09-02 01:21:37 +0000443bool ReduceCrashingBlocks::TestBlocks(std::vector<const BasicBlock *> &BBs) {
Misha Brukmancf00c4a2003-10-10 17:57:28 +0000444 // Clone the program to try hacking it apart...
Rafael Espindola1ed219a2010-10-13 01:36:30 +0000445 ValueToValueMapTy VMap;
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000446 std::unique_ptr<Module> M = CloneModule(BD.getProgram(), VMap);
Misha Brukman3da94ae2005-04-22 00:00:37 +0000447
Chris Lattner286921e2003-04-24 23:51:38 +0000448 // Convert list to set for fast lookup...
Justin Bogner388e8b92016-09-02 01:21:37 +0000449 SmallPtrSet<BasicBlock *, 8> Blocks;
Nick Lewyckye0325902009-04-04 09:39:23 +0000450 for (unsigned i = 0, e = BBs.size(); i != e; ++i)
Devang Patele9916a32010-06-24 00:33:28 +0000451 Blocks.insert(cast<BasicBlock>(VMap[BBs[i]]));
Chris Lattner286921e2003-04-24 23:51:38 +0000452
Dan Gohmanac95cc72009-07-16 15:30:09 +0000453 outs() << "Checking for crash with only these blocks:";
Chris Lattner73b96bd2003-10-27 04:44:59 +0000454 unsigned NumPrint = Blocks.size();
Justin Bogner388e8b92016-09-02 01:21:37 +0000455 if (NumPrint > 10)
456 NumPrint = 10;
Chris Lattner73b96bd2003-10-27 04:44:59 +0000457 for (unsigned i = 0, e = NumPrint; i != e; ++i)
Dan Gohmanac95cc72009-07-16 15:30:09 +0000458 outs() << " " << BBs[i]->getName();
Chris Lattner73b96bd2003-10-27 04:44:59 +0000459 if (NumPrint < Blocks.size())
Dan Gohmanac95cc72009-07-16 15:30:09 +0000460 outs() << "... <" << Blocks.size() << " total>";
461 outs() << ": ";
Chris Lattner286921e2003-04-24 23:51:38 +0000462
463 // Loop over and delete any hack up any blocks that are not listed...
Vedant Kumar00088b82018-02-09 05:09:50 +0000464 for (Function &F : M->functions()) {
465 for (BasicBlock &BB : F) {
466 if (!Blocks.count(&BB) && BB.getTerminator()->getNumSuccessors()) {
Chris Lattner286921e2003-04-24 23:51:38 +0000467 // Loop over all of the successors of this block, deleting any PHI nodes
468 // that might include it.
Vedant Kumar00088b82018-02-09 05:09:50 +0000469 for (BasicBlock *Succ : successors(&BB))
470 Succ->removePredecessor(&BB);
Chris Lattner286921e2003-04-24 23:51:38 +0000471
Chandler Carruthd8d83712018-10-15 10:42:50 +0000472 Instruction *BBTerm = BB.getTerminator();
Philip Reames2d7feeb2016-06-29 00:15:35 +0000473 if (BBTerm->isEHPad() || BBTerm->getType()->isTokenTy())
David Majnemerd9aac4c2015-11-08 04:16:12 +0000474 continue;
Philip Reames2d7feeb2016-06-29 00:15:35 +0000475 if (!BBTerm->getType()->isVoidTy())
Owen Andersona7235ea2009-07-31 20:28:14 +0000476 BBTerm->replaceAllUsesWith(Constant::getNullValue(BBTerm->getType()));
Chris Lattner8bc098b2003-11-22 02:10:38 +0000477
Chris Lattnere78109e2008-04-28 00:04:58 +0000478 // Replace the old terminator instruction.
Vedant Kumar00088b82018-02-09 05:09:50 +0000479 BB.getInstList().pop_back();
480 new UnreachableInst(BB.getContext(), &BB);
Chris Lattner286921e2003-04-24 23:51:38 +0000481 }
Vedant Kumar00088b82018-02-09 05:09:50 +0000482 }
483 }
Chris Lattner286921e2003-04-24 23:51:38 +0000484
485 // The CFG Simplifier pass may delete one of the basic blocks we are
486 // interested in. If it does we need to take the block out of the list. Make
487 // a "persistent mapping" by turning basic blocks into <function, name> pairs.
488 // This won't work well if blocks are unnamed, but that is just the risk we
Vedant Kumar00088b82018-02-09 05:09:50 +0000489 // have to take. FIXME: Can we just name the blocks?
Justin Bogner388e8b92016-09-02 01:21:37 +0000490 std::vector<std::pair<std::string, std::string>> BlockInfo;
Chris Lattner286921e2003-04-24 23:51:38 +0000491
Craig Topper273fd112014-08-24 23:23:06 +0000492 for (BasicBlock *BB : Blocks)
Benjamin Kramer9589ff82015-05-29 19:43:39 +0000493 BlockInfo.emplace_back(BB->getParent()->getName(), BB->getName());
Justin Bogner388e8b92016-09-02 01:21:37 +0000494
Daniel Berlinad0220c2016-07-28 22:29:25 +0000495 SmallVector<BasicBlock *, 16> ToProcess;
Justin Bogner388e8b92016-09-02 01:21:37 +0000496 for (auto &F : *M) {
Daniel Berlinad0220c2016-07-28 22:29:25 +0000497 for (auto &BB : F)
498 if (!Blocks.count(&BB))
499 ToProcess.push_back(&BB);
500 simpleSimplifyCfg(F, ToProcess);
501 ToProcess.clear();
502 }
503 // Verify we didn't break anything
Rafael Espindola866aa0d2010-08-10 15:46:11 +0000504 std::vector<std::string> Passes;
Rafael Espindola866aa0d2010-08-10 15:46:11 +0000505 Passes.push_back("verify");
Vedant Kumar00088b82018-02-09 05:09:50 +0000506 std::unique_ptr<Module> New = BD.runPassesOn(M.get(), Passes);
Rafael Espindola866aa0d2010-08-10 15:46:11 +0000507 if (!New) {
Daniel Berlinad0220c2016-07-28 22:29:25 +0000508 errs() << "verify failed!\n";
Rafael Espindola866aa0d2010-08-10 15:46:11 +0000509 exit(1);
510 }
Vedant Kumar00088b82018-02-09 05:09:50 +0000511 M = std::move(New);
Justin Bogner388e8b92016-09-02 01:21:37 +0000512
Chris Lattner286921e2003-04-24 23:51:38 +0000513 // Try running on the hacked up program...
Vedant Kumar00088b82018-02-09 05:09:50 +0000514 if (TestFn(BD, M.get())) {
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000515 BD.setNewProgram(std::move(M)); // It crashed, keep the trimmed version...
Chris Lattner286921e2003-04-24 23:51:38 +0000516
517 // Make sure to use basic block pointers that point into the now-current
518 // module, and that they don't include any deleted blocks.
519 BBs.clear();
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000520 const ValueSymbolTable &GST = BD.getProgram().getValueSymbolTable();
Vedant Kumar00088b82018-02-09 05:09:50 +0000521 for (const auto &BI : BlockInfo) {
522 Function *F = cast<Function>(GST.lookup(BI.first));
523 Value *V = F->getValueSymbolTable()->lookup(BI.second);
Owen Anderson1d0be152009-08-13 21:58:54 +0000524 if (V && V->getType() == Type::getLabelTy(V->getContext()))
Reid Spenceref9b9a72007-02-05 20:47:22 +0000525 BBs.push_back(cast<BasicBlock>(V));
Chris Lattner286921e2003-04-24 23:51:38 +0000526 }
527 return true;
528 }
Vedant Kumar00088b82018-02-09 05:09:50 +0000529 // It didn't crash, try something else.
Chris Lattner286921e2003-04-24 23:51:38 +0000530 return false;
531}
532
Nick Lewycky4c8f9af2009-05-25 05:30:00 +0000533namespace {
Daniel Berlin41bc5c22016-07-27 16:13:25 +0000534/// ReduceCrashingConditionals reducer - This works by changing
535/// conditional branches to unconditional ones, then simplifying the CFG
536/// This has the effect of chopping up the CFG really fast which can reduce
537/// large functions quickly.
538///
539class ReduceCrashingConditionals : public ListReducer<const BasicBlock *> {
540 BugDriver &BD;
Vedant Kumar26757892018-02-08 18:46:49 +0000541 BugTester TestFn;
Daniel Berlin41bc5c22016-07-27 16:13:25 +0000542 bool Direction;
543
544public:
Vedant Kumar26757892018-02-08 18:46:49 +0000545 ReduceCrashingConditionals(BugDriver &bd, BugTester testFn, bool Direction)
Daniel Berlin41bc5c22016-07-27 16:13:25 +0000546 : BD(bd), TestFn(testFn), Direction(Direction) {}
547
Justin Bognerd8090ae2016-09-06 17:18:22 +0000548 Expected<TestResult> doTest(std::vector<const BasicBlock *> &Prefix,
549 std::vector<const BasicBlock *> &Kept) override {
Daniel Berlin41bc5c22016-07-27 16:13:25 +0000550 if (!Kept.empty() && TestBlocks(Kept))
551 return KeepSuffix;
552 if (!Prefix.empty() && TestBlocks(Prefix))
553 return KeepPrefix;
554 return NoFailure;
555 }
556
557 bool TestBlocks(std::vector<const BasicBlock *> &Prefix);
558};
559}
560
561bool ReduceCrashingConditionals::TestBlocks(
562 std::vector<const BasicBlock *> &BBs) {
563 // Clone the program to try hacking it apart...
564 ValueToValueMapTy VMap;
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000565 std::unique_ptr<Module> M = CloneModule(BD.getProgram(), VMap);
Daniel Berlin41bc5c22016-07-27 16:13:25 +0000566
567 // Convert list to set for fast lookup...
568 SmallPtrSet<const BasicBlock *, 8> Blocks;
Justin Bogner388e8b92016-09-02 01:21:37 +0000569 for (const auto *BB : BBs)
Daniel Berlin41bc5c22016-07-27 16:13:25 +0000570 Blocks.insert(cast<BasicBlock>(VMap[BB]));
571
572 outs() << "Checking for crash with changing conditionals to always jump to "
573 << (Direction ? "true" : "false") << ":";
574 unsigned NumPrint = Blocks.size();
575 if (NumPrint > 10)
576 NumPrint = 10;
577 for (unsigned i = 0, e = NumPrint; i != e; ++i)
578 outs() << " " << BBs[i]->getName();
579 if (NumPrint < Blocks.size())
580 outs() << "... <" << Blocks.size() << " total>";
581 outs() << ": ";
582
583 // Loop over and delete any hack up any blocks that are not listed...
Justin Bogner388e8b92016-09-02 01:21:37 +0000584 for (auto &F : *M)
Daniel Berlin41bc5c22016-07-27 16:13:25 +0000585 for (auto &BB : F)
586 if (!Blocks.count(&BB)) {
587 auto *BR = dyn_cast<BranchInst>(BB.getTerminator());
588 if (!BR || !BR->isConditional())
589 continue;
590 if (Direction)
591 BR->setCondition(ConstantInt::getTrue(BR->getContext()));
592 else
593 BR->setCondition(ConstantInt::getFalse(BR->getContext()));
594 }
595
596 // The following may destroy some blocks, so we save them first
597 std::vector<std::pair<std::string, std::string>> BlockInfo;
598
599 for (const BasicBlock *BB : Blocks)
600 BlockInfo.emplace_back(BB->getParent()->getName(), BB->getName());
601
602 SmallVector<BasicBlock *, 16> ToProcess;
Justin Bogner388e8b92016-09-02 01:21:37 +0000603 for (auto &F : *M) {
Daniel Berlin41bc5c22016-07-27 16:13:25 +0000604 for (auto &BB : F)
605 if (!Blocks.count(&BB))
606 ToProcess.push_back(&BB);
607 simpleSimplifyCfg(F, ToProcess);
608 ToProcess.clear();
609 }
610 // Verify we didn't break anything
611 std::vector<std::string> Passes;
612 Passes.push_back("verify");
Vedant Kumar00088b82018-02-09 05:09:50 +0000613 std::unique_ptr<Module> New = BD.runPassesOn(M.get(), Passes);
Daniel Berlin41bc5c22016-07-27 16:13:25 +0000614 if (!New) {
615 errs() << "verify failed!\n";
616 exit(1);
617 }
Vedant Kumar00088b82018-02-09 05:09:50 +0000618 M = std::move(New);
Daniel Berlin41bc5c22016-07-27 16:13:25 +0000619
620 // Try running on the hacked up program...
Vedant Kumar00088b82018-02-09 05:09:50 +0000621 if (TestFn(BD, M.get())) {
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000622 BD.setNewProgram(std::move(M)); // It crashed, keep the trimmed version...
Daniel Berlin41bc5c22016-07-27 16:13:25 +0000623
624 // Make sure to use basic block pointers that point into the now-current
625 // module, and that they don't include any deleted blocks.
626 BBs.clear();
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000627 const ValueSymbolTable &GST = BD.getProgram().getValueSymbolTable();
Daniel Berlin41bc5c22016-07-27 16:13:25 +0000628 for (auto &BI : BlockInfo) {
629 auto *F = cast<Function>(GST.lookup(BI.first));
Mehdi Aminid1e3c5a2016-09-17 06:00:02 +0000630 Value *V = F->getValueSymbolTable()->lookup(BI.second);
Daniel Berlin41bc5c22016-07-27 16:13:25 +0000631 if (V && V->getType() == Type::getLabelTy(V->getContext()))
632 BBs.push_back(cast<BasicBlock>(V));
633 }
634 return true;
635 }
Vedant Kumar00088b82018-02-09 05:09:50 +0000636 // It didn't crash, try something else.
Daniel Berlin41bc5c22016-07-27 16:13:25 +0000637 return false;
638}
639
640namespace {
Daniel Berlinad0220c2016-07-28 22:29:25 +0000641/// SimplifyCFG reducer - This works by calling SimplifyCFG on each basic block
642/// in the program.
643
644class ReduceSimplifyCFG : public ListReducer<const BasicBlock *> {
645 BugDriver &BD;
Vedant Kumar26757892018-02-08 18:46:49 +0000646 BugTester TestFn;
Daniel Berlinad0220c2016-07-28 22:29:25 +0000647 TargetTransformInfo TTI;
Justin Bogner388e8b92016-09-02 01:21:37 +0000648
Daniel Berlinad0220c2016-07-28 22:29:25 +0000649public:
Vedant Kumar26757892018-02-08 18:46:49 +0000650 ReduceSimplifyCFG(BugDriver &bd, BugTester testFn)
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000651 : BD(bd), TestFn(testFn), TTI(bd.getProgram().getDataLayout()) {}
Daniel Berlinad0220c2016-07-28 22:29:25 +0000652
Justin Bognerd8090ae2016-09-06 17:18:22 +0000653 Expected<TestResult> doTest(std::vector<const BasicBlock *> &Prefix,
654 std::vector<const BasicBlock *> &Kept) override {
Daniel Berlinad0220c2016-07-28 22:29:25 +0000655 if (!Kept.empty() && TestBlocks(Kept))
656 return KeepSuffix;
657 if (!Prefix.empty() && TestBlocks(Prefix))
658 return KeepPrefix;
659 return NoFailure;
660 }
661
662 bool TestBlocks(std::vector<const BasicBlock *> &Prefix);
663};
664}
665
Justin Bogner388e8b92016-09-02 01:21:37 +0000666bool ReduceSimplifyCFG::TestBlocks(std::vector<const BasicBlock *> &BBs) {
Daniel Berlinad0220c2016-07-28 22:29:25 +0000667 // Clone the program to try hacking it apart...
668 ValueToValueMapTy VMap;
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000669 std::unique_ptr<Module> M = CloneModule(BD.getProgram(), VMap);
Daniel Berlinad0220c2016-07-28 22:29:25 +0000670
671 // Convert list to set for fast lookup...
672 SmallPtrSet<const BasicBlock *, 8> Blocks;
Justin Bogner388e8b92016-09-02 01:21:37 +0000673 for (const auto *BB : BBs)
Daniel Berlinad0220c2016-07-28 22:29:25 +0000674 Blocks.insert(cast<BasicBlock>(VMap[BB]));
675
676 outs() << "Checking for crash with CFG simplifying:";
677 unsigned NumPrint = Blocks.size();
678 if (NumPrint > 10)
679 NumPrint = 10;
680 for (unsigned i = 0, e = NumPrint; i != e; ++i)
681 outs() << " " << BBs[i]->getName();
682 if (NumPrint < Blocks.size())
683 outs() << "... <" << Blocks.size() << " total>";
684 outs() << ": ";
685
Justin Bogner388e8b92016-09-02 01:21:37 +0000686 // The following may destroy some blocks, so we save them first
Daniel Berlinad0220c2016-07-28 22:29:25 +0000687 std::vector<std::pair<std::string, std::string>> BlockInfo;
688
689 for (const BasicBlock *BB : Blocks)
690 BlockInfo.emplace_back(BB->getParent()->getName(), BB->getName());
691
Daniel Berlinad0220c2016-07-28 22:29:25 +0000692 // Loop over and delete any hack up any blocks that are not listed...
Justin Bogner388e8b92016-09-02 01:21:37 +0000693 for (auto &F : *M)
694 // Loop over all of the basic blocks and remove them if they are unneeded.
695 for (Function::iterator BBIt = F.begin(); BBIt != F.end();) {
696 if (!Blocks.count(&*BBIt)) {
697 ++BBIt;
698 continue;
699 }
Sanjay Pateldfc9ea22017-10-04 20:26:25 +0000700 simplifyCFG(&*BBIt++, TTI);
Justin Bogner388e8b92016-09-02 01:21:37 +0000701 }
Daniel Berlinad0220c2016-07-28 22:29:25 +0000702 // Verify we didn't break anything
703 std::vector<std::string> Passes;
704 Passes.push_back("verify");
Vedant Kumar00088b82018-02-09 05:09:50 +0000705 std::unique_ptr<Module> New = BD.runPassesOn(M.get(), Passes);
Daniel Berlinad0220c2016-07-28 22:29:25 +0000706 if (!New) {
707 errs() << "verify failed!\n";
708 exit(1);
709 }
Vedant Kumar00088b82018-02-09 05:09:50 +0000710 M = std::move(New);
Daniel Berlinad0220c2016-07-28 22:29:25 +0000711
712 // Try running on the hacked up program...
Vedant Kumar00088b82018-02-09 05:09:50 +0000713 if (TestFn(BD, M.get())) {
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000714 BD.setNewProgram(std::move(M)); // It crashed, keep the trimmed version...
Daniel Berlinad0220c2016-07-28 22:29:25 +0000715
716 // Make sure to use basic block pointers that point into the now-current
717 // module, and that they don't include any deleted blocks.
718 BBs.clear();
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000719 const ValueSymbolTable &GST = BD.getProgram().getValueSymbolTable();
Justin Bogner388e8b92016-09-02 01:21:37 +0000720 for (auto &BI : BlockInfo) {
Daniel Berlinad0220c2016-07-28 22:29:25 +0000721 auto *F = cast<Function>(GST.lookup(BI.first));
Mehdi Aminid1e3c5a2016-09-17 06:00:02 +0000722 Value *V = F->getValueSymbolTable()->lookup(BI.second);
Daniel Berlinad0220c2016-07-28 22:29:25 +0000723 if (V && V->getType() == Type::getLabelTy(V->getContext()))
724 BBs.push_back(cast<BasicBlock>(V));
725 }
726 return true;
727 }
Vedant Kumar00088b82018-02-09 05:09:50 +0000728 // It didn't crash, try something else.
Daniel Berlinad0220c2016-07-28 22:29:25 +0000729 return false;
730}
731
732namespace {
Justin Bogner388e8b92016-09-02 01:21:37 +0000733/// ReduceCrashingInstructions reducer - This works by removing the specified
734/// non-terminator instructions and replacing them with undef.
735///
736class ReduceCrashingInstructions : public ListReducer<const Instruction *> {
737 BugDriver &BD;
Vedant Kumar26757892018-02-08 18:46:49 +0000738 BugTester TestFn;
Justin Bogner388e8b92016-09-02 01:21:37 +0000739
740public:
Vedant Kumar26757892018-02-08 18:46:49 +0000741 ReduceCrashingInstructions(BugDriver &bd, BugTester testFn)
Nick Lewycky4c8f9af2009-05-25 05:30:00 +0000742 : BD(bd), TestFn(testFn) {}
743
Justin Bognerd8090ae2016-09-06 17:18:22 +0000744 Expected<TestResult> doTest(std::vector<const Instruction *> &Prefix,
745 std::vector<const Instruction *> &Kept) override {
Justin Bogner388e8b92016-09-02 01:21:37 +0000746 if (!Kept.empty() && TestInsts(Kept))
747 return KeepSuffix;
748 if (!Prefix.empty() && TestInsts(Prefix))
749 return KeepPrefix;
750 return NoFailure;
751 }
Nick Lewycky4c8f9af2009-05-25 05:30:00 +0000752
Justin Bogner388e8b92016-09-02 01:21:37 +0000753 bool TestInsts(std::vector<const Instruction *> &Prefix);
754};
Nick Lewycky4c8f9af2009-05-25 05:30:00 +0000755}
756
Justin Bogner388e8b92016-09-02 01:21:37 +0000757bool ReduceCrashingInstructions::TestInsts(
758 std::vector<const Instruction *> &Insts) {
Nick Lewycky4c8f9af2009-05-25 05:30:00 +0000759 // Clone the program to try hacking it apart...
Rafael Espindola1ed219a2010-10-13 01:36:30 +0000760 ValueToValueMapTy VMap;
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000761 std::unique_ptr<Module> M = CloneModule(BD.getProgram(), VMap);
Nick Lewycky4c8f9af2009-05-25 05:30:00 +0000762
763 // Convert list to set for fast lookup...
Justin Bogner388e8b92016-09-02 01:21:37 +0000764 SmallPtrSet<Instruction *, 32> Instructions;
Nick Lewycky4c8f9af2009-05-25 05:30:00 +0000765 for (unsigned i = 0, e = Insts.size(); i != e; ++i) {
Chandler Carruth9179aee2018-08-26 09:51:22 +0000766 assert(!Insts[i]->isTerminator());
Devang Patele9916a32010-06-24 00:33:28 +0000767 Instructions.insert(cast<Instruction>(VMap[Insts[i]]));
Nick Lewycky4c8f9af2009-05-25 05:30:00 +0000768 }
769
Dan Gohmanac95cc72009-07-16 15:30:09 +0000770 outs() << "Checking for crash with only " << Instructions.size();
Nick Lewycky4c8f9af2009-05-25 05:30:00 +0000771 if (Instructions.size() == 1)
Dan Gohmanac95cc72009-07-16 15:30:09 +0000772 outs() << " instruction: ";
Nick Lewycky4c8f9af2009-05-25 05:30:00 +0000773 else
Dan Gohmanac95cc72009-07-16 15:30:09 +0000774 outs() << " instructions: ";
Nick Lewycky4c8f9af2009-05-25 05:30:00 +0000775
776 for (Module::iterator MI = M->begin(), ME = M->end(); MI != ME; ++MI)
777 for (Function::iterator FI = MI->begin(), FE = MI->end(); FI != FE; ++FI)
778 for (BasicBlock::iterator I = FI->begin(), E = FI->end(); I != E;) {
Duncan P. N. Exon Smith1e221d52015-10-20 19:36:39 +0000779 Instruction *Inst = &*I++;
Chandler Carruth9179aee2018-08-26 09:51:22 +0000780 if (!Instructions.count(Inst) && !Inst->isTerminator() &&
Arnold Schwaighofer43959ee2017-03-07 20:28:59 +0000781 !Inst->isEHPad() && !Inst->getType()->isTokenTy() &&
782 !Inst->isSwiftError()) {
Philip Reames2d7feeb2016-06-29 00:15:35 +0000783 if (!Inst->getType()->isVoidTy())
Nick Lewycky4c8f9af2009-05-25 05:30:00 +0000784 Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
785 Inst->eraseFromParent();
786 }
787 }
788
789 // Verify that this is still valid.
Chandler Carruth417c5c12015-02-13 10:01:29 +0000790 legacy::PassManager Passes;
Adrian Prantlda27c362016-10-18 16:24:43 +0000791 Passes.add(createVerifierPass(/*FatalErrors=*/false));
Nick Lewycky4c8f9af2009-05-25 05:30:00 +0000792 Passes.run(*M);
793
794 // Try running on the hacked up program...
Rafael Espindolad1920612018-02-14 20:25:18 +0000795 if (TestFn(BD, M.get())) {
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000796 BD.setNewProgram(std::move(M)); // It crashed, keep the trimmed version...
Nick Lewycky4c8f9af2009-05-25 05:30:00 +0000797
798 // Make sure to use instruction pointers that point into the now-current
799 // module, and that they don't include any deleted blocks.
800 Insts.clear();
Craig Topper273fd112014-08-24 23:23:06 +0000801 for (Instruction *Inst : Instructions)
802 Insts.push_back(Inst);
Nick Lewycky4c8f9af2009-05-25 05:30:00 +0000803 return true;
804 }
Rafael Espindolad1920612018-02-14 20:25:18 +0000805 // It didn't crash, try something else.
Nick Lewycky4c8f9af2009-05-25 05:30:00 +0000806 return false;
807}
808
Keno Fischer11e0c312015-11-06 00:12:50 +0000809namespace {
810// Reduce the list of Named Metadata nodes. We keep this as a list of
811// names to avoid having to convert back and forth every time.
812class ReduceCrashingNamedMD : public ListReducer<std::string> {
813 BugDriver &BD;
Vedant Kumar26757892018-02-08 18:46:49 +0000814 BugTester TestFn;
Keno Fischer11e0c312015-11-06 00:12:50 +0000815
816public:
Vedant Kumar26757892018-02-08 18:46:49 +0000817 ReduceCrashingNamedMD(BugDriver &bd, BugTester testFn)
Keno Fischer11e0c312015-11-06 00:12:50 +0000818 : BD(bd), TestFn(testFn) {}
819
Justin Bognerd8090ae2016-09-06 17:18:22 +0000820 Expected<TestResult> doTest(std::vector<std::string> &Prefix,
821 std::vector<std::string> &Kept) override {
Keno Fischer11e0c312015-11-06 00:12:50 +0000822 if (!Kept.empty() && TestNamedMDs(Kept))
823 return KeepSuffix;
824 if (!Prefix.empty() && TestNamedMDs(Prefix))
825 return KeepPrefix;
826 return NoFailure;
827 }
828
829 bool TestNamedMDs(std::vector<std::string> &NamedMDs);
830};
831}
832
833bool ReduceCrashingNamedMD::TestNamedMDs(std::vector<std::string> &NamedMDs) {
834
835 ValueToValueMapTy VMap;
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000836 std::unique_ptr<Module> M = CloneModule(BD.getProgram(), VMap);
Keno Fischer11e0c312015-11-06 00:12:50 +0000837
838 outs() << "Checking for crash with only these named metadata nodes:";
839 unsigned NumPrint = std::min<size_t>(NamedMDs.size(), 10);
840 for (unsigned i = 0, e = NumPrint; i != e; ++i)
841 outs() << " " << NamedMDs[i];
842 if (NumPrint < NamedMDs.size())
843 outs() << "... <" << NamedMDs.size() << " total>";
844 outs() << ": ";
845
846 // Make a StringMap for faster lookup
847 StringSet<> Names;
848 for (const std::string &Name : NamedMDs)
849 Names.insert(Name);
850
851 // First collect all the metadata to delete in a vector, then
852 // delete them all at once to avoid invalidating the iterator
853 std::vector<NamedMDNode *> ToDelete;
854 ToDelete.reserve(M->named_metadata_size() - Names.size());
855 for (auto &NamedMD : M->named_metadata())
Adrian Prantl8d4b7e72016-03-28 21:06:26 +0000856 // Always keep a nonempty llvm.dbg.cu because the Verifier would complain.
857 if (!Names.count(NamedMD.getName()) &&
858 (!(NamedMD.getName() == "llvm.dbg.cu" && NamedMD.getNumOperands() > 0)))
Keno Fischer11e0c312015-11-06 00:12:50 +0000859 ToDelete.push_back(&NamedMD);
860
861 for (auto *NamedMD : ToDelete)
862 NamedMD->eraseFromParent();
863
864 // Verify that this is still valid.
865 legacy::PassManager Passes;
Adrian Prantlda27c362016-10-18 16:24:43 +0000866 Passes.add(createVerifierPass(/*FatalErrors=*/false));
Keno Fischer11e0c312015-11-06 00:12:50 +0000867 Passes.run(*M);
868
869 // Try running on the hacked up program...
Rafael Espindola1db3d992018-02-14 20:53:38 +0000870 if (TestFn(BD, M.get())) {
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000871 BD.setNewProgram(std::move(M)); // It crashed, keep the trimmed version...
Keno Fischer11e0c312015-11-06 00:12:50 +0000872 return true;
873 }
Keno Fischer11e0c312015-11-06 00:12:50 +0000874 return false;
875}
876
877namespace {
878// Reduce the list of operands to named metadata nodes
879class ReduceCrashingNamedMDOps : public ListReducer<const MDNode *> {
880 BugDriver &BD;
Vedant Kumar26757892018-02-08 18:46:49 +0000881 BugTester TestFn;
Keno Fischer11e0c312015-11-06 00:12:50 +0000882
883public:
Vedant Kumar26757892018-02-08 18:46:49 +0000884 ReduceCrashingNamedMDOps(BugDriver &bd, BugTester testFn)
Keno Fischer11e0c312015-11-06 00:12:50 +0000885 : BD(bd), TestFn(testFn) {}
886
Justin Bognerd8090ae2016-09-06 17:18:22 +0000887 Expected<TestResult> doTest(std::vector<const MDNode *> &Prefix,
888 std::vector<const MDNode *> &Kept) override {
Keno Fischer11e0c312015-11-06 00:12:50 +0000889 if (!Kept.empty() && TestNamedMDOps(Kept))
890 return KeepSuffix;
891 if (!Prefix.empty() && TestNamedMDOps(Prefix))
892 return KeepPrefix;
893 return NoFailure;
894 }
895
896 bool TestNamedMDOps(std::vector<const MDNode *> &NamedMDOps);
897};
898}
899
900bool ReduceCrashingNamedMDOps::TestNamedMDOps(
901 std::vector<const MDNode *> &NamedMDOps) {
902 // Convert list to set for fast lookup...
Matthias Braun5e08bd32016-01-30 01:24:31 +0000903 SmallPtrSet<const MDNode *, 32> OldMDNodeOps;
Keno Fischer11e0c312015-11-06 00:12:50 +0000904 for (unsigned i = 0, e = NamedMDOps.size(); i != e; ++i) {
905 OldMDNodeOps.insert(NamedMDOps[i]);
906 }
907
908 outs() << "Checking for crash with only " << OldMDNodeOps.size();
909 if (OldMDNodeOps.size() == 1)
910 outs() << " named metadata operand: ";
911 else
912 outs() << " named metadata operands: ";
913
914 ValueToValueMapTy VMap;
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000915 std::unique_ptr<Module> M = CloneModule(BD.getProgram(), VMap);
Keno Fischer11e0c312015-11-06 00:12:50 +0000916
917 // This is a little wasteful. In the future it might be good if we could have
918 // these dropped during cloning.
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000919 for (auto &NamedMD : BD.getProgram().named_metadata()) {
Keno Fischer11e0c312015-11-06 00:12:50 +0000920 // Drop the old one and create a new one
921 M->eraseNamedMetadata(M->getNamedMetadata(NamedMD.getName()));
922 NamedMDNode *NewNamedMDNode =
923 M->getOrInsertNamedMetadata(NamedMD.getName());
924 for (MDNode *op : NamedMD.operands())
925 if (OldMDNodeOps.count(op))
926 NewNamedMDNode->addOperand(cast<MDNode>(MapMetadata(op, VMap)));
927 }
928
929 // Verify that this is still valid.
930 legacy::PassManager Passes;
Adrian Prantlda27c362016-10-18 16:24:43 +0000931 Passes.add(createVerifierPass(/*FatalErrors=*/false));
Keno Fischer11e0c312015-11-06 00:12:50 +0000932 Passes.run(*M);
933
934 // Try running on the hacked up program...
Rafael Espindolac84d87c2018-02-14 20:59:39 +0000935 if (TestFn(BD, M.get())) {
Keno Fischer11e0c312015-11-06 00:12:50 +0000936 // Make sure to use instruction pointers that point into the now-current
937 // module, and that they don't include any deleted blocks.
938 NamedMDOps.clear();
939 for (const MDNode *Node : OldMDNodeOps)
Duncan P. N. Exon Smitheeb2c7e2016-04-02 17:04:38 +0000940 NamedMDOps.push_back(cast<MDNode>(*VMap.getMappedMD(Node)));
Keno Fischer11e0c312015-11-06 00:12:50 +0000941
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000942 BD.setNewProgram(std::move(M)); // It crashed, keep the trimmed version...
Keno Fischer11e0c312015-11-06 00:12:50 +0000943 return true;
944 }
Rafael Espindolac84d87c2018-02-14 20:59:39 +0000945 // It didn't crash, try something else.
Keno Fischer11e0c312015-11-06 00:12:50 +0000946 return false;
947}
948
Vedant Kumar0f1e6f82018-02-08 20:27:09 +0000949/// Attempt to eliminate as many global initializers as possible.
Vedant Kumar26757892018-02-08 18:46:49 +0000950static Error ReduceGlobalInitializers(BugDriver &BD, BugTester TestFn) {
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000951 Module &OrigM = BD.getProgram();
952 if (OrigM.global_empty())
Vedant Kumar0f1e6f82018-02-08 20:27:09 +0000953 return Error::success();
Misha Brukman3da94ae2005-04-22 00:00:37 +0000954
Vedant Kumar0f1e6f82018-02-08 20:27:09 +0000955 // Now try to reduce the number of global variable initializers in the
956 // module to something small.
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000957 std::unique_ptr<Module> M = CloneModule(OrigM);
Vedant Kumar0f1e6f82018-02-08 20:27:09 +0000958 bool DeletedInit = false;
Bill Wendling4e3be892006-10-25 18:36:14 +0000959
Vedant Kumar0f1e6f82018-02-08 20:27:09 +0000960 for (GlobalVariable &GV : M->globals()) {
961 if (GV.hasInitializer()) {
962 DeleteGlobalInitializer(&GV);
963 GV.setLinkage(GlobalValue::ExternalLinkage);
964 GV.setComdat(nullptr);
965 DeletedInit = true;
Chris Lattner5f73e382003-04-25 00:53:05 +0000966 }
967 }
Vedant Kumar0f1e6f82018-02-08 20:27:09 +0000968
969 if (!DeletedInit)
970 return Error::success();
971
972 // See if the program still causes a crash...
973 outs() << "\nChecking to see if we can delete global inits: ";
974
975 if (TestFn(BD, M.get())) { // Still crashes?
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000976 BD.setNewProgram(std::move(M));
Vedant Kumar0f1e6f82018-02-08 20:27:09 +0000977 outs() << "\n*** Able to remove all global initializers!\n";
978 return Error::success();
979 }
980
981 // No longer crashes.
982 outs() << " - Removing all global inits hides problem!\n";
983
984 std::vector<GlobalVariable *> GVs;
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000985 for (GlobalVariable &GV : OrigM.globals())
Vedant Kumar0f1e6f82018-02-08 20:27:09 +0000986 if (GV.hasInitializer())
987 GVs.push_back(&GV);
988
989 if (GVs.size() > 1 && !BugpointIsInterrupted) {
990 outs() << "\n*** Attempting to reduce the number of global initializers "
991 << "in the testcase\n";
992
993 unsigned OldSize = GVs.size();
994 Expected<bool> Result =
995 ReduceCrashingGlobalInitializers(BD, TestFn).reduceList(GVs);
996 if (Error E = Result.takeError())
997 return E;
998
999 if (GVs.size() < OldSize)
1000 BD.EmitProgressBitcode(BD.getProgram(), "reduced-global-variables");
1001 }
Justin Bognerd8090ae2016-09-06 17:18:22 +00001002 return Error::success();
Philip Reames67d87be2016-06-29 00:43:18 +00001003}
1004
Vedant Kumar26757892018-02-08 18:46:49 +00001005static Error ReduceInsts(BugDriver &BD, BugTester TestFn) {
Philip Reames67d87be2016-06-29 00:43:18 +00001006 // Attempt to delete instructions using bisection. This should help out nasty
1007 // cases with large basic blocks where the problem is at one end.
1008 if (!BugpointIsInterrupted) {
Justin Bogner388e8b92016-09-02 01:21:37 +00001009 std::vector<const Instruction *> Insts;
Rafael Espindolacdac12c2018-02-14 21:44:34 +00001010 for (const Function &F : BD.getProgram())
Philip Reames67d87be2016-06-29 00:43:18 +00001011 for (const BasicBlock &BB : F)
1012 for (const Instruction &I : BB)
Chandler Carruth9179aee2018-08-26 09:51:22 +00001013 if (!I.isTerminator())
Philip Reames67d87be2016-06-29 00:43:18 +00001014 Insts.push_back(&I);
1015
Justin Bognerd8090ae2016-09-06 17:18:22 +00001016 Expected<bool> Result =
1017 ReduceCrashingInstructions(BD, TestFn).reduceList(Insts);
1018 if (Error E = Result.takeError())
1019 return E;
Philip Reames67d87be2016-06-29 00:43:18 +00001020 }
1021
1022 unsigned Simplification = 2;
1023 do {
1024 if (BugpointIsInterrupted)
Justin Bognerd8090ae2016-09-06 17:18:22 +00001025 // TODO: Should we distinguish this with an "interrupted error"?
1026 return Error::success();
Philip Reames67d87be2016-06-29 00:43:18 +00001027 --Simplification;
1028 outs() << "\n*** Attempting to reduce testcase by deleting instruc"
1029 << "tions: Simplification Level #" << Simplification << '\n';
1030
1031 // Now that we have deleted the functions that are unnecessary for the
1032 // program, try to remove instructions that are not necessary to cause the
1033 // crash. To do this, we loop through all of the instructions in the
1034 // remaining functions, deleting them (replacing any values produced with
1035 // nulls), and then running ADCE and SimplifyCFG. If the transformed input
1036 // still triggers failure, keep deleting until we cannot trigger failure
1037 // anymore.
1038 //
1039 unsigned InstructionsToSkipBeforeDeleting = 0;
1040 TryAgain:
1041
1042 // Loop over all of the (non-terminator) instructions remaining in the
1043 // function, attempting to delete them.
1044 unsigned CurInstructionNum = 0;
Rafael Espindolacdac12c2018-02-14 21:44:34 +00001045 for (Module::const_iterator FI = BD.getProgram().begin(),
1046 E = BD.getProgram().end();
Justin Bogner388e8b92016-09-02 01:21:37 +00001047 FI != E; ++FI)
Philip Reames67d87be2016-06-29 00:43:18 +00001048 if (!FI->isDeclaration())
1049 for (Function::const_iterator BI = FI->begin(), E = FI->end(); BI != E;
1050 ++BI)
1051 for (BasicBlock::const_iterator I = BI->begin(), E = --BI->end();
1052 I != E; ++I, ++CurInstructionNum) {
1053 if (InstructionsToSkipBeforeDeleting) {
1054 --InstructionsToSkipBeforeDeleting;
1055 } else {
1056 if (BugpointIsInterrupted)
Justin Bognerd8090ae2016-09-06 17:18:22 +00001057 // TODO: Should this be some kind of interrupted error?
1058 return Error::success();
Philip Reames67d87be2016-06-29 00:43:18 +00001059
Arnold Schwaighofer43959ee2017-03-07 20:28:59 +00001060 if (I->isEHPad() || I->getType()->isTokenTy() ||
1061 I->isSwiftError())
Philip Reames67d87be2016-06-29 00:43:18 +00001062 continue;
1063
1064 outs() << "Checking instruction: " << *I;
1065 std::unique_ptr<Module> M =
1066 BD.deleteInstructionFromProgram(&*I, Simplification);
1067
1068 // Find out if the pass still crashes on this pass...
1069 if (TestFn(BD, M.get())) {
1070 // Yup, it does, we delete the old module, and continue trying
1071 // to reduce the testcase...
Rafael Espindolacdac12c2018-02-14 21:44:34 +00001072 BD.setNewProgram(std::move(M));
Philip Reames67d87be2016-06-29 00:43:18 +00001073 InstructionsToSkipBeforeDeleting = CurInstructionNum;
Justin Bogner388e8b92016-09-02 01:21:37 +00001074 goto TryAgain; // I wish I had a multi-level break here!
Philip Reames67d87be2016-06-29 00:43:18 +00001075 }
1076 }
1077 }
1078
1079 if (InstructionsToSkipBeforeDeleting) {
1080 InstructionsToSkipBeforeDeleting = 0;
1081 goto TryAgain;
1082 }
1083
1084 } while (Simplification);
1085 BD.EmitProgressBitcode(BD.getProgram(), "reduced-instructions");
Justin Bognerd8090ae2016-09-06 17:18:22 +00001086 return Error::success();
Philip Reames67d87be2016-06-29 00:43:18 +00001087}
1088
Philip Reames67d87be2016-06-29 00:43:18 +00001089/// DebugACrash - Given a predicate that determines whether a component crashes
1090/// on a program, try to destructively reduce the program while still keeping
1091/// the predicate true.
Vedant Kumar26757892018-02-08 18:46:49 +00001092static Error DebugACrash(BugDriver &BD, BugTester TestFn) {
Philip Reames67d87be2016-06-29 00:43:18 +00001093 // See if we can get away with nuking some of the global variable initializers
1094 // in the program...
1095 if (!NoGlobalRM)
Justin Bognerd8090ae2016-09-06 17:18:22 +00001096 if (Error E = ReduceGlobalInitializers(BD, TestFn))
1097 return E;
Misha Brukman3da94ae2005-04-22 00:00:37 +00001098
Chris Lattneraae33f92003-04-24 22:24:58 +00001099 // Now try to reduce the number of functions in the module to something small.
Justin Bogner388e8b92016-09-02 01:21:37 +00001100 std::vector<Function *> Functions;
Rafael Espindolacdac12c2018-02-14 21:44:34 +00001101 for (Function &F : BD.getProgram())
Duncan P. N. Exon Smith1e221d52015-10-20 19:36:39 +00001102 if (!F.isDeclaration())
1103 Functions.push_back(&F);
Chris Lattnerafade922002-11-20 22:28:10 +00001104
Chris Lattnerf9aaae02005-08-02 02:16:17 +00001105 if (Functions.size() > 1 && !BugpointIsInterrupted) {
Dan Gohmanac95cc72009-07-16 15:30:09 +00001106 outs() << "\n*** Attempting to reduce the number of functions "
Justin Bogner388e8b92016-09-02 01:21:37 +00001107 "in the testcase\n";
Chris Lattnerafade922002-11-20 22:28:10 +00001108
Chris Lattner8b189272004-02-18 23:26:28 +00001109 unsigned OldSize = Functions.size();
Justin Bognerd8090ae2016-09-06 17:18:22 +00001110 Expected<bool> Result =
1111 ReduceCrashingFunctions(BD, TestFn).reduceList(Functions);
1112 if (Error E = Result.takeError())
1113 return E;
Chris Lattnerafade922002-11-20 22:28:10 +00001114
Chris Lattnerf9aaae02005-08-02 02:16:17 +00001115 if (Functions.size() < OldSize)
Rafael Espindolabae1b712010-07-28 18:12:30 +00001116 BD.EmitProgressBitcode(BD.getProgram(), "reduced-function");
Chris Lattnerafade922002-11-20 22:28:10 +00001117 }
1118
Brian Gesiak79550f62018-12-19 03:42:19 +00001119 // For each remaining function, try to reduce that function's attributes.
1120 std::vector<std::string> FunctionNames;
1121 for (Function &F : BD.getProgram())
1122 FunctionNames.push_back(F.getName());
1123
1124 if (!FunctionNames.empty() && !BugpointIsInterrupted) {
1125 outs() << "\n*** Attempting to reduce the number of function attributes in "
1126 "the testcase\n";
1127
1128 unsigned OldSize = 0;
1129 unsigned NewSize = 0;
1130 for (std::string &Name : FunctionNames) {
1131 Function *Fn = BD.getProgram().getFunction(Name);
1132 assert(Fn && "Could not find funcion?");
1133
1134 std::vector<Attribute> Attrs;
1135 for (Attribute A : Fn->getAttributes().getFnAttributes())
1136 Attrs.push_back(A);
1137
1138 OldSize += Attrs.size();
1139 Expected<bool> Result =
1140 ReduceCrashingFunctionAttributes(BD, Name, TestFn).reduceList(Attrs);
1141 if (Error E = Result.takeError())
1142 return E;
1143
1144 NewSize += Attrs.size();
1145 }
1146
1147 if (OldSize < NewSize)
1148 BD.EmitProgressBitcode(BD.getProgram(), "reduced-function-attributes");
1149 }
1150
Daniel Berlin41bc5c22016-07-27 16:13:25 +00001151 // Attempt to change conditional branches into unconditional branches to
1152 // eliminate blocks.
1153 if (!DisableSimplifyCFG && !BugpointIsInterrupted) {
Justin Bogner388e8b92016-09-02 01:21:37 +00001154 std::vector<const BasicBlock *> Blocks;
Rafael Espindolacdac12c2018-02-14 21:44:34 +00001155 for (Function &F : BD.getProgram())
Daniel Berlin41bc5c22016-07-27 16:13:25 +00001156 for (BasicBlock &BB : F)
1157 Blocks.push_back(&BB);
1158 unsigned OldSize = Blocks.size();
Justin Bognerd8090ae2016-09-06 17:18:22 +00001159 Expected<bool> Result =
1160 ReduceCrashingConditionals(BD, TestFn, true).reduceList(Blocks);
1161 if (Error E = Result.takeError())
1162 return E;
1163 Result = ReduceCrashingConditionals(BD, TestFn, false).reduceList(Blocks);
1164 if (Error E = Result.takeError())
1165 return E;
Daniel Berlin41bc5c22016-07-27 16:13:25 +00001166 if (Blocks.size() < OldSize)
1167 BD.EmitProgressBitcode(BD.getProgram(), "reduced-conditionals");
1168 }
1169
Chris Lattner286921e2003-04-24 23:51:38 +00001170 // Attempt to delete entire basic blocks at a time to speed up
1171 // convergence... this actually works by setting the terminator of the blocks
1172 // to a return instruction then running simplifycfg, which can potentially
1173 // shrinks the code dramatically quickly
1174 //
Chris Lattnerf9aaae02005-08-02 02:16:17 +00001175 if (!DisableSimplifyCFG && !BugpointIsInterrupted) {
Justin Bogner388e8b92016-09-02 01:21:37 +00001176 std::vector<const BasicBlock *> Blocks;
Rafael Espindolacdac12c2018-02-14 21:44:34 +00001177 for (Function &F : BD.getProgram())
Duncan P. N. Exon Smith1e221d52015-10-20 19:36:39 +00001178 for (BasicBlock &BB : F)
1179 Blocks.push_back(&BB);
Torok Edwin2c235012009-05-24 09:40:47 +00001180 unsigned OldSize = Blocks.size();
Justin Bognerd8090ae2016-09-06 17:18:22 +00001181 Expected<bool> Result = ReduceCrashingBlocks(BD, TestFn).reduceList(Blocks);
1182 if (Error E = Result.takeError())
1183 return E;
Torok Edwin2c235012009-05-24 09:40:47 +00001184 if (Blocks.size() < OldSize)
Rafael Espindolabae1b712010-07-28 18:12:30 +00001185 BD.EmitProgressBitcode(BD.getProgram(), "reduced-blocks");
Chris Lattner47ae4a12003-08-05 15:51:05 +00001186 }
Chris Lattner218e26e2002-12-23 23:49:59 +00001187
Simon Pilgrimc15f96952017-04-14 15:21:15 +00001188 if (!DisableSimplifyCFG && !BugpointIsInterrupted) {
Justin Bogner388e8b92016-09-02 01:21:37 +00001189 std::vector<const BasicBlock *> Blocks;
Rafael Espindolacdac12c2018-02-14 21:44:34 +00001190 for (Function &F : BD.getProgram())
Daniel Berlinad0220c2016-07-28 22:29:25 +00001191 for (BasicBlock &BB : F)
1192 Blocks.push_back(&BB);
1193 unsigned OldSize = Blocks.size();
Justin Bognerd8090ae2016-09-06 17:18:22 +00001194 Expected<bool> Result = ReduceSimplifyCFG(BD, TestFn).reduceList(Blocks);
1195 if (Error E = Result.takeError())
1196 return E;
Daniel Berlinad0220c2016-07-28 22:29:25 +00001197 if (Blocks.size() < OldSize)
1198 BD.EmitProgressBitcode(BD.getProgram(), "reduced-simplifycfg");
1199 }
Justin Bogner388e8b92016-09-02 01:21:37 +00001200
Nick Lewycky4c8f9af2009-05-25 05:30:00 +00001201 // Attempt to delete instructions using bisection. This should help out nasty
1202 // cases with large basic blocks where the problem is at one end.
Philip Reames67d87be2016-06-29 00:43:18 +00001203 if (!BugpointIsInterrupted)
Justin Bognerd8090ae2016-09-06 17:18:22 +00001204 if (Error E = ReduceInsts(BD, TestFn))
1205 return E;
Keno Fischer11e0c312015-11-06 00:12:50 +00001206
Michael Ilseman5bd98bf2016-10-25 18:44:13 +00001207 // Attempt to strip debug info metadata.
1208 auto stripMetadata = [&](std::function<bool(Module &)> strip) {
Rafael Espindolacdac12c2018-02-14 21:44:34 +00001209 std::unique_ptr<Module> M = CloneModule(BD.getProgram());
Michael Ilseman5bd98bf2016-10-25 18:44:13 +00001210 strip(*M);
1211 if (TestFn(BD, M.get()))
Rafael Espindolacdac12c2018-02-14 21:44:34 +00001212 BD.setNewProgram(std::move(M));
Michael Ilseman5bd98bf2016-10-25 18:44:13 +00001213 };
1214 if (!NoStripDebugInfo && !BugpointIsInterrupted) {
1215 outs() << "\n*** Attempting to strip the debug info: ";
1216 stripMetadata(StripDebugInfo);
1217 }
1218 if (!NoStripDebugTypeInfo && !BugpointIsInterrupted) {
1219 outs() << "\n*** Attempting to strip the debug type info: ";
1220 stripMetadata(stripNonLineTableDebugInfo);
1221 }
1222
Keno Fischer11e0c312015-11-06 00:12:50 +00001223 if (!NoNamedMDRM) {
Keno Fischer11e0c312015-11-06 00:12:50 +00001224 if (!BugpointIsInterrupted) {
1225 // Try to reduce the amount of global metadata (particularly debug info),
1226 // by dropping global named metadata that anchors them
1227 outs() << "\n*** Attempting to remove named metadata: ";
1228 std::vector<std::string> NamedMDNames;
Rafael Espindolacdac12c2018-02-14 21:44:34 +00001229 for (auto &NamedMD : BD.getProgram().named_metadata())
Keno Fischer11e0c312015-11-06 00:12:50 +00001230 NamedMDNames.push_back(NamedMD.getName().str());
Justin Bognerd8090ae2016-09-06 17:18:22 +00001231 Expected<bool> Result =
1232 ReduceCrashingNamedMD(BD, TestFn).reduceList(NamedMDNames);
1233 if (Error E = Result.takeError())
1234 return E;
Keno Fischer11e0c312015-11-06 00:12:50 +00001235 }
1236
1237 if (!BugpointIsInterrupted) {
1238 // Now that we quickly dropped all the named metadata that doesn't
1239 // contribute to the crash, bisect the operands of the remaining ones
1240 std::vector<const MDNode *> NamedMDOps;
Rafael Espindolacdac12c2018-02-14 21:44:34 +00001241 for (auto &NamedMD : BD.getProgram().named_metadata())
Keno Fischerccae7232015-11-06 00:45:47 +00001242 for (auto op : NamedMD.operands())
1243 NamedMDOps.push_back(op);
Justin Bognerd8090ae2016-09-06 17:18:22 +00001244 Expected<bool> Result =
1245 ReduceCrashingNamedMDOps(BD, TestFn).reduceList(NamedMDOps);
1246 if (Error E = Result.takeError())
1247 return E;
Keno Fischer11e0c312015-11-06 00:12:50 +00001248 }
Philip Reames95301342016-06-29 00:10:39 +00001249 BD.EmitProgressBitcode(BD.getProgram(), "reduced-named-md");
Keno Fischer11e0c312015-11-06 00:12:50 +00001250 }
1251
Chris Lattnerba386d92003-02-28 16:13:20 +00001252 // Try to clean up the testcase by running funcresolve and globaldce...
Chris Lattnerf9aaae02005-08-02 02:16:17 +00001253 if (!BugpointIsInterrupted) {
Dan Gohmanac95cc72009-07-16 15:30:09 +00001254 outs() << "\n*** Attempting to perform final cleanups: ";
Rafael Espindolacdac12c2018-02-14 21:44:34 +00001255 std::unique_ptr<Module> M = CloneModule(BD.getProgram());
Rafael Espindola46e55022018-04-24 20:15:27 +00001256 M = BD.performFinalCleanups(std::move(M), true);
Misha Brukman3da94ae2005-04-22 00:00:37 +00001257
Chris Lattnerf9aaae02005-08-02 02:16:17 +00001258 // Find out if the pass still crashes on the cleaned up program...
Vedant Kumar00088b82018-02-09 05:09:50 +00001259 if (M && TestFn(BD, M.get()))
Rafael Espindolacdac12c2018-02-14 21:44:34 +00001260 BD.setNewProgram(
1261 std::move(M)); // Yup, it does, keep the reduced version...
Chris Lattnerba386d92003-02-28 16:13:20 +00001262 }
1263
Rafael Espindolabae1b712010-07-28 18:12:30 +00001264 BD.EmitProgressBitcode(BD.getProgram(), "reduced-simplified");
Chris Lattnerba386d92003-02-28 16:13:20 +00001265
Justin Bognerd8090ae2016-09-06 17:18:22 +00001266 return Error::success();
Chris Lattnerafade922002-11-20 22:28:10 +00001267}
Brian Gaeked0fde302003-11-11 22:41:34 +00001268
Rafael Espindola248d1c62010-08-05 03:00:22 +00001269static bool TestForOptimizerCrash(const BugDriver &BD, Module *M) {
Rafael Espindolacdac12c2018-02-14 21:44:34 +00001270 return BD.runPasses(*M, BD.getPassesToRun());
Chris Lattner8b189272004-02-18 23:26:28 +00001271}
Chris Lattner02526262004-02-18 21:02:04 +00001272
Chris Lattner8b189272004-02-18 23:26:28 +00001273/// debugOptimizerCrash - This method is called when some pass crashes on input.
1274/// It attempts to prune down the testcase to something reasonable, and figure
1275/// out exactly which pass is crashing.
1276///
Justin Bognerd8090ae2016-09-06 17:18:22 +00001277Error BugDriver::debugOptimizerCrash(const std::string &ID) {
Dan Gohmanac95cc72009-07-16 15:30:09 +00001278 outs() << "\n*** Debugging optimizer crash!\n";
Chris Lattner8b189272004-02-18 23:26:28 +00001279
1280 // Reduce the list of passes which causes the optimizer to crash...
Justin Bognerd8090ae2016-09-06 17:18:22 +00001281 if (!BugpointIsInterrupted && !DontReducePassList) {
1282 Expected<bool> Result = ReducePassList(*this).reduceList(PassesToRun);
1283 if (Error E = Result.takeError())
1284 return E;
1285 }
Chris Lattner8b189272004-02-18 23:26:28 +00001286
Dan Gohmanac95cc72009-07-16 15:30:09 +00001287 outs() << "\n*** Found crashing pass"
1288 << (PassesToRun.size() == 1 ? ": " : "es: ")
1289 << getPassesString(PassesToRun) << '\n';
Chris Lattner8b189272004-02-18 23:26:28 +00001290
Rafael Espindolacdac12c2018-02-14 21:44:34 +00001291 EmitProgressBitcode(*Program, ID);
Chris Lattner8b189272004-02-18 23:26:28 +00001292
Justin Bognerd8090ae2016-09-06 17:18:22 +00001293 return DebugACrash(*this, TestForOptimizerCrash);
Chris Lattner8b189272004-02-18 23:26:28 +00001294}
1295
Rafael Espindola248d1c62010-08-05 03:00:22 +00001296static bool TestForCodeGenCrash(const BugDriver &BD, Module *M) {
Rafael Espindolacdac12c2018-02-14 21:44:34 +00001297 if (Error E = BD.compileProgram(*M)) {
Sebastian Pop91aa2f62016-07-15 23:15:06 +00001298 if (VerboseErrors)
Justin Bognerd8090ae2016-09-06 17:18:22 +00001299 errs() << toString(std::move(E)) << "\n";
1300 else {
1301 consumeError(std::move(E));
Sebastian Pop91aa2f62016-07-15 23:15:06 +00001302 errs() << "<crash>\n";
Justin Bognerd8090ae2016-09-06 17:18:22 +00001303 }
Justin Bogner388e8b92016-09-02 01:21:37 +00001304 return true; // Tool is still crashing.
Chris Lattner8b189272004-02-18 23:26:28 +00001305 }
Nick Lewycky22ff7482010-04-12 05:08:25 +00001306 errs() << '\n';
1307 return false;
Chris Lattner8b189272004-02-18 23:26:28 +00001308}
Chris Lattner02526262004-02-18 21:02:04 +00001309
1310/// debugCodeGeneratorCrash - This method is called when the code generator
1311/// crashes on an input. It attempts to reduce the input as much as possible
1312/// while still causing the code generator to crash.
Justin Bognerd8090ae2016-09-06 17:18:22 +00001313Error BugDriver::debugCodeGeneratorCrash() {
Dan Gohman65f57c22009-07-15 16:35:29 +00001314 errs() << "*** Debugging code generator crash!\n";
Chris Lattner02526262004-02-18 21:02:04 +00001315
Justin Bognerd8090ae2016-09-06 17:18:22 +00001316 return DebugACrash(*this, TestForCodeGenCrash);
Chris Lattner02526262004-02-18 21:02:04 +00001317}