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> ReplaceFuncsWithNull(
48     "replace-funcs-with-null",
49     cl::desc("When stubbing functions, replace all uses will null"),
50     cl::init(false));
51 cl::opt<bool> DontReducePassList("disable-pass-list-reduction",
52                                  cl::desc("Skip pass list reduction steps"),
53                                  cl::init(false));
54 
55 cl::opt<bool> NoNamedMDRM("disable-namedmd-remove",
56                           cl::desc("Do not remove global named metadata"),
57                           cl::init(false));
58 cl::opt<bool> NoStripDebugInfo("disable-strip-debuginfo",
59                                cl::desc("Do not strip debug info metadata"),
60                                cl::init(false));
61 cl::opt<bool> NoStripDebugTypeInfo("disable-strip-debug-types",
62                                cl::desc("Do not strip debug type info metadata"),
63                                cl::init(false));
64 cl::opt<bool> VerboseErrors("verbose-errors",
65                             cl::desc("Print the output of crashing program"),
66                             cl::init(false));
67 }
68 
69 namespace llvm {
70 class ReducePassList : public ListReducer<std::string> {
71   BugDriver &BD;
72 
73 public:
74   ReducePassList(BugDriver &bd) : BD(bd) {}
75 
76   // 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;
81 };
82 }
83 
84 Expected<ReducePassList::TestResult>
85 ReducePassList::doTest(std::vector<std::string> &Prefix,
86                        std::vector<std::string> &Suffix) {
87   std::string PrefixOutput;
88   std::unique_ptr<Module> OrigProgram;
89   if (!Prefix.empty()) {
90     outs() << "Checking to see if these passes crash: "
91            << getPassesString(Prefix) << ": ";
92     if (BD.runPasses(BD.getProgram(), Prefix, PrefixOutput))
93       return KeepPrefix;
94 
95     OrigProgram = std::move(BD.Program);
96 
97     BD.Program = parseInputFile(PrefixOutput, BD.getContext());
98     if (BD.Program == nullptr) {
99       errs() << BD.getToolName() << ": Error reading bitcode file '"
100              << PrefixOutput << "'!\n";
101       exit(1);
102     }
103     sys::fs::remove(PrefixOutput);
104   }
105 
106   outs() << "Checking to see if these passes crash: " << getPassesString(Suffix)
107          << ": ";
108 
109   if (BD.runPasses(BD.getProgram(), Suffix))
110     return KeepSuffix; // The suffix crashes alone...
111 
112   // Nothing failed, restore state...
113   if (OrigProgram)
114     BD.Program = std::move(OrigProgram);
115   return NoFailure;
116 }
117 
118 using BugTester = bool (*)(const BugDriver &, Module *);
119 
120 namespace {
121 /// 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.
124 class ReduceCrashingGlobalInitializers : public ListReducer<GlobalVariable *> {
125   BugDriver &BD;
126   BugTester TestFn;
127 
128 public:
129   ReduceCrashingGlobalInitializers(BugDriver &bd, BugTester testFn)
130       : BD(bd), TestFn(testFn) {}
131 
132   Expected<TestResult> doTest(std::vector<GlobalVariable *> &Prefix,
133                               std::vector<GlobalVariable *> &Kept) override {
134     if (!Kept.empty() && TestGlobalVariables(Kept))
135       return KeepSuffix;
136     if (!Prefix.empty() && TestGlobalVariables(Prefix))
137       return KeepPrefix;
138     return NoFailure;
139   }
140 
141   bool TestGlobalVariables(std::vector<GlobalVariable *> &GVs);
142 };
143 }
144 
145 bool ReduceCrashingGlobalInitializers::TestGlobalVariables(
146     std::vector<GlobalVariable *> &GVs) {
147   // Clone the program to try hacking it apart...
148   ValueToValueMapTy VMap;
149   std::unique_ptr<Module> M = CloneModule(BD.getProgram(), VMap);
150 
151   // Convert list to set for fast lookup...
152   std::set<GlobalVariable *> GVSet;
153 
154   for (unsigned i = 0, e = GVs.size(); i != e; ++i) {
155     GlobalVariable *CMGV = cast<GlobalVariable>(VMap[GVs[i]]);
156     assert(CMGV && "Global Variable not in module?!");
157     GVSet.insert(CMGV);
158   }
159 
160   outs() << "Checking for crash with only these global variables: ";
161   PrintGlobalVariableList(GVs);
162   outs() << ": ";
163 
164   // Loop over and delete any global variables which we aren't supposed to be
165   // playing with...
166   for (GlobalVariable &I : M->globals())
167     if (I.hasInitializer() && !GVSet.count(&I)) {
168       DeleteGlobalInitializer(&I);
169       I.setLinkage(GlobalValue::ExternalLinkage);
170       I.setComdat(nullptr);
171     }
172 
173   // Try running the hacked up program...
174   if (TestFn(BD, M.get())) {
175     BD.setNewProgram(std::move(M)); // It crashed, keep the trimmed version...
176 
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 
183   return false;
184 }
185 
186 namespace {
187 /// 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 ///
191 class ReduceCrashingFunctions : public ListReducer<Function *> {
192   BugDriver &BD;
193   BugTester TestFn;
194 
195 public:
196   ReduceCrashingFunctions(BugDriver &bd, BugTester testFn)
197       : BD(bd), TestFn(testFn) {}
198 
199   Expected<TestResult> doTest(std::vector<Function *> &Prefix,
200                               std::vector<Function *> &Kept) override {
201     if (!Kept.empty() && TestFuncs(Kept))
202       return KeepSuffix;
203     if (!Prefix.empty() && TestFuncs(Prefix))
204       return KeepPrefix;
205     return NoFailure;
206   }
207 
208   bool TestFuncs(std::vector<Function *> &Prefix);
209 };
210 }
211 
212 static void RemoveFunctionReferences(Module *M, const char *Name) {
213   auto *UsedVar = M->getGlobalVariable(Name, true);
214   if (!UsedVar || !UsedVar->hasInitializer())
215     return;
216   if (isa<ConstantAggregateZero>(UsedVar->getInitializer())) {
217     assert(UsedVar->use_empty());
218     UsedVar->eraseFromParent();
219     return;
220   }
221   auto *OldUsedVal = cast<ConstantArray>(UsedVar->getInitializer());
222   std::vector<Constant *> Used;
223   for (Value *V : OldUsedVal->operand_values()) {
224     Constant *Op = cast<Constant>(V->stripPointerCasts());
225     if (!Op->isNullValue()) {
226       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 
236 bool ReduceCrashingFunctions::TestFuncs(std::vector<Function *> &Funcs) {
237   // If main isn't present, claim there is no problem.
238   if (KeepMain && !is_contained(Funcs, BD.getProgram().getFunction("main")))
239     return false;
240 
241   // Clone the program to try hacking it apart...
242   ValueToValueMapTy VMap;
243   std::unique_ptr<Module> M = CloneModule(BD.getProgram(), VMap);
244 
245   // Convert list to set for fast lookup...
246   std::set<Function *> Functions;
247   for (unsigned i = 0, e = Funcs.size(); i != e; ++i) {
248     Function *CMF = cast<Function>(VMap[Funcs[i]]);
249     assert(CMF && "Function not in module?!");
250     assert(CMF->getFunctionType() == Funcs[i]->getFunctionType() && "wrong ty");
251     assert(CMF->getName() == Funcs[i]->getName() && "wrong name");
252     Functions.insert(CMF);
253   }
254 
255   outs() << "Checking for crash with only these functions: ";
256   PrintFunctionList(Funcs);
257   outs() << ": ";
258   if (!ReplaceFuncsWithNull) {
259     // Loop over and delete any functions which we aren't supposed to be playing
260     // with...
261     for (Function &I : *M)
262       if (!I.isDeclaration() && !Functions.count(&I))
263         DeleteFunctionBody(&I);
264   } else {
265     std::vector<GlobalValue *> ToRemove;
266     // First, remove aliases to functions we're about to purge.
267     for (GlobalAlias &Alias : M->aliases()) {
268       GlobalObject *Root = Alias.getBaseObject();
269       Function *F = dyn_cast_or_null<Function>(Root);
270       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       }
281 
282       PointerType *Ty = cast<PointerType>(Alias.getType());
283       Constant *Replacement = ConstantPointerNull::get(Ty);
284       Alias.replaceAllUsesWith(Replacement);
285       ToRemove.push_back(&Alias);
286     }
287 
288     for (Function &I : *M) {
289       if (!I.isDeclaration() && !Functions.count(&I)) {
290         PointerType *Ty = cast<PointerType>(I.getType());
291         Constant *Replacement = ConstantPointerNull::get(Ty);
292         I.replaceAllUsesWith(Replacement);
293         ToRemove.push_back(&I);
294       }
295     }
296 
297     for (auto *F : ToRemove) {
298       F->eraseFromParent();
299     }
300 
301     // Finally, remove any null members from any global intrinsic.
302     RemoveFunctionReferences(M.get(), "llvm.used");
303     RemoveFunctionReferences(M.get(), "llvm.compiler.used");
304   }
305   // Try running the hacked up program...
306   if (TestFn(BD, M.get())) {
307     BD.setNewProgram(std::move(M)); // It crashed, keep the trimmed version...
308 
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   }
314   return false;
315 }
316 
317 namespace {
318 /// 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 ///
322 class ReduceCrashingFunctionAttributes : public ListReducer<Attribute> {
323   BugDriver &BD;
324   std::string FnName;
325   BugTester TestFn;
326 
327 public:
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 
345 bool 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 
377 namespace {
378 /// 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".
382 void 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.
408   for (auto *BB : Unreachable) {
409     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 }
417 /// 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 ///
422 class ReduceCrashingBlocks : public ListReducer<const BasicBlock *> {
423   BugDriver &BD;
424   BugTester TestFn;
425 
426 public:
427   ReduceCrashingBlocks(BugDriver &BD, BugTester testFn)
428       : BD(BD), TestFn(testFn) {}
429 
430   Expected<TestResult> doTest(std::vector<const BasicBlock *> &Prefix,
431                               std::vector<const BasicBlock *> &Kept) override {
432     if (!Kept.empty() && TestBlocks(Kept))
433       return KeepSuffix;
434     if (!Prefix.empty() && TestBlocks(Prefix))
435       return KeepPrefix;
436     return NoFailure;
437   }
438 
439   bool TestBlocks(std::vector<const BasicBlock *> &Prefix);
440 };
441 }
442 
443 bool ReduceCrashingBlocks::TestBlocks(std::vector<const BasicBlock *> &BBs) {
444   // Clone the program to try hacking it apart...
445   ValueToValueMapTy VMap;
446   std::unique_ptr<Module> M = CloneModule(BD.getProgram(), VMap);
447 
448   // Convert list to set for fast lookup...
449   SmallPtrSet<BasicBlock *, 8> Blocks;
450   for (unsigned i = 0, e = BBs.size(); i != e; ++i)
451     Blocks.insert(cast<BasicBlock>(VMap[BBs[i]]));
452 
453   outs() << "Checking for crash with only these blocks:";
454   unsigned NumPrint = Blocks.size();
455   if (NumPrint > 10)
456     NumPrint = 10;
457   for (unsigned i = 0, e = NumPrint; i != e; ++i)
458     outs() << " " << BBs[i]->getName();
459   if (NumPrint < Blocks.size())
460     outs() << "... <" << Blocks.size() << " total>";
461   outs() << ": ";
462 
463   // Loop over and delete any hack up any blocks that are not listed...
464   for (Function &F : M->functions()) {
465     for (BasicBlock &BB : F) {
466       if (!Blocks.count(&BB) && BB.getTerminator()->getNumSuccessors()) {
467         // Loop over all of the successors of this block, deleting any PHI nodes
468         // that might include it.
469         for (BasicBlock *Succ : successors(&BB))
470           Succ->removePredecessor(&BB);
471 
472         Instruction *BBTerm = BB.getTerminator();
473         if (BBTerm->isEHPad() || BBTerm->getType()->isTokenTy())
474           continue;
475         if (!BBTerm->getType()->isVoidTy())
476           BBTerm->replaceAllUsesWith(Constant::getNullValue(BBTerm->getType()));
477 
478         // Replace the old terminator instruction.
479         BB.getInstList().pop_back();
480         new UnreachableInst(BB.getContext(), &BB);
481       }
482     }
483   }
484 
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
489   // have to take. FIXME: Can we just name the blocks?
490   std::vector<std::pair<std::string, std::string>> BlockInfo;
491 
492   for (BasicBlock *BB : Blocks)
493     BlockInfo.emplace_back(BB->getParent()->getName(), BB->getName());
494 
495   SmallVector<BasicBlock *, 16> ToProcess;
496   for (auto &F : *M) {
497     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
504   std::vector<std::string> Passes;
505   Passes.push_back("verify");
506   std::unique_ptr<Module> New = BD.runPassesOn(M.get(), Passes);
507   if (!New) {
508     errs() << "verify failed!\n";
509     exit(1);
510   }
511   M = std::move(New);
512 
513   // Try running on the hacked up program...
514   if (TestFn(BD, M.get())) {
515     BD.setNewProgram(std::move(M)); // It crashed, keep the trimmed version...
516 
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();
520     const ValueSymbolTable &GST = BD.getProgram().getValueSymbolTable();
521     for (const auto &BI : BlockInfo) {
522       Function *F = cast<Function>(GST.lookup(BI.first));
523       Value *V = F->getValueSymbolTable()->lookup(BI.second);
524       if (V && V->getType() == Type::getLabelTy(V->getContext()))
525         BBs.push_back(cast<BasicBlock>(V));
526     }
527     return true;
528   }
529   // It didn't crash, try something else.
530   return false;
531 }
532 
533 namespace {
534 /// 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 ///
539 class ReduceCrashingConditionals : public ListReducer<const BasicBlock *> {
540   BugDriver &BD;
541   BugTester TestFn;
542   bool Direction;
543 
544 public:
545   ReduceCrashingConditionals(BugDriver &bd, BugTester testFn, bool Direction)
546       : BD(bd), TestFn(testFn), Direction(Direction) {}
547 
548   Expected<TestResult> doTest(std::vector<const BasicBlock *> &Prefix,
549                               std::vector<const BasicBlock *> &Kept) override {
550     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 
561 bool ReduceCrashingConditionals::TestBlocks(
562     std::vector<const BasicBlock *> &BBs) {
563   // Clone the program to try hacking it apart...
564   ValueToValueMapTy VMap;
565   std::unique_ptr<Module> M = CloneModule(BD.getProgram(), VMap);
566 
567   // Convert list to set for fast lookup...
568   SmallPtrSet<const BasicBlock *, 8> Blocks;
569   for (const auto *BB : BBs)
570     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...
584   for (auto &F : *M)
585     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;
603   for (auto &F : *M) {
604     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");
613   std::unique_ptr<Module> New = BD.runPassesOn(M.get(), Passes);
614   if (!New) {
615     errs() << "verify failed!\n";
616     exit(1);
617   }
618   M = std::move(New);
619 
620   // Try running on the hacked up program...
621   if (TestFn(BD, M.get())) {
622     BD.setNewProgram(std::move(M)); // It crashed, keep the trimmed version...
623 
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();
627     const ValueSymbolTable &GST = BD.getProgram().getValueSymbolTable();
628     for (auto &BI : BlockInfo) {
629       auto *F = cast<Function>(GST.lookup(BI.first));
630       Value *V = F->getValueSymbolTable()->lookup(BI.second);
631       if (V && V->getType() == Type::getLabelTy(V->getContext()))
632         BBs.push_back(cast<BasicBlock>(V));
633     }
634     return true;
635   }
636   // It didn't crash, try something else.
637   return false;
638 }
639 
640 namespace {
641 /// SimplifyCFG reducer - This works by calling SimplifyCFG on each basic block
642 /// in the program.
643 
644 class ReduceSimplifyCFG : public ListReducer<const BasicBlock *> {
645   BugDriver &BD;
646   BugTester TestFn;
647   TargetTransformInfo TTI;
648 
649 public:
650   ReduceSimplifyCFG(BugDriver &bd, BugTester testFn)
651       : BD(bd), TestFn(testFn), TTI(bd.getProgram().getDataLayout()) {}
652 
653   Expected<TestResult> doTest(std::vector<const BasicBlock *> &Prefix,
654                               std::vector<const BasicBlock *> &Kept) override {
655     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 
666 bool ReduceSimplifyCFG::TestBlocks(std::vector<const BasicBlock *> &BBs) {
667   // Clone the program to try hacking it apart...
668   ValueToValueMapTy VMap;
669   std::unique_ptr<Module> M = CloneModule(BD.getProgram(), VMap);
670 
671   // Convert list to set for fast lookup...
672   SmallPtrSet<const BasicBlock *, 8> Blocks;
673   for (const auto *BB : BBs)
674     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 
686   // The following may destroy some blocks, so we save them first
687   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 
692   // Loop over and delete any hack up any blocks that are not listed...
693   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       }
700       simplifyCFG(&*BBIt++, TTI);
701     }
702   // Verify we didn't break anything
703   std::vector<std::string> Passes;
704   Passes.push_back("verify");
705   std::unique_ptr<Module> New = BD.runPassesOn(M.get(), Passes);
706   if (!New) {
707     errs() << "verify failed!\n";
708     exit(1);
709   }
710   M = std::move(New);
711 
712   // Try running on the hacked up program...
713   if (TestFn(BD, M.get())) {
714     BD.setNewProgram(std::move(M)); // It crashed, keep the trimmed version...
715 
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();
719     const ValueSymbolTable &GST = BD.getProgram().getValueSymbolTable();
720     for (auto &BI : BlockInfo) {
721       auto *F = cast<Function>(GST.lookup(BI.first));
722       Value *V = F->getValueSymbolTable()->lookup(BI.second);
723       if (V && V->getType() == Type::getLabelTy(V->getContext()))
724         BBs.push_back(cast<BasicBlock>(V));
725     }
726     return true;
727   }
728   // It didn't crash, try something else.
729   return false;
730 }
731 
732 namespace {
733 /// ReduceCrashingInstructions reducer - This works by removing the specified
734 /// non-terminator instructions and replacing them with undef.
735 ///
736 class ReduceCrashingInstructions : public ListReducer<const Instruction *> {
737   BugDriver &BD;
738   BugTester TestFn;
739 
740 public:
741   ReduceCrashingInstructions(BugDriver &bd, BugTester testFn)
742       : BD(bd), TestFn(testFn) {}
743 
744   Expected<TestResult> doTest(std::vector<const Instruction *> &Prefix,
745                               std::vector<const Instruction *> &Kept) override {
746     if (!Kept.empty() && TestInsts(Kept))
747       return KeepSuffix;
748     if (!Prefix.empty() && TestInsts(Prefix))
749       return KeepPrefix;
750     return NoFailure;
751   }
752 
753   bool TestInsts(std::vector<const Instruction *> &Prefix);
754 };
755 }
756 
757 bool ReduceCrashingInstructions::TestInsts(
758     std::vector<const Instruction *> &Insts) {
759   // Clone the program to try hacking it apart...
760   ValueToValueMapTy VMap;
761   std::unique_ptr<Module> M = CloneModule(BD.getProgram(), VMap);
762 
763   // Convert list to set for fast lookup...
764   SmallPtrSet<Instruction *, 32> Instructions;
765   for (unsigned i = 0, e = Insts.size(); i != e; ++i) {
766     assert(!Insts[i]->isTerminator());
767     Instructions.insert(cast<Instruction>(VMap[Insts[i]]));
768   }
769 
770   outs() << "Checking for crash with only " << Instructions.size();
771   if (Instructions.size() == 1)
772     outs() << " instruction: ";
773   else
774     outs() << " instructions: ";
775 
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;) {
779         Instruction *Inst = &*I++;
780         if (!Instructions.count(Inst) && !Inst->isTerminator() &&
781             !Inst->isEHPad() && !Inst->getType()->isTokenTy() &&
782             !Inst->isSwiftError()) {
783           if (!Inst->getType()->isVoidTy())
784             Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
785           Inst->eraseFromParent();
786         }
787       }
788 
789   // Verify that this is still valid.
790   legacy::PassManager Passes;
791   Passes.add(createVerifierPass(/*FatalErrors=*/false));
792   Passes.run(*M);
793 
794   // Try running on the hacked up program...
795   if (TestFn(BD, M.get())) {
796     BD.setNewProgram(std::move(M)); // It crashed, keep the trimmed version...
797 
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();
801     for (Instruction *Inst : Instructions)
802       Insts.push_back(Inst);
803     return true;
804   }
805   // It didn't crash, try something else.
806   return false;
807 }
808 
809 namespace {
810 /// ReduceCrashingMetadata reducer - This works by removing all metadata from
811 /// the specified instructions.
812 ///
813 class ReduceCrashingMetadata : public ListReducer<Instruction *> {
814   BugDriver &BD;
815   BugTester TestFn;
816 
817 public:
818   ReduceCrashingMetadata(BugDriver &bd, BugTester testFn)
819       : BD(bd), TestFn(testFn) {}
820 
821   Expected<TestResult> doTest(std::vector<Instruction *> &Prefix,
822                               std::vector<Instruction *> &Kept) override {
823     if (!Kept.empty() && TestInsts(Kept))
824       return KeepSuffix;
825     if (!Prefix.empty() && TestInsts(Prefix))
826       return KeepPrefix;
827     return NoFailure;
828   }
829 
830   bool TestInsts(std::vector<Instruction *> &Prefix);
831 };
832 } // namespace
833 
834 bool ReduceCrashingMetadata::TestInsts(std::vector<Instruction *> &Insts) {
835   // Clone the program to try hacking it apart...
836   ValueToValueMapTy VMap;
837   std::unique_ptr<Module> M = CloneModule(BD.getProgram(), VMap);
838 
839   // Convert list to set for fast lookup...
840   SmallPtrSet<Instruction *, 32> Instructions;
841   for (Instruction *I : Insts)
842     Instructions.insert(cast<Instruction>(VMap[I]));
843 
844   outs() << "Checking for crash with metadata retained from "
845          << Instructions.size();
846   if (Instructions.size() == 1)
847     outs() << " instruction: ";
848   else
849     outs() << " instructions: ";
850 
851   // Try to drop instruction metadata from all instructions, except the ones
852   // selected in Instructions.
853   for (Function &F : *M)
854     for (Instruction &Inst : instructions(F)) {
855       if (Instructions.find(&Inst) == Instructions.end()) {
856         Inst.dropUnknownNonDebugMetadata();
857         Inst.setDebugLoc({});
858       }
859     }
860 
861   // Verify that this is still valid.
862   legacy::PassManager Passes;
863   Passes.add(createVerifierPass(/*FatalErrors=*/false));
864   Passes.run(*M);
865 
866   // Try running on the hacked up program...
867   if (TestFn(BD, M.get())) {
868     BD.setNewProgram(std::move(M)); // It crashed, keep the trimmed version...
869 
870     // Make sure to use instruction pointers that point into the now-current
871     // module, and that they don't include any deleted blocks.
872     Insts.clear();
873     for (Instruction *I : Instructions)
874       Insts.push_back(I);
875     return true;
876   }
877   // It didn't crash, try something else.
878   return false;
879 }
880 
881 namespace {
882 // Reduce the list of Named Metadata nodes. We keep this as a list of
883 // names to avoid having to convert back and forth every time.
884 class ReduceCrashingNamedMD : public ListReducer<std::string> {
885   BugDriver &BD;
886   BugTester TestFn;
887 
888 public:
889   ReduceCrashingNamedMD(BugDriver &bd, BugTester testFn)
890       : BD(bd), TestFn(testFn) {}
891 
892   Expected<TestResult> doTest(std::vector<std::string> &Prefix,
893                               std::vector<std::string> &Kept) override {
894     if (!Kept.empty() && TestNamedMDs(Kept))
895       return KeepSuffix;
896     if (!Prefix.empty() && TestNamedMDs(Prefix))
897       return KeepPrefix;
898     return NoFailure;
899   }
900 
901   bool TestNamedMDs(std::vector<std::string> &NamedMDs);
902 };
903 }
904 
905 bool ReduceCrashingNamedMD::TestNamedMDs(std::vector<std::string> &NamedMDs) {
906 
907   ValueToValueMapTy VMap;
908   std::unique_ptr<Module> M = CloneModule(BD.getProgram(), VMap);
909 
910   outs() << "Checking for crash with only these named metadata nodes:";
911   unsigned NumPrint = std::min<size_t>(NamedMDs.size(), 10);
912   for (unsigned i = 0, e = NumPrint; i != e; ++i)
913     outs() << " " << NamedMDs[i];
914   if (NumPrint < NamedMDs.size())
915     outs() << "... <" << NamedMDs.size() << " total>";
916   outs() << ": ";
917 
918   // Make a StringMap for faster lookup
919   StringSet<> Names;
920   for (const std::string &Name : NamedMDs)
921     Names.insert(Name);
922 
923   // First collect all the metadata to delete in a vector, then
924   // delete them all at once to avoid invalidating the iterator
925   std::vector<NamedMDNode *> ToDelete;
926   ToDelete.reserve(M->named_metadata_size() - Names.size());
927   for (auto &NamedMD : M->named_metadata())
928     // Always keep a nonempty llvm.dbg.cu because the Verifier would complain.
929     if (!Names.count(NamedMD.getName()) &&
930         (!(NamedMD.getName() == "llvm.dbg.cu" && NamedMD.getNumOperands() > 0)))
931       ToDelete.push_back(&NamedMD);
932 
933   for (auto *NamedMD : ToDelete)
934     NamedMD->eraseFromParent();
935 
936   // Verify that this is still valid.
937   legacy::PassManager Passes;
938   Passes.add(createVerifierPass(/*FatalErrors=*/false));
939   Passes.run(*M);
940 
941   // Try running on the hacked up program...
942   if (TestFn(BD, M.get())) {
943     BD.setNewProgram(std::move(M)); // It crashed, keep the trimmed version...
944     return true;
945   }
946   return false;
947 }
948 
949 namespace {
950 // Reduce the list of operands to named metadata nodes
951 class ReduceCrashingNamedMDOps : public ListReducer<const MDNode *> {
952   BugDriver &BD;
953   BugTester TestFn;
954 
955 public:
956   ReduceCrashingNamedMDOps(BugDriver &bd, BugTester testFn)
957       : BD(bd), TestFn(testFn) {}
958 
959   Expected<TestResult> doTest(std::vector<const MDNode *> &Prefix,
960                               std::vector<const MDNode *> &Kept) override {
961     if (!Kept.empty() && TestNamedMDOps(Kept))
962       return KeepSuffix;
963     if (!Prefix.empty() && TestNamedMDOps(Prefix))
964       return KeepPrefix;
965     return NoFailure;
966   }
967 
968   bool TestNamedMDOps(std::vector<const MDNode *> &NamedMDOps);
969 };
970 }
971 
972 bool ReduceCrashingNamedMDOps::TestNamedMDOps(
973     std::vector<const MDNode *> &NamedMDOps) {
974   // Convert list to set for fast lookup...
975   SmallPtrSet<const MDNode *, 32> OldMDNodeOps;
976   for (unsigned i = 0, e = NamedMDOps.size(); i != e; ++i) {
977     OldMDNodeOps.insert(NamedMDOps[i]);
978   }
979 
980   outs() << "Checking for crash with only " << OldMDNodeOps.size();
981   if (OldMDNodeOps.size() == 1)
982     outs() << " named metadata operand: ";
983   else
984     outs() << " named metadata operands: ";
985 
986   ValueToValueMapTy VMap;
987   std::unique_ptr<Module> M = CloneModule(BD.getProgram(), VMap);
988 
989   // This is a little wasteful. In the future it might be good if we could have
990   // these dropped during cloning.
991   for (auto &NamedMD : BD.getProgram().named_metadata()) {
992     // Drop the old one and create a new one
993     M->eraseNamedMetadata(M->getNamedMetadata(NamedMD.getName()));
994     NamedMDNode *NewNamedMDNode =
995         M->getOrInsertNamedMetadata(NamedMD.getName());
996     for (MDNode *op : NamedMD.operands())
997       if (OldMDNodeOps.count(op))
998         NewNamedMDNode->addOperand(cast<MDNode>(MapMetadata(op, VMap)));
999   }
1000 
1001   // Verify that this is still valid.
1002   legacy::PassManager Passes;
1003   Passes.add(createVerifierPass(/*FatalErrors=*/false));
1004   Passes.run(*M);
1005 
1006   // Try running on the hacked up program...
1007   if (TestFn(BD, M.get())) {
1008     // Make sure to use instruction pointers that point into the now-current
1009     // module, and that they don't include any deleted blocks.
1010     NamedMDOps.clear();
1011     for (const MDNode *Node : OldMDNodeOps)
1012       NamedMDOps.push_back(cast<MDNode>(*VMap.getMappedMD(Node)));
1013 
1014     BD.setNewProgram(std::move(M)); // It crashed, keep the trimmed version...
1015     return true;
1016   }
1017   // It didn't crash, try something else.
1018   return false;
1019 }
1020 
1021 /// Attempt to eliminate as many global initializers as possible.
1022 static Error ReduceGlobalInitializers(BugDriver &BD, BugTester TestFn) {
1023   Module &OrigM = BD.getProgram();
1024   if (OrigM.global_empty())
1025     return Error::success();
1026 
1027   // Now try to reduce the number of global variable initializers in the
1028   // module to something small.
1029   std::unique_ptr<Module> M = CloneModule(OrigM);
1030   bool DeletedInit = false;
1031 
1032   for (GlobalVariable &GV : M->globals()) {
1033     if (GV.hasInitializer()) {
1034       DeleteGlobalInitializer(&GV);
1035       GV.setLinkage(GlobalValue::ExternalLinkage);
1036       GV.setComdat(nullptr);
1037       DeletedInit = true;
1038     }
1039   }
1040 
1041   if (!DeletedInit)
1042     return Error::success();
1043 
1044   // See if the program still causes a crash...
1045   outs() << "\nChecking to see if we can delete global inits: ";
1046 
1047   if (TestFn(BD, M.get())) { // Still crashes?
1048     BD.setNewProgram(std::move(M));
1049     outs() << "\n*** Able to remove all global initializers!\n";
1050     return Error::success();
1051   }
1052 
1053   // No longer crashes.
1054   outs() << "  - Removing all global inits hides problem!\n";
1055 
1056   std::vector<GlobalVariable *> GVs;
1057   for (GlobalVariable &GV : OrigM.globals())
1058     if (GV.hasInitializer())
1059       GVs.push_back(&GV);
1060 
1061   if (GVs.size() > 1 && !BugpointIsInterrupted) {
1062     outs() << "\n*** Attempting to reduce the number of global initializers "
1063            << "in the testcase\n";
1064 
1065     unsigned OldSize = GVs.size();
1066     Expected<bool> Result =
1067         ReduceCrashingGlobalInitializers(BD, TestFn).reduceList(GVs);
1068     if (Error E = Result.takeError())
1069       return E;
1070 
1071     if (GVs.size() < OldSize)
1072       BD.EmitProgressBitcode(BD.getProgram(), "reduced-global-variables");
1073   }
1074   return Error::success();
1075 }
1076 
1077 static Error ReduceInsts(BugDriver &BD, BugTester TestFn) {
1078   // Attempt to delete instructions using bisection. This should help out nasty
1079   // cases with large basic blocks where the problem is at one end.
1080   if (!BugpointIsInterrupted) {
1081     std::vector<const Instruction *> Insts;
1082     for (const Function &F : BD.getProgram())
1083       for (const BasicBlock &BB : F)
1084         for (const Instruction &I : BB)
1085           if (!I.isTerminator())
1086             Insts.push_back(&I);
1087 
1088     Expected<bool> Result =
1089         ReduceCrashingInstructions(BD, TestFn).reduceList(Insts);
1090     if (Error E = Result.takeError())
1091       return E;
1092   }
1093 
1094   unsigned Simplification = 2;
1095   do {
1096     if (BugpointIsInterrupted)
1097       // TODO: Should we distinguish this with an "interrupted error"?
1098       return Error::success();
1099     --Simplification;
1100     outs() << "\n*** Attempting to reduce testcase by deleting instruc"
1101            << "tions: Simplification Level #" << Simplification << '\n';
1102 
1103     // Now that we have deleted the functions that are unnecessary for the
1104     // program, try to remove instructions that are not necessary to cause the
1105     // crash.  To do this, we loop through all of the instructions in the
1106     // remaining functions, deleting them (replacing any values produced with
1107     // nulls), and then running ADCE and SimplifyCFG.  If the transformed input
1108     // still triggers failure, keep deleting until we cannot trigger failure
1109     // anymore.
1110     //
1111     unsigned InstructionsToSkipBeforeDeleting = 0;
1112   TryAgain:
1113 
1114     // Loop over all of the (non-terminator) instructions remaining in the
1115     // function, attempting to delete them.
1116     unsigned CurInstructionNum = 0;
1117     for (Module::const_iterator FI = BD.getProgram().begin(),
1118                                 E = BD.getProgram().end();
1119          FI != E; ++FI)
1120       if (!FI->isDeclaration())
1121         for (Function::const_iterator BI = FI->begin(), E = FI->end(); BI != E;
1122              ++BI)
1123           for (BasicBlock::const_iterator I = BI->begin(), E = --BI->end();
1124                I != E; ++I, ++CurInstructionNum) {
1125             if (InstructionsToSkipBeforeDeleting) {
1126               --InstructionsToSkipBeforeDeleting;
1127             } else {
1128               if (BugpointIsInterrupted)
1129                 // TODO: Should this be some kind of interrupted error?
1130                 return Error::success();
1131 
1132               if (I->isEHPad() || I->getType()->isTokenTy() ||
1133                   I->isSwiftError())
1134                 continue;
1135 
1136               outs() << "Checking instruction: " << *I;
1137               std::unique_ptr<Module> M =
1138                   BD.deleteInstructionFromProgram(&*I, Simplification);
1139 
1140               // Find out if the pass still crashes on this pass...
1141               if (TestFn(BD, M.get())) {
1142                 // Yup, it does, we delete the old module, and continue trying
1143                 // to reduce the testcase...
1144                 BD.setNewProgram(std::move(M));
1145                 InstructionsToSkipBeforeDeleting = CurInstructionNum;
1146                 goto TryAgain; // I wish I had a multi-level break here!
1147               }
1148             }
1149           }
1150 
1151     if (InstructionsToSkipBeforeDeleting) {
1152       InstructionsToSkipBeforeDeleting = 0;
1153       goto TryAgain;
1154     }
1155 
1156   } while (Simplification);
1157 
1158   // Attempt to drop metadata from instructions that does not contribute to the
1159   // crash.
1160   if (!BugpointIsInterrupted) {
1161     std::vector<Instruction *> Insts;
1162     for (Function &F : BD.getProgram())
1163       for (Instruction &I : instructions(F))
1164         Insts.push_back(&I);
1165 
1166     Expected<bool> Result =
1167         ReduceCrashingMetadata(BD, TestFn).reduceList(Insts);
1168     if (Error E = Result.takeError())
1169       return E;
1170   }
1171 
1172   BD.EmitProgressBitcode(BD.getProgram(), "reduced-instructions");
1173   return Error::success();
1174 }
1175 
1176 /// DebugACrash - Given a predicate that determines whether a component crashes
1177 /// on a program, try to destructively reduce the program while still keeping
1178 /// the predicate true.
1179 static Error DebugACrash(BugDriver &BD, BugTester TestFn) {
1180   // See if we can get away with nuking some of the global variable initializers
1181   // in the program...
1182   if (!NoGlobalRM)
1183     if (Error E = ReduceGlobalInitializers(BD, TestFn))
1184       return E;
1185 
1186   // Now try to reduce the number of functions in the module to something small.
1187   std::vector<Function *> Functions;
1188   for (Function &F : BD.getProgram())
1189     if (!F.isDeclaration())
1190       Functions.push_back(&F);
1191 
1192   if (Functions.size() > 1 && !BugpointIsInterrupted) {
1193     outs() << "\n*** Attempting to reduce the number of functions "
1194               "in the testcase\n";
1195 
1196     unsigned OldSize = Functions.size();
1197     Expected<bool> Result =
1198         ReduceCrashingFunctions(BD, TestFn).reduceList(Functions);
1199     if (Error E = Result.takeError())
1200       return E;
1201 
1202     if (Functions.size() < OldSize)
1203       BD.EmitProgressBitcode(BD.getProgram(), "reduced-function");
1204   }
1205 
1206   // For each remaining function, try to reduce that function's attributes.
1207   std::vector<std::string> FunctionNames;
1208   for (Function &F : BD.getProgram())
1209     FunctionNames.push_back(F.getName());
1210 
1211   if (!FunctionNames.empty() && !BugpointIsInterrupted) {
1212     outs() << "\n*** Attempting to reduce the number of function attributes in "
1213               "the testcase\n";
1214 
1215     unsigned OldSize = 0;
1216     unsigned NewSize = 0;
1217     for (std::string &Name : FunctionNames) {
1218       Function *Fn = BD.getProgram().getFunction(Name);
1219       assert(Fn && "Could not find funcion?");
1220 
1221       std::vector<Attribute> Attrs;
1222       for (Attribute A : Fn->getAttributes().getFnAttributes())
1223         Attrs.push_back(A);
1224 
1225       OldSize += Attrs.size();
1226       Expected<bool> Result =
1227           ReduceCrashingFunctionAttributes(BD, Name, TestFn).reduceList(Attrs);
1228       if (Error E = Result.takeError())
1229         return E;
1230 
1231       NewSize += Attrs.size();
1232     }
1233 
1234     if (OldSize < NewSize)
1235       BD.EmitProgressBitcode(BD.getProgram(), "reduced-function-attributes");
1236   }
1237 
1238   // Attempt to change conditional branches into unconditional branches to
1239   // eliminate blocks.
1240   if (!DisableSimplifyCFG && !BugpointIsInterrupted) {
1241     std::vector<const BasicBlock *> Blocks;
1242     for (Function &F : BD.getProgram())
1243       for (BasicBlock &BB : F)
1244         Blocks.push_back(&BB);
1245     unsigned OldSize = Blocks.size();
1246     Expected<bool> Result =
1247         ReduceCrashingConditionals(BD, TestFn, true).reduceList(Blocks);
1248     if (Error E = Result.takeError())
1249       return E;
1250     Result = ReduceCrashingConditionals(BD, TestFn, false).reduceList(Blocks);
1251     if (Error E = Result.takeError())
1252       return E;
1253     if (Blocks.size() < OldSize)
1254       BD.EmitProgressBitcode(BD.getProgram(), "reduced-conditionals");
1255   }
1256 
1257   // Attempt to delete entire basic blocks at a time to speed up
1258   // convergence... this actually works by setting the terminator of the blocks
1259   // to a return instruction then running simplifycfg, which can potentially
1260   // shrinks the code dramatically quickly
1261   //
1262   if (!DisableSimplifyCFG && !BugpointIsInterrupted) {
1263     std::vector<const BasicBlock *> Blocks;
1264     for (Function &F : BD.getProgram())
1265       for (BasicBlock &BB : F)
1266         Blocks.push_back(&BB);
1267     unsigned OldSize = Blocks.size();
1268     Expected<bool> Result = ReduceCrashingBlocks(BD, TestFn).reduceList(Blocks);
1269     if (Error E = Result.takeError())
1270       return E;
1271     if (Blocks.size() < OldSize)
1272       BD.EmitProgressBitcode(BD.getProgram(), "reduced-blocks");
1273   }
1274 
1275   if (!DisableSimplifyCFG && !BugpointIsInterrupted) {
1276     std::vector<const BasicBlock *> Blocks;
1277     for (Function &F : BD.getProgram())
1278       for (BasicBlock &BB : F)
1279         Blocks.push_back(&BB);
1280     unsigned OldSize = Blocks.size();
1281     Expected<bool> Result = ReduceSimplifyCFG(BD, TestFn).reduceList(Blocks);
1282     if (Error E = Result.takeError())
1283       return E;
1284     if (Blocks.size() < OldSize)
1285       BD.EmitProgressBitcode(BD.getProgram(), "reduced-simplifycfg");
1286   }
1287 
1288   // Attempt to delete instructions using bisection. This should help out nasty
1289   // cases with large basic blocks where the problem is at one end.
1290   if (!BugpointIsInterrupted)
1291     if (Error E = ReduceInsts(BD, TestFn))
1292       return E;
1293 
1294   // Attempt to strip debug info metadata.
1295   auto stripMetadata = [&](std::function<bool(Module &)> strip) {
1296     std::unique_ptr<Module> M = CloneModule(BD.getProgram());
1297     strip(*M);
1298     if (TestFn(BD, M.get()))
1299       BD.setNewProgram(std::move(M));
1300   };
1301   if (!NoStripDebugInfo && !BugpointIsInterrupted) {
1302     outs() << "\n*** Attempting to strip the debug info: ";
1303     stripMetadata(StripDebugInfo);
1304   }
1305   if (!NoStripDebugTypeInfo && !BugpointIsInterrupted) {
1306     outs() << "\n*** Attempting to strip the debug type info: ";
1307     stripMetadata(stripNonLineTableDebugInfo);
1308   }
1309 
1310   if (!NoNamedMDRM) {
1311     if (!BugpointIsInterrupted) {
1312       // Try to reduce the amount of global metadata (particularly debug info),
1313       // by dropping global named metadata that anchors them
1314       outs() << "\n*** Attempting to remove named metadata: ";
1315       std::vector<std::string> NamedMDNames;
1316       for (auto &NamedMD : BD.getProgram().named_metadata())
1317         NamedMDNames.push_back(NamedMD.getName().str());
1318       Expected<bool> Result =
1319           ReduceCrashingNamedMD(BD, TestFn).reduceList(NamedMDNames);
1320       if (Error E = Result.takeError())
1321         return E;
1322     }
1323 
1324     if (!BugpointIsInterrupted) {
1325       // Now that we quickly dropped all the named metadata that doesn't
1326       // contribute to the crash, bisect the operands of the remaining ones
1327       std::vector<const MDNode *> NamedMDOps;
1328       for (auto &NamedMD : BD.getProgram().named_metadata())
1329         for (auto op : NamedMD.operands())
1330           NamedMDOps.push_back(op);
1331       Expected<bool> Result =
1332           ReduceCrashingNamedMDOps(BD, TestFn).reduceList(NamedMDOps);
1333       if (Error E = Result.takeError())
1334         return E;
1335     }
1336     BD.EmitProgressBitcode(BD.getProgram(), "reduced-named-md");
1337   }
1338 
1339   // Try to clean up the testcase by running funcresolve and globaldce...
1340   if (!BugpointIsInterrupted) {
1341     outs() << "\n*** Attempting to perform final cleanups: ";
1342     std::unique_ptr<Module> M = CloneModule(BD.getProgram());
1343     M = BD.performFinalCleanups(std::move(M), true);
1344 
1345     // Find out if the pass still crashes on the cleaned up program...
1346     if (M && TestFn(BD, M.get()))
1347       BD.setNewProgram(
1348           std::move(M)); // Yup, it does, keep the reduced version...
1349   }
1350 
1351   BD.EmitProgressBitcode(BD.getProgram(), "reduced-simplified");
1352 
1353   return Error::success();
1354 }
1355 
1356 static bool TestForOptimizerCrash(const BugDriver &BD, Module *M) {
1357   return BD.runPasses(*M, BD.getPassesToRun());
1358 }
1359 
1360 /// debugOptimizerCrash - This method is called when some pass crashes on input.
1361 /// It attempts to prune down the testcase to something reasonable, and figure
1362 /// out exactly which pass is crashing.
1363 ///
1364 Error BugDriver::debugOptimizerCrash(const std::string &ID) {
1365   outs() << "\n*** Debugging optimizer crash!\n";
1366 
1367   // Reduce the list of passes which causes the optimizer to crash...
1368   if (!BugpointIsInterrupted && !DontReducePassList) {
1369     Expected<bool> Result = ReducePassList(*this).reduceList(PassesToRun);
1370     if (Error E = Result.takeError())
1371       return E;
1372   }
1373 
1374   outs() << "\n*** Found crashing pass"
1375          << (PassesToRun.size() == 1 ? ": " : "es: ")
1376          << getPassesString(PassesToRun) << '\n';
1377 
1378   EmitProgressBitcode(*Program, ID);
1379 
1380   auto Res = DebugACrash(*this, TestForOptimizerCrash);
1381   if (Res || DontReducePassList)
1382     return Res;
1383   // Try to reduce the pass list again. This covers additional cases
1384   // we failed to reduce earlier, because of more complex pass dependencies
1385   // triggering the crash.
1386   auto SecondRes = ReducePassList(*this).reduceList(PassesToRun);
1387   if (Error E = SecondRes.takeError())
1388     return E;
1389   outs() << "\n*** Found crashing pass"
1390          << (PassesToRun.size() == 1 ? ": " : "es: ")
1391          << getPassesString(PassesToRun) << '\n';
1392 
1393   EmitProgressBitcode(getProgram(), "reduced-simplified");
1394   return Res;
1395 }
1396 
1397 static bool TestForCodeGenCrash(const BugDriver &BD, Module *M) {
1398   if (Error E = BD.compileProgram(*M)) {
1399     if (VerboseErrors)
1400       errs() << toString(std::move(E)) << "\n";
1401     else {
1402       consumeError(std::move(E));
1403       errs() << "<crash>\n";
1404     }
1405     return true; // Tool is still crashing.
1406   }
1407   errs() << '\n';
1408   return false;
1409 }
1410 
1411 /// debugCodeGeneratorCrash - This method is called when the code generator
1412 /// crashes on an input.  It attempts to reduce the input as much as possible
1413 /// while still causing the code generator to crash.
1414 Error BugDriver::debugCodeGeneratorCrash() {
1415   errs() << "*** Debugging code generator crash!\n";
1416 
1417   return DebugACrash(*this, TestForCodeGenCrash);
1418 }
1419