1 //===- CrashDebugger.cpp - Debug compilation crashes ----------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the bugpoint internals that narrow down compilation crashes
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "BugDriver.h"
14 #include "ListReducer.h"
15 #include "ToolRunner.h"
16 #include "llvm/ADT/SmallPtrSet.h"
17 #include "llvm/ADT/StringSet.h"
18 #include "llvm/Analysis/TargetTransformInfo.h"
19 #include "llvm/IR/CFG.h"
20 #include "llvm/IR/Constants.h"
21 #include "llvm/IR/DebugInfo.h"
22 #include "llvm/IR/DerivedTypes.h"
23 #include "llvm/IR/InstIterator.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/IR/LegacyPassManager.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/IR/ValueSymbolTable.h"
28 #include "llvm/IR/Verifier.h"
29 #include "llvm/Pass.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/FileUtilities.h"
32 #include "llvm/Transforms/Scalar.h"
33 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
34 #include "llvm/Transforms/Utils/Cloning.h"
35 #include "llvm/Transforms/Utils/Local.h"
36 #include <set>
37 using namespace llvm;
38 
39 namespace {
40 cl::opt<bool> KeepMain("keep-main",
41                        cl::desc("Force function reduction to keep main"),
42                        cl::init(false));
43 cl::opt<bool> NoGlobalRM("disable-global-remove",
44                          cl::desc("Do not remove global variables"),
45                          cl::init(false));
46 
47 cl::opt<bool> NoAttributeRM("disable-attribute-remove",
48                          cl::desc("Do not remove function attributes"),
49                          cl::init(false));
50 
51 cl::opt<bool> ReplaceFuncsWithNull(
52     "replace-funcs-with-null",
53     cl::desc("When stubbing functions, replace all uses will null"),
54     cl::init(false));
55 cl::opt<bool> DontReducePassList("disable-pass-list-reduction",
56                                  cl::desc("Skip pass list reduction steps"),
57                                  cl::init(false));
58 
59 cl::opt<bool> NoNamedMDRM("disable-namedmd-remove",
60                           cl::desc("Do not remove global named metadata"),
61                           cl::init(false));
62 cl::opt<bool> NoStripDebugInfo("disable-strip-debuginfo",
63                                cl::desc("Do not strip debug info metadata"),
64                                cl::init(false));
65 cl::opt<bool> NoStripDebugTypeInfo("disable-strip-debug-types",
66                                cl::desc("Do not strip debug type info metadata"),
67                                cl::init(false));
68 cl::opt<bool> VerboseErrors("verbose-errors",
69                             cl::desc("Print the output of crashing program"),
70                             cl::init(false));
71 }
72 
73 namespace llvm {
74 class ReducePassList : public ListReducer<std::string> {
75   BugDriver &BD;
76 
77 public:
78   ReducePassList(BugDriver &bd) : BD(bd) {}
79 
80   // Return true iff running the "removed" passes succeeds, and running the
81   // "Kept" passes fail when run on the output of the "removed" passes.  If we
82   // return true, we update the current module of bugpoint.
83   Expected<TestResult> doTest(std::vector<std::string> &Removed,
84                               std::vector<std::string> &Kept) override;
85 };
86 }
87 
88 Expected<ReducePassList::TestResult>
89 ReducePassList::doTest(std::vector<std::string> &Prefix,
90                        std::vector<std::string> &Suffix) {
91   std::string PrefixOutput;
92   std::unique_ptr<Module> OrigProgram;
93   if (!Prefix.empty()) {
94     outs() << "Checking to see if these passes crash: "
95            << getPassesString(Prefix) << ": ";
96     if (BD.runPasses(BD.getProgram(), Prefix, PrefixOutput))
97       return KeepPrefix;
98 
99     OrigProgram = std::move(BD.Program);
100 
101     BD.Program = parseInputFile(PrefixOutput, BD.getContext());
102     if (BD.Program == nullptr) {
103       errs() << BD.getToolName() << ": Error reading bitcode file '"
104              << PrefixOutput << "'!\n";
105       exit(1);
106     }
107     sys::fs::remove(PrefixOutput);
108   }
109 
110   outs() << "Checking to see if these passes crash: " << getPassesString(Suffix)
111          << ": ";
112 
113   if (BD.runPasses(BD.getProgram(), Suffix))
114     return KeepSuffix; // The suffix crashes alone...
115 
116   // Nothing failed, restore state...
117   if (OrigProgram)
118     BD.Program = std::move(OrigProgram);
119   return NoFailure;
120 }
121 
122 using BugTester = bool (*)(const BugDriver &, Module *);
123 
124 namespace {
125 /// ReduceCrashingGlobalInitializers - This works by removing global variable
126 /// initializers and seeing if the program still crashes. If it does, then we
127 /// keep that program and try again.
128 class ReduceCrashingGlobalInitializers : public ListReducer<GlobalVariable *> {
129   BugDriver &BD;
130   BugTester TestFn;
131 
132 public:
133   ReduceCrashingGlobalInitializers(BugDriver &bd, BugTester testFn)
134       : BD(bd), TestFn(testFn) {}
135 
136   Expected<TestResult> doTest(std::vector<GlobalVariable *> &Prefix,
137                               std::vector<GlobalVariable *> &Kept) override {
138     if (!Kept.empty() && TestGlobalVariables(Kept))
139       return KeepSuffix;
140     if (!Prefix.empty() && TestGlobalVariables(Prefix))
141       return KeepPrefix;
142     return NoFailure;
143   }
144 
145   bool TestGlobalVariables(std::vector<GlobalVariable *> &GVs);
146 };
147 }
148 
149 bool ReduceCrashingGlobalInitializers::TestGlobalVariables(
150     std::vector<GlobalVariable *> &GVs) {
151   // Clone the program to try hacking it apart...
152   ValueToValueMapTy VMap;
153   std::unique_ptr<Module> M = CloneModule(BD.getProgram(), VMap);
154 
155   // Convert list to set for fast lookup...
156   std::set<GlobalVariable *> GVSet;
157 
158   for (unsigned i = 0, e = GVs.size(); i != e; ++i) {
159     GlobalVariable *CMGV = cast<GlobalVariable>(VMap[GVs[i]]);
160     assert(CMGV && "Global Variable not in module?!");
161     GVSet.insert(CMGV);
162   }
163 
164   outs() << "Checking for crash with only these global variables: ";
165   PrintGlobalVariableList(GVs);
166   outs() << ": ";
167 
168   // Loop over and delete any global variables which we aren't supposed to be
169   // playing with...
170   for (GlobalVariable &I : M->globals())
171     if (I.hasInitializer() && !GVSet.count(&I)) {
172       DeleteGlobalInitializer(&I);
173       I.setLinkage(GlobalValue::ExternalLinkage);
174       I.setComdat(nullptr);
175     }
176 
177   // Try running the hacked up program...
178   if (TestFn(BD, M.get())) {
179     BD.setNewProgram(std::move(M)); // It crashed, keep the trimmed version...
180 
181     // Make sure to use global variable pointers that point into the now-current
182     // module.
183     GVs.assign(GVSet.begin(), GVSet.end());
184     return true;
185   }
186 
187   return false;
188 }
189 
190 namespace {
191 /// ReduceCrashingFunctions reducer - This works by removing functions and
192 /// seeing if the program still crashes. If it does, then keep the newer,
193 /// smaller program.
194 ///
195 class ReduceCrashingFunctions : public ListReducer<Function *> {
196   BugDriver &BD;
197   BugTester TestFn;
198 
199 public:
200   ReduceCrashingFunctions(BugDriver &bd, BugTester testFn)
201       : BD(bd), TestFn(testFn) {}
202 
203   Expected<TestResult> doTest(std::vector<Function *> &Prefix,
204                               std::vector<Function *> &Kept) override {
205     if (!Kept.empty() && TestFuncs(Kept))
206       return KeepSuffix;
207     if (!Prefix.empty() && TestFuncs(Prefix))
208       return KeepPrefix;
209     return NoFailure;
210   }
211 
212   bool TestFuncs(std::vector<Function *> &Prefix);
213 };
214 }
215 
216 static void RemoveFunctionReferences(Module *M, const char *Name) {
217   auto *UsedVar = M->getGlobalVariable(Name, true);
218   if (!UsedVar || !UsedVar->hasInitializer())
219     return;
220   if (isa<ConstantAggregateZero>(UsedVar->getInitializer())) {
221     assert(UsedVar->use_empty());
222     UsedVar->eraseFromParent();
223     return;
224   }
225   auto *OldUsedVal = cast<ConstantArray>(UsedVar->getInitializer());
226   std::vector<Constant *> Used;
227   for (Value *V : OldUsedVal->operand_values()) {
228     Constant *Op = cast<Constant>(V->stripPointerCasts());
229     if (!Op->isNullValue()) {
230       Used.push_back(cast<Constant>(V));
231     }
232   }
233   auto *NewValElemTy = OldUsedVal->getType()->getElementType();
234   auto *NewValTy = ArrayType::get(NewValElemTy, Used.size());
235   auto *NewUsedVal = ConstantArray::get(NewValTy, Used);
236   UsedVar->mutateType(NewUsedVal->getType()->getPointerTo());
237   UsedVar->setInitializer(NewUsedVal);
238 }
239 
240 bool ReduceCrashingFunctions::TestFuncs(std::vector<Function *> &Funcs) {
241   // If main isn't present, claim there is no problem.
242   if (KeepMain && !is_contained(Funcs, BD.getProgram().getFunction("main")))
243     return false;
244 
245   // Clone the program to try hacking it apart...
246   ValueToValueMapTy VMap;
247   std::unique_ptr<Module> M = CloneModule(BD.getProgram(), VMap);
248 
249   // Convert list to set for fast lookup...
250   std::set<Function *> Functions;
251   for (unsigned i = 0, e = Funcs.size(); i != e; ++i) {
252     Function *CMF = cast<Function>(VMap[Funcs[i]]);
253     assert(CMF && "Function not in module?!");
254     assert(CMF->getFunctionType() == Funcs[i]->getFunctionType() && "wrong ty");
255     assert(CMF->getName() == Funcs[i]->getName() && "wrong name");
256     Functions.insert(CMF);
257   }
258 
259   outs() << "Checking for crash with only these functions: ";
260   PrintFunctionList(Funcs);
261   outs() << ": ";
262   if (!ReplaceFuncsWithNull) {
263     // Loop over and delete any functions which we aren't supposed to be playing
264     // with...
265     for (Function &I : *M)
266       if (!I.isDeclaration() && !Functions.count(&I))
267         DeleteFunctionBody(&I);
268   } else {
269     std::vector<GlobalValue *> ToRemove;
270     // First, remove aliases to functions we're about to purge.
271     for (GlobalAlias &Alias : M->aliases()) {
272       GlobalObject *Root = Alias.getBaseObject();
273       Function *F = dyn_cast_or_null<Function>(Root);
274       if (F) {
275         if (Functions.count(F))
276           // We're keeping this function.
277           continue;
278       } else if (Root->isNullValue()) {
279         // This referenced a globalalias that we've already replaced,
280         // so we still need to replace this alias.
281       } else if (!F) {
282         // Not a function, therefore not something we mess with.
283         continue;
284       }
285 
286       PointerType *Ty = cast<PointerType>(Alias.getType());
287       Constant *Replacement = ConstantPointerNull::get(Ty);
288       Alias.replaceAllUsesWith(Replacement);
289       ToRemove.push_back(&Alias);
290     }
291 
292     for (Function &I : *M) {
293       if (!I.isDeclaration() && !Functions.count(&I)) {
294         PointerType *Ty = cast<PointerType>(I.getType());
295         Constant *Replacement = ConstantPointerNull::get(Ty);
296         I.replaceAllUsesWith(Replacement);
297         ToRemove.push_back(&I);
298       }
299     }
300 
301     for (auto *F : ToRemove) {
302       F->eraseFromParent();
303     }
304 
305     // Finally, remove any null members from any global intrinsic.
306     RemoveFunctionReferences(M.get(), "llvm.used");
307     RemoveFunctionReferences(M.get(), "llvm.compiler.used");
308   }
309   // Try running the hacked up program...
310   if (TestFn(BD, M.get())) {
311     BD.setNewProgram(std::move(M)); // It crashed, keep the trimmed version...
312 
313     // Make sure to use function pointers that point into the now-current
314     // module.
315     Funcs.assign(Functions.begin(), Functions.end());
316     return true;
317   }
318   return false;
319 }
320 
321 namespace {
322 /// ReduceCrashingFunctionAttributes reducer - This works by removing
323 /// attributes on a particular function and seeing if the program still crashes.
324 /// If it does, then keep the newer, smaller program.
325 ///
326 class ReduceCrashingFunctionAttributes : public ListReducer<Attribute> {
327   BugDriver &BD;
328   std::string FnName;
329   BugTester TestFn;
330 
331 public:
332   ReduceCrashingFunctionAttributes(BugDriver &bd, const std::string &FnName,
333                                    BugTester testFn)
334       : BD(bd), FnName(FnName), TestFn(testFn) {}
335 
336   Expected<TestResult> doTest(std::vector<Attribute> &Prefix,
337                               std::vector<Attribute> &Kept) override {
338     if (!Kept.empty() && TestFuncAttrs(Kept))
339       return KeepSuffix;
340     if (!Prefix.empty() && TestFuncAttrs(Prefix))
341       return KeepPrefix;
342     return NoFailure;
343   }
344 
345   bool TestFuncAttrs(std::vector<Attribute> &Attrs);
346 };
347 }
348 
349 bool ReduceCrashingFunctionAttributes::TestFuncAttrs(
350     std::vector<Attribute> &Attrs) {
351   // Clone the program to try hacking it apart...
352   std::unique_ptr<Module> M = CloneModule(BD.getProgram());
353   Function *F = M->getFunction(FnName);
354 
355   // Build up an AttributeList from the attributes we've been given by the
356   // reducer.
357   AttrBuilder AB;
358   for (auto A : Attrs)
359     AB.addAttribute(A);
360   AttributeList NewAttrs;
361   NewAttrs =
362       NewAttrs.addAttributes(BD.getContext(), AttributeList::FunctionIndex, AB);
363 
364   // Set this new list of attributes on the function.
365   F->setAttributes(NewAttrs);
366 
367   // Try running on the hacked up program...
368   if (TestFn(BD, M.get())) {
369     BD.setNewProgram(std::move(M)); // It crashed, keep the trimmed version...
370 
371     // Pass along the set of attributes that caused the crash.
372     Attrs.clear();
373     for (Attribute A : NewAttrs.getFnAttributes()) {
374       Attrs.push_back(A);
375     }
376     return true;
377   }
378   return false;
379 }
380 
381 namespace {
382 /// Simplify the CFG without completely destroying it.
383 /// This is not well defined, but basically comes down to "try to eliminate
384 /// unreachable blocks and constant fold terminators without deciding that
385 /// certain undefined behavior cuts off the program at the legs".
386 void simpleSimplifyCfg(Function &F, SmallVectorImpl<BasicBlock *> &BBs) {
387   if (F.empty())
388     return;
389 
390   for (auto *BB : BBs) {
391     ConstantFoldTerminator(BB);
392     MergeBlockIntoPredecessor(BB);
393   }
394 
395   // Remove unreachable blocks
396   // removeUnreachableBlocks can't be used here, it will turn various
397   // undefined behavior into unreachables, but bugpoint was the thing that
398   // generated the undefined behavior, and we don't want it to kill the entire
399   // program.
400   SmallPtrSet<BasicBlock *, 16> Visited;
401   for (auto *BB : depth_first(&F.getEntryBlock()))
402     Visited.insert(BB);
403 
404   SmallVector<BasicBlock *, 16> Unreachable;
405   for (auto &BB : F)
406     if (!Visited.count(&BB))
407       Unreachable.push_back(&BB);
408 
409   // The dead BB's may be in a dead cycle or otherwise have references to each
410   // other.  Because of this, we have to drop all references first, then delete
411   // them all at once.
412   for (auto *BB : Unreachable) {
413     for (BasicBlock *Successor : successors(&*BB))
414       if (Visited.count(Successor))
415         Successor->removePredecessor(&*BB);
416     BB->dropAllReferences();
417   }
418   for (auto *BB : Unreachable)
419     BB->eraseFromParent();
420 }
421 /// ReduceCrashingBlocks reducer - This works by setting the terminators of
422 /// all terminators except the specified basic blocks to a 'ret' instruction,
423 /// then running the simplify-cfg pass.  This has the effect of chopping up
424 /// the CFG really fast which can reduce large functions quickly.
425 ///
426 class ReduceCrashingBlocks : public ListReducer<const BasicBlock *> {
427   BugDriver &BD;
428   BugTester TestFn;
429 
430 public:
431   ReduceCrashingBlocks(BugDriver &BD, BugTester testFn)
432       : BD(BD), TestFn(testFn) {}
433 
434   Expected<TestResult> doTest(std::vector<const BasicBlock *> &Prefix,
435                               std::vector<const BasicBlock *> &Kept) override {
436     if (!Kept.empty() && TestBlocks(Kept))
437       return KeepSuffix;
438     if (!Prefix.empty() && TestBlocks(Prefix))
439       return KeepPrefix;
440     return NoFailure;
441   }
442 
443   bool TestBlocks(std::vector<const BasicBlock *> &Prefix);
444 };
445 }
446 
447 bool ReduceCrashingBlocks::TestBlocks(std::vector<const BasicBlock *> &BBs) {
448   // Clone the program to try hacking it apart...
449   ValueToValueMapTy VMap;
450   std::unique_ptr<Module> M = CloneModule(BD.getProgram(), VMap);
451 
452   // Convert list to set for fast lookup...
453   SmallPtrSet<BasicBlock *, 8> Blocks;
454   for (unsigned i = 0, e = BBs.size(); i != e; ++i)
455     Blocks.insert(cast<BasicBlock>(VMap[BBs[i]]));
456 
457   outs() << "Checking for crash with only these blocks:";
458   unsigned NumPrint = Blocks.size();
459   if (NumPrint > 10)
460     NumPrint = 10;
461   for (unsigned i = 0, e = NumPrint; i != e; ++i)
462     outs() << " " << BBs[i]->getName();
463   if (NumPrint < Blocks.size())
464     outs() << "... <" << Blocks.size() << " total>";
465   outs() << ": ";
466 
467   // Loop over and delete any hack up any blocks that are not listed...
468   for (Function &F : M->functions()) {
469     for (BasicBlock &BB : F) {
470       if (!Blocks.count(&BB) && BB.getTerminator()->getNumSuccessors()) {
471         // Loop over all of the successors of this block, deleting any PHI nodes
472         // that might include it.
473         for (BasicBlock *Succ : successors(&BB))
474           Succ->removePredecessor(&BB);
475 
476         Instruction *BBTerm = BB.getTerminator();
477         if (BBTerm->isEHPad() || BBTerm->getType()->isTokenTy())
478           continue;
479         if (!BBTerm->getType()->isVoidTy())
480           BBTerm->replaceAllUsesWith(Constant::getNullValue(BBTerm->getType()));
481 
482         // Replace the old terminator instruction.
483         BB.getInstList().pop_back();
484         new UnreachableInst(BB.getContext(), &BB);
485       }
486     }
487   }
488 
489   // The CFG Simplifier pass may delete one of the basic blocks we are
490   // interested in.  If it does we need to take the block out of the list.  Make
491   // a "persistent mapping" by turning basic blocks into <function, name> pairs.
492   // This won't work well if blocks are unnamed, but that is just the risk we
493   // have to take. FIXME: Can we just name the blocks?
494   std::vector<std::pair<std::string, std::string>> BlockInfo;
495 
496   for (BasicBlock *BB : Blocks)
497     BlockInfo.emplace_back(BB->getParent()->getName(), BB->getName());
498 
499   SmallVector<BasicBlock *, 16> ToProcess;
500   for (auto &F : *M) {
501     for (auto &BB : F)
502       if (!Blocks.count(&BB))
503         ToProcess.push_back(&BB);
504     simpleSimplifyCfg(F, ToProcess);
505     ToProcess.clear();
506   }
507   // Verify we didn't break anything
508   std::vector<std::string> Passes;
509   Passes.push_back("verify");
510   std::unique_ptr<Module> New = BD.runPassesOn(M.get(), Passes);
511   if (!New) {
512     errs() << "verify failed!\n";
513     exit(1);
514   }
515   M = std::move(New);
516 
517   // Try running on the hacked up program...
518   if (TestFn(BD, M.get())) {
519     BD.setNewProgram(std::move(M)); // It crashed, keep the trimmed version...
520 
521     // Make sure to use basic block pointers that point into the now-current
522     // module, and that they don't include any deleted blocks.
523     BBs.clear();
524     const ValueSymbolTable &GST = BD.getProgram().getValueSymbolTable();
525     for (const auto &BI : BlockInfo) {
526       Function *F = cast<Function>(GST.lookup(BI.first));
527       Value *V = F->getValueSymbolTable()->lookup(BI.second);
528       if (V && V->getType() == Type::getLabelTy(V->getContext()))
529         BBs.push_back(cast<BasicBlock>(V));
530     }
531     return true;
532   }
533   // It didn't crash, try something else.
534   return false;
535 }
536 
537 namespace {
538 /// ReduceCrashingConditionals reducer - This works by changing
539 /// conditional branches to unconditional ones, then simplifying the CFG
540 /// This has the effect of chopping up the CFG really fast which can reduce
541 /// large functions quickly.
542 ///
543 class ReduceCrashingConditionals : public ListReducer<const BasicBlock *> {
544   BugDriver &BD;
545   BugTester TestFn;
546   bool Direction;
547 
548 public:
549   ReduceCrashingConditionals(BugDriver &bd, BugTester testFn, bool Direction)
550       : BD(bd), TestFn(testFn), Direction(Direction) {}
551 
552   Expected<TestResult> doTest(std::vector<const BasicBlock *> &Prefix,
553                               std::vector<const BasicBlock *> &Kept) override {
554     if (!Kept.empty() && TestBlocks(Kept))
555       return KeepSuffix;
556     if (!Prefix.empty() && TestBlocks(Prefix))
557       return KeepPrefix;
558     return NoFailure;
559   }
560 
561   bool TestBlocks(std::vector<const BasicBlock *> &Prefix);
562 };
563 }
564 
565 bool ReduceCrashingConditionals::TestBlocks(
566     std::vector<const BasicBlock *> &BBs) {
567   // Clone the program to try hacking it apart...
568   ValueToValueMapTy VMap;
569   std::unique_ptr<Module> M = CloneModule(BD.getProgram(), VMap);
570 
571   // Convert list to set for fast lookup...
572   SmallPtrSet<const BasicBlock *, 8> Blocks;
573   for (const auto *BB : BBs)
574     Blocks.insert(cast<BasicBlock>(VMap[BB]));
575 
576   outs() << "Checking for crash with changing conditionals to always jump to "
577          << (Direction ? "true" : "false") << ":";
578   unsigned NumPrint = Blocks.size();
579   if (NumPrint > 10)
580     NumPrint = 10;
581   for (unsigned i = 0, e = NumPrint; i != e; ++i)
582     outs() << " " << BBs[i]->getName();
583   if (NumPrint < Blocks.size())
584     outs() << "... <" << Blocks.size() << " total>";
585   outs() << ": ";
586 
587   // Loop over and delete any hack up any blocks that are not listed...
588   for (auto &F : *M)
589     for (auto &BB : F)
590       if (!Blocks.count(&BB)) {
591         auto *BR = dyn_cast<BranchInst>(BB.getTerminator());
592         if (!BR || !BR->isConditional())
593           continue;
594         if (Direction)
595           BR->setCondition(ConstantInt::getTrue(BR->getContext()));
596         else
597           BR->setCondition(ConstantInt::getFalse(BR->getContext()));
598       }
599 
600   // The following may destroy some blocks, so we save them first
601   std::vector<std::pair<std::string, std::string>> BlockInfo;
602 
603   for (const BasicBlock *BB : Blocks)
604     BlockInfo.emplace_back(BB->getParent()->getName(), BB->getName());
605 
606   SmallVector<BasicBlock *, 16> ToProcess;
607   for (auto &F : *M) {
608     for (auto &BB : F)
609       if (!Blocks.count(&BB))
610         ToProcess.push_back(&BB);
611     simpleSimplifyCfg(F, ToProcess);
612     ToProcess.clear();
613   }
614   // Verify we didn't break anything
615   std::vector<std::string> Passes;
616   Passes.push_back("verify");
617   std::unique_ptr<Module> New = BD.runPassesOn(M.get(), Passes);
618   if (!New) {
619     errs() << "verify failed!\n";
620     exit(1);
621   }
622   M = std::move(New);
623 
624   // Try running on the hacked up program...
625   if (TestFn(BD, M.get())) {
626     BD.setNewProgram(std::move(M)); // It crashed, keep the trimmed version...
627 
628     // Make sure to use basic block pointers that point into the now-current
629     // module, and that they don't include any deleted blocks.
630     BBs.clear();
631     const ValueSymbolTable &GST = BD.getProgram().getValueSymbolTable();
632     for (auto &BI : BlockInfo) {
633       auto *F = cast<Function>(GST.lookup(BI.first));
634       Value *V = F->getValueSymbolTable()->lookup(BI.second);
635       if (V && V->getType() == Type::getLabelTy(V->getContext()))
636         BBs.push_back(cast<BasicBlock>(V));
637     }
638     return true;
639   }
640   // It didn't crash, try something else.
641   return false;
642 }
643 
644 namespace {
645 /// SimplifyCFG reducer - This works by calling SimplifyCFG on each basic block
646 /// in the program.
647 
648 class ReduceSimplifyCFG : public ListReducer<const BasicBlock *> {
649   BugDriver &BD;
650   BugTester TestFn;
651   TargetTransformInfo TTI;
652 
653 public:
654   ReduceSimplifyCFG(BugDriver &bd, BugTester testFn)
655       : BD(bd), TestFn(testFn), TTI(bd.getProgram().getDataLayout()) {}
656 
657   Expected<TestResult> doTest(std::vector<const BasicBlock *> &Prefix,
658                               std::vector<const BasicBlock *> &Kept) override {
659     if (!Kept.empty() && TestBlocks(Kept))
660       return KeepSuffix;
661     if (!Prefix.empty() && TestBlocks(Prefix))
662       return KeepPrefix;
663     return NoFailure;
664   }
665 
666   bool TestBlocks(std::vector<const BasicBlock *> &Prefix);
667 };
668 }
669 
670 bool ReduceSimplifyCFG::TestBlocks(std::vector<const BasicBlock *> &BBs) {
671   // Clone the program to try hacking it apart...
672   ValueToValueMapTy VMap;
673   std::unique_ptr<Module> M = CloneModule(BD.getProgram(), VMap);
674 
675   // Convert list to set for fast lookup...
676   SmallPtrSet<const BasicBlock *, 8> Blocks;
677   for (const auto *BB : BBs)
678     Blocks.insert(cast<BasicBlock>(VMap[BB]));
679 
680   outs() << "Checking for crash with CFG simplifying:";
681   unsigned NumPrint = Blocks.size();
682   if (NumPrint > 10)
683     NumPrint = 10;
684   for (unsigned i = 0, e = NumPrint; i != e; ++i)
685     outs() << " " << BBs[i]->getName();
686   if (NumPrint < Blocks.size())
687     outs() << "... <" << Blocks.size() << " total>";
688   outs() << ": ";
689 
690   // The following may destroy some blocks, so we save them first
691   std::vector<std::pair<std::string, std::string>> BlockInfo;
692 
693   for (const BasicBlock *BB : Blocks)
694     BlockInfo.emplace_back(BB->getParent()->getName(), BB->getName());
695 
696   // Loop over and delete any hack up any blocks that are not listed...
697   for (auto &F : *M)
698     // Loop over all of the basic blocks and remove them if they are unneeded.
699     for (Function::iterator BBIt = F.begin(); BBIt != F.end();) {
700       if (!Blocks.count(&*BBIt)) {
701         ++BBIt;
702         continue;
703       }
704       simplifyCFG(&*BBIt++, TTI);
705     }
706   // Verify we didn't break anything
707   std::vector<std::string> Passes;
708   Passes.push_back("verify");
709   std::unique_ptr<Module> New = BD.runPassesOn(M.get(), Passes);
710   if (!New) {
711     errs() << "verify failed!\n";
712     exit(1);
713   }
714   M = std::move(New);
715 
716   // Try running on the hacked up program...
717   if (TestFn(BD, M.get())) {
718     BD.setNewProgram(std::move(M)); // It crashed, keep the trimmed version...
719 
720     // Make sure to use basic block pointers that point into the now-current
721     // module, and that they don't include any deleted blocks.
722     BBs.clear();
723     const ValueSymbolTable &GST = BD.getProgram().getValueSymbolTable();
724     for (auto &BI : BlockInfo) {
725       auto *F = cast<Function>(GST.lookup(BI.first));
726       Value *V = F->getValueSymbolTable()->lookup(BI.second);
727       if (V && V->getType() == Type::getLabelTy(V->getContext()))
728         BBs.push_back(cast<BasicBlock>(V));
729     }
730     return true;
731   }
732   // It didn't crash, try something else.
733   return false;
734 }
735 
736 namespace {
737 /// ReduceCrashingInstructions reducer - This works by removing the specified
738 /// non-terminator instructions and replacing them with undef.
739 ///
740 class ReduceCrashingInstructions : public ListReducer<const Instruction *> {
741   BugDriver &BD;
742   BugTester TestFn;
743 
744 public:
745   ReduceCrashingInstructions(BugDriver &bd, BugTester testFn)
746       : BD(bd), TestFn(testFn) {}
747 
748   Expected<TestResult> doTest(std::vector<const Instruction *> &Prefix,
749                               std::vector<const Instruction *> &Kept) override {
750     if (!Kept.empty() && TestInsts(Kept))
751       return KeepSuffix;
752     if (!Prefix.empty() && TestInsts(Prefix))
753       return KeepPrefix;
754     return NoFailure;
755   }
756 
757   bool TestInsts(std::vector<const Instruction *> &Prefix);
758 };
759 }
760 
761 bool ReduceCrashingInstructions::TestInsts(
762     std::vector<const Instruction *> &Insts) {
763   // Clone the program to try hacking it apart...
764   ValueToValueMapTy VMap;
765   std::unique_ptr<Module> M = CloneModule(BD.getProgram(), VMap);
766 
767   // Convert list to set for fast lookup...
768   SmallPtrSet<Instruction *, 32> Instructions;
769   for (unsigned i = 0, e = Insts.size(); i != e; ++i) {
770     assert(!Insts[i]->isTerminator());
771     Instructions.insert(cast<Instruction>(VMap[Insts[i]]));
772   }
773 
774   outs() << "Checking for crash with only " << Instructions.size();
775   if (Instructions.size() == 1)
776     outs() << " instruction: ";
777   else
778     outs() << " instructions: ";
779 
780   for (Module::iterator MI = M->begin(), ME = M->end(); MI != ME; ++MI)
781     for (Function::iterator FI = MI->begin(), FE = MI->end(); FI != FE; ++FI)
782       for (BasicBlock::iterator I = FI->begin(), E = FI->end(); I != E;) {
783         Instruction *Inst = &*I++;
784         if (!Instructions.count(Inst) && !Inst->isTerminator() &&
785             !Inst->isEHPad() && !Inst->getType()->isTokenTy() &&
786             !Inst->isSwiftError()) {
787           if (!Inst->getType()->isVoidTy())
788             Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
789           Inst->eraseFromParent();
790         }
791       }
792 
793   // Verify that this is still valid.
794   legacy::PassManager Passes;
795   Passes.add(createVerifierPass(/*FatalErrors=*/false));
796   Passes.run(*M);
797 
798   // Try running on the hacked up program...
799   if (TestFn(BD, M.get())) {
800     BD.setNewProgram(std::move(M)); // It crashed, keep the trimmed version...
801 
802     // Make sure to use instruction pointers that point into the now-current
803     // module, and that they don't include any deleted blocks.
804     Insts.clear();
805     for (Instruction *Inst : Instructions)
806       Insts.push_back(Inst);
807     return true;
808   }
809   // It didn't crash, try something else.
810   return false;
811 }
812 
813 namespace {
814 /// ReduceCrashingMetadata reducer - This works by removing all metadata from
815 /// the specified instructions.
816 ///
817 class ReduceCrashingMetadata : public ListReducer<Instruction *> {
818   BugDriver &BD;
819   BugTester TestFn;
820 
821 public:
822   ReduceCrashingMetadata(BugDriver &bd, BugTester testFn)
823       : BD(bd), TestFn(testFn) {}
824 
825   Expected<TestResult> doTest(std::vector<Instruction *> &Prefix,
826                               std::vector<Instruction *> &Kept) override {
827     if (!Kept.empty() && TestInsts(Kept))
828       return KeepSuffix;
829     if (!Prefix.empty() && TestInsts(Prefix))
830       return KeepPrefix;
831     return NoFailure;
832   }
833 
834   bool TestInsts(std::vector<Instruction *> &Prefix);
835 };
836 } // namespace
837 
838 bool ReduceCrashingMetadata::TestInsts(std::vector<Instruction *> &Insts) {
839   // Clone the program to try hacking it apart...
840   ValueToValueMapTy VMap;
841   std::unique_ptr<Module> M = CloneModule(BD.getProgram(), VMap);
842 
843   // Convert list to set for fast lookup...
844   SmallPtrSet<Instruction *, 32> Instructions;
845   for (Instruction *I : Insts)
846     Instructions.insert(cast<Instruction>(VMap[I]));
847 
848   outs() << "Checking for crash with metadata retained from "
849          << Instructions.size();
850   if (Instructions.size() == 1)
851     outs() << " instruction: ";
852   else
853     outs() << " instructions: ";
854 
855   // Try to drop instruction metadata from all instructions, except the ones
856   // selected in Instructions.
857   for (Function &F : *M)
858     for (Instruction &Inst : instructions(F)) {
859       if (Instructions.find(&Inst) == Instructions.end()) {
860         Inst.dropUnknownNonDebugMetadata();
861         Inst.setDebugLoc({});
862       }
863     }
864 
865   // Verify that this is still valid.
866   legacy::PassManager Passes;
867   Passes.add(createVerifierPass(/*FatalErrors=*/false));
868   Passes.run(*M);
869 
870   // Try running on the hacked up program...
871   if (TestFn(BD, M.get())) {
872     BD.setNewProgram(std::move(M)); // It crashed, keep the trimmed version...
873 
874     // Make sure to use instruction pointers that point into the now-current
875     // module, and that they don't include any deleted blocks.
876     Insts.clear();
877     for (Instruction *I : Instructions)
878       Insts.push_back(I);
879     return true;
880   }
881   // It didn't crash, try something else.
882   return false;
883 }
884 
885 namespace {
886 // Reduce the list of Named Metadata nodes. We keep this as a list of
887 // names to avoid having to convert back and forth every time.
888 class ReduceCrashingNamedMD : public ListReducer<std::string> {
889   BugDriver &BD;
890   BugTester TestFn;
891 
892 public:
893   ReduceCrashingNamedMD(BugDriver &bd, BugTester testFn)
894       : BD(bd), TestFn(testFn) {}
895 
896   Expected<TestResult> doTest(std::vector<std::string> &Prefix,
897                               std::vector<std::string> &Kept) override {
898     if (!Kept.empty() && TestNamedMDs(Kept))
899       return KeepSuffix;
900     if (!Prefix.empty() && TestNamedMDs(Prefix))
901       return KeepPrefix;
902     return NoFailure;
903   }
904 
905   bool TestNamedMDs(std::vector<std::string> &NamedMDs);
906 };
907 }
908 
909 bool ReduceCrashingNamedMD::TestNamedMDs(std::vector<std::string> &NamedMDs) {
910 
911   ValueToValueMapTy VMap;
912   std::unique_ptr<Module> M = CloneModule(BD.getProgram(), VMap);
913 
914   outs() << "Checking for crash with only these named metadata nodes:";
915   unsigned NumPrint = std::min<size_t>(NamedMDs.size(), 10);
916   for (unsigned i = 0, e = NumPrint; i != e; ++i)
917     outs() << " " << NamedMDs[i];
918   if (NumPrint < NamedMDs.size())
919     outs() << "... <" << NamedMDs.size() << " total>";
920   outs() << ": ";
921 
922   // Make a StringMap for faster lookup
923   StringSet<> Names;
924   for (const std::string &Name : NamedMDs)
925     Names.insert(Name);
926 
927   // First collect all the metadata to delete in a vector, then
928   // delete them all at once to avoid invalidating the iterator
929   std::vector<NamedMDNode *> ToDelete;
930   ToDelete.reserve(M->named_metadata_size() - Names.size());
931   for (auto &NamedMD : M->named_metadata())
932     // Always keep a nonempty llvm.dbg.cu because the Verifier would complain.
933     if (!Names.count(NamedMD.getName()) &&
934         (!(NamedMD.getName() == "llvm.dbg.cu" && NamedMD.getNumOperands() > 0)))
935       ToDelete.push_back(&NamedMD);
936 
937   for (auto *NamedMD : ToDelete)
938     NamedMD->eraseFromParent();
939 
940   // Verify that this is still valid.
941   legacy::PassManager Passes;
942   Passes.add(createVerifierPass(/*FatalErrors=*/false));
943   Passes.run(*M);
944 
945   // Try running on the hacked up program...
946   if (TestFn(BD, M.get())) {
947     BD.setNewProgram(std::move(M)); // It crashed, keep the trimmed version...
948     return true;
949   }
950   return false;
951 }
952 
953 namespace {
954 // Reduce the list of operands to named metadata nodes
955 class ReduceCrashingNamedMDOps : public ListReducer<const MDNode *> {
956   BugDriver &BD;
957   BugTester TestFn;
958 
959 public:
960   ReduceCrashingNamedMDOps(BugDriver &bd, BugTester testFn)
961       : BD(bd), TestFn(testFn) {}
962 
963   Expected<TestResult> doTest(std::vector<const MDNode *> &Prefix,
964                               std::vector<const MDNode *> &Kept) override {
965     if (!Kept.empty() && TestNamedMDOps(Kept))
966       return KeepSuffix;
967     if (!Prefix.empty() && TestNamedMDOps(Prefix))
968       return KeepPrefix;
969     return NoFailure;
970   }
971 
972   bool TestNamedMDOps(std::vector<const MDNode *> &NamedMDOps);
973 };
974 }
975 
976 bool ReduceCrashingNamedMDOps::TestNamedMDOps(
977     std::vector<const MDNode *> &NamedMDOps) {
978   // Convert list to set for fast lookup...
979   SmallPtrSet<const MDNode *, 32> OldMDNodeOps;
980   for (unsigned i = 0, e = NamedMDOps.size(); i != e; ++i) {
981     OldMDNodeOps.insert(NamedMDOps[i]);
982   }
983 
984   outs() << "Checking for crash with only " << OldMDNodeOps.size();
985   if (OldMDNodeOps.size() == 1)
986     outs() << " named metadata operand: ";
987   else
988     outs() << " named metadata operands: ";
989 
990   ValueToValueMapTy VMap;
991   std::unique_ptr<Module> M = CloneModule(BD.getProgram(), VMap);
992 
993   // This is a little wasteful. In the future it might be good if we could have
994   // these dropped during cloning.
995   for (auto &NamedMD : BD.getProgram().named_metadata()) {
996     // Drop the old one and create a new one
997     M->eraseNamedMetadata(M->getNamedMetadata(NamedMD.getName()));
998     NamedMDNode *NewNamedMDNode =
999         M->getOrInsertNamedMetadata(NamedMD.getName());
1000     for (MDNode *op : NamedMD.operands())
1001       if (OldMDNodeOps.count(op))
1002         NewNamedMDNode->addOperand(cast<MDNode>(MapMetadata(op, VMap)));
1003   }
1004 
1005   // Verify that this is still valid.
1006   legacy::PassManager Passes;
1007   Passes.add(createVerifierPass(/*FatalErrors=*/false));
1008   Passes.run(*M);
1009 
1010   // Try running on the hacked up program...
1011   if (TestFn(BD, M.get())) {
1012     // Make sure to use instruction pointers that point into the now-current
1013     // module, and that they don't include any deleted blocks.
1014     NamedMDOps.clear();
1015     for (const MDNode *Node : OldMDNodeOps)
1016       NamedMDOps.push_back(cast<MDNode>(*VMap.getMappedMD(Node)));
1017 
1018     BD.setNewProgram(std::move(M)); // It crashed, keep the trimmed version...
1019     return true;
1020   }
1021   // It didn't crash, try something else.
1022   return false;
1023 }
1024 
1025 /// Attempt to eliminate as many global initializers as possible.
1026 static Error ReduceGlobalInitializers(BugDriver &BD, BugTester TestFn) {
1027   Module &OrigM = BD.getProgram();
1028   if (OrigM.global_empty())
1029     return Error::success();
1030 
1031   // Now try to reduce the number of global variable initializers in the
1032   // module to something small.
1033   std::unique_ptr<Module> M = CloneModule(OrigM);
1034   bool DeletedInit = false;
1035 
1036   for (GlobalVariable &GV : M->globals()) {
1037     if (GV.hasInitializer()) {
1038       DeleteGlobalInitializer(&GV);
1039       GV.setLinkage(GlobalValue::ExternalLinkage);
1040       GV.setComdat(nullptr);
1041       DeletedInit = true;
1042     }
1043   }
1044 
1045   if (!DeletedInit)
1046     return Error::success();
1047 
1048   // See if the program still causes a crash...
1049   outs() << "\nChecking to see if we can delete global inits: ";
1050 
1051   if (TestFn(BD, M.get())) { // Still crashes?
1052     BD.setNewProgram(std::move(M));
1053     outs() << "\n*** Able to remove all global initializers!\n";
1054     return Error::success();
1055   }
1056 
1057   // No longer crashes.
1058   outs() << "  - Removing all global inits hides problem!\n";
1059 
1060   std::vector<GlobalVariable *> GVs;
1061   for (GlobalVariable &GV : OrigM.globals())
1062     if (GV.hasInitializer())
1063       GVs.push_back(&GV);
1064 
1065   if (GVs.size() > 1 && !BugpointIsInterrupted) {
1066     outs() << "\n*** Attempting to reduce the number of global initializers "
1067            << "in the testcase\n";
1068 
1069     unsigned OldSize = GVs.size();
1070     Expected<bool> Result =
1071         ReduceCrashingGlobalInitializers(BD, TestFn).reduceList(GVs);
1072     if (Error E = Result.takeError())
1073       return E;
1074 
1075     if (GVs.size() < OldSize)
1076       BD.EmitProgressBitcode(BD.getProgram(), "reduced-global-variables");
1077   }
1078   return Error::success();
1079 }
1080 
1081 static Error ReduceInsts(BugDriver &BD, BugTester TestFn) {
1082   // Attempt to delete instructions using bisection. This should help out nasty
1083   // cases with large basic blocks where the problem is at one end.
1084   if (!BugpointIsInterrupted) {
1085     std::vector<const Instruction *> Insts;
1086     for (const Function &F : BD.getProgram())
1087       for (const BasicBlock &BB : F)
1088         for (const Instruction &I : BB)
1089           if (!I.isTerminator())
1090             Insts.push_back(&I);
1091 
1092     Expected<bool> Result =
1093         ReduceCrashingInstructions(BD, TestFn).reduceList(Insts);
1094     if (Error E = Result.takeError())
1095       return E;
1096   }
1097 
1098   unsigned Simplification = 2;
1099   do {
1100     if (BugpointIsInterrupted)
1101       // TODO: Should we distinguish this with an "interrupted error"?
1102       return Error::success();
1103     --Simplification;
1104     outs() << "\n*** Attempting to reduce testcase by deleting instruc"
1105            << "tions: Simplification Level #" << Simplification << '\n';
1106 
1107     // Now that we have deleted the functions that are unnecessary for the
1108     // program, try to remove instructions that are not necessary to cause the
1109     // crash.  To do this, we loop through all of the instructions in the
1110     // remaining functions, deleting them (replacing any values produced with
1111     // nulls), and then running ADCE and SimplifyCFG.  If the transformed input
1112     // still triggers failure, keep deleting until we cannot trigger failure
1113     // anymore.
1114     //
1115     unsigned InstructionsToSkipBeforeDeleting = 0;
1116   TryAgain:
1117 
1118     // Loop over all of the (non-terminator) instructions remaining in the
1119     // function, attempting to delete them.
1120     unsigned CurInstructionNum = 0;
1121     for (Module::const_iterator FI = BD.getProgram().begin(),
1122                                 E = BD.getProgram().end();
1123          FI != E; ++FI)
1124       if (!FI->isDeclaration())
1125         for (Function::const_iterator BI = FI->begin(), E = FI->end(); BI != E;
1126              ++BI)
1127           for (BasicBlock::const_iterator I = BI->begin(), E = --BI->end();
1128                I != E; ++I, ++CurInstructionNum) {
1129             if (InstructionsToSkipBeforeDeleting) {
1130               --InstructionsToSkipBeforeDeleting;
1131             } else {
1132               if (BugpointIsInterrupted)
1133                 // TODO: Should this be some kind of interrupted error?
1134                 return Error::success();
1135 
1136               if (I->isEHPad() || I->getType()->isTokenTy() ||
1137                   I->isSwiftError())
1138                 continue;
1139 
1140               outs() << "Checking instruction: " << *I;
1141               std::unique_ptr<Module> M =
1142                   BD.deleteInstructionFromProgram(&*I, Simplification);
1143 
1144               // Find out if the pass still crashes on this pass...
1145               if (TestFn(BD, M.get())) {
1146                 // Yup, it does, we delete the old module, and continue trying
1147                 // to reduce the testcase...
1148                 BD.setNewProgram(std::move(M));
1149                 InstructionsToSkipBeforeDeleting = CurInstructionNum;
1150                 goto TryAgain; // I wish I had a multi-level break here!
1151               }
1152             }
1153           }
1154 
1155     if (InstructionsToSkipBeforeDeleting) {
1156       InstructionsToSkipBeforeDeleting = 0;
1157       goto TryAgain;
1158     }
1159 
1160   } while (Simplification);
1161 
1162   // Attempt to drop metadata from instructions that does not contribute to the
1163   // crash.
1164   if (!BugpointIsInterrupted) {
1165     std::vector<Instruction *> Insts;
1166     for (Function &F : BD.getProgram())
1167       for (Instruction &I : instructions(F))
1168         Insts.push_back(&I);
1169 
1170     Expected<bool> Result =
1171         ReduceCrashingMetadata(BD, TestFn).reduceList(Insts);
1172     if (Error E = Result.takeError())
1173       return E;
1174   }
1175 
1176   BD.EmitProgressBitcode(BD.getProgram(), "reduced-instructions");
1177   return Error::success();
1178 }
1179 
1180 /// DebugACrash - Given a predicate that determines whether a component crashes
1181 /// on a program, try to destructively reduce the program while still keeping
1182 /// the predicate true.
1183 static Error DebugACrash(BugDriver &BD, BugTester TestFn) {
1184   // See if we can get away with nuking some of the global variable initializers
1185   // in the program...
1186   if (!NoGlobalRM)
1187     if (Error E = ReduceGlobalInitializers(BD, TestFn))
1188       return E;
1189 
1190   // Now try to reduce the number of functions in the module to something small.
1191   std::vector<Function *> Functions;
1192   for (Function &F : BD.getProgram())
1193     if (!F.isDeclaration())
1194       Functions.push_back(&F);
1195 
1196   if (Functions.size() > 1 && !BugpointIsInterrupted) {
1197     outs() << "\n*** Attempting to reduce the number of functions "
1198               "in the testcase\n";
1199 
1200     unsigned OldSize = Functions.size();
1201     Expected<bool> Result =
1202         ReduceCrashingFunctions(BD, TestFn).reduceList(Functions);
1203     if (Error E = Result.takeError())
1204       return E;
1205 
1206     if (Functions.size() < OldSize)
1207       BD.EmitProgressBitcode(BD.getProgram(), "reduced-function");
1208   }
1209 
1210   if (!NoAttributeRM) {
1211     // For each remaining function, try to reduce that function's attributes.
1212     std::vector<std::string> FunctionNames;
1213     for (Function &F : BD.getProgram())
1214       FunctionNames.push_back(F.getName());
1215 
1216     if (!FunctionNames.empty() && !BugpointIsInterrupted) {
1217       outs() << "\n*** Attempting to reduce the number of function attributes"
1218                 " in the testcase\n";
1219 
1220       unsigned OldSize = 0;
1221       unsigned NewSize = 0;
1222       for (std::string &Name : FunctionNames) {
1223         Function *Fn = BD.getProgram().getFunction(Name);
1224         assert(Fn && "Could not find funcion?");
1225 
1226         std::vector<Attribute> Attrs;
1227         for (Attribute A : Fn->getAttributes().getFnAttributes())
1228           Attrs.push_back(A);
1229 
1230         OldSize += Attrs.size();
1231         Expected<bool> Result =
1232           ReduceCrashingFunctionAttributes(BD, Name, TestFn).reduceList(Attrs);
1233         if (Error E = Result.takeError())
1234           return E;
1235 
1236         NewSize += Attrs.size();
1237       }
1238 
1239       if (OldSize < NewSize)
1240         BD.EmitProgressBitcode(BD.getProgram(), "reduced-function-attributes");
1241     }
1242   }
1243 
1244   // Attempt to change conditional branches into unconditional branches to
1245   // eliminate blocks.
1246   if (!DisableSimplifyCFG && !BugpointIsInterrupted) {
1247     std::vector<const BasicBlock *> Blocks;
1248     for (Function &F : BD.getProgram())
1249       for (BasicBlock &BB : F)
1250         Blocks.push_back(&BB);
1251     unsigned OldSize = Blocks.size();
1252     Expected<bool> Result =
1253         ReduceCrashingConditionals(BD, TestFn, true).reduceList(Blocks);
1254     if (Error E = Result.takeError())
1255       return E;
1256     Result = ReduceCrashingConditionals(BD, TestFn, false).reduceList(Blocks);
1257     if (Error E = Result.takeError())
1258       return E;
1259     if (Blocks.size() < OldSize)
1260       BD.EmitProgressBitcode(BD.getProgram(), "reduced-conditionals");
1261   }
1262 
1263   // Attempt to delete entire basic blocks at a time to speed up
1264   // convergence... this actually works by setting the terminator of the blocks
1265   // to a return instruction then running simplifycfg, which can potentially
1266   // shrinks the code dramatically quickly
1267   //
1268   if (!DisableSimplifyCFG && !BugpointIsInterrupted) {
1269     std::vector<const BasicBlock *> Blocks;
1270     for (Function &F : BD.getProgram())
1271       for (BasicBlock &BB : F)
1272         Blocks.push_back(&BB);
1273     unsigned OldSize = Blocks.size();
1274     Expected<bool> Result = ReduceCrashingBlocks(BD, TestFn).reduceList(Blocks);
1275     if (Error E = Result.takeError())
1276       return E;
1277     if (Blocks.size() < OldSize)
1278       BD.EmitProgressBitcode(BD.getProgram(), "reduced-blocks");
1279   }
1280 
1281   if (!DisableSimplifyCFG && !BugpointIsInterrupted) {
1282     std::vector<const BasicBlock *> Blocks;
1283     for (Function &F : BD.getProgram())
1284       for (BasicBlock &BB : F)
1285         Blocks.push_back(&BB);
1286     unsigned OldSize = Blocks.size();
1287     Expected<bool> Result = ReduceSimplifyCFG(BD, TestFn).reduceList(Blocks);
1288     if (Error E = Result.takeError())
1289       return E;
1290     if (Blocks.size() < OldSize)
1291       BD.EmitProgressBitcode(BD.getProgram(), "reduced-simplifycfg");
1292   }
1293 
1294   // Attempt to delete instructions using bisection. This should help out nasty
1295   // cases with large basic blocks where the problem is at one end.
1296   if (!BugpointIsInterrupted)
1297     if (Error E = ReduceInsts(BD, TestFn))
1298       return E;
1299 
1300   // Attempt to strip debug info metadata.
1301   auto stripMetadata = [&](std::function<bool(Module &)> strip) {
1302     std::unique_ptr<Module> M = CloneModule(BD.getProgram());
1303     strip(*M);
1304     if (TestFn(BD, M.get()))
1305       BD.setNewProgram(std::move(M));
1306   };
1307   if (!NoStripDebugInfo && !BugpointIsInterrupted) {
1308     outs() << "\n*** Attempting to strip the debug info: ";
1309     stripMetadata(StripDebugInfo);
1310   }
1311   if (!NoStripDebugTypeInfo && !BugpointIsInterrupted) {
1312     outs() << "\n*** Attempting to strip the debug type info: ";
1313     stripMetadata(stripNonLineTableDebugInfo);
1314   }
1315 
1316   if (!NoNamedMDRM) {
1317     if (!BugpointIsInterrupted) {
1318       // Try to reduce the amount of global metadata (particularly debug info),
1319       // by dropping global named metadata that anchors them
1320       outs() << "\n*** Attempting to remove named metadata: ";
1321       std::vector<std::string> NamedMDNames;
1322       for (auto &NamedMD : BD.getProgram().named_metadata())
1323         NamedMDNames.push_back(NamedMD.getName().str());
1324       Expected<bool> Result =
1325           ReduceCrashingNamedMD(BD, TestFn).reduceList(NamedMDNames);
1326       if (Error E = Result.takeError())
1327         return E;
1328     }
1329 
1330     if (!BugpointIsInterrupted) {
1331       // Now that we quickly dropped all the named metadata that doesn't
1332       // contribute to the crash, bisect the operands of the remaining ones
1333       std::vector<const MDNode *> NamedMDOps;
1334       for (auto &NamedMD : BD.getProgram().named_metadata())
1335         for (auto op : NamedMD.operands())
1336           NamedMDOps.push_back(op);
1337       Expected<bool> Result =
1338           ReduceCrashingNamedMDOps(BD, TestFn).reduceList(NamedMDOps);
1339       if (Error E = Result.takeError())
1340         return E;
1341     }
1342     BD.EmitProgressBitcode(BD.getProgram(), "reduced-named-md");
1343   }
1344 
1345   // Try to clean up the testcase by running funcresolve and globaldce...
1346   if (!BugpointIsInterrupted) {
1347     outs() << "\n*** Attempting to perform final cleanups: ";
1348     std::unique_ptr<Module> M = CloneModule(BD.getProgram());
1349     M = BD.performFinalCleanups(std::move(M), true);
1350 
1351     // Find out if the pass still crashes on the cleaned up program...
1352     if (M && TestFn(BD, M.get()))
1353       BD.setNewProgram(
1354           std::move(M)); // Yup, it does, keep the reduced version...
1355   }
1356 
1357   BD.EmitProgressBitcode(BD.getProgram(), "reduced-simplified");
1358 
1359   return Error::success();
1360 }
1361 
1362 static bool TestForOptimizerCrash(const BugDriver &BD, Module *M) {
1363   return BD.runPasses(*M, BD.getPassesToRun());
1364 }
1365 
1366 /// debugOptimizerCrash - This method is called when some pass crashes on input.
1367 /// It attempts to prune down the testcase to something reasonable, and figure
1368 /// out exactly which pass is crashing.
1369 ///
1370 Error BugDriver::debugOptimizerCrash(const std::string &ID) {
1371   outs() << "\n*** Debugging optimizer crash!\n";
1372 
1373   // Reduce the list of passes which causes the optimizer to crash...
1374   if (!BugpointIsInterrupted && !DontReducePassList) {
1375     Expected<bool> Result = ReducePassList(*this).reduceList(PassesToRun);
1376     if (Error E = Result.takeError())
1377       return E;
1378   }
1379 
1380   outs() << "\n*** Found crashing pass"
1381          << (PassesToRun.size() == 1 ? ": " : "es: ")
1382          << getPassesString(PassesToRun) << '\n';
1383 
1384   EmitProgressBitcode(*Program, ID);
1385 
1386   auto Res = DebugACrash(*this, TestForOptimizerCrash);
1387   if (Res || DontReducePassList)
1388     return Res;
1389   // Try to reduce the pass list again. This covers additional cases
1390   // we failed to reduce earlier, because of more complex pass dependencies
1391   // triggering the crash.
1392   auto SecondRes = ReducePassList(*this).reduceList(PassesToRun);
1393   if (Error E = SecondRes.takeError())
1394     return E;
1395   outs() << "\n*** Found crashing pass"
1396          << (PassesToRun.size() == 1 ? ": " : "es: ")
1397          << getPassesString(PassesToRun) << '\n';
1398 
1399   EmitProgressBitcode(getProgram(), "reduced-simplified");
1400   return Res;
1401 }
1402 
1403 static bool TestForCodeGenCrash(const BugDriver &BD, Module *M) {
1404   if (Error E = BD.compileProgram(*M)) {
1405     if (VerboseErrors)
1406       errs() << toString(std::move(E)) << "\n";
1407     else {
1408       consumeError(std::move(E));
1409       errs() << "<crash>\n";
1410     }
1411     return true; // Tool is still crashing.
1412   }
1413   errs() << '\n';
1414   return false;
1415 }
1416 
1417 /// debugCodeGeneratorCrash - This method is called when the code generator
1418 /// crashes on an input.  It attempts to reduce the input as much as possible
1419 /// while still causing the code generator to crash.
1420 Error BugDriver::debugCodeGeneratorCrash() {
1421   errs() << "*** Debugging code generator crash!\n";
1422 
1423   return DebugACrash(*this, TestForCodeGenCrash);
1424 }
1425