1 //===- Miscompilation.cpp - Debug program miscompilations -----------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file was developed by the LLVM research group and is distributed under 6 // the University of Illinois Open Source License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements optimizer and code generation miscompilation debugging 11 // support. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "BugDriver.h" 16 #include "ListReducer.h" 17 #include "llvm/Constants.h" 18 #include "llvm/DerivedTypes.h" 19 #include "llvm/Instructions.h" 20 #include "llvm/Linker.h" 21 #include "llvm/Module.h" 22 #include "llvm/Pass.h" 23 #include "llvm/Analysis/Verifier.h" 24 #include "llvm/Support/Mangler.h" 25 #include "llvm/Transforms/Utils/Cloning.h" 26 #include "llvm/Support/CommandLine.h" 27 #include "llvm/Support/FileUtilities.h" 28 #include "llvm/Config/config.h" // for HAVE_LINK_R 29 using namespace llvm; 30 31 namespace llvm { 32 extern cl::list<std::string> InputArgv; 33 } 34 35 namespace { 36 class ReduceMiscompilingPasses : public ListReducer<const PassInfo*> { 37 BugDriver &BD; 38 public: 39 ReduceMiscompilingPasses(BugDriver &bd) : BD(bd) {} 40 41 virtual TestResult doTest(std::vector<const PassInfo*> &Prefix, 42 std::vector<const PassInfo*> &Suffix); 43 }; 44 } 45 46 /// TestResult - After passes have been split into a test group and a control 47 /// group, see if they still break the program. 48 /// 49 ReduceMiscompilingPasses::TestResult 50 ReduceMiscompilingPasses::doTest(std::vector<const PassInfo*> &Prefix, 51 std::vector<const PassInfo*> &Suffix) { 52 // First, run the program with just the Suffix passes. If it is still broken 53 // with JUST the kept passes, discard the prefix passes. 54 std::cout << "Checking to see if '" << getPassesString(Suffix) 55 << "' compile correctly: "; 56 57 std::string BytecodeResult; 58 if (BD.runPasses(Suffix, BytecodeResult, false/*delete*/, true/*quiet*/)) { 59 std::cerr << " Error running this sequence of passes" 60 << " on the input program!\n"; 61 BD.setPassesToRun(Suffix); 62 BD.EmitProgressBytecode("pass-error", false); 63 exit(BD.debugOptimizerCrash()); 64 } 65 66 // Check to see if the finished program matches the reference output... 67 if (BD.diffProgram(BytecodeResult, "", true /*delete bytecode*/)) { 68 std::cout << " nope.\n"; 69 if (Suffix.empty()) { 70 std::cerr << BD.getToolName() << ": I'm confused: the test fails when " 71 << "no passes are run, nondeterministic program?\n"; 72 exit(1); 73 } 74 return KeepSuffix; // Miscompilation detected! 75 } 76 std::cout << " yup.\n"; // No miscompilation! 77 78 if (Prefix.empty()) return NoFailure; 79 80 // Next, see if the program is broken if we run the "prefix" passes first, 81 // then separately run the "kept" passes. 82 std::cout << "Checking to see if '" << getPassesString(Prefix) 83 << "' compile correctly: "; 84 85 // If it is not broken with the kept passes, it's possible that the prefix 86 // passes must be run before the kept passes to break it. If the program 87 // WORKS after the prefix passes, but then fails if running the prefix AND 88 // kept passes, we can update our bytecode file to include the result of the 89 // prefix passes, then discard the prefix passes. 90 // 91 if (BD.runPasses(Prefix, BytecodeResult, false/*delete*/, true/*quiet*/)) { 92 std::cerr << " Error running this sequence of passes" 93 << " on the input program!\n"; 94 BD.setPassesToRun(Prefix); 95 BD.EmitProgressBytecode("pass-error", false); 96 exit(BD.debugOptimizerCrash()); 97 } 98 99 // If the prefix maintains the predicate by itself, only keep the prefix! 100 if (BD.diffProgram(BytecodeResult)) { 101 std::cout << " nope.\n"; 102 sys::Path(BytecodeResult).eraseFromDisk(); 103 return KeepPrefix; 104 } 105 std::cout << " yup.\n"; // No miscompilation! 106 107 // Ok, so now we know that the prefix passes work, try running the suffix 108 // passes on the result of the prefix passes. 109 // 110 Module *PrefixOutput = ParseInputFile(BytecodeResult); 111 if (PrefixOutput == 0) { 112 std::cerr << BD.getToolName() << ": Error reading bytecode file '" 113 << BytecodeResult << "'!\n"; 114 exit(1); 115 } 116 sys::Path(BytecodeResult).eraseFromDisk(); // No longer need the file on disk 117 118 // Don't check if there are no passes in the suffix. 119 if (Suffix.empty()) 120 return NoFailure; 121 122 std::cout << "Checking to see if '" << getPassesString(Suffix) 123 << "' passes compile correctly after the '" 124 << getPassesString(Prefix) << "' passes: "; 125 126 Module *OriginalInput = BD.swapProgramIn(PrefixOutput); 127 if (BD.runPasses(Suffix, BytecodeResult, false/*delete*/, true/*quiet*/)) { 128 std::cerr << " Error running this sequence of passes" 129 << " on the input program!\n"; 130 BD.setPassesToRun(Suffix); 131 BD.EmitProgressBytecode("pass-error", false); 132 exit(BD.debugOptimizerCrash()); 133 } 134 135 // Run the result... 136 if (BD.diffProgram(BytecodeResult, "", true/*delete bytecode*/)) { 137 std::cout << " nope.\n"; 138 delete OriginalInput; // We pruned down the original input... 139 return KeepSuffix; 140 } 141 142 // Otherwise, we must not be running the bad pass anymore. 143 std::cout << " yup.\n"; // No miscompilation! 144 delete BD.swapProgramIn(OriginalInput); // Restore orig program & free test 145 return NoFailure; 146 } 147 148 namespace { 149 class ReduceMiscompilingFunctions : public ListReducer<Function*> { 150 BugDriver &BD; 151 bool (*TestFn)(BugDriver &, Module *, Module *); 152 public: 153 ReduceMiscompilingFunctions(BugDriver &bd, 154 bool (*F)(BugDriver &, Module *, Module *)) 155 : BD(bd), TestFn(F) {} 156 157 virtual TestResult doTest(std::vector<Function*> &Prefix, 158 std::vector<Function*> &Suffix) { 159 if (!Suffix.empty() && TestFuncs(Suffix)) 160 return KeepSuffix; 161 if (!Prefix.empty() && TestFuncs(Prefix)) 162 return KeepPrefix; 163 return NoFailure; 164 } 165 166 bool TestFuncs(const std::vector<Function*> &Prefix); 167 }; 168 } 169 170 /// TestMergedProgram - Given two modules, link them together and run the 171 /// program, checking to see if the program matches the diff. If the diff 172 /// matches, return false, otherwise return true. If the DeleteInputs argument 173 /// is set to true then this function deletes both input modules before it 174 /// returns. 175 /// 176 static bool TestMergedProgram(BugDriver &BD, Module *M1, Module *M2, 177 bool DeleteInputs) { 178 // Link the two portions of the program back to together. 179 std::string ErrorMsg; 180 if (!DeleteInputs) { 181 M1 = CloneModule(M1); 182 M2 = CloneModule(M2); 183 } 184 if (Linker::LinkModules(M1, M2, &ErrorMsg)) { 185 std::cerr << BD.getToolName() << ": Error linking modules together:" 186 << ErrorMsg << '\n'; 187 exit(1); 188 } 189 delete M2; // We are done with this module. 190 191 Module *OldProgram = BD.swapProgramIn(M1); 192 193 // Execute the program. If it does not match the expected output, we must 194 // return true. 195 bool Broken = BD.diffProgram(); 196 197 // Delete the linked module & restore the original 198 BD.swapProgramIn(OldProgram); 199 delete M1; 200 return Broken; 201 } 202 203 /// TestFuncs - split functions in a Module into two groups: those that are 204 /// under consideration for miscompilation vs. those that are not, and test 205 /// accordingly. Each group of functions becomes a separate Module. 206 /// 207 bool ReduceMiscompilingFunctions::TestFuncs(const std::vector<Function*>&Funcs){ 208 // Test to see if the function is misoptimized if we ONLY run it on the 209 // functions listed in Funcs. 210 std::cout << "Checking to see if the program is misoptimized when " 211 << (Funcs.size()==1 ? "this function is" : "these functions are") 212 << " run through the pass" 213 << (BD.getPassesToRun().size() == 1 ? "" : "es") << ":"; 214 PrintFunctionList(Funcs); 215 std::cout << '\n'; 216 217 // Split the module into the two halves of the program we want. 218 Module *ToNotOptimize = CloneModule(BD.getProgram()); 219 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize, Funcs); 220 221 // Run the predicate, not that the predicate will delete both input modules. 222 return TestFn(BD, ToOptimize, ToNotOptimize); 223 } 224 225 /// DisambiguateGlobalSymbols - Mangle symbols to guarantee uniqueness by 226 /// modifying predominantly internal symbols rather than external ones. 227 /// 228 static void DisambiguateGlobalSymbols(Module *M) { 229 // Try not to cause collisions by minimizing chances of renaming an 230 // already-external symbol, so take in external globals and functions as-is. 231 // The code should work correctly without disambiguation (assuming the same 232 // mangler is used by the two code generators), but having symbols with the 233 // same name causes warnings to be emitted by the code generator. 234 Mangler Mang(*M); 235 for (Module::global_iterator I = M->global_begin(), E = M->global_end(); I != E; ++I) 236 I->setName(Mang.getValueName(I)); 237 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) 238 I->setName(Mang.getValueName(I)); 239 } 240 241 /// ExtractLoops - Given a reduced list of functions that still exposed the bug, 242 /// check to see if we can extract the loops in the region without obscuring the 243 /// bug. If so, it reduces the amount of code identified. 244 /// 245 static bool ExtractLoops(BugDriver &BD, 246 bool (*TestFn)(BugDriver &, Module *, Module *), 247 std::vector<Function*> &MiscompiledFunctions) { 248 bool MadeChange = false; 249 while (1) { 250 Module *ToNotOptimize = CloneModule(BD.getProgram()); 251 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize, 252 MiscompiledFunctions); 253 Module *ToOptimizeLoopExtracted = BD.ExtractLoop(ToOptimize); 254 if (!ToOptimizeLoopExtracted) { 255 // If the loop extractor crashed or if there were no extractible loops, 256 // then this chapter of our odyssey is over with. 257 delete ToNotOptimize; 258 delete ToOptimize; 259 return MadeChange; 260 } 261 262 std::cerr << "Extracted a loop from the breaking portion of the program.\n"; 263 264 // Bugpoint is intentionally not very trusting of LLVM transformations. In 265 // particular, we're not going to assume that the loop extractor works, so 266 // we're going to test the newly loop extracted program to make sure nothing 267 // has broken. If something broke, then we'll inform the user and stop 268 // extraction. 269 AbstractInterpreter *AI = BD.switchToCBE(); 270 if (TestMergedProgram(BD, ToOptimizeLoopExtracted, ToNotOptimize, false)) { 271 BD.switchToInterpreter(AI); 272 273 // Merged program doesn't work anymore! 274 std::cerr << " *** ERROR: Loop extraction broke the program. :(" 275 << " Please report a bug!\n"; 276 std::cerr << " Continuing on with un-loop-extracted version.\n"; 277 278 BD.writeProgramToFile("bugpoint-loop-extract-fail-tno.bc", ToNotOptimize); 279 BD.writeProgramToFile("bugpoint-loop-extract-fail-to.bc", ToOptimize); 280 BD.writeProgramToFile("bugpoint-loop-extract-fail-to-le.bc", 281 ToOptimizeLoopExtracted); 282 283 std::cerr << "Please submit the bugpoint-loop-extract-fail-*.bc files.\n"; 284 delete ToOptimize; 285 delete ToNotOptimize; 286 delete ToOptimizeLoopExtracted; 287 return MadeChange; 288 } 289 delete ToOptimize; 290 BD.switchToInterpreter(AI); 291 292 std::cout << " Testing after loop extraction:\n"; 293 // Clone modules, the tester function will free them. 294 Module *TOLEBackup = CloneModule(ToOptimizeLoopExtracted); 295 Module *TNOBackup = CloneModule(ToNotOptimize); 296 if (!TestFn(BD, ToOptimizeLoopExtracted, ToNotOptimize)) { 297 std::cout << "*** Loop extraction masked the problem. Undoing.\n"; 298 // If the program is not still broken, then loop extraction did something 299 // that masked the error. Stop loop extraction now. 300 delete TOLEBackup; 301 delete TNOBackup; 302 return MadeChange; 303 } 304 ToOptimizeLoopExtracted = TOLEBackup; 305 ToNotOptimize = TNOBackup; 306 307 std::cout << "*** Loop extraction successful!\n"; 308 309 std::vector<std::pair<std::string, const FunctionType*> > MisCompFunctions; 310 for (Module::iterator I = ToOptimizeLoopExtracted->begin(), 311 E = ToOptimizeLoopExtracted->end(); I != E; ++I) 312 if (!I->isExternal()) 313 MisCompFunctions.push_back(std::make_pair(I->getName(), 314 I->getFunctionType())); 315 316 // Okay, great! Now we know that we extracted a loop and that loop 317 // extraction both didn't break the program, and didn't mask the problem. 318 // Replace the current program with the loop extracted version, and try to 319 // extract another loop. 320 std::string ErrorMsg; 321 if (Linker::LinkModules(ToNotOptimize, ToOptimizeLoopExtracted, &ErrorMsg)){ 322 std::cerr << BD.getToolName() << ": Error linking modules together:" 323 << ErrorMsg << '\n'; 324 exit(1); 325 } 326 delete ToOptimizeLoopExtracted; 327 328 // All of the Function*'s in the MiscompiledFunctions list are in the old 329 // module. Update this list to include all of the functions in the 330 // optimized and loop extracted module. 331 MiscompiledFunctions.clear(); 332 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) { 333 Function *NewF = ToNotOptimize->getFunction(MisCompFunctions[i].first, 334 MisCompFunctions[i].second); 335 assert(NewF && "Function not found??"); 336 MiscompiledFunctions.push_back(NewF); 337 } 338 339 BD.setNewProgram(ToNotOptimize); 340 MadeChange = true; 341 } 342 } 343 344 namespace { 345 class ReduceMiscompiledBlocks : public ListReducer<BasicBlock*> { 346 BugDriver &BD; 347 bool (*TestFn)(BugDriver &, Module *, Module *); 348 std::vector<Function*> FunctionsBeingTested; 349 public: 350 ReduceMiscompiledBlocks(BugDriver &bd, 351 bool (*F)(BugDriver &, Module *, Module *), 352 const std::vector<Function*> &Fns) 353 : BD(bd), TestFn(F), FunctionsBeingTested(Fns) {} 354 355 virtual TestResult doTest(std::vector<BasicBlock*> &Prefix, 356 std::vector<BasicBlock*> &Suffix) { 357 if (!Suffix.empty() && TestFuncs(Suffix)) 358 return KeepSuffix; 359 if (TestFuncs(Prefix)) 360 return KeepPrefix; 361 return NoFailure; 362 } 363 364 bool TestFuncs(const std::vector<BasicBlock*> &Prefix); 365 }; 366 } 367 368 /// TestFuncs - Extract all blocks for the miscompiled functions except for the 369 /// specified blocks. If the problem still exists, return true. 370 /// 371 bool ReduceMiscompiledBlocks::TestFuncs(const std::vector<BasicBlock*> &BBs) { 372 // Test to see if the function is misoptimized if we ONLY run it on the 373 // functions listed in Funcs. 374 std::cout << "Checking to see if the program is misoptimized when all "; 375 if (!BBs.empty()) { 376 std::cout << "but these " << BBs.size() << " blocks are extracted: "; 377 for (unsigned i = 0, e = BBs.size() < 10 ? BBs.size() : 10; i != e; ++i) 378 std::cout << BBs[i]->getName() << " "; 379 if (BBs.size() > 10) std::cout << "..."; 380 } else { 381 std::cout << "blocks are extracted."; 382 } 383 std::cout << '\n'; 384 385 // Split the module into the two halves of the program we want. 386 Module *ToNotOptimize = CloneModule(BD.getProgram()); 387 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize, 388 FunctionsBeingTested); 389 390 // Try the extraction. If it doesn't work, then the block extractor crashed 391 // or something, in which case bugpoint can't chase down this possibility. 392 if (Module *New = BD.ExtractMappedBlocksFromModule(BBs, ToOptimize)) { 393 delete ToOptimize; 394 // Run the predicate, not that the predicate will delete both input modules. 395 return TestFn(BD, New, ToNotOptimize); 396 } 397 delete ToOptimize; 398 delete ToNotOptimize; 399 return false; 400 } 401 402 403 /// ExtractBlocks - Given a reduced list of functions that still expose the bug, 404 /// extract as many basic blocks from the region as possible without obscuring 405 /// the bug. 406 /// 407 static bool ExtractBlocks(BugDriver &BD, 408 bool (*TestFn)(BugDriver &, Module *, Module *), 409 std::vector<Function*> &MiscompiledFunctions) { 410 if (BugpointIsInterrupted) return false; 411 412 std::vector<BasicBlock*> Blocks; 413 for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i) 414 for (Function::iterator I = MiscompiledFunctions[i]->begin(), 415 E = MiscompiledFunctions[i]->end(); I != E; ++I) 416 Blocks.push_back(I); 417 418 // Use the list reducer to identify blocks that can be extracted without 419 // obscuring the bug. The Blocks list will end up containing blocks that must 420 // be retained from the original program. 421 unsigned OldSize = Blocks.size(); 422 423 // Check to see if all blocks are extractible first. 424 if (ReduceMiscompiledBlocks(BD, TestFn, 425 MiscompiledFunctions).TestFuncs(std::vector<BasicBlock*>())) { 426 Blocks.clear(); 427 } else { 428 ReduceMiscompiledBlocks(BD, TestFn,MiscompiledFunctions).reduceList(Blocks); 429 if (Blocks.size() == OldSize) 430 return false; 431 } 432 433 Module *ProgClone = CloneModule(BD.getProgram()); 434 Module *ToExtract = SplitFunctionsOutOfModule(ProgClone, 435 MiscompiledFunctions); 436 Module *Extracted = BD.ExtractMappedBlocksFromModule(Blocks, ToExtract); 437 if (Extracted == 0) { 438 // Weird, extraction should have worked. 439 std::cerr << "Nondeterministic problem extracting blocks??\n"; 440 delete ProgClone; 441 delete ToExtract; 442 return false; 443 } 444 445 // Otherwise, block extraction succeeded. Link the two program fragments back 446 // together. 447 delete ToExtract; 448 449 std::vector<std::pair<std::string, const FunctionType*> > MisCompFunctions; 450 for (Module::iterator I = Extracted->begin(), E = Extracted->end(); 451 I != E; ++I) 452 if (!I->isExternal()) 453 MisCompFunctions.push_back(std::make_pair(I->getName(), 454 I->getFunctionType())); 455 456 std::string ErrorMsg; 457 if (Linker::LinkModules(ProgClone, Extracted, &ErrorMsg)) { 458 std::cerr << BD.getToolName() << ": Error linking modules together:" 459 << ErrorMsg << '\n'; 460 exit(1); 461 } 462 delete Extracted; 463 464 // Set the new program and delete the old one. 465 BD.setNewProgram(ProgClone); 466 467 // Update the list of miscompiled functions. 468 MiscompiledFunctions.clear(); 469 470 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) { 471 Function *NewF = ProgClone->getFunction(MisCompFunctions[i].first, 472 MisCompFunctions[i].second); 473 assert(NewF && "Function not found??"); 474 MiscompiledFunctions.push_back(NewF); 475 } 476 477 return true; 478 } 479 480 481 /// DebugAMiscompilation - This is a generic driver to narrow down 482 /// miscompilations, either in an optimization or a code generator. 483 /// 484 static std::vector<Function*> 485 DebugAMiscompilation(BugDriver &BD, 486 bool (*TestFn)(BugDriver &, Module *, Module *)) { 487 // Okay, now that we have reduced the list of passes which are causing the 488 // failure, see if we can pin down which functions are being 489 // miscompiled... first build a list of all of the non-external functions in 490 // the program. 491 std::vector<Function*> MiscompiledFunctions; 492 Module *Prog = BD.getProgram(); 493 for (Module::iterator I = Prog->begin(), E = Prog->end(); I != E; ++I) 494 if (!I->isExternal()) 495 MiscompiledFunctions.push_back(I); 496 497 // Do the reduction... 498 if (!BugpointIsInterrupted) 499 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions); 500 501 std::cout << "\n*** The following function" 502 << (MiscompiledFunctions.size() == 1 ? " is" : "s are") 503 << " being miscompiled: "; 504 PrintFunctionList(MiscompiledFunctions); 505 std::cout << '\n'; 506 507 // See if we can rip any loops out of the miscompiled functions and still 508 // trigger the problem. 509 if (ExtractLoops(BD, TestFn, MiscompiledFunctions)) { 510 // Okay, we extracted some loops and the problem still appears. See if we 511 // can eliminate some of the created functions from being candidates. 512 513 // Loop extraction can introduce functions with the same name (foo_code). 514 // Make sure to disambiguate the symbols so that when the program is split 515 // apart that we can link it back together again. 516 DisambiguateGlobalSymbols(BD.getProgram()); 517 518 // Do the reduction... 519 if (!BugpointIsInterrupted) 520 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions); 521 522 std::cout << "\n*** The following function" 523 << (MiscompiledFunctions.size() == 1 ? " is" : "s are") 524 << " being miscompiled: "; 525 PrintFunctionList(MiscompiledFunctions); 526 std::cout << '\n'; 527 } 528 529 if (ExtractBlocks(BD, TestFn, MiscompiledFunctions)) { 530 // Okay, we extracted some blocks and the problem still appears. See if we 531 // can eliminate some of the created functions from being candidates. 532 533 // Block extraction can introduce functions with the same name (foo_code). 534 // Make sure to disambiguate the symbols so that when the program is split 535 // apart that we can link it back together again. 536 DisambiguateGlobalSymbols(BD.getProgram()); 537 538 // Do the reduction... 539 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions); 540 541 std::cout << "\n*** The following function" 542 << (MiscompiledFunctions.size() == 1 ? " is" : "s are") 543 << " being miscompiled: "; 544 PrintFunctionList(MiscompiledFunctions); 545 std::cout << '\n'; 546 } 547 548 return MiscompiledFunctions; 549 } 550 551 /// TestOptimizer - This is the predicate function used to check to see if the 552 /// "Test" portion of the program is misoptimized. If so, return true. In any 553 /// case, both module arguments are deleted. 554 /// 555 static bool TestOptimizer(BugDriver &BD, Module *Test, Module *Safe) { 556 // Run the optimization passes on ToOptimize, producing a transformed version 557 // of the functions being tested. 558 std::cout << " Optimizing functions being tested: "; 559 Module *Optimized = BD.runPassesOn(Test, BD.getPassesToRun(), 560 /*AutoDebugCrashes*/true); 561 std::cout << "done.\n"; 562 delete Test; 563 564 std::cout << " Checking to see if the merged program executes correctly: "; 565 bool Broken = TestMergedProgram(BD, Optimized, Safe, true); 566 std::cout << (Broken ? " nope.\n" : " yup.\n"); 567 return Broken; 568 } 569 570 571 /// debugMiscompilation - This method is used when the passes selected are not 572 /// crashing, but the generated output is semantically different from the 573 /// input. 574 /// 575 bool BugDriver::debugMiscompilation() { 576 // Make sure something was miscompiled... 577 if (!BugpointIsInterrupted) 578 if (!ReduceMiscompilingPasses(*this).reduceList(PassesToRun)) { 579 std::cerr << "*** Optimized program matches reference output! No problem" 580 << " detected...\nbugpoint can't help you with your problem!\n"; 581 return false; 582 } 583 584 std::cout << "\n*** Found miscompiling pass" 585 << (getPassesToRun().size() == 1 ? "" : "es") << ": " 586 << getPassesString(getPassesToRun()) << '\n'; 587 EmitProgressBytecode("passinput"); 588 589 std::vector<Function*> MiscompiledFunctions = 590 DebugAMiscompilation(*this, TestOptimizer); 591 592 // Output a bunch of bytecode files for the user... 593 std::cout << "Outputting reduced bytecode files which expose the problem:\n"; 594 Module *ToNotOptimize = CloneModule(getProgram()); 595 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize, 596 MiscompiledFunctions); 597 598 std::cout << " Non-optimized portion: "; 599 ToNotOptimize = swapProgramIn(ToNotOptimize); 600 EmitProgressBytecode("tonotoptimize", true); 601 setNewProgram(ToNotOptimize); // Delete hacked module. 602 603 std::cout << " Portion that is input to optimizer: "; 604 ToOptimize = swapProgramIn(ToOptimize); 605 EmitProgressBytecode("tooptimize"); 606 setNewProgram(ToOptimize); // Delete hacked module. 607 608 return false; 609 } 610 611 /// CleanupAndPrepareModules - Get the specified modules ready for code 612 /// generator testing. 613 /// 614 static void CleanupAndPrepareModules(BugDriver &BD, Module *&Test, 615 Module *Safe) { 616 // Clean up the modules, removing extra cruft that we don't need anymore... 617 Test = BD.performFinalCleanups(Test); 618 619 // If we are executing the JIT, we have several nasty issues to take care of. 620 if (!BD.isExecutingJIT()) return; 621 622 // First, if the main function is in the Safe module, we must add a stub to 623 // the Test module to call into it. Thus, we create a new function `main' 624 // which just calls the old one. 625 if (Function *oldMain = Safe->getNamedFunction("main")) 626 if (!oldMain->isExternal()) { 627 // Rename it 628 oldMain->setName("llvm_bugpoint_old_main"); 629 // Create a NEW `main' function with same type in the test module. 630 Function *newMain = new Function(oldMain->getFunctionType(), 631 GlobalValue::ExternalLinkage, 632 "main", Test); 633 // Create an `oldmain' prototype in the test module, which will 634 // corresponds to the real main function in the same module. 635 Function *oldMainProto = new Function(oldMain->getFunctionType(), 636 GlobalValue::ExternalLinkage, 637 oldMain->getName(), Test); 638 // Set up and remember the argument list for the main function. 639 std::vector<Value*> args; 640 for (Function::arg_iterator 641 I = newMain->arg_begin(), E = newMain->arg_end(), 642 OI = oldMain->arg_begin(); I != E; ++I, ++OI) { 643 I->setName(OI->getName()); // Copy argument names from oldMain 644 args.push_back(I); 645 } 646 647 // Call the old main function and return its result 648 BasicBlock *BB = new BasicBlock("entry", newMain); 649 CallInst *call = new CallInst(oldMainProto, args, "", BB); 650 651 // If the type of old function wasn't void, return value of call 652 new ReturnInst(call, BB); 653 } 654 655 // The second nasty issue we must deal with in the JIT is that the Safe 656 // module cannot directly reference any functions defined in the test 657 // module. Instead, we use a JIT API call to dynamically resolve the 658 // symbol. 659 660 // Add the resolver to the Safe module. 661 // Prototype: void *getPointerToNamedFunction(const char* Name) 662 Function *resolverFunc = 663 Safe->getOrInsertFunction("getPointerToNamedFunction", 664 PointerType::get(Type::SByteTy), 665 PointerType::get(Type::SByteTy), 0); 666 667 // Use the function we just added to get addresses of functions we need. 668 for (Module::iterator F = Safe->begin(), E = Safe->end(); F != E; ++F) { 669 if (F->isExternal() && !F->use_empty() && &*F != resolverFunc && 670 F->getIntrinsicID() == 0 /* ignore intrinsics */) { 671 Function *TestFn = Test->getNamedFunction(F->getName()); 672 673 // Don't forward functions which are external in the test module too. 674 if (TestFn && !TestFn->isExternal()) { 675 // 1. Add a string constant with its name to the global file 676 Constant *InitArray = ConstantArray::get(F->getName()); 677 GlobalVariable *funcName = 678 new GlobalVariable(InitArray->getType(), true /*isConstant*/, 679 GlobalValue::InternalLinkage, InitArray, 680 F->getName() + "_name", Safe); 681 682 // 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an 683 // sbyte* so it matches the signature of the resolver function. 684 685 // GetElementPtr *funcName, ulong 0, ulong 0 686 std::vector<Constant*> GEPargs(2,Constant::getNullValue(Type::IntTy)); 687 Value *GEP = 688 ConstantExpr::getGetElementPtr(funcName, GEPargs); 689 std::vector<Value*> ResolverArgs; 690 ResolverArgs.push_back(GEP); 691 692 // Rewrite uses of F in global initializers, etc. to uses of a wrapper 693 // function that dynamically resolves the calls to F via our JIT API 694 if (!F->use_empty()) { 695 // Create a new global to hold the cached function pointer. 696 Constant *NullPtr = ConstantPointerNull::get(F->getType()); 697 GlobalVariable *Cache = 698 new GlobalVariable(F->getType(), false,GlobalValue::InternalLinkage, 699 NullPtr,F->getName()+".fpcache", F->getParent()); 700 701 // Construct a new stub function that will re-route calls to F 702 const FunctionType *FuncTy = F->getFunctionType(); 703 Function *FuncWrapper = new Function(FuncTy, 704 GlobalValue::InternalLinkage, 705 F->getName() + "_wrapper", 706 F->getParent()); 707 BasicBlock *EntryBB = new BasicBlock("entry", FuncWrapper); 708 BasicBlock *DoCallBB = new BasicBlock("usecache", FuncWrapper); 709 BasicBlock *LookupBB = new BasicBlock("lookupfp", FuncWrapper); 710 711 // Check to see if we already looked up the value. 712 Value *CachedVal = new LoadInst(Cache, "fpcache", EntryBB); 713 Value *IsNull = new SetCondInst(Instruction::SetEQ, CachedVal, 714 NullPtr, "isNull", EntryBB); 715 new BranchInst(LookupBB, DoCallBB, IsNull, EntryBB); 716 717 // Resolve the call to function F via the JIT API: 718 // 719 // call resolver(GetElementPtr...) 720 CallInst *Resolver = new CallInst(resolverFunc, ResolverArgs, 721 "resolver", LookupBB); 722 // cast the result from the resolver to correctly-typed function 723 CastInst *CastedResolver = 724 new CastInst(Resolver, PointerType::get(F->getFunctionType()), 725 "resolverCast", LookupBB); 726 // Save the value in our cache. 727 new StoreInst(CastedResolver, Cache, LookupBB); 728 new BranchInst(DoCallBB, LookupBB); 729 730 PHINode *FuncPtr = new PHINode(NullPtr->getType(), "fp", DoCallBB); 731 FuncPtr->addIncoming(CastedResolver, LookupBB); 732 FuncPtr->addIncoming(CachedVal, EntryBB); 733 734 // Save the argument list. 735 std::vector<Value*> Args; 736 for (Function::arg_iterator i = FuncWrapper->arg_begin(), 737 e = FuncWrapper->arg_end(); i != e; ++i) 738 Args.push_back(i); 739 740 // Pass on the arguments to the real function, return its result 741 if (F->getReturnType() == Type::VoidTy) { 742 CallInst *Call = new CallInst(FuncPtr, Args, "", DoCallBB); 743 new ReturnInst(DoCallBB); 744 } else { 745 CallInst *Call = new CallInst(FuncPtr, Args, "retval", DoCallBB); 746 new ReturnInst(Call, DoCallBB); 747 } 748 749 // Use the wrapper function instead of the old function 750 F->replaceAllUsesWith(FuncWrapper); 751 } 752 } 753 } 754 } 755 756 if (verifyModule(*Test) || verifyModule(*Safe)) { 757 std::cerr << "Bugpoint has a bug, which corrupted a module!!\n"; 758 abort(); 759 } 760 } 761 762 763 764 /// TestCodeGenerator - This is the predicate function used to check to see if 765 /// the "Test" portion of the program is miscompiled by the code generator under 766 /// test. If so, return true. In any case, both module arguments are deleted. 767 /// 768 static bool TestCodeGenerator(BugDriver &BD, Module *Test, Module *Safe) { 769 CleanupAndPrepareModules(BD, Test, Safe); 770 771 sys::Path TestModuleBC("bugpoint.test.bc"); 772 TestModuleBC.makeUnique(); 773 if (BD.writeProgramToFile(TestModuleBC.toString(), Test)) { 774 std::cerr << "Error writing bytecode to `" << TestModuleBC << "'\nExiting."; 775 exit(1); 776 } 777 delete Test; 778 779 // Make the shared library 780 sys::Path SafeModuleBC("bugpoint.safe.bc"); 781 SafeModuleBC.makeUnique(); 782 783 if (BD.writeProgramToFile(SafeModuleBC.toString(), Safe)) { 784 std::cerr << "Error writing bytecode to `" << SafeModuleBC << "'\nExiting."; 785 exit(1); 786 } 787 std::string SharedObject = BD.compileSharedObject(SafeModuleBC.toString()); 788 delete Safe; 789 790 // Run the code generator on the `Test' code, loading the shared library. 791 // The function returns whether or not the new output differs from reference. 792 int Result = BD.diffProgram(TestModuleBC.toString(), SharedObject, false); 793 794 if (Result) 795 std::cerr << ": still failing!\n"; 796 else 797 std::cerr << ": didn't fail.\n"; 798 TestModuleBC.eraseFromDisk(); 799 SafeModuleBC.eraseFromDisk(); 800 sys::Path(SharedObject).eraseFromDisk(); 801 802 return Result; 803 } 804 805 806 /// debugCodeGenerator - debug errors in LLC, LLI, or CBE. 807 /// 808 bool BugDriver::debugCodeGenerator() { 809 if ((void*)cbe == (void*)Interpreter) { 810 std::string Result = executeProgramWithCBE("bugpoint.cbe.out"); 811 std::cout << "\n*** The C backend cannot match the reference diff, but it " 812 << "is used as the 'known good'\n code generator, so I can't" 813 << " debug it. Perhaps you have a front-end problem?\n As a" 814 << " sanity check, I left the result of executing the program " 815 << "with the C backend\n in this file for you: '" 816 << Result << "'.\n"; 817 return true; 818 } 819 820 DisambiguateGlobalSymbols(Program); 821 822 std::vector<Function*> Funcs = DebugAMiscompilation(*this, TestCodeGenerator); 823 824 // Split the module into the two halves of the program we want. 825 Module *ToNotCodeGen = CloneModule(getProgram()); 826 Module *ToCodeGen = SplitFunctionsOutOfModule(ToNotCodeGen, Funcs); 827 828 // Condition the modules 829 CleanupAndPrepareModules(*this, ToCodeGen, ToNotCodeGen); 830 831 sys::Path TestModuleBC("bugpoint.test.bc"); 832 TestModuleBC.makeUnique(); 833 834 if (writeProgramToFile(TestModuleBC.toString(), ToCodeGen)) { 835 std::cerr << "Error writing bytecode to `" << TestModuleBC << "'\nExiting."; 836 exit(1); 837 } 838 delete ToCodeGen; 839 840 // Make the shared library 841 sys::Path SafeModuleBC("bugpoint.safe.bc"); 842 SafeModuleBC.makeUnique(); 843 844 if (writeProgramToFile(SafeModuleBC.toString(), ToNotCodeGen)) { 845 std::cerr << "Error writing bytecode to `" << SafeModuleBC << "'\nExiting."; 846 exit(1); 847 } 848 std::string SharedObject = compileSharedObject(SafeModuleBC.toString()); 849 delete ToNotCodeGen; 850 851 std::cout << "You can reproduce the problem with the command line: \n"; 852 if (isExecutingJIT()) { 853 std::cout << " lli -load " << SharedObject << " " << TestModuleBC; 854 } else { 855 std::cout << " llc -f " << TestModuleBC << " -o " << TestModuleBC<< ".s\n"; 856 std::cout << " gcc " << SharedObject << " " << TestModuleBC 857 << ".s -o " << TestModuleBC << ".exe"; 858 #if defined (HAVE_LINK_R) 859 std::cout << "-Wl,-R."; 860 #endif 861 std::cout << "\n"; 862 std::cout << " " << TestModuleBC << ".exe"; 863 } 864 for (unsigned i=0, e = InputArgv.size(); i != e; ++i) 865 std::cout << " " << InputArgv[i]; 866 std::cout << '\n'; 867 std::cout << "The shared object was created with:\n llc -march=c " 868 << SafeModuleBC << " -o temporary.c\n" 869 << " gcc -xc temporary.c -O2 -o " << SharedObject 870 #if defined(sparc) || defined(__sparc__) || defined(__sparcv9) 871 << " -G" // Compile a shared library, `-G' for Sparc 872 #else 873 << " -shared" // `-shared' for Linux/X86, maybe others 874 #endif 875 << " -fno-strict-aliasing\n"; 876 877 return false; 878 } 879