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/Instructions.h"
22 #include "llvm/IR/Module.h"
23 #include "llvm/IR/Verifier.h"
24 #include "llvm/Linker/Linker.h"
25 #include "llvm/Pass.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/FileUtilities.h"
28 #include "llvm/Transforms/Utils/Cloning.h"
33 extern cl::opt<std::string> OutputPrefix;
34 extern cl::list<std::string> InputArgv;
35 } // end namespace llvm
38 static llvm::cl::opt<bool> DisableLoopExtraction(
39 "disable-loop-extraction",
40 cl::desc("Don't extract loops when searching for miscompilations"),
42 static llvm::cl::opt<bool> DisableBlockExtraction(
43 "disable-block-extraction",
44 cl::desc("Don't extract blocks when searching for miscompilations"),
47 class ReduceMiscompilingPasses : public ListReducer<std::string> {
51 ReduceMiscompilingPasses(BugDriver &bd) : BD(bd) {}
53 Expected<TestResult> doTest(std::vector<std::string> &Prefix,
54 std::vector<std::string> &Suffix) override;
56 } // end anonymous namespace
58 /// TestResult - After passes have been split into a test group and a control
59 /// group, see if they still break the program.
61 Expected<ReduceMiscompilingPasses::TestResult>
62 ReduceMiscompilingPasses::doTest(std::vector<std::string> &Prefix,
63 std::vector<std::string> &Suffix) {
64 // First, run the program with just the Suffix passes. If it is still broken
65 // with JUST the kept passes, discard the prefix passes.
66 outs() << "Checking to see if '" << getPassesString(Suffix)
67 << "' compiles correctly: ";
69 std::string BitcodeResult;
70 if (BD.runPasses(BD.getProgram(), Suffix, BitcodeResult, false /*delete*/,
72 errs() << " Error running this sequence of passes"
73 << " on the input program!\n";
74 BD.setPassesToRun(Suffix);
75 BD.EmitProgressBitcode(BD.getProgram(), "pass-error", false);
76 // TODO: This should propagate the error instead of exiting.
77 if (Error E = BD.debugOptimizerCrash())
82 // Check to see if the finished program matches the reference output...
83 Expected<bool> Diff = BD.diffProgram(BD.getProgram(), BitcodeResult, "",
84 true /*delete bitcode*/);
85 if (Error E = Diff.takeError())
90 errs() << BD.getToolName() << ": I'm confused: the test fails when "
91 << "no passes are run, nondeterministic program?\n";
94 return KeepSuffix; // Miscompilation detected!
96 outs() << " yup.\n"; // No miscompilation!
101 // Next, see if the program is broken if we run the "prefix" passes first,
102 // then separately run the "kept" passes.
103 outs() << "Checking to see if '" << getPassesString(Prefix)
104 << "' compiles correctly: ";
106 // If it is not broken with the kept passes, it's possible that the prefix
107 // passes must be run before the kept passes to break it. If the program
108 // WORKS after the prefix passes, but then fails if running the prefix AND
109 // kept passes, we can update our bitcode file to include the result of the
110 // prefix passes, then discard the prefix passes.
112 if (BD.runPasses(BD.getProgram(), Prefix, BitcodeResult, false /*delete*/,
114 errs() << " Error running this sequence of passes"
115 << " on the input program!\n";
116 BD.setPassesToRun(Prefix);
117 BD.EmitProgressBitcode(BD.getProgram(), "pass-error", false);
118 // TODO: This should propagate the error instead of exiting.
119 if (Error E = BD.debugOptimizerCrash())
124 // If the prefix maintains the predicate by itself, only keep the prefix!
125 Diff = BD.diffProgram(BD.getProgram(), BitcodeResult, "", false);
126 if (Error E = Diff.takeError())
129 outs() << " nope.\n";
130 sys::fs::remove(BitcodeResult);
133 outs() << " yup.\n"; // No miscompilation!
135 // Ok, so now we know that the prefix passes work, try running the suffix
136 // passes on the result of the prefix passes.
138 std::unique_ptr<Module> PrefixOutput =
139 parseInputFile(BitcodeResult, BD.getContext());
141 errs() << BD.getToolName() << ": Error reading bitcode file '"
142 << BitcodeResult << "'!\n";
145 sys::fs::remove(BitcodeResult);
147 // Don't check if there are no passes in the suffix.
151 outs() << "Checking to see if '" << getPassesString(Suffix)
152 << "' passes compile correctly after the '" << getPassesString(Prefix)
155 std::unique_ptr<Module> OriginalInput(
156 BD.swapProgramIn(PrefixOutput.release()));
157 if (BD.runPasses(BD.getProgram(), Suffix, BitcodeResult, false /*delete*/,
159 errs() << " Error running this sequence of passes"
160 << " on the input program!\n";
161 BD.setPassesToRun(Suffix);
162 BD.EmitProgressBitcode(BD.getProgram(), "pass-error", false);
163 // TODO: This should propagate the error instead of exiting.
164 if (Error E = BD.debugOptimizerCrash())
170 Diff = BD.diffProgram(BD.getProgram(), BitcodeResult, "",
171 true /*delete bitcode*/);
172 if (Error E = Diff.takeError())
175 outs() << " nope.\n";
179 // Otherwise, we must not be running the bad pass anymore.
180 outs() << " yup.\n"; // No miscompilation!
181 // Restore orig program & free test.
182 delete BD.swapProgramIn(OriginalInput.release());
187 class ReduceMiscompilingFunctions : public ListReducer<Function *> {
189 Expected<bool> (*TestFn)(BugDriver &, std::unique_ptr<Module>,
190 std::unique_ptr<Module>);
193 ReduceMiscompilingFunctions(BugDriver &bd,
194 Expected<bool> (*F)(BugDriver &,
195 std::unique_ptr<Module>,
196 std::unique_ptr<Module>))
197 : BD(bd), TestFn(F) {}
199 Expected<TestResult> doTest(std::vector<Function *> &Prefix,
200 std::vector<Function *> &Suffix) override {
201 if (!Suffix.empty()) {
202 Expected<bool> Ret = TestFuncs(Suffix);
203 if (Error E = Ret.takeError())
208 if (!Prefix.empty()) {
209 Expected<bool> Ret = TestFuncs(Prefix);
210 if (Error E = Ret.takeError())
218 Expected<bool> TestFuncs(const std::vector<Function *> &Prefix);
220 } // end anonymous namespace
222 /// Given two modules, link them together and run the program, checking to see
223 /// if the program matches the diff. If there is an error, return NULL. If not,
224 /// return the merged module. The Broken argument will be set to true if the
225 /// output is different. If the DeleteInputs argument is set to true then this
226 /// function deletes both input modules before it returns.
228 static Expected<std::unique_ptr<Module>> testMergedProgram(const BugDriver &BD,
232 // Resulting merge of M1 and M2.
233 auto Merged = CloneModule(&M1);
234 if (Linker::linkModules(*Merged, CloneModule(&M2)))
235 // TODO: Shouldn't we thread the error up instead of exiting?
238 // Execute the program.
239 Expected<bool> Diff = BD.diffProgram(Merged.get(), "", "", false);
240 if (Error E = Diff.takeError())
243 return std::move(Merged);
246 /// TestFuncs - split functions in a Module into two groups: those that are
247 /// under consideration for miscompilation vs. those that are not, and test
248 /// accordingly. Each group of functions becomes a separate Module.
251 ReduceMiscompilingFunctions::TestFuncs(const std::vector<Function *> &Funcs) {
252 // Test to see if the function is misoptimized if we ONLY run it on the
253 // functions listed in Funcs.
254 outs() << "Checking to see if the program is misoptimized when "
255 << (Funcs.size() == 1 ? "this function is" : "these functions are")
256 << " run through the pass"
257 << (BD.getPassesToRun().size() == 1 ? "" : "es") << ":";
258 PrintFunctionList(Funcs);
261 // Create a clone for two reasons:
262 // * If the optimization passes delete any function, the deleted function
263 // will be in the clone and Funcs will still point to valid memory
264 // * If the optimization passes use interprocedural information to break
265 // a function, we want to continue with the original function. Otherwise
266 // we can conclude that a function triggers the bug when in fact one
267 // needs a larger set of original functions to do so.
268 ValueToValueMapTy VMap;
269 Module *Clone = CloneModule(BD.getProgram(), VMap).release();
270 Module *Orig = BD.swapProgramIn(Clone);
272 std::vector<Function *> FuncsOnClone;
273 for (unsigned i = 0, e = Funcs.size(); i != e; ++i) {
274 Function *F = cast<Function>(VMap[Funcs[i]]);
275 FuncsOnClone.push_back(F);
278 // Split the module into the two halves of the program we want.
280 std::unique_ptr<Module> ToNotOptimize = CloneModule(BD.getProgram(), VMap);
281 std::unique_ptr<Module> ToOptimize =
282 SplitFunctionsOutOfModule(ToNotOptimize.get(), FuncsOnClone, VMap);
284 Expected<bool> Broken =
285 TestFn(BD, std::move(ToOptimize), std::move(ToNotOptimize));
287 delete BD.swapProgramIn(Orig);
292 /// DisambiguateGlobalSymbols - Give anonymous global values names.
294 static void DisambiguateGlobalSymbols(Module *M) {
295 for (Module::global_iterator I = M->global_begin(), E = M->global_end();
298 I->setName("anon_global");
299 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
301 I->setName("anon_fn");
304 /// Given a reduced list of functions that still exposed the bug, check to see
305 /// if we can extract the loops in the region without obscuring the bug. If so,
306 /// it reduces the amount of code identified.
308 static Expected<bool>
309 ExtractLoops(BugDriver &BD,
310 Expected<bool> (*TestFn)(BugDriver &, std::unique_ptr<Module>,
311 std::unique_ptr<Module>),
312 std::vector<Function *> &MiscompiledFunctions) {
313 bool MadeChange = false;
315 if (BugpointIsInterrupted)
318 ValueToValueMapTy VMap;
319 std::unique_ptr<Module> ToNotOptimize = CloneModule(BD.getProgram(), VMap);
320 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize.get(),
321 MiscompiledFunctions, VMap)
323 std::unique_ptr<Module> ToOptimizeLoopExtracted =
324 BD.extractLoop(ToOptimize);
325 if (!ToOptimizeLoopExtracted) {
326 // If the loop extractor crashed or if there were no extractible loops,
327 // then this chapter of our odyssey is over with.
332 errs() << "Extracted a loop from the breaking portion of the program.\n";
334 // Bugpoint is intentionally not very trusting of LLVM transformations. In
335 // particular, we're not going to assume that the loop extractor works, so
336 // we're going to test the newly loop extracted program to make sure nothing
337 // has broken. If something broke, then we'll inform the user and stop
339 AbstractInterpreter *AI = BD.switchToSafeInterpreter();
341 Expected<std::unique_ptr<Module>> New = testMergedProgram(
342 BD, *ToOptimizeLoopExtracted, *ToNotOptimize, Failure);
343 if (Error E = New.takeError())
348 // Delete the original and set the new program.
349 Module *Old = BD.swapProgramIn(New->release());
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",
363 ToNotOptimize.get());
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 " << OutputPrefix
370 << "-loop-extract-fail-*.bc files.\n";
375 BD.switchToInterpreter(AI);
377 outs() << " Testing after loop extraction:\n";
378 // Clone modules, the tester function will free them.
379 std::unique_ptr<Module> TOLEBackup =
380 CloneModule(ToOptimizeLoopExtracted.get(), VMap);
381 std::unique_ptr<Module> TNOBackup = CloneModule(ToNotOptimize.get(), VMap);
383 for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
384 MiscompiledFunctions[i] = cast<Function>(VMap[MiscompiledFunctions[i]]);
386 Expected<bool> Result = TestFn(BD, std::move(ToOptimizeLoopExtracted),
387 std::move(ToNotOptimize));
388 if (Error E = Result.takeError())
391 ToOptimizeLoopExtracted = std::move(TOLEBackup);
392 ToNotOptimize = std::move(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,
405 std::move(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.release());
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();
426 if (!I->isDeclaration())
427 MisCompFunctions.emplace_back(I->getName(), I->getFunctionType());
429 // Okay, great! Now we know that we extracted a loop and that loop
430 // extraction both didn't break the program, and didn't mask the problem.
431 // Replace the current program with the loop extracted version, and try to
432 // extract another loop.
433 if (Linker::linkModules(*ToNotOptimize, std::move(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.release());
453 class ReduceMiscompiledBlocks : public ListReducer<BasicBlock *> {
455 Expected<bool> (*TestFn)(BugDriver &, std::unique_ptr<Module>,
456 std::unique_ptr<Module>);
457 std::vector<Function *> FunctionsBeingTested;
460 ReduceMiscompiledBlocks(BugDriver &bd,
461 Expected<bool> (*F)(BugDriver &,
462 std::unique_ptr<Module>,
463 std::unique_ptr<Module>),
464 const std::vector<Function *> &Fns)
465 : BD(bd), TestFn(F), FunctionsBeingTested(Fns) {}
467 Expected<TestResult> doTest(std::vector<BasicBlock *> &Prefix,
468 std::vector<BasicBlock *> &Suffix) override {
469 if (!Suffix.empty()) {
470 Expected<bool> Ret = TestFuncs(Suffix);
471 if (Error E = Ret.takeError())
476 if (!Prefix.empty()) {
477 Expected<bool> Ret = TestFuncs(Prefix);
478 if (Error E = Ret.takeError())
486 Expected<bool> TestFuncs(const std::vector<BasicBlock *> &BBs);
488 } // end anonymous namespace
490 /// TestFuncs - Extract all blocks for the miscompiled functions except for the
491 /// specified blocks. If the problem still exists, return true.
494 ReduceMiscompiledBlocks::TestFuncs(const std::vector<BasicBlock *> &BBs) {
495 // Test to see if the function is misoptimized if we ONLY run it on the
496 // functions listed in Funcs.
497 outs() << "Checking to see if the program is misoptimized when all ";
499 outs() << "but these " << BBs.size() << " blocks are extracted: ";
500 for (unsigned i = 0, e = BBs.size() < 10 ? BBs.size() : 10; i != e; ++i)
501 outs() << BBs[i]->getName() << " ";
505 outs() << "blocks are extracted.";
509 // Split the module into the two halves of the program we want.
510 ValueToValueMapTy VMap;
511 Module *Clone = CloneModule(BD.getProgram(), VMap).release();
512 Module *Orig = BD.swapProgramIn(Clone);
513 std::vector<Function *> FuncsOnClone;
514 std::vector<BasicBlock *> BBsOnClone;
515 for (unsigned i = 0, e = FunctionsBeingTested.size(); i != e; ++i) {
516 Function *F = cast<Function>(VMap[FunctionsBeingTested[i]]);
517 FuncsOnClone.push_back(F);
519 for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
520 BasicBlock *BB = cast<BasicBlock>(VMap[BBs[i]]);
521 BBsOnClone.push_back(BB);
525 std::unique_ptr<Module> ToNotOptimize = CloneModule(BD.getProgram(), VMap);
526 std::unique_ptr<Module> ToOptimize =
527 SplitFunctionsOutOfModule(ToNotOptimize.get(), FuncsOnClone, VMap);
529 // Try the extraction. If it doesn't work, then the block extractor crashed
530 // or something, in which case bugpoint can't chase down this possibility.
531 if (std::unique_ptr<Module> New =
532 BD.extractMappedBlocksFromModule(BBsOnClone, ToOptimize.get())) {
533 Expected<bool> Ret = TestFn(BD, std::move(New), std::move(ToNotOptimize));
534 delete BD.swapProgramIn(Orig);
537 delete BD.swapProgramIn(Orig);
541 /// Given a reduced list of functions that still expose the bug, extract as many
542 /// basic blocks from the region as possible without obscuring the bug.
544 static Expected<bool>
545 ExtractBlocks(BugDriver &BD,
546 Expected<bool> (*TestFn)(BugDriver &, std::unique_ptr<Module>,
547 std::unique_ptr<Module>),
548 std::vector<Function *> &MiscompiledFunctions) {
549 if (BugpointIsInterrupted)
552 std::vector<BasicBlock *> Blocks;
553 for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
554 for (BasicBlock &BB : *MiscompiledFunctions[i])
555 Blocks.push_back(&BB);
557 // Use the list reducer to identify blocks that can be extracted without
558 // obscuring the bug. The Blocks list will end up containing blocks that must
559 // be retained from the original program.
560 unsigned OldSize = Blocks.size();
562 // Check to see if all blocks are extractible first.
563 Expected<bool> Ret = ReduceMiscompiledBlocks(BD, TestFn, MiscompiledFunctions)
564 .TestFuncs(std::vector<BasicBlock *>());
565 if (Error E = Ret.takeError())
571 ReduceMiscompiledBlocks(BD, TestFn, MiscompiledFunctions)
573 if (Error E = Ret.takeError())
575 if (Blocks.size() == OldSize)
579 ValueToValueMapTy VMap;
580 Module *ProgClone = CloneModule(BD.getProgram(), VMap).release();
582 SplitFunctionsOutOfModule(ProgClone, MiscompiledFunctions, VMap)
584 std::unique_ptr<Module> Extracted =
585 BD.extractMappedBlocksFromModule(Blocks, ToExtract);
587 // Weird, extraction should have worked.
588 errs() << "Nondeterministic problem extracting blocks??\n";
594 // Otherwise, block extraction succeeded. Link the two program fragments back
598 std::vector<std::pair<std::string, FunctionType *>> MisCompFunctions;
599 for (Module::iterator I = Extracted->begin(), E = Extracted->end(); I != E;
601 if (!I->isDeclaration())
602 MisCompFunctions.emplace_back(I->getName(), I->getFunctionType());
604 if (Linker::linkModules(*ProgClone, std::move(Extracted)))
607 // Set the new program and delete the old one.
608 BD.setNewProgram(ProgClone);
610 // Update the list of miscompiled functions.
611 MiscompiledFunctions.clear();
613 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
614 Function *NewF = ProgClone->getFunction(MisCompFunctions[i].first);
615 assert(NewF && "Function not found??");
616 MiscompiledFunctions.push_back(NewF);
622 /// This is a generic driver to narrow down miscompilations, either in an
623 /// optimization or a code generator.
625 static Expected<std::vector<Function *>> DebugAMiscompilation(
627 Expected<bool> (*TestFn)(BugDriver &, std::unique_ptr<Module>,
628 std::unique_ptr<Module>)) {
629 // Okay, now that we have reduced the list of passes which are causing the
630 // failure, see if we can pin down which functions are being
631 // miscompiled... first build a list of all of the non-external functions in
633 std::vector<Function *> MiscompiledFunctions;
634 Module *Prog = BD.getProgram();
635 for (Function &F : *Prog)
636 if (!F.isDeclaration())
637 MiscompiledFunctions.push_back(&F);
639 // Do the reduction...
640 if (!BugpointIsInterrupted) {
641 Expected<bool> Ret = ReduceMiscompilingFunctions(BD, TestFn)
642 .reduceList(MiscompiledFunctions);
643 if (Error E = Ret.takeError()) {
644 errs() << "\n***Cannot reduce functions: ";
648 outs() << "\n*** The following function"
649 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
650 << " being miscompiled: ";
651 PrintFunctionList(MiscompiledFunctions);
654 // See if we can rip any loops out of the miscompiled functions and still
655 // trigger the problem.
657 if (!BugpointIsInterrupted && !DisableLoopExtraction) {
658 Expected<bool> Ret = ExtractLoops(BD, TestFn, MiscompiledFunctions);
659 if (Error E = Ret.takeError())
662 // Okay, we extracted some loops and the problem still appears. See if
663 // we can eliminate some of the created functions from being candidates.
664 DisambiguateGlobalSymbols(BD.getProgram());
666 // Do the reduction...
667 if (!BugpointIsInterrupted)
668 Ret = ReduceMiscompilingFunctions(BD, TestFn)
669 .reduceList(MiscompiledFunctions);
670 if (Error E = Ret.takeError())
673 outs() << "\n*** The following function"
674 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
675 << " being miscompiled: ";
676 PrintFunctionList(MiscompiledFunctions);
681 if (!BugpointIsInterrupted && !DisableBlockExtraction) {
682 Expected<bool> Ret = ExtractBlocks(BD, TestFn, MiscompiledFunctions);
683 if (Error E = Ret.takeError())
686 // Okay, we extracted some blocks and the problem still appears. See if
687 // we can eliminate some of the created functions from being candidates.
688 DisambiguateGlobalSymbols(BD.getProgram());
690 // Do the reduction...
691 Ret = ReduceMiscompilingFunctions(BD, TestFn)
692 .reduceList(MiscompiledFunctions);
693 if (Error E = Ret.takeError())
696 outs() << "\n*** The following function"
697 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
698 << " being miscompiled: ";
699 PrintFunctionList(MiscompiledFunctions);
704 return MiscompiledFunctions;
707 /// This is the predicate function used to check to see if the "Test" portion of
708 /// the program is misoptimized. If so, return true. In any case, both module
709 /// arguments are deleted.
711 static Expected<bool> TestOptimizer(BugDriver &BD, std::unique_ptr<Module> Test,
712 std::unique_ptr<Module> Safe) {
713 // Run the optimization passes on ToOptimize, producing a transformed version
714 // of the functions being tested.
715 outs() << " Optimizing functions being tested: ";
716 std::unique_ptr<Module> Optimized =
717 BD.runPassesOn(Test.get(), BD.getPassesToRun());
719 errs() << " Error running this sequence of passes"
720 << " on the input program!\n";
721 delete BD.swapProgramIn(Test.get());
722 BD.EmitProgressBitcode(Test.get(), "pass-error", false);
723 if (Error E = BD.debugOptimizerCrash())
729 outs() << " Checking to see if the merged program executes correctly: ";
731 auto Result = testMergedProgram(BD, *Optimized, *Safe, Broken);
732 if (Error E = Result.takeError())
734 if (auto New = std::move(*Result)) {
735 outs() << (Broken ? " nope.\n" : " yup.\n");
736 // Delete the original and set the new program.
737 delete BD.swapProgramIn(New.release());
742 /// debugMiscompilation - This method is used when the passes selected are not
743 /// crashing, but the generated output is semantically different from the
746 Error BugDriver::debugMiscompilation() {
747 // Make sure something was miscompiled...
748 if (!BugpointIsInterrupted) {
749 Expected<bool> Result =
750 ReduceMiscompilingPasses(*this).reduceList(PassesToRun);
751 if (Error E = Result.takeError())
754 return make_error<StringError>(
755 "*** Optimized program matches reference output! No problem"
756 " detected...\nbugpoint can't help you with your problem!\n",
757 inconvertibleErrorCode());
760 outs() << "\n*** Found miscompiling pass"
761 << (getPassesToRun().size() == 1 ? "" : "es") << ": "
762 << getPassesString(getPassesToRun()) << '\n';
763 EmitProgressBitcode(Program, "passinput");
765 Expected<std::vector<Function *>> MiscompiledFunctions =
766 DebugAMiscompilation(*this, TestOptimizer);
767 if (Error E = MiscompiledFunctions.takeError())
770 // Output a bunch of bitcode files for the user...
771 outs() << "Outputting reduced bitcode files which expose the problem:\n";
772 ValueToValueMapTy VMap;
773 Module *ToNotOptimize = CloneModule(getProgram(), VMap).release();
775 SplitFunctionsOutOfModule(ToNotOptimize, *MiscompiledFunctions, VMap)
778 outs() << " Non-optimized portion: ";
779 EmitProgressBitcode(ToNotOptimize, "tonotoptimize", true);
780 delete ToNotOptimize; // Delete hacked module.
782 outs() << " Portion that is input to optimizer: ";
783 EmitProgressBitcode(ToOptimize, "tooptimize");
784 delete ToOptimize; // Delete hacked module.
786 return Error::success();
789 /// Get the specified modules ready for code generator testing.
791 static void CleanupAndPrepareModules(BugDriver &BD,
792 std::unique_ptr<Module> &Test,
794 // Clean up the modules, removing extra cruft that we don't need anymore...
795 Test = BD.performFinalCleanups(Test.get());
797 // If we are executing the JIT, we have several nasty issues to take care of.
798 if (!BD.isExecutingJIT())
801 // First, if the main function is in the Safe module, we must add a stub to
802 // the Test module to call into it. Thus, we create a new function `main'
803 // which just calls the old one.
804 if (Function *oldMain = Safe->getFunction("main"))
805 if (!oldMain->isDeclaration()) {
807 oldMain->setName("llvm_bugpoint_old_main");
808 // Create a NEW `main' function with same type in the test module.
810 Function::Create(oldMain->getFunctionType(),
811 GlobalValue::ExternalLinkage, "main", Test.get());
812 // Create an `oldmain' prototype in the test module, which will
813 // corresponds to the real main function in the same module.
814 Function *oldMainProto = Function::Create(oldMain->getFunctionType(),
815 GlobalValue::ExternalLinkage,
816 oldMain->getName(), Test.get());
817 // Set up and remember the argument list for the main function.
818 std::vector<Value *> args;
819 for (Function::arg_iterator I = newMain->arg_begin(),
820 E = newMain->arg_end(),
821 OI = oldMain->arg_begin();
823 I->setName(OI->getName()); // Copy argument names from oldMain
827 // Call the old main function and return its result
828 BasicBlock *BB = BasicBlock::Create(Safe->getContext(), "entry", newMain);
829 CallInst *call = CallInst::Create(oldMainProto, args, "", BB);
831 // If the type of old function wasn't void, return value of call
832 ReturnInst::Create(Safe->getContext(), call, BB);
835 // The second nasty issue we must deal with in the JIT is that the Safe
836 // module cannot directly reference any functions defined in the test
837 // module. Instead, we use a JIT API call to dynamically resolve the
840 // Add the resolver to the Safe module.
841 // Prototype: void *getPointerToNamedFunction(const char* Name)
842 Constant *resolverFunc = Safe->getOrInsertFunction(
843 "getPointerToNamedFunction", Type::getInt8PtrTy(Safe->getContext()),
844 Type::getInt8PtrTy(Safe->getContext()));
846 // Use the function we just added to get addresses of functions we need.
847 for (Module::iterator F = Safe->begin(), E = Safe->end(); F != E; ++F) {
848 if (F->isDeclaration() && !F->use_empty() && &*F != resolverFunc &&
849 !F->isIntrinsic() /* ignore intrinsics */) {
850 Function *TestFn = Test->getFunction(F->getName());
852 // Don't forward functions which are external in the test module too.
853 if (TestFn && !TestFn->isDeclaration()) {
854 // 1. Add a string constant with its name to the global file
855 Constant *InitArray =
856 ConstantDataArray::getString(F->getContext(), F->getName());
857 GlobalVariable *funcName = new GlobalVariable(
858 *Safe, InitArray->getType(), true /*isConstant*/,
859 GlobalValue::InternalLinkage, InitArray, F->getName() + "_name");
861 // 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an
862 // sbyte* so it matches the signature of the resolver function.
864 // GetElementPtr *funcName, ulong 0, ulong 0
865 std::vector<Constant *> GEPargs(
866 2, Constant::getNullValue(Type::getInt32Ty(F->getContext())));
867 Value *GEP = ConstantExpr::getGetElementPtr(InitArray->getType(),
869 std::vector<Value *> ResolverArgs;
870 ResolverArgs.push_back(GEP);
872 // Rewrite uses of F in global initializers, etc. to uses of a wrapper
873 // function that dynamically resolves the calls to F via our JIT API
874 if (!F->use_empty()) {
875 // Create a new global to hold the cached function pointer.
876 Constant *NullPtr = ConstantPointerNull::get(F->getType());
877 GlobalVariable *Cache = new GlobalVariable(
878 *F->getParent(), F->getType(), false,
879 GlobalValue::InternalLinkage, NullPtr, F->getName() + ".fpcache");
881 // Construct a new stub function that will re-route calls to F
882 FunctionType *FuncTy = F->getFunctionType();
883 Function *FuncWrapper =
884 Function::Create(FuncTy, GlobalValue::InternalLinkage,
885 F->getName() + "_wrapper", F->getParent());
886 BasicBlock *EntryBB =
887 BasicBlock::Create(F->getContext(), "entry", FuncWrapper);
888 BasicBlock *DoCallBB =
889 BasicBlock::Create(F->getContext(), "usecache", FuncWrapper);
890 BasicBlock *LookupBB =
891 BasicBlock::Create(F->getContext(), "lookupfp", FuncWrapper);
893 // Check to see if we already looked up the value.
894 Value *CachedVal = new LoadInst(Cache, "fpcache", EntryBB);
895 Value *IsNull = new ICmpInst(*EntryBB, ICmpInst::ICMP_EQ, CachedVal,
897 BranchInst::Create(LookupBB, DoCallBB, IsNull, EntryBB);
899 // Resolve the call to function F via the JIT API:
901 // call resolver(GetElementPtr...)
902 CallInst *Resolver = CallInst::Create(resolverFunc, ResolverArgs,
903 "resolver", LookupBB);
905 // Cast the result from the resolver to correctly-typed function.
906 CastInst *CastedResolver = new BitCastInst(
907 Resolver, PointerType::getUnqual(F->getFunctionType()),
908 "resolverCast", LookupBB);
910 // Save the value in our cache.
911 new StoreInst(CastedResolver, Cache, LookupBB);
912 BranchInst::Create(DoCallBB, LookupBB);
915 PHINode::Create(NullPtr->getType(), 2, "fp", DoCallBB);
916 FuncPtr->addIncoming(CastedResolver, LookupBB);
917 FuncPtr->addIncoming(CachedVal, EntryBB);
919 // Save the argument list.
920 std::vector<Value *> Args;
921 for (Argument &A : FuncWrapper->args())
924 // Pass on the arguments to the real function, return its result
925 if (F->getReturnType()->isVoidTy()) {
926 CallInst::Create(FuncPtr, Args, "", DoCallBB);
927 ReturnInst::Create(F->getContext(), DoCallBB);
930 CallInst::Create(FuncPtr, Args, "retval", DoCallBB);
931 ReturnInst::Create(F->getContext(), Call, DoCallBB);
934 // Use the wrapper function instead of the old function
935 F->replaceAllUsesWith(FuncWrapper);
941 if (verifyModule(*Test) || verifyModule(*Safe)) {
942 errs() << "Bugpoint has a bug, which corrupted a module!!\n";
947 /// This is the predicate function used to check to see if the "Test" portion of
948 /// the program is miscompiled by the code generator under test. If so, return
949 /// true. In any case, both module arguments are deleted.
951 static Expected<bool> TestCodeGenerator(BugDriver &BD,
952 std::unique_ptr<Module> Test,
953 std::unique_ptr<Module> Safe) {
954 CleanupAndPrepareModules(BD, Test, Safe.get());
956 SmallString<128> TestModuleBC;
958 std::error_code EC = sys::fs::createTemporaryFile("bugpoint.test", "bc",
959 TestModuleFD, TestModuleBC);
961 errs() << BD.getToolName()
962 << "Error making unique filename: " << EC.message() << "\n";
965 if (BD.writeProgramToFile(TestModuleBC.str(), TestModuleFD, Test.get())) {
966 errs() << "Error writing bitcode to `" << TestModuleBC.str()
971 FileRemover TestModuleBCRemover(TestModuleBC.str(), !SaveTemps);
973 // Make the shared library
974 SmallString<128> SafeModuleBC;
976 EC = sys::fs::createTemporaryFile("bugpoint.safe", "bc", SafeModuleFD,
979 errs() << BD.getToolName()
980 << "Error making unique filename: " << EC.message() << "\n";
984 if (BD.writeProgramToFile(SafeModuleBC.str(), SafeModuleFD, Safe.get())) {
985 errs() << "Error writing bitcode to `" << SafeModuleBC << "'\nExiting.";
989 FileRemover SafeModuleBCRemover(SafeModuleBC.str(), !SaveTemps);
991 Expected<std::string> SharedObject =
992 BD.compileSharedObject(SafeModuleBC.str());
993 if (Error E = SharedObject.takeError())
996 FileRemover SharedObjectRemover(*SharedObject, !SaveTemps);
998 // Run the code generator on the `Test' code, loading the shared library.
999 // The function returns whether or not the new output differs from reference.
1000 Expected<bool> Result =
1001 BD.diffProgram(BD.getProgram(), TestModuleBC.str(), *SharedObject, false);
1002 if (Error E = Result.takeError())
1003 return std::move(E);
1006 errs() << ": still failing!\n";
1008 errs() << ": didn't fail.\n";
1013 /// debugCodeGenerator - debug errors in LLC, LLI, or CBE.
1015 Error BugDriver::debugCodeGenerator() {
1016 if ((void *)SafeInterpreter == (void *)Interpreter) {
1017 Expected<std::string> Result =
1018 executeProgramSafely(Program, "bugpoint.safe.out");
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 "
1026 << "you: '" << *Result << "'.\n";
1028 return Error::success();
1031 DisambiguateGlobalSymbols(Program);
1033 Expected<std::vector<Function *>> Funcs =
1034 DebugAMiscompilation(*this, TestCodeGenerator);
1035 if (Error E = Funcs.takeError())
1038 // Split the module into the two halves of the program we want.
1039 ValueToValueMapTy VMap;
1040 std::unique_ptr<Module> ToNotCodeGen = CloneModule(getProgram(), VMap);
1041 std::unique_ptr<Module> ToCodeGen =
1042 SplitFunctionsOutOfModule(ToNotCodeGen.get(), *Funcs, VMap);
1044 // Condition the modules
1045 CleanupAndPrepareModules(*this, ToCodeGen, ToNotCodeGen.get());
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: " << EC.message()
1057 if (writeProgramToFile(TestModuleBC.str(), TestModuleFD, ToCodeGen.get())) {
1058 errs() << "Error writing bitcode to `" << TestModuleBC << "'\nExiting.";
1062 // Make the shared library
1063 SmallString<128> SafeModuleBC;
1065 EC = sys::fs::createTemporaryFile("bugpoint.safe", "bc", SafeModuleFD,
1068 errs() << getToolName() << "Error making unique filename: " << EC.message()
1073 if (writeProgramToFile(SafeModuleBC.str(), SafeModuleFD,
1074 ToNotCodeGen.get())) {
1075 errs() << "Error writing bitcode to `" << SafeModuleBC << "'\nExiting.";
1078 Expected<std::string> SharedObject = compileSharedObject(SafeModuleBC.str());
1079 if (Error E = SharedObject.takeError())
1082 outs() << "You can reproduce the problem with the command line: \n";
1083 if (isExecutingJIT()) {
1084 outs() << " lli -load " << *SharedObject << " " << TestModuleBC;
1086 outs() << " llc " << TestModuleBC << " -o " << TestModuleBC << ".s\n";
1087 outs() << " cc " << *SharedObject << " " << TestModuleBC.str() << ".s -o "
1088 << TestModuleBC << ".exe\n";
1089 outs() << " ./" << TestModuleBC << ".exe";
1091 for (unsigned i = 0, e = InputArgv.size(); i != e; ++i)
1092 outs() << " " << InputArgv[i];
1094 outs() << "The shared object was created with:\n llc -march=c "
1095 << SafeModuleBC.str() << " -o temporary.c\n"
1096 << " cc -xc temporary.c -O2 -o " << *SharedObject;
1097 if (TargetTriple.getArch() == Triple::sparc)
1098 outs() << " -G"; // Compile a shared library, `-G' for Sparc
1100 outs() << " -fPIC -shared"; // `-shared' for Linux/X86, maybe others
1102 outs() << " -fno-strict-aliasing\n";
1104 return Error::success();