1 //===- Miscompilation.cpp - Debug program miscompilations -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements optimizer and code generation miscompilation debugging
13 //===----------------------------------------------------------------------===//
15 #include "BugDriver.h"
16 #include "ListReducer.h"
17 #include "ToolRunner.h"
18 #include "llvm/Config/config.h" // for HAVE_LINK_R
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/DerivedTypes.h"
21 #include "llvm/IR/DiagnosticPrinter.h"
22 #include "llvm/IR/Instructions.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IR/Verifier.h"
25 #include "llvm/Linker/Linker.h"
26 #include "llvm/Pass.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/FileUtilities.h"
29 #include "llvm/Transforms/Utils/Cloning.h"
33 extern cl::opt<std::string> OutputPrefix;
34 extern cl::list<std::string> InputArgv;
38 static llvm::cl::opt<bool>
39 DisableLoopExtraction("disable-loop-extraction",
40 cl::desc("Don't extract loops when searching for miscompilations"),
42 static llvm::cl::opt<bool>
43 DisableBlockExtraction("disable-block-extraction",
44 cl::desc("Don't extract blocks when searching for miscompilations"),
47 class ReduceMiscompilingPasses : public ListReducer<std::string> {
50 ReduceMiscompilingPasses(BugDriver &bd) : BD(bd) {}
52 TestResult doTest(std::vector<std::string> &Prefix,
53 std::vector<std::string> &Suffix,
54 std::string &Error) override;
58 /// TestResult - After passes have been split into a test group and a control
59 /// group, see if they still break the program.
61 ReduceMiscompilingPasses::TestResult
62 ReduceMiscompilingPasses::doTest(std::vector<std::string> &Prefix,
63 std::vector<std::string> &Suffix,
65 // First, run the program with just the Suffix passes. If it is still broken
66 // with JUST the kept passes, discard the prefix passes.
67 outs() << "Checking to see if '" << getPassesString(Suffix)
68 << "' compiles correctly: ";
70 std::string BitcodeResult;
71 if (BD.runPasses(BD.getProgram(), Suffix, BitcodeResult, false/*delete*/,
73 errs() << " Error running this sequence of passes"
74 << " on the input program!\n";
75 BD.setPassesToRun(Suffix);
76 BD.EmitProgressBitcode(BD.getProgram(), "pass-error", false);
77 exit(BD.debugOptimizerCrash());
80 // Check to see if the finished program matches the reference output...
81 bool Diff = BD.diffProgram(BD.getProgram(), BitcodeResult, "",
82 true /*delete bitcode*/, &Error);
88 errs() << BD.getToolName() << ": I'm confused: the test fails when "
89 << "no passes are run, nondeterministic program?\n";
92 return KeepSuffix; // Miscompilation detected!
94 outs() << " yup.\n"; // No miscompilation!
96 if (Prefix.empty()) return NoFailure;
98 // Next, see if the program is broken if we run the "prefix" passes first,
99 // then separately run the "kept" passes.
100 outs() << "Checking to see if '" << getPassesString(Prefix)
101 << "' compiles correctly: ";
103 // If it is not broken with the kept passes, it's possible that the prefix
104 // passes must be run before the kept passes to break it. If the program
105 // WORKS after the prefix passes, but then fails if running the prefix AND
106 // kept passes, we can update our bitcode file to include the result of the
107 // prefix passes, then discard the prefix passes.
109 if (BD.runPasses(BD.getProgram(), Prefix, BitcodeResult, false/*delete*/,
111 errs() << " Error running this sequence of passes"
112 << " on the input program!\n";
113 BD.setPassesToRun(Prefix);
114 BD.EmitProgressBitcode(BD.getProgram(), "pass-error", false);
115 exit(BD.debugOptimizerCrash());
118 // If the prefix maintains the predicate by itself, only keep the prefix!
119 Diff = BD.diffProgram(BD.getProgram(), BitcodeResult, "", false, &Error);
121 return InternalError;
123 outs() << " nope.\n";
124 sys::fs::remove(BitcodeResult);
127 outs() << " yup.\n"; // No miscompilation!
129 // Ok, so now we know that the prefix passes work, try running the suffix
130 // passes on the result of the prefix passes.
132 std::unique_ptr<Module> PrefixOutput =
133 parseInputFile(BitcodeResult, BD.getContext());
135 errs() << BD.getToolName() << ": Error reading bitcode file '"
136 << BitcodeResult << "'!\n";
139 sys::fs::remove(BitcodeResult);
141 // Don't check if there are no passes in the suffix.
145 outs() << "Checking to see if '" << getPassesString(Suffix)
146 << "' passes compile correctly after the '"
147 << getPassesString(Prefix) << "' passes: ";
149 std::unique_ptr<Module> OriginalInput(
150 BD.swapProgramIn(PrefixOutput.release()));
151 if (BD.runPasses(BD.getProgram(), Suffix, BitcodeResult, false/*delete*/,
153 errs() << " Error running this sequence of passes"
154 << " on the input program!\n";
155 BD.setPassesToRun(Suffix);
156 BD.EmitProgressBitcode(BD.getProgram(), "pass-error", false);
157 exit(BD.debugOptimizerCrash());
161 Diff = BD.diffProgram(BD.getProgram(), BitcodeResult, "",
162 true /*delete bitcode*/, &Error);
164 return InternalError;
166 outs() << " nope.\n";
170 // Otherwise, we must not be running the bad pass anymore.
171 outs() << " yup.\n"; // No miscompilation!
172 // Restore orig program & free test.
173 delete BD.swapProgramIn(OriginalInput.release());
178 class ReduceMiscompilingFunctions : public ListReducer<Function*> {
180 bool (*TestFn)(BugDriver &, Module *, Module *, std::string &);
182 ReduceMiscompilingFunctions(BugDriver &bd,
183 bool (*F)(BugDriver &, Module *, Module *,
185 : BD(bd), TestFn(F) {}
187 TestResult doTest(std::vector<Function*> &Prefix,
188 std::vector<Function*> &Suffix,
189 std::string &Error) override {
190 if (!Suffix.empty()) {
191 bool Ret = TestFuncs(Suffix, Error);
193 return InternalError;
197 if (!Prefix.empty()) {
198 bool Ret = TestFuncs(Prefix, Error);
200 return InternalError;
207 bool TestFuncs(const std::vector<Function*> &Prefix, std::string &Error);
211 static void diagnosticHandler(const DiagnosticInfo &DI) {
212 DiagnosticPrinterRawOStream DP(errs());
215 if (DI.getSeverity() == DS_Error)
219 /// TestMergedProgram - Given two modules, link them together and run the
220 /// program, checking to see if the program matches the diff. If there is
221 /// an error, return NULL. If not, return the merged module. The Broken argument
222 /// will be set to true if the output is different. If the DeleteInputs
223 /// argument is set to true then this function deletes both input
224 /// modules before it returns.
226 static Module *TestMergedProgram(const BugDriver &BD, Module *M1, Module *M2,
227 bool DeleteInputs, std::string &Error,
229 // Link the two portions of the program back to together.
231 M1 = CloneModule(M1).release();
232 M2 = CloneModule(M2).release();
234 if (Linker::linkModules(*M1, *M2, diagnosticHandler))
236 delete M2; // We are done with this module.
238 // Execute the program.
239 Broken = BD.diffProgram(M1, "", "", false, &Error);
240 if (!Error.empty()) {
241 // Delete the linked module
248 /// TestFuncs - split functions in a Module into two groups: those that are
249 /// under consideration for miscompilation vs. those that are not, and test
250 /// accordingly. Each group of functions becomes a separate Module.
252 bool ReduceMiscompilingFunctions::TestFuncs(const std::vector<Function*> &Funcs,
253 std::string &Error) {
254 // Test to see if the function is misoptimized if we ONLY run it on the
255 // functions listed in Funcs.
256 outs() << "Checking to see if the program is misoptimized when "
257 << (Funcs.size()==1 ? "this function is" : "these functions are")
258 << " run through the pass"
259 << (BD.getPassesToRun().size() == 1 ? "" : "es") << ":";
260 PrintFunctionList(Funcs);
263 // Create a clone for two reasons:
264 // * If the optimization passes delete any function, the deleted function
265 // will be in the clone and Funcs will still point to valid memory
266 // * If the optimization passes use interprocedural information to break
267 // a function, we want to continue with the original function. Otherwise
268 // we can conclude that a function triggers the bug when in fact one
269 // needs a larger set of original functions to do so.
270 ValueToValueMapTy VMap;
271 Module *Clone = CloneModule(BD.getProgram(), VMap).release();
272 Module *Orig = BD.swapProgramIn(Clone);
274 std::vector<Function*> FuncsOnClone;
275 for (unsigned i = 0, e = Funcs.size(); i != e; ++i) {
276 Function *F = cast<Function>(VMap[Funcs[i]]);
277 FuncsOnClone.push_back(F);
280 // Split the module into the two halves of the program we want.
282 Module *ToNotOptimize = CloneModule(BD.getProgram(), VMap).release();
283 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize, FuncsOnClone,
286 // Run the predicate, note that the predicate will delete both input modules.
287 bool Broken = TestFn(BD, ToOptimize, ToNotOptimize, Error);
289 delete BD.swapProgramIn(Orig);
294 /// DisambiguateGlobalSymbols - Give anonymous global values names.
296 static void DisambiguateGlobalSymbols(Module *M) {
297 for (Module::global_iterator I = M->global_begin(), E = M->global_end();
300 I->setName("anon_global");
301 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
303 I->setName("anon_fn");
306 /// ExtractLoops - Given a reduced list of functions that still exposed the bug,
307 /// check to see if we can extract the loops in the region without obscuring the
308 /// bug. If so, it reduces the amount of code identified.
310 static bool ExtractLoops(BugDriver &BD,
311 bool (*TestFn)(BugDriver &, Module *, Module *,
313 std::vector<Function*> &MiscompiledFunctions,
314 std::string &Error) {
315 bool MadeChange = false;
317 if (BugpointIsInterrupted) return MadeChange;
319 ValueToValueMapTy VMap;
320 Module *ToNotOptimize = CloneModule(BD.getProgram(), VMap).release();
321 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
322 MiscompiledFunctions,
324 std::unique_ptr<Module> ToOptimizeLoopExtracted =
325 BD.extractLoop(ToOptimize);
326 if (!ToOptimizeLoopExtracted) {
327 // If the loop extractor crashed or if there were no extractible loops,
328 // then this chapter of our odyssey is over with.
329 delete ToNotOptimize;
334 errs() << "Extracted a loop from the breaking portion of the program.\n";
336 // Bugpoint is intentionally not very trusting of LLVM transformations. In
337 // particular, we're not going to assume that the loop extractor works, so
338 // we're going to test the newly loop extracted program to make sure nothing
339 // has broken. If something broke, then we'll inform the user and stop
341 AbstractInterpreter *AI = BD.switchToSafeInterpreter();
343 Module *New = TestMergedProgram(BD, ToOptimizeLoopExtracted.get(),
344 ToNotOptimize, false, Error, Failure);
348 // Delete the original and set the new program.
349 Module *Old = BD.swapProgramIn(New);
350 for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
351 MiscompiledFunctions[i] = cast<Function>(VMap[MiscompiledFunctions[i]]);
355 BD.switchToInterpreter(AI);
357 // Merged program doesn't work anymore!
358 errs() << " *** ERROR: Loop extraction broke the program. :("
359 << " Please report a bug!\n";
360 errs() << " Continuing on with un-loop-extracted version.\n";
362 BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-tno.bc",
364 BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-to.bc",
366 BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-to-le.bc",
367 ToOptimizeLoopExtracted.get());
369 errs() << "Please submit the "
370 << OutputPrefix << "-loop-extract-fail-*.bc files.\n";
372 delete ToNotOptimize;
376 BD.switchToInterpreter(AI);
378 outs() << " Testing after loop extraction:\n";
379 // Clone modules, the tester function will free them.
380 std::unique_ptr<Module> TOLEBackup =
381 CloneModule(ToOptimizeLoopExtracted.get(), VMap);
382 Module *TNOBackup = CloneModule(ToNotOptimize, VMap).release();
384 for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
385 MiscompiledFunctions[i] = cast<Function>(VMap[MiscompiledFunctions[i]]);
387 Failure = TestFn(BD, ToOptimizeLoopExtracted.get(), ToNotOptimize, Error);
391 ToOptimizeLoopExtracted = std::move(TOLEBackup);
392 ToNotOptimize = TNOBackup;
395 outs() << "*** Loop extraction masked the problem. Undoing.\n";
396 // If the program is not still broken, then loop extraction did something
397 // that masked the error. Stop loop extraction now.
399 std::vector<std::pair<std::string, FunctionType*> > MisCompFunctions;
400 for (Function *F : MiscompiledFunctions) {
401 MisCompFunctions.emplace_back(F->getName(), F->getFunctionType());
404 if (Linker::linkModules(*ToNotOptimize, *ToOptimizeLoopExtracted,
408 MiscompiledFunctions.clear();
409 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
410 Function *NewF = ToNotOptimize->getFunction(MisCompFunctions[i].first);
412 assert(NewF && "Function not found??");
413 MiscompiledFunctions.push_back(NewF);
416 BD.setNewProgram(ToNotOptimize);
420 outs() << "*** Loop extraction successful!\n";
422 std::vector<std::pair<std::string, FunctionType*> > MisCompFunctions;
423 for (Module::iterator I = ToOptimizeLoopExtracted->begin(),
424 E = ToOptimizeLoopExtracted->end(); I != E; ++I)
425 if (!I->isDeclaration())
426 MisCompFunctions.emplace_back(I->getName(), I->getFunctionType());
428 // Okay, great! Now we know that we extracted a loop and that loop
429 // extraction both didn't break the program, and didn't mask the problem.
430 // Replace the current program with the loop extracted version, and try to
431 // extract another loop.
432 if (Linker::linkModules(*ToNotOptimize, *ToOptimizeLoopExtracted,
436 // All of the Function*'s in the MiscompiledFunctions list are in the old
437 // module. Update this list to include all of the functions in the
438 // optimized and loop extracted module.
439 MiscompiledFunctions.clear();
440 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
441 Function *NewF = ToNotOptimize->getFunction(MisCompFunctions[i].first);
443 assert(NewF && "Function not found??");
444 MiscompiledFunctions.push_back(NewF);
447 BD.setNewProgram(ToNotOptimize);
453 class ReduceMiscompiledBlocks : public ListReducer<BasicBlock*> {
455 bool (*TestFn)(BugDriver &, Module *, Module *, std::string &);
456 std::vector<Function*> FunctionsBeingTested;
458 ReduceMiscompiledBlocks(BugDriver &bd,
459 bool (*F)(BugDriver &, Module *, Module *,
461 const std::vector<Function*> &Fns)
462 : BD(bd), TestFn(F), FunctionsBeingTested(Fns) {}
464 TestResult doTest(std::vector<BasicBlock*> &Prefix,
465 std::vector<BasicBlock*> &Suffix,
466 std::string &Error) override {
467 if (!Suffix.empty()) {
468 bool Ret = TestFuncs(Suffix, Error);
470 return InternalError;
474 if (!Prefix.empty()) {
475 bool Ret = TestFuncs(Prefix, Error);
477 return InternalError;
484 bool TestFuncs(const std::vector<BasicBlock*> &BBs, std::string &Error);
488 /// TestFuncs - Extract all blocks for the miscompiled functions except for the
489 /// specified blocks. If the problem still exists, return true.
491 bool ReduceMiscompiledBlocks::TestFuncs(const std::vector<BasicBlock*> &BBs,
492 std::string &Error) {
493 // Test to see if the function is misoptimized if we ONLY run it on the
494 // functions listed in Funcs.
495 outs() << "Checking to see if the program is misoptimized when all ";
497 outs() << "but these " << BBs.size() << " blocks are extracted: ";
498 for (unsigned i = 0, e = BBs.size() < 10 ? BBs.size() : 10; i != e; ++i)
499 outs() << BBs[i]->getName() << " ";
500 if (BBs.size() > 10) outs() << "...";
502 outs() << "blocks are extracted.";
506 // Split the module into the two halves of the program we want.
507 ValueToValueMapTy VMap;
508 Module *Clone = CloneModule(BD.getProgram(), VMap).release();
509 Module *Orig = BD.swapProgramIn(Clone);
510 std::vector<Function*> FuncsOnClone;
511 std::vector<BasicBlock*> BBsOnClone;
512 for (unsigned i = 0, e = FunctionsBeingTested.size(); i != e; ++i) {
513 Function *F = cast<Function>(VMap[FunctionsBeingTested[i]]);
514 FuncsOnClone.push_back(F);
516 for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
517 BasicBlock *BB = cast<BasicBlock>(VMap[BBs[i]]);
518 BBsOnClone.push_back(BB);
522 Module *ToNotOptimize = CloneModule(BD.getProgram(), VMap).release();
523 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
527 // Try the extraction. If it doesn't work, then the block extractor crashed
528 // or something, in which case bugpoint can't chase down this possibility.
529 if (std::unique_ptr<Module> New =
530 BD.extractMappedBlocksFromModule(BBsOnClone, ToOptimize)) {
532 // Run the predicate,
533 // note that the predicate will delete both input modules.
534 bool Ret = TestFn(BD, New.get(), ToNotOptimize, Error);
535 delete BD.swapProgramIn(Orig);
538 delete BD.swapProgramIn(Orig);
540 delete ToNotOptimize;
545 /// ExtractBlocks - Given a reduced list of functions that still expose the bug,
546 /// extract as many basic blocks from the region as possible without obscuring
549 static bool ExtractBlocks(BugDriver &BD,
550 bool (*TestFn)(BugDriver &, Module *, Module *,
552 std::vector<Function*> &MiscompiledFunctions,
553 std::string &Error) {
554 if (BugpointIsInterrupted) return false;
556 std::vector<BasicBlock*> Blocks;
557 for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
558 for (BasicBlock &BB : *MiscompiledFunctions[i])
559 Blocks.push_back(&BB);
561 // Use the list reducer to identify blocks that can be extracted without
562 // obscuring the bug. The Blocks list will end up containing blocks that must
563 // be retained from the original program.
564 unsigned OldSize = Blocks.size();
566 // Check to see if all blocks are extractible first.
567 bool Ret = ReduceMiscompiledBlocks(BD, TestFn, MiscompiledFunctions)
568 .TestFuncs(std::vector<BasicBlock*>(), Error);
574 ReduceMiscompiledBlocks(BD, TestFn,
575 MiscompiledFunctions).reduceList(Blocks, Error);
578 if (Blocks.size() == OldSize)
582 ValueToValueMapTy VMap;
583 Module *ProgClone = CloneModule(BD.getProgram(), VMap).release();
584 Module *ToExtract = SplitFunctionsOutOfModule(ProgClone,
585 MiscompiledFunctions,
587 std::unique_ptr<Module> Extracted =
588 BD.extractMappedBlocksFromModule(Blocks, ToExtract);
590 // Weird, extraction should have worked.
591 errs() << "Nondeterministic problem extracting blocks??\n";
597 // Otherwise, block extraction succeeded. Link the two program fragments back
601 std::vector<std::pair<std::string, FunctionType*> > MisCompFunctions;
602 for (Module::iterator I = Extracted->begin(), E = Extracted->end();
604 if (!I->isDeclaration())
605 MisCompFunctions.emplace_back(I->getName(), I->getFunctionType());
607 if (Linker::linkModules(*ProgClone, *Extracted, diagnosticHandler))
610 // Set the new program and delete the old one.
611 BD.setNewProgram(ProgClone);
613 // Update the list of miscompiled functions.
614 MiscompiledFunctions.clear();
616 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
617 Function *NewF = ProgClone->getFunction(MisCompFunctions[i].first);
618 assert(NewF && "Function not found??");
619 MiscompiledFunctions.push_back(NewF);
626 /// DebugAMiscompilation - This is a generic driver to narrow down
627 /// miscompilations, either in an optimization or a code generator.
629 static std::vector<Function*>
630 DebugAMiscompilation(BugDriver &BD,
631 bool (*TestFn)(BugDriver &, Module *, Module *,
633 std::string &Error) {
634 // Okay, now that we have reduced the list of passes which are causing the
635 // failure, see if we can pin down which functions are being
636 // miscompiled... first build a list of all of the non-external functions in
638 std::vector<Function*> MiscompiledFunctions;
639 Module *Prog = BD.getProgram();
640 for (Function &F : *Prog)
641 if (!F.isDeclaration())
642 MiscompiledFunctions.push_back(&F);
644 // Do the reduction...
645 if (!BugpointIsInterrupted)
646 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions,
648 if (!Error.empty()) {
649 errs() << "\n***Cannot reduce functions: ";
650 return MiscompiledFunctions;
652 outs() << "\n*** The following function"
653 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
654 << " being miscompiled: ";
655 PrintFunctionList(MiscompiledFunctions);
658 // See if we can rip any loops out of the miscompiled functions and still
659 // trigger the problem.
661 if (!BugpointIsInterrupted && !DisableLoopExtraction) {
662 bool Ret = ExtractLoops(BD, TestFn, MiscompiledFunctions, Error);
664 return MiscompiledFunctions;
666 // Okay, we extracted some loops and the problem still appears. See if
667 // we can eliminate some of the created functions from being candidates.
668 DisambiguateGlobalSymbols(BD.getProgram());
670 // Do the reduction...
671 if (!BugpointIsInterrupted)
672 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions,
675 return MiscompiledFunctions;
677 outs() << "\n*** The following function"
678 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
679 << " being miscompiled: ";
680 PrintFunctionList(MiscompiledFunctions);
685 if (!BugpointIsInterrupted && !DisableBlockExtraction) {
686 bool Ret = ExtractBlocks(BD, TestFn, MiscompiledFunctions, Error);
688 return MiscompiledFunctions;
690 // Okay, we extracted some blocks and the problem still appears. See if
691 // we can eliminate some of the created functions from being candidates.
692 DisambiguateGlobalSymbols(BD.getProgram());
694 // Do the reduction...
695 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions,
698 return MiscompiledFunctions;
700 outs() << "\n*** The following function"
701 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
702 << " being miscompiled: ";
703 PrintFunctionList(MiscompiledFunctions);
708 return MiscompiledFunctions;
711 /// TestOptimizer - This is the predicate function used to check to see if the
712 /// "Test" portion of the program is misoptimized. If so, return true. In any
713 /// case, both module arguments are deleted.
715 static bool TestOptimizer(BugDriver &BD, Module *Test, Module *Safe,
716 std::string &Error) {
717 // Run the optimization passes on ToOptimize, producing a transformed version
718 // of the functions being tested.
719 outs() << " Optimizing functions being tested: ";
720 std::unique_ptr<Module> Optimized = BD.runPassesOn(Test, BD.getPassesToRun(),
721 /*AutoDebugCrashes*/ true);
725 outs() << " Checking to see if the merged program executes correctly: ";
728 TestMergedProgram(BD, Optimized.get(), Safe, true, Error, Broken);
730 outs() << (Broken ? " nope.\n" : " yup.\n");
731 // Delete the original and set the new program.
732 delete BD.swapProgramIn(New);
738 /// debugMiscompilation - This method is used when the passes selected are not
739 /// crashing, but the generated output is semantically different from the
742 void BugDriver::debugMiscompilation(std::string *Error) {
743 // Make sure something was miscompiled...
744 if (!BugpointIsInterrupted)
745 if (!ReduceMiscompilingPasses(*this).reduceList(PassesToRun, *Error)) {
747 errs() << "*** Optimized program matches reference output! No problem"
748 << " detected...\nbugpoint can't help you with your problem!\n";
752 outs() << "\n*** Found miscompiling pass"
753 << (getPassesToRun().size() == 1 ? "" : "es") << ": "
754 << getPassesString(getPassesToRun()) << '\n';
755 EmitProgressBitcode(Program, "passinput");
757 std::vector<Function *> MiscompiledFunctions =
758 DebugAMiscompilation(*this, TestOptimizer, *Error);
762 // Output a bunch of bitcode files for the user...
763 outs() << "Outputting reduced bitcode files which expose the problem:\n";
764 ValueToValueMapTy VMap;
765 Module *ToNotOptimize = CloneModule(getProgram(), VMap).release();
766 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
767 MiscompiledFunctions,
770 outs() << " Non-optimized portion: ";
771 EmitProgressBitcode(ToNotOptimize, "tonotoptimize", true);
772 delete ToNotOptimize; // Delete hacked module.
774 outs() << " Portion that is input to optimizer: ";
775 EmitProgressBitcode(ToOptimize, "tooptimize");
776 delete ToOptimize; // Delete hacked module.
781 /// CleanupAndPrepareModules - Get the specified modules ready for code
782 /// generator testing.
784 static void CleanupAndPrepareModules(BugDriver &BD, Module *&Test,
786 // Clean up the modules, removing extra cruft that we don't need anymore...
787 Test = BD.performFinalCleanups(Test).release();
789 // If we are executing the JIT, we have several nasty issues to take care of.
790 if (!BD.isExecutingJIT()) return;
792 // First, if the main function is in the Safe module, we must add a stub to
793 // the Test module to call into it. Thus, we create a new function `main'
794 // which just calls the old one.
795 if (Function *oldMain = Safe->getFunction("main"))
796 if (!oldMain->isDeclaration()) {
798 oldMain->setName("llvm_bugpoint_old_main");
799 // Create a NEW `main' function with same type in the test module.
800 Function *newMain = Function::Create(oldMain->getFunctionType(),
801 GlobalValue::ExternalLinkage,
803 // Create an `oldmain' prototype in the test module, which will
804 // corresponds to the real main function in the same module.
805 Function *oldMainProto = Function::Create(oldMain->getFunctionType(),
806 GlobalValue::ExternalLinkage,
807 oldMain->getName(), Test);
808 // Set up and remember the argument list for the main function.
809 std::vector<Value*> args;
810 for (Function::arg_iterator
811 I = newMain->arg_begin(), E = newMain->arg_end(),
812 OI = oldMain->arg_begin(); I != E; ++I, ++OI) {
813 I->setName(OI->getName()); // Copy argument names from oldMain
817 // Call the old main function and return its result
818 BasicBlock *BB = BasicBlock::Create(Safe->getContext(), "entry", newMain);
819 CallInst *call = CallInst::Create(oldMainProto, args, "", BB);
821 // If the type of old function wasn't void, return value of call
822 ReturnInst::Create(Safe->getContext(), call, BB);
825 // The second nasty issue we must deal with in the JIT is that the Safe
826 // module cannot directly reference any functions defined in the test
827 // module. Instead, we use a JIT API call to dynamically resolve the
830 // Add the resolver to the Safe module.
831 // Prototype: void *getPointerToNamedFunction(const char* Name)
832 Constant *resolverFunc =
833 Safe->getOrInsertFunction("getPointerToNamedFunction",
834 Type::getInt8PtrTy(Safe->getContext()),
835 Type::getInt8PtrTy(Safe->getContext()),
838 // Use the function we just added to get addresses of functions we need.
839 for (Module::iterator F = Safe->begin(), E = Safe->end(); F != E; ++F) {
840 if (F->isDeclaration() && !F->use_empty() && &*F != resolverFunc &&
841 !F->isIntrinsic() /* ignore intrinsics */) {
842 Function *TestFn = Test->getFunction(F->getName());
844 // Don't forward functions which are external in the test module too.
845 if (TestFn && !TestFn->isDeclaration()) {
846 // 1. Add a string constant with its name to the global file
847 Constant *InitArray =
848 ConstantDataArray::getString(F->getContext(), F->getName());
849 GlobalVariable *funcName =
850 new GlobalVariable(*Safe, InitArray->getType(), true /*isConstant*/,
851 GlobalValue::InternalLinkage, InitArray,
852 F->getName() + "_name");
854 // 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an
855 // sbyte* so it matches the signature of the resolver function.
857 // GetElementPtr *funcName, ulong 0, ulong 0
858 std::vector<Constant*> GEPargs(2,
859 Constant::getNullValue(Type::getInt32Ty(F->getContext())));
860 Value *GEP = ConstantExpr::getGetElementPtr(InitArray->getType(),
862 std::vector<Value*> ResolverArgs;
863 ResolverArgs.push_back(GEP);
865 // Rewrite uses of F in global initializers, etc. to uses of a wrapper
866 // function that dynamically resolves the calls to F via our JIT API
867 if (!F->use_empty()) {
868 // Create a new global to hold the cached function pointer.
869 Constant *NullPtr = ConstantPointerNull::get(F->getType());
870 GlobalVariable *Cache =
871 new GlobalVariable(*F->getParent(), F->getType(),
872 false, GlobalValue::InternalLinkage,
873 NullPtr,F->getName()+".fpcache");
875 // Construct a new stub function that will re-route calls to F
876 FunctionType *FuncTy = F->getFunctionType();
877 Function *FuncWrapper = Function::Create(FuncTy,
878 GlobalValue::InternalLinkage,
879 F->getName() + "_wrapper",
881 BasicBlock *EntryBB = BasicBlock::Create(F->getContext(),
882 "entry", FuncWrapper);
883 BasicBlock *DoCallBB = BasicBlock::Create(F->getContext(),
884 "usecache", FuncWrapper);
885 BasicBlock *LookupBB = BasicBlock::Create(F->getContext(),
886 "lookupfp", FuncWrapper);
888 // Check to see if we already looked up the value.
889 Value *CachedVal = new LoadInst(Cache, "fpcache", EntryBB);
890 Value *IsNull = new ICmpInst(*EntryBB, ICmpInst::ICMP_EQ, CachedVal,
892 BranchInst::Create(LookupBB, DoCallBB, IsNull, EntryBB);
894 // Resolve the call to function F via the JIT API:
896 // call resolver(GetElementPtr...)
898 CallInst::Create(resolverFunc, ResolverArgs, "resolver", LookupBB);
900 // Cast the result from the resolver to correctly-typed function.
901 CastInst *CastedResolver =
902 new BitCastInst(Resolver,
903 PointerType::getUnqual(F->getFunctionType()),
904 "resolverCast", LookupBB);
906 // Save the value in our cache.
907 new StoreInst(CastedResolver, Cache, LookupBB);
908 BranchInst::Create(DoCallBB, LookupBB);
910 PHINode *FuncPtr = PHINode::Create(NullPtr->getType(), 2,
912 FuncPtr->addIncoming(CastedResolver, LookupBB);
913 FuncPtr->addIncoming(CachedVal, EntryBB);
915 // Save the argument list.
916 std::vector<Value*> Args;
917 for (Argument &A : FuncWrapper->args())
920 // Pass on the arguments to the real function, return its result
921 if (F->getReturnType()->isVoidTy()) {
922 CallInst::Create(FuncPtr, Args, "", DoCallBB);
923 ReturnInst::Create(F->getContext(), DoCallBB);
925 CallInst *Call = CallInst::Create(FuncPtr, Args,
927 ReturnInst::Create(F->getContext(),Call, DoCallBB);
930 // Use the wrapper function instead of the old function
931 F->replaceAllUsesWith(FuncWrapper);
937 if (verifyModule(*Test) || verifyModule(*Safe)) {
938 errs() << "Bugpoint has a bug, which corrupted a module!!\n";
945 /// TestCodeGenerator - This is the predicate function used to check to see if
946 /// the "Test" portion of the program is miscompiled by the code generator under
947 /// test. If so, return true. In any case, both module arguments are deleted.
949 static bool TestCodeGenerator(BugDriver &BD, Module *Test, Module *Safe,
950 std::string &Error) {
951 CleanupAndPrepareModules(BD, Test, Safe);
953 SmallString<128> TestModuleBC;
955 std::error_code EC = sys::fs::createTemporaryFile("bugpoint.test", "bc",
956 TestModuleFD, TestModuleBC);
958 errs() << BD.getToolName() << "Error making unique filename: "
959 << EC.message() << "\n";
962 if (BD.writeProgramToFile(TestModuleBC.str(), TestModuleFD, Test)) {
963 errs() << "Error writing bitcode to `" << TestModuleBC.str()
969 FileRemover TestModuleBCRemover(TestModuleBC.str(), !SaveTemps);
971 // Make the shared library
972 SmallString<128> SafeModuleBC;
974 EC = sys::fs::createTemporaryFile("bugpoint.safe", "bc", SafeModuleFD,
977 errs() << BD.getToolName() << "Error making unique filename: "
978 << EC.message() << "\n";
982 if (BD.writeProgramToFile(SafeModuleBC.str(), SafeModuleFD, Safe)) {
983 errs() << "Error writing bitcode to `" << SafeModuleBC
988 FileRemover SafeModuleBCRemover(SafeModuleBC.str(), !SaveTemps);
990 std::string SharedObject = BD.compileSharedObject(SafeModuleBC.str(), Error);
995 FileRemover SharedObjectRemover(SharedObject, !SaveTemps);
997 // Run the code generator on the `Test' code, loading the shared library.
998 // The function returns whether or not the new output differs from reference.
999 bool Result = BD.diffProgram(BD.getProgram(), TestModuleBC.str(),
1000 SharedObject, false, &Error);
1005 errs() << ": still failing!\n";
1007 errs() << ": didn't fail.\n";
1013 /// debugCodeGenerator - debug errors in LLC, LLI, or CBE.
1015 bool BugDriver::debugCodeGenerator(std::string *Error) {
1016 if ((void*)SafeInterpreter == (void*)Interpreter) {
1017 std::string Result = executeProgramSafely(Program, "bugpoint.safe.out",
1019 if (Error->empty()) {
1020 outs() << "\n*** The \"safe\" i.e. 'known good' backend cannot match "
1021 << "the reference diff. This may be due to a\n front-end "
1022 << "bug or a bug in the original program, but this can also "
1023 << "happen if bugpoint isn't running the program with the "
1024 << "right flags or input.\n I left the result of executing "
1025 << "the program with the \"safe\" backend in this file for "
1027 << Result << "'.\n";
1032 DisambiguateGlobalSymbols(Program);
1034 std::vector<Function*> Funcs = DebugAMiscompilation(*this, TestCodeGenerator,
1036 if (!Error->empty())
1039 // Split the module into the two halves of the program we want.
1040 ValueToValueMapTy VMap;
1041 Module *ToNotCodeGen = CloneModule(getProgram(), VMap).release();
1042 Module *ToCodeGen = SplitFunctionsOutOfModule(ToNotCodeGen, Funcs, VMap);
1044 // Condition the modules
1045 CleanupAndPrepareModules(*this, ToCodeGen, ToNotCodeGen);
1047 SmallString<128> TestModuleBC;
1049 std::error_code EC = sys::fs::createTemporaryFile("bugpoint.test", "bc",
1050 TestModuleFD, TestModuleBC);
1052 errs() << getToolName() << "Error making unique filename: "
1053 << EC.message() << "\n";
1057 if (writeProgramToFile(TestModuleBC.str(), TestModuleFD, ToCodeGen)) {
1058 errs() << "Error writing bitcode to `" << TestModuleBC
1064 // Make the shared library
1065 SmallString<128> SafeModuleBC;
1067 EC = sys::fs::createTemporaryFile("bugpoint.safe", "bc", SafeModuleFD,
1070 errs() << getToolName() << "Error making unique filename: "
1071 << EC.message() << "\n";
1075 if (writeProgramToFile(SafeModuleBC.str(), SafeModuleFD, ToNotCodeGen)) {
1076 errs() << "Error writing bitcode to `" << SafeModuleBC
1080 std::string SharedObject = compileSharedObject(SafeModuleBC.str(), *Error);
1081 if (!Error->empty())
1083 delete ToNotCodeGen;
1085 outs() << "You can reproduce the problem with the command line: \n";
1086 if (isExecutingJIT()) {
1087 outs() << " lli -load " << SharedObject << " " << TestModuleBC;
1089 outs() << " llc " << TestModuleBC << " -o " << TestModuleBC
1091 outs() << " cc " << SharedObject << " " << TestModuleBC.str()
1092 << ".s -o " << TestModuleBC << ".exe";
1093 #if defined (HAVE_LINK_R)
1094 outs() << " -Wl,-R.";
1097 outs() << " " << TestModuleBC << ".exe";
1099 for (unsigned i = 0, e = InputArgv.size(); i != e; ++i)
1100 outs() << " " << InputArgv[i];
1102 outs() << "The shared object was created with:\n llc -march=c "
1103 << SafeModuleBC.str() << " -o temporary.c\n"
1104 << " cc -xc temporary.c -O2 -o " << SharedObject;
1105 if (TargetTriple.getArch() == Triple::sparc)
1106 outs() << " -G"; // Compile a shared library, `-G' for Sparc
1108 outs() << " -fPIC -shared"; // `-shared' for Linux/X86, maybe others
1110 outs() << " -fno-strict-aliasing\n";