CrashDebugger.cpp revision 344779
1//===- CrashDebugger.cpp - Debug compilation crashes ----------------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file defines the bugpoint internals that narrow down compilation crashes 11// 12//===----------------------------------------------------------------------===// 13 14#include "BugDriver.h" 15#include "ListReducer.h" 16#include "ToolRunner.h" 17#include "llvm/ADT/SmallPtrSet.h" 18#include "llvm/ADT/StringSet.h" 19#include "llvm/Analysis/TargetTransformInfo.h" 20#include "llvm/Transforms/Utils/Local.h" 21#include "llvm/IR/CFG.h" 22#include "llvm/IR/Constants.h" 23#include "llvm/IR/DebugInfo.h" 24#include "llvm/IR/DerivedTypes.h" 25#include "llvm/IR/Instructions.h" 26#include "llvm/IR/LegacyPassManager.h" 27#include "llvm/IR/Module.h" 28#include "llvm/IR/ValueSymbolTable.h" 29#include "llvm/IR/Verifier.h" 30#include "llvm/Pass.h" 31#include "llvm/Support/CommandLine.h" 32#include "llvm/Support/FileUtilities.h" 33#include "llvm/Transforms/Scalar.h" 34#include "llvm/Transforms/Utils/BasicBlockUtils.h" 35#include "llvm/Transforms/Utils/Cloning.h" 36#include <set> 37using namespace llvm; 38 39namespace { 40cl::opt<bool> KeepMain("keep-main", 41 cl::desc("Force function reduction to keep main"), 42 cl::init(false)); 43cl::opt<bool> NoGlobalRM("disable-global-remove", 44 cl::desc("Do not remove global variables"), 45 cl::init(false)); 46 47cl::opt<bool> ReplaceFuncsWithNull( 48 "replace-funcs-with-null", 49 cl::desc("When stubbing functions, replace all uses will null"), 50 cl::init(false)); 51cl::opt<bool> DontReducePassList("disable-pass-list-reduction", 52 cl::desc("Skip pass list reduction steps"), 53 cl::init(false)); 54 55cl::opt<bool> NoNamedMDRM("disable-namedmd-remove", 56 cl::desc("Do not remove global named metadata"), 57 cl::init(false)); 58cl::opt<bool> NoStripDebugInfo("disable-strip-debuginfo", 59 cl::desc("Do not strip debug info metadata"), 60 cl::init(false)); 61cl::opt<bool> NoStripDebugTypeInfo("disable-strip-debug-types", 62 cl::desc("Do not strip debug type info metadata"), 63 cl::init(false)); 64cl::opt<bool> VerboseErrors("verbose-errors", 65 cl::desc("Print the output of crashing program"), 66 cl::init(false)); 67} 68 69namespace llvm { 70class ReducePassList : public ListReducer<std::string> { 71 BugDriver &BD; 72 73public: 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 84Expected<ReducePassList::TestResult> 85ReducePassList::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 118using BugTester = bool (*)(const BugDriver &, Module *); 119 120namespace { 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. 124class ReduceCrashingGlobalInitializers : public ListReducer<GlobalVariable *> { 125 BugDriver &BD; 126 BugTester TestFn; 127 128public: 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 145bool 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 186namespace { 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/// 191class ReduceCrashingFunctions : public ListReducer<Function *> { 192 BugDriver &BD; 193 BugTester TestFn; 194 195public: 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 212static 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 236bool 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 317namespace { 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/// 322class ReduceCrashingFunctionAttributes : public ListReducer<Attribute> { 323 BugDriver &BD; 324 std::string FnName; 325 BugTester TestFn; 326 327public: 328 ReduceCrashingFunctionAttributes(BugDriver &bd, const std::string &FnName, 329 BugTester testFn) 330 : BD(bd), FnName(FnName), TestFn(testFn) {} 331 332 Expected<TestResult> doTest(std::vector<Attribute> &Prefix, 333 std::vector<Attribute> &Kept) override { 334 if (!Kept.empty() && TestFuncAttrs(Kept)) 335 return KeepSuffix; 336 if (!Prefix.empty() && TestFuncAttrs(Prefix)) 337 return KeepPrefix; 338 return NoFailure; 339 } 340 341 bool TestFuncAttrs(std::vector<Attribute> &Attrs); 342}; 343} 344 345bool ReduceCrashingFunctionAttributes::TestFuncAttrs( 346 std::vector<Attribute> &Attrs) { 347 // Clone the program to try hacking it apart... 348 std::unique_ptr<Module> M = CloneModule(BD.getProgram()); 349 Function *F = M->getFunction(FnName); 350 351 // Build up an AttributeList from the attributes we've been given by the 352 // reducer. 353 AttrBuilder AB; 354 for (auto A : Attrs) 355 AB.addAttribute(A); 356 AttributeList NewAttrs; 357 NewAttrs = 358 NewAttrs.addAttributes(BD.getContext(), AttributeList::FunctionIndex, AB); 359 360 // Set this new list of attributes on the function. 361 F->setAttributes(NewAttrs); 362 363 // Try running on the hacked up program... 364 if (TestFn(BD, M.get())) { 365 BD.setNewProgram(std::move(M)); // It crashed, keep the trimmed version... 366 367 // Pass along the set of attributes that caused the crash. 368 Attrs.clear(); 369 for (Attribute A : NewAttrs.getFnAttributes()) { 370 Attrs.push_back(A); 371 } 372 return true; 373 } 374 return false; 375} 376 377namespace { 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". 382void simpleSimplifyCfg(Function &F, SmallVectorImpl<BasicBlock *> &BBs) { 383 if (F.empty()) 384 return; 385 386 for (auto *BB : BBs) { 387 ConstantFoldTerminator(BB); 388 MergeBlockIntoPredecessor(BB); 389 } 390 391 // Remove unreachable blocks 392 // removeUnreachableBlocks can't be used here, it will turn various 393 // undefined behavior into unreachables, but bugpoint was the thing that 394 // generated the undefined behavior, and we don't want it to kill the entire 395 // program. 396 SmallPtrSet<BasicBlock *, 16> Visited; 397 for (auto *BB : depth_first(&F.getEntryBlock())) 398 Visited.insert(BB); 399 400 SmallVector<BasicBlock *, 16> Unreachable; 401 for (auto &BB : F) 402 if (!Visited.count(&BB)) 403 Unreachable.push_back(&BB); 404 405 // The dead BB's may be in a dead cycle or otherwise have references to each 406 // other. Because of this, we have to drop all references first, then delete 407 // them all at once. 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/// 422class ReduceCrashingBlocks : public ListReducer<const BasicBlock *> { 423 BugDriver &BD; 424 BugTester TestFn; 425 426public: 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 443bool 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 533namespace { 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/// 539class ReduceCrashingConditionals : public ListReducer<const BasicBlock *> { 540 BugDriver &BD; 541 BugTester TestFn; 542 bool Direction; 543 544public: 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 561bool 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 640namespace { 641/// SimplifyCFG reducer - This works by calling SimplifyCFG on each basic block 642/// in the program. 643 644class ReduceSimplifyCFG : public ListReducer<const BasicBlock *> { 645 BugDriver &BD; 646 BugTester TestFn; 647 TargetTransformInfo TTI; 648 649public: 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 666bool 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 732namespace { 733/// ReduceCrashingInstructions reducer - This works by removing the specified 734/// non-terminator instructions and replacing them with undef. 735/// 736class ReduceCrashingInstructions : public ListReducer<const Instruction *> { 737 BugDriver &BD; 738 BugTester TestFn; 739 740public: 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 757bool 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 809namespace { 810// Reduce the list of Named Metadata nodes. We keep this as a list of 811// names to avoid having to convert back and forth every time. 812class ReduceCrashingNamedMD : public ListReducer<std::string> { 813 BugDriver &BD; 814 BugTester TestFn; 815 816public: 817 ReduceCrashingNamedMD(BugDriver &bd, BugTester testFn) 818 : BD(bd), TestFn(testFn) {} 819 820 Expected<TestResult> doTest(std::vector<std::string> &Prefix, 821 std::vector<std::string> &Kept) override { 822 if (!Kept.empty() && TestNamedMDs(Kept)) 823 return KeepSuffix; 824 if (!Prefix.empty() && TestNamedMDs(Prefix)) 825 return KeepPrefix; 826 return NoFailure; 827 } 828 829 bool TestNamedMDs(std::vector<std::string> &NamedMDs); 830}; 831} 832 833bool ReduceCrashingNamedMD::TestNamedMDs(std::vector<std::string> &NamedMDs) { 834 835 ValueToValueMapTy VMap; 836 std::unique_ptr<Module> M = CloneModule(BD.getProgram(), VMap); 837 838 outs() << "Checking for crash with only these named metadata nodes:"; 839 unsigned NumPrint = std::min<size_t>(NamedMDs.size(), 10); 840 for (unsigned i = 0, e = NumPrint; i != e; ++i) 841 outs() << " " << NamedMDs[i]; 842 if (NumPrint < NamedMDs.size()) 843 outs() << "... <" << NamedMDs.size() << " total>"; 844 outs() << ": "; 845 846 // Make a StringMap for faster lookup 847 StringSet<> Names; 848 for (const std::string &Name : NamedMDs) 849 Names.insert(Name); 850 851 // First collect all the metadata to delete in a vector, then 852 // delete them all at once to avoid invalidating the iterator 853 std::vector<NamedMDNode *> ToDelete; 854 ToDelete.reserve(M->named_metadata_size() - Names.size()); 855 for (auto &NamedMD : M->named_metadata()) 856 // Always keep a nonempty llvm.dbg.cu because the Verifier would complain. 857 if (!Names.count(NamedMD.getName()) && 858 (!(NamedMD.getName() == "llvm.dbg.cu" && NamedMD.getNumOperands() > 0))) 859 ToDelete.push_back(&NamedMD); 860 861 for (auto *NamedMD : ToDelete) 862 NamedMD->eraseFromParent(); 863 864 // Verify that this is still valid. 865 legacy::PassManager Passes; 866 Passes.add(createVerifierPass(/*FatalErrors=*/false)); 867 Passes.run(*M); 868 869 // Try running on the hacked up program... 870 if (TestFn(BD, M.get())) { 871 BD.setNewProgram(std::move(M)); // It crashed, keep the trimmed version... 872 return true; 873 } 874 return false; 875} 876 877namespace { 878// Reduce the list of operands to named metadata nodes 879class ReduceCrashingNamedMDOps : public ListReducer<const MDNode *> { 880 BugDriver &BD; 881 BugTester TestFn; 882 883public: 884 ReduceCrashingNamedMDOps(BugDriver &bd, BugTester testFn) 885 : BD(bd), TestFn(testFn) {} 886 887 Expected<TestResult> doTest(std::vector<const MDNode *> &Prefix, 888 std::vector<const MDNode *> &Kept) override { 889 if (!Kept.empty() && TestNamedMDOps(Kept)) 890 return KeepSuffix; 891 if (!Prefix.empty() && TestNamedMDOps(Prefix)) 892 return KeepPrefix; 893 return NoFailure; 894 } 895 896 bool TestNamedMDOps(std::vector<const MDNode *> &NamedMDOps); 897}; 898} 899 900bool ReduceCrashingNamedMDOps::TestNamedMDOps( 901 std::vector<const MDNode *> &NamedMDOps) { 902 // Convert list to set for fast lookup... 903 SmallPtrSet<const MDNode *, 32> OldMDNodeOps; 904 for (unsigned i = 0, e = NamedMDOps.size(); i != e; ++i) { 905 OldMDNodeOps.insert(NamedMDOps[i]); 906 } 907 908 outs() << "Checking for crash with only " << OldMDNodeOps.size(); 909 if (OldMDNodeOps.size() == 1) 910 outs() << " named metadata operand: "; 911 else 912 outs() << " named metadata operands: "; 913 914 ValueToValueMapTy VMap; 915 std::unique_ptr<Module> M = CloneModule(BD.getProgram(), VMap); 916 917 // This is a little wasteful. In the future it might be good if we could have 918 // these dropped during cloning. 919 for (auto &NamedMD : BD.getProgram().named_metadata()) { 920 // Drop the old one and create a new one 921 M->eraseNamedMetadata(M->getNamedMetadata(NamedMD.getName())); 922 NamedMDNode *NewNamedMDNode = 923 M->getOrInsertNamedMetadata(NamedMD.getName()); 924 for (MDNode *op : NamedMD.operands()) 925 if (OldMDNodeOps.count(op)) 926 NewNamedMDNode->addOperand(cast<MDNode>(MapMetadata(op, VMap))); 927 } 928 929 // Verify that this is still valid. 930 legacy::PassManager Passes; 931 Passes.add(createVerifierPass(/*FatalErrors=*/false)); 932 Passes.run(*M); 933 934 // Try running on the hacked up program... 935 if (TestFn(BD, M.get())) { 936 // Make sure to use instruction pointers that point into the now-current 937 // module, and that they don't include any deleted blocks. 938 NamedMDOps.clear(); 939 for (const MDNode *Node : OldMDNodeOps) 940 NamedMDOps.push_back(cast<MDNode>(*VMap.getMappedMD(Node))); 941 942 BD.setNewProgram(std::move(M)); // It crashed, keep the trimmed version... 943 return true; 944 } 945 // It didn't crash, try something else. 946 return false; 947} 948 949/// Attempt to eliminate as many global initializers as possible. 950static Error ReduceGlobalInitializers(BugDriver &BD, BugTester TestFn) { 951 Module &OrigM = BD.getProgram(); 952 if (OrigM.global_empty()) 953 return Error::success(); 954 955 // Now try to reduce the number of global variable initializers in the 956 // module to something small. 957 std::unique_ptr<Module> M = CloneModule(OrigM); 958 bool DeletedInit = false; 959 960 for (GlobalVariable &GV : M->globals()) { 961 if (GV.hasInitializer()) { 962 DeleteGlobalInitializer(&GV); 963 GV.setLinkage(GlobalValue::ExternalLinkage); 964 GV.setComdat(nullptr); 965 DeletedInit = true; 966 } 967 } 968 969 if (!DeletedInit) 970 return Error::success(); 971 972 // See if the program still causes a crash... 973 outs() << "\nChecking to see if we can delete global inits: "; 974 975 if (TestFn(BD, M.get())) { // Still crashes? 976 BD.setNewProgram(std::move(M)); 977 outs() << "\n*** Able to remove all global initializers!\n"; 978 return Error::success(); 979 } 980 981 // No longer crashes. 982 outs() << " - Removing all global inits hides problem!\n"; 983 984 std::vector<GlobalVariable *> GVs; 985 for (GlobalVariable &GV : OrigM.globals()) 986 if (GV.hasInitializer()) 987 GVs.push_back(&GV); 988 989 if (GVs.size() > 1 && !BugpointIsInterrupted) { 990 outs() << "\n*** Attempting to reduce the number of global initializers " 991 << "in the testcase\n"; 992 993 unsigned OldSize = GVs.size(); 994 Expected<bool> Result = 995 ReduceCrashingGlobalInitializers(BD, TestFn).reduceList(GVs); 996 if (Error E = Result.takeError()) 997 return E; 998 999 if (GVs.size() < OldSize) 1000 BD.EmitProgressBitcode(BD.getProgram(), "reduced-global-variables"); 1001 } 1002 return Error::success(); 1003} 1004 1005static Error ReduceInsts(BugDriver &BD, BugTester TestFn) { 1006 // Attempt to delete instructions using bisection. This should help out nasty 1007 // cases with large basic blocks where the problem is at one end. 1008 if (!BugpointIsInterrupted) { 1009 std::vector<const Instruction *> Insts; 1010 for (const Function &F : BD.getProgram()) 1011 for (const BasicBlock &BB : F) 1012 for (const Instruction &I : BB) 1013 if (!I.isTerminator()) 1014 Insts.push_back(&I); 1015 1016 Expected<bool> Result = 1017 ReduceCrashingInstructions(BD, TestFn).reduceList(Insts); 1018 if (Error E = Result.takeError()) 1019 return E; 1020 } 1021 1022 unsigned Simplification = 2; 1023 do { 1024 if (BugpointIsInterrupted) 1025 // TODO: Should we distinguish this with an "interrupted error"? 1026 return Error::success(); 1027 --Simplification; 1028 outs() << "\n*** Attempting to reduce testcase by deleting instruc" 1029 << "tions: Simplification Level #" << Simplification << '\n'; 1030 1031 // Now that we have deleted the functions that are unnecessary for the 1032 // program, try to remove instructions that are not necessary to cause the 1033 // crash. To do this, we loop through all of the instructions in the 1034 // remaining functions, deleting them (replacing any values produced with 1035 // nulls), and then running ADCE and SimplifyCFG. If the transformed input 1036 // still triggers failure, keep deleting until we cannot trigger failure 1037 // anymore. 1038 // 1039 unsigned InstructionsToSkipBeforeDeleting = 0; 1040 TryAgain: 1041 1042 // Loop over all of the (non-terminator) instructions remaining in the 1043 // function, attempting to delete them. 1044 unsigned CurInstructionNum = 0; 1045 for (Module::const_iterator FI = BD.getProgram().begin(), 1046 E = BD.getProgram().end(); 1047 FI != E; ++FI) 1048 if (!FI->isDeclaration()) 1049 for (Function::const_iterator BI = FI->begin(), E = FI->end(); BI != E; 1050 ++BI) 1051 for (BasicBlock::const_iterator I = BI->begin(), E = --BI->end(); 1052 I != E; ++I, ++CurInstructionNum) { 1053 if (InstructionsToSkipBeforeDeleting) { 1054 --InstructionsToSkipBeforeDeleting; 1055 } else { 1056 if (BugpointIsInterrupted) 1057 // TODO: Should this be some kind of interrupted error? 1058 return Error::success(); 1059 1060 if (I->isEHPad() || I->getType()->isTokenTy() || 1061 I->isSwiftError()) 1062 continue; 1063 1064 outs() << "Checking instruction: " << *I; 1065 std::unique_ptr<Module> M = 1066 BD.deleteInstructionFromProgram(&*I, Simplification); 1067 1068 // Find out if the pass still crashes on this pass... 1069 if (TestFn(BD, M.get())) { 1070 // Yup, it does, we delete the old module, and continue trying 1071 // to reduce the testcase... 1072 BD.setNewProgram(std::move(M)); 1073 InstructionsToSkipBeforeDeleting = CurInstructionNum; 1074 goto TryAgain; // I wish I had a multi-level break here! 1075 } 1076 } 1077 } 1078 1079 if (InstructionsToSkipBeforeDeleting) { 1080 InstructionsToSkipBeforeDeleting = 0; 1081 goto TryAgain; 1082 } 1083 1084 } while (Simplification); 1085 BD.EmitProgressBitcode(BD.getProgram(), "reduced-instructions"); 1086 return Error::success(); 1087} 1088 1089/// DebugACrash - Given a predicate that determines whether a component crashes 1090/// on a program, try to destructively reduce the program while still keeping 1091/// the predicate true. 1092static Error DebugACrash(BugDriver &BD, BugTester TestFn) { 1093 // See if we can get away with nuking some of the global variable initializers 1094 // in the program... 1095 if (!NoGlobalRM) 1096 if (Error E = ReduceGlobalInitializers(BD, TestFn)) 1097 return E; 1098 1099 // Now try to reduce the number of functions in the module to something small. 1100 std::vector<Function *> Functions; 1101 for (Function &F : BD.getProgram()) 1102 if (!F.isDeclaration()) 1103 Functions.push_back(&F); 1104 1105 if (Functions.size() > 1 && !BugpointIsInterrupted) { 1106 outs() << "\n*** Attempting to reduce the number of functions " 1107 "in the testcase\n"; 1108 1109 unsigned OldSize = Functions.size(); 1110 Expected<bool> Result = 1111 ReduceCrashingFunctions(BD, TestFn).reduceList(Functions); 1112 if (Error E = Result.takeError()) 1113 return E; 1114 1115 if (Functions.size() < OldSize) 1116 BD.EmitProgressBitcode(BD.getProgram(), "reduced-function"); 1117 } 1118 1119 // For each remaining function, try to reduce that function's attributes. 1120 std::vector<std::string> FunctionNames; 1121 for (Function &F : BD.getProgram()) 1122 FunctionNames.push_back(F.getName()); 1123 1124 if (!FunctionNames.empty() && !BugpointIsInterrupted) { 1125 outs() << "\n*** Attempting to reduce the number of function attributes in " 1126 "the testcase\n"; 1127 1128 unsigned OldSize = 0; 1129 unsigned NewSize = 0; 1130 for (std::string &Name : FunctionNames) { 1131 Function *Fn = BD.getProgram().getFunction(Name); 1132 assert(Fn && "Could not find funcion?"); 1133 1134 std::vector<Attribute> Attrs; 1135 for (Attribute A : Fn->getAttributes().getFnAttributes()) 1136 Attrs.push_back(A); 1137 1138 OldSize += Attrs.size(); 1139 Expected<bool> Result = 1140 ReduceCrashingFunctionAttributes(BD, Name, TestFn).reduceList(Attrs); 1141 if (Error E = Result.takeError()) 1142 return E; 1143 1144 NewSize += Attrs.size(); 1145 } 1146 1147 if (OldSize < NewSize) 1148 BD.EmitProgressBitcode(BD.getProgram(), "reduced-function-attributes"); 1149 } 1150 1151 // Attempt to change conditional branches into unconditional branches to 1152 // eliminate blocks. 1153 if (!DisableSimplifyCFG && !BugpointIsInterrupted) { 1154 std::vector<const BasicBlock *> Blocks; 1155 for (Function &F : BD.getProgram()) 1156 for (BasicBlock &BB : F) 1157 Blocks.push_back(&BB); 1158 unsigned OldSize = Blocks.size(); 1159 Expected<bool> Result = 1160 ReduceCrashingConditionals(BD, TestFn, true).reduceList(Blocks); 1161 if (Error E = Result.takeError()) 1162 return E; 1163 Result = ReduceCrashingConditionals(BD, TestFn, false).reduceList(Blocks); 1164 if (Error E = Result.takeError()) 1165 return E; 1166 if (Blocks.size() < OldSize) 1167 BD.EmitProgressBitcode(BD.getProgram(), "reduced-conditionals"); 1168 } 1169 1170 // Attempt to delete entire basic blocks at a time to speed up 1171 // convergence... this actually works by setting the terminator of the blocks 1172 // to a return instruction then running simplifycfg, which can potentially 1173 // shrinks the code dramatically quickly 1174 // 1175 if (!DisableSimplifyCFG && !BugpointIsInterrupted) { 1176 std::vector<const BasicBlock *> Blocks; 1177 for (Function &F : BD.getProgram()) 1178 for (BasicBlock &BB : F) 1179 Blocks.push_back(&BB); 1180 unsigned OldSize = Blocks.size(); 1181 Expected<bool> Result = ReduceCrashingBlocks(BD, TestFn).reduceList(Blocks); 1182 if (Error E = Result.takeError()) 1183 return E; 1184 if (Blocks.size() < OldSize) 1185 BD.EmitProgressBitcode(BD.getProgram(), "reduced-blocks"); 1186 } 1187 1188 if (!DisableSimplifyCFG && !BugpointIsInterrupted) { 1189 std::vector<const BasicBlock *> Blocks; 1190 for (Function &F : BD.getProgram()) 1191 for (BasicBlock &BB : F) 1192 Blocks.push_back(&BB); 1193 unsigned OldSize = Blocks.size(); 1194 Expected<bool> Result = ReduceSimplifyCFG(BD, TestFn).reduceList(Blocks); 1195 if (Error E = Result.takeError()) 1196 return E; 1197 if (Blocks.size() < OldSize) 1198 BD.EmitProgressBitcode(BD.getProgram(), "reduced-simplifycfg"); 1199 } 1200 1201 // Attempt to delete instructions using bisection. This should help out nasty 1202 // cases with large basic blocks where the problem is at one end. 1203 if (!BugpointIsInterrupted) 1204 if (Error E = ReduceInsts(BD, TestFn)) 1205 return E; 1206 1207 // Attempt to strip debug info metadata. 1208 auto stripMetadata = [&](std::function<bool(Module &)> strip) { 1209 std::unique_ptr<Module> M = CloneModule(BD.getProgram()); 1210 strip(*M); 1211 if (TestFn(BD, M.get())) 1212 BD.setNewProgram(std::move(M)); 1213 }; 1214 if (!NoStripDebugInfo && !BugpointIsInterrupted) { 1215 outs() << "\n*** Attempting to strip the debug info: "; 1216 stripMetadata(StripDebugInfo); 1217 } 1218 if (!NoStripDebugTypeInfo && !BugpointIsInterrupted) { 1219 outs() << "\n*** Attempting to strip the debug type info: "; 1220 stripMetadata(stripNonLineTableDebugInfo); 1221 } 1222 1223 if (!NoNamedMDRM) { 1224 if (!BugpointIsInterrupted) { 1225 // Try to reduce the amount of global metadata (particularly debug info), 1226 // by dropping global named metadata that anchors them 1227 outs() << "\n*** Attempting to remove named metadata: "; 1228 std::vector<std::string> NamedMDNames; 1229 for (auto &NamedMD : BD.getProgram().named_metadata()) 1230 NamedMDNames.push_back(NamedMD.getName().str()); 1231 Expected<bool> Result = 1232 ReduceCrashingNamedMD(BD, TestFn).reduceList(NamedMDNames); 1233 if (Error E = Result.takeError()) 1234 return E; 1235 } 1236 1237 if (!BugpointIsInterrupted) { 1238 // Now that we quickly dropped all the named metadata that doesn't 1239 // contribute to the crash, bisect the operands of the remaining ones 1240 std::vector<const MDNode *> NamedMDOps; 1241 for (auto &NamedMD : BD.getProgram().named_metadata()) 1242 for (auto op : NamedMD.operands()) 1243 NamedMDOps.push_back(op); 1244 Expected<bool> Result = 1245 ReduceCrashingNamedMDOps(BD, TestFn).reduceList(NamedMDOps); 1246 if (Error E = Result.takeError()) 1247 return E; 1248 } 1249 BD.EmitProgressBitcode(BD.getProgram(), "reduced-named-md"); 1250 } 1251 1252 // Try to clean up the testcase by running funcresolve and globaldce... 1253 if (!BugpointIsInterrupted) { 1254 outs() << "\n*** Attempting to perform final cleanups: "; 1255 std::unique_ptr<Module> M = CloneModule(BD.getProgram()); 1256 M = BD.performFinalCleanups(std::move(M), true); 1257 1258 // Find out if the pass still crashes on the cleaned up program... 1259 if (M && TestFn(BD, M.get())) 1260 BD.setNewProgram( 1261 std::move(M)); // Yup, it does, keep the reduced version... 1262 } 1263 1264 BD.EmitProgressBitcode(BD.getProgram(), "reduced-simplified"); 1265 1266 return Error::success(); 1267} 1268 1269static bool TestForOptimizerCrash(const BugDriver &BD, Module *M) { 1270 return BD.runPasses(*M, BD.getPassesToRun()); 1271} 1272 1273/// debugOptimizerCrash - This method is called when some pass crashes on input. 1274/// It attempts to prune down the testcase to something reasonable, and figure 1275/// out exactly which pass is crashing. 1276/// 1277Error BugDriver::debugOptimizerCrash(const std::string &ID) { 1278 outs() << "\n*** Debugging optimizer crash!\n"; 1279 1280 // Reduce the list of passes which causes the optimizer to crash... 1281 if (!BugpointIsInterrupted && !DontReducePassList) { 1282 Expected<bool> Result = ReducePassList(*this).reduceList(PassesToRun); 1283 if (Error E = Result.takeError()) 1284 return E; 1285 } 1286 1287 outs() << "\n*** Found crashing pass" 1288 << (PassesToRun.size() == 1 ? ": " : "es: ") 1289 << getPassesString(PassesToRun) << '\n'; 1290 1291 EmitProgressBitcode(*Program, ID); 1292 1293 return DebugACrash(*this, TestForOptimizerCrash); 1294} 1295 1296static bool TestForCodeGenCrash(const BugDriver &BD, Module *M) { 1297 if (Error E = BD.compileProgram(*M)) { 1298 if (VerboseErrors) 1299 errs() << toString(std::move(E)) << "\n"; 1300 else { 1301 consumeError(std::move(E)); 1302 errs() << "<crash>\n"; 1303 } 1304 return true; // Tool is still crashing. 1305 } 1306 errs() << '\n'; 1307 return false; 1308} 1309 1310/// debugCodeGeneratorCrash - This method is called when the code generator 1311/// crashes on an input. It attempts to reduce the input as much as possible 1312/// while still causing the code generator to crash. 1313Error BugDriver::debugCodeGeneratorCrash() { 1314 errs() << "*** Debugging code generator crash!\n"; 1315 1316 return DebugACrash(*this, TestForCodeGenCrash); 1317} 1318