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