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 "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
33 extern cl::list<std::string> InputArgv;
37 static llvm::cl::opt<bool>
38 DisableLoopExtraction("disable-loop-extraction",
39 cl::desc("Don't extract loops when searching for miscompilations"),
42 class ReduceMiscompilingPasses : public ListReducer<const PassInfo*> {
45 ReduceMiscompilingPasses(BugDriver &bd) : BD(bd) {}
47 virtual TestResult doTest(std::vector<const PassInfo*> &Prefix,
48 std::vector<const PassInfo*> &Suffix);
52 /// TestResult - After passes have been split into a test group and a control
53 /// group, see if they still break the program.
55 ReduceMiscompilingPasses::TestResult
56 ReduceMiscompilingPasses::doTest(std::vector<const PassInfo*> &Prefix,
57 std::vector<const PassInfo*> &Suffix) {
58 // First, run the program with just the Suffix passes. If it is still broken
59 // with JUST the kept passes, discard the prefix passes.
60 std::cout << "Checking to see if '" << getPassesString(Suffix)
61 << "' compiles correctly: ";
63 std::string BitcodeResult;
64 if (BD.runPasses(Suffix, BitcodeResult, false/*delete*/, true/*quiet*/)) {
65 errs() << " Error running this sequence of passes"
66 << " on the input program!\n";
67 BD.setPassesToRun(Suffix);
68 BD.EmitProgressBitcode("pass-error", false);
69 exit(BD.debugOptimizerCrash());
72 // Check to see if the finished program matches the reference output...
73 if (BD.diffProgram(BitcodeResult, "", true /*delete bitcode*/)) {
74 std::cout << " nope.\n";
76 errs() << BD.getToolName() << ": I'm confused: the test fails when "
77 << "no passes are run, nondeterministic program?\n";
80 return KeepSuffix; // Miscompilation detected!
82 std::cout << " yup.\n"; // No miscompilation!
84 if (Prefix.empty()) return NoFailure;
86 // Next, see if the program is broken if we run the "prefix" passes first,
87 // then separately run the "kept" passes.
88 std::cout << "Checking to see if '" << getPassesString(Prefix)
89 << "' compiles correctly: ";
91 // If it is not broken with the kept passes, it's possible that the prefix
92 // passes must be run before the kept passes to break it. If the program
93 // WORKS after the prefix passes, but then fails if running the prefix AND
94 // kept passes, we can update our bitcode file to include the result of the
95 // prefix passes, then discard the prefix passes.
97 if (BD.runPasses(Prefix, BitcodeResult, false/*delete*/, true/*quiet*/)) {
98 errs() << " Error running this sequence of passes"
99 << " on the input program!\n";
100 BD.setPassesToRun(Prefix);
101 BD.EmitProgressBitcode("pass-error", false);
102 exit(BD.debugOptimizerCrash());
105 // If the prefix maintains the predicate by itself, only keep the prefix!
106 if (BD.diffProgram(BitcodeResult)) {
107 std::cout << " nope.\n";
108 sys::Path(BitcodeResult).eraseFromDisk();
111 std::cout << " yup.\n"; // No miscompilation!
113 // Ok, so now we know that the prefix passes work, try running the suffix
114 // passes on the result of the prefix passes.
116 Module *PrefixOutput = ParseInputFile(BitcodeResult, BD.getContext());
117 if (PrefixOutput == 0) {
118 errs() << BD.getToolName() << ": Error reading bitcode file '"
119 << BitcodeResult << "'!\n";
122 sys::Path(BitcodeResult).eraseFromDisk(); // No longer need the file on disk
124 // Don't check if there are no passes in the suffix.
128 std::cout << "Checking to see if '" << getPassesString(Suffix)
129 << "' passes compile correctly after the '"
130 << getPassesString(Prefix) << "' passes: ";
132 Module *OriginalInput = BD.swapProgramIn(PrefixOutput);
133 if (BD.runPasses(Suffix, BitcodeResult, false/*delete*/, true/*quiet*/)) {
134 errs() << " Error running this sequence of passes"
135 << " on the input program!\n";
136 BD.setPassesToRun(Suffix);
137 BD.EmitProgressBitcode("pass-error", false);
138 exit(BD.debugOptimizerCrash());
142 if (BD.diffProgram(BitcodeResult, "", true/*delete bitcode*/)) {
143 std::cout << " nope.\n";
144 delete OriginalInput; // We pruned down the original input...
148 // Otherwise, we must not be running the bad pass anymore.
149 std::cout << " yup.\n"; // No miscompilation!
150 delete BD.swapProgramIn(OriginalInput); // Restore orig program & free test
155 class ReduceMiscompilingFunctions : public ListReducer<Function*> {
157 bool (*TestFn)(BugDriver &, Module *, Module *);
159 ReduceMiscompilingFunctions(BugDriver &bd,
160 bool (*F)(BugDriver &, Module *, Module *))
161 : BD(bd), TestFn(F) {}
163 virtual TestResult doTest(std::vector<Function*> &Prefix,
164 std::vector<Function*> &Suffix) {
165 if (!Suffix.empty() && TestFuncs(Suffix))
167 if (!Prefix.empty() && TestFuncs(Prefix))
172 bool TestFuncs(const std::vector<Function*> &Prefix);
176 /// TestMergedProgram - Given two modules, link them together and run the
177 /// program, checking to see if the program matches the diff. If the diff
178 /// matches, return false, otherwise return true. If the DeleteInputs argument
179 /// is set to true then this function deletes both input modules before it
182 static bool TestMergedProgram(BugDriver &BD, Module *M1, Module *M2,
184 // Link the two portions of the program back to together.
185 std::string ErrorMsg;
187 M1 = CloneModule(M1);
188 M2 = CloneModule(M2);
190 if (Linker::LinkModules(M1, M2, &ErrorMsg)) {
191 errs() << BD.getToolName() << ": Error linking modules together:"
195 delete M2; // We are done with this module.
197 Module *OldProgram = BD.swapProgramIn(M1);
199 // Execute the program. If it does not match the expected output, we must
201 bool Broken = BD.diffProgram();
203 // Delete the linked module & restore the original
204 BD.swapProgramIn(OldProgram);
209 /// TestFuncs - split functions in a Module into two groups: those that are
210 /// under consideration for miscompilation vs. those that are not, and test
211 /// accordingly. Each group of functions becomes a separate Module.
213 bool ReduceMiscompilingFunctions::TestFuncs(const std::vector<Function*>&Funcs){
214 // Test to see if the function is misoptimized if we ONLY run it on the
215 // functions listed in Funcs.
216 std::cout << "Checking to see if the program is misoptimized when "
217 << (Funcs.size()==1 ? "this function is" : "these functions are")
218 << " run through the pass"
219 << (BD.getPassesToRun().size() == 1 ? "" : "es") << ":";
220 PrintFunctionList(Funcs);
223 // Split the module into the two halves of the program we want.
224 DenseMap<const Value*, Value*> ValueMap;
225 Module *ToNotOptimize = CloneModule(BD.getProgram(), ValueMap);
226 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize, Funcs,
229 // Run the predicate, note that the predicate will delete both input modules.
230 return TestFn(BD, ToOptimize, ToNotOptimize);
233 /// DisambiguateGlobalSymbols - Mangle symbols to guarantee uniqueness by
234 /// modifying predominantly internal symbols rather than external ones.
236 static void DisambiguateGlobalSymbols(Module *M) {
237 // Try not to cause collisions by minimizing chances of renaming an
238 // already-external symbol, so take in external globals and functions as-is.
239 // The code should work correctly without disambiguation (assuming the same
240 // mangler is used by the two code generators), but having symbols with the
241 // same name causes warnings to be emitted by the code generator.
243 // Agree with the CBE on symbol naming
244 Mang.markCharUnacceptable('.');
245 for (Module::global_iterator I = M->global_begin(), E = M->global_end();
247 // Don't mangle asm names.
248 if (!I->hasName() || I->getName()[0] != 1)
249 I->setName(Mang.getMangledName(I));
251 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) {
252 // Don't mangle asm names.
253 if (!I->hasName() || I->getName()[0] != 1)
254 I->setName(Mang.getMangledName(I));
258 /// ExtractLoops - Given a reduced list of functions that still exposed the bug,
259 /// check to see if we can extract the loops in the region without obscuring the
260 /// bug. If so, it reduces the amount of code identified.
262 static bool ExtractLoops(BugDriver &BD,
263 bool (*TestFn)(BugDriver &, Module *, Module *),
264 std::vector<Function*> &MiscompiledFunctions) {
265 bool MadeChange = false;
267 if (BugpointIsInterrupted) return MadeChange;
269 DenseMap<const Value*, Value*> ValueMap;
270 Module *ToNotOptimize = CloneModule(BD.getProgram(), ValueMap);
271 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
272 MiscompiledFunctions,
274 Module *ToOptimizeLoopExtracted = BD.ExtractLoop(ToOptimize);
275 if (!ToOptimizeLoopExtracted) {
276 // If the loop extractor crashed or if there were no extractible loops,
277 // then this chapter of our odyssey is over with.
278 delete ToNotOptimize;
283 errs() << "Extracted a loop from the breaking portion of the program.\n";
285 // Bugpoint is intentionally not very trusting of LLVM transformations. In
286 // particular, we're not going to assume that the loop extractor works, so
287 // we're going to test the newly loop extracted program to make sure nothing
288 // has broken. If something broke, then we'll inform the user and stop
290 AbstractInterpreter *AI = BD.switchToSafeInterpreter();
291 if (TestMergedProgram(BD, ToOptimizeLoopExtracted, ToNotOptimize, false)) {
292 BD.switchToInterpreter(AI);
294 // Merged program doesn't work anymore!
295 errs() << " *** ERROR: Loop extraction broke the program. :("
296 << " Please report a bug!\n";
297 errs() << " Continuing on with un-loop-extracted version.\n";
299 BD.writeProgramToFile("bugpoint-loop-extract-fail-tno.bc", ToNotOptimize);
300 BD.writeProgramToFile("bugpoint-loop-extract-fail-to.bc", ToOptimize);
301 BD.writeProgramToFile("bugpoint-loop-extract-fail-to-le.bc",
302 ToOptimizeLoopExtracted);
304 errs() << "Please submit the bugpoint-loop-extract-fail-*.bc files.\n";
306 delete ToNotOptimize;
307 delete ToOptimizeLoopExtracted;
311 BD.switchToInterpreter(AI);
313 std::cout << " Testing after loop extraction:\n";
314 // Clone modules, the tester function will free them.
315 Module *TOLEBackup = CloneModule(ToOptimizeLoopExtracted);
316 Module *TNOBackup = CloneModule(ToNotOptimize);
317 if (!TestFn(BD, ToOptimizeLoopExtracted, ToNotOptimize)) {
318 std::cout << "*** Loop extraction masked the problem. Undoing.\n";
319 // If the program is not still broken, then loop extraction did something
320 // that masked the error. Stop loop extraction now.
325 ToOptimizeLoopExtracted = TOLEBackup;
326 ToNotOptimize = TNOBackup;
328 std::cout << "*** Loop extraction successful!\n";
330 std::vector<std::pair<std::string, const FunctionType*> > MisCompFunctions;
331 for (Module::iterator I = ToOptimizeLoopExtracted->begin(),
332 E = ToOptimizeLoopExtracted->end(); I != E; ++I)
333 if (!I->isDeclaration())
334 MisCompFunctions.push_back(std::make_pair(I->getName(),
335 I->getFunctionType()));
337 // Okay, great! Now we know that we extracted a loop and that loop
338 // extraction both didn't break the program, and didn't mask the problem.
339 // Replace the current program with the loop extracted version, and try to
340 // extract another loop.
341 std::string ErrorMsg;
342 if (Linker::LinkModules(ToNotOptimize, ToOptimizeLoopExtracted, &ErrorMsg)){
343 errs() << BD.getToolName() << ": Error linking modules together:"
347 delete ToOptimizeLoopExtracted;
349 // All of the Function*'s in the MiscompiledFunctions list are in the old
350 // module. Update this list to include all of the functions in the
351 // optimized and loop extracted module.
352 MiscompiledFunctions.clear();
353 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
354 Function *NewF = ToNotOptimize->getFunction(MisCompFunctions[i].first);
356 assert(NewF && "Function not found??");
357 assert(NewF->getFunctionType() == MisCompFunctions[i].second &&
358 "found wrong function type?");
359 MiscompiledFunctions.push_back(NewF);
362 BD.setNewProgram(ToNotOptimize);
368 class ReduceMiscompiledBlocks : public ListReducer<BasicBlock*> {
370 bool (*TestFn)(BugDriver &, Module *, Module *);
371 std::vector<Function*> FunctionsBeingTested;
373 ReduceMiscompiledBlocks(BugDriver &bd,
374 bool (*F)(BugDriver &, Module *, Module *),
375 const std::vector<Function*> &Fns)
376 : BD(bd), TestFn(F), FunctionsBeingTested(Fns) {}
378 virtual TestResult doTest(std::vector<BasicBlock*> &Prefix,
379 std::vector<BasicBlock*> &Suffix) {
380 if (!Suffix.empty() && TestFuncs(Suffix))
382 if (TestFuncs(Prefix))
387 bool TestFuncs(const std::vector<BasicBlock*> &Prefix);
391 /// TestFuncs - Extract all blocks for the miscompiled functions except for the
392 /// specified blocks. If the problem still exists, return true.
394 bool ReduceMiscompiledBlocks::TestFuncs(const std::vector<BasicBlock*> &BBs) {
395 // Test to see if the function is misoptimized if we ONLY run it on the
396 // functions listed in Funcs.
397 std::cout << "Checking to see if the program is misoptimized when all ";
399 std::cout << "but these " << BBs.size() << " blocks are extracted: ";
400 for (unsigned i = 0, e = BBs.size() < 10 ? BBs.size() : 10; i != e; ++i)
401 std::cout << BBs[i]->getName() << " ";
402 if (BBs.size() > 10) std::cout << "...";
404 std::cout << "blocks are extracted.";
408 // Split the module into the two halves of the program we want.
409 DenseMap<const Value*, Value*> ValueMap;
410 Module *ToNotOptimize = CloneModule(BD.getProgram(), ValueMap);
411 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
412 FunctionsBeingTested,
415 // Try the extraction. If it doesn't work, then the block extractor crashed
416 // or something, in which case bugpoint can't chase down this possibility.
417 if (Module *New = BD.ExtractMappedBlocksFromModule(BBs, ToOptimize)) {
419 // Run the predicate, not that the predicate will delete both input modules.
420 return TestFn(BD, New, ToNotOptimize);
423 delete ToNotOptimize;
428 /// ExtractBlocks - Given a reduced list of functions that still expose the bug,
429 /// extract as many basic blocks from the region as possible without obscuring
432 static bool ExtractBlocks(BugDriver &BD,
433 bool (*TestFn)(BugDriver &, Module *, Module *),
434 std::vector<Function*> &MiscompiledFunctions) {
435 if (BugpointIsInterrupted) return false;
437 std::vector<BasicBlock*> Blocks;
438 for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
439 for (Function::iterator I = MiscompiledFunctions[i]->begin(),
440 E = MiscompiledFunctions[i]->end(); I != E; ++I)
443 // Use the list reducer to identify blocks that can be extracted without
444 // obscuring the bug. The Blocks list will end up containing blocks that must
445 // be retained from the original program.
446 unsigned OldSize = Blocks.size();
448 // Check to see if all blocks are extractible first.
449 if (ReduceMiscompiledBlocks(BD, TestFn,
450 MiscompiledFunctions).TestFuncs(std::vector<BasicBlock*>())) {
453 ReduceMiscompiledBlocks(BD, TestFn,MiscompiledFunctions).reduceList(Blocks);
454 if (Blocks.size() == OldSize)
458 DenseMap<const Value*, Value*> ValueMap;
459 Module *ProgClone = CloneModule(BD.getProgram(), ValueMap);
460 Module *ToExtract = SplitFunctionsOutOfModule(ProgClone,
461 MiscompiledFunctions,
463 Module *Extracted = BD.ExtractMappedBlocksFromModule(Blocks, ToExtract);
464 if (Extracted == 0) {
465 // Weird, extraction should have worked.
466 errs() << "Nondeterministic problem extracting blocks??\n";
472 // Otherwise, block extraction succeeded. Link the two program fragments back
476 std::vector<std::pair<std::string, const FunctionType*> > MisCompFunctions;
477 for (Module::iterator I = Extracted->begin(), E = Extracted->end();
479 if (!I->isDeclaration())
480 MisCompFunctions.push_back(std::make_pair(I->getName(),
481 I->getFunctionType()));
483 std::string ErrorMsg;
484 if (Linker::LinkModules(ProgClone, Extracted, &ErrorMsg)) {
485 errs() << BD.getToolName() << ": Error linking modules together:"
491 // Set the new program and delete the old one.
492 BD.setNewProgram(ProgClone);
494 // Update the list of miscompiled functions.
495 MiscompiledFunctions.clear();
497 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
498 Function *NewF = ProgClone->getFunction(MisCompFunctions[i].first);
499 assert(NewF && "Function not found??");
500 assert(NewF->getFunctionType() == MisCompFunctions[i].second &&
501 "Function has wrong type??");
502 MiscompiledFunctions.push_back(NewF);
509 /// DebugAMiscompilation - This is a generic driver to narrow down
510 /// miscompilations, either in an optimization or a code generator.
512 static std::vector<Function*>
513 DebugAMiscompilation(BugDriver &BD,
514 bool (*TestFn)(BugDriver &, Module *, Module *)) {
515 // Okay, now that we have reduced the list of passes which are causing the
516 // failure, see if we can pin down which functions are being
517 // miscompiled... first build a list of all of the non-external functions in
519 std::vector<Function*> MiscompiledFunctions;
520 Module *Prog = BD.getProgram();
521 for (Module::iterator I = Prog->begin(), E = Prog->end(); I != E; ++I)
522 if (!I->isDeclaration())
523 MiscompiledFunctions.push_back(I);
525 // Do the reduction...
526 if (!BugpointIsInterrupted)
527 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
529 std::cout << "\n*** The following function"
530 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
531 << " being miscompiled: ";
532 PrintFunctionList(MiscompiledFunctions);
535 // See if we can rip any loops out of the miscompiled functions and still
536 // trigger the problem.
538 if (!BugpointIsInterrupted && !DisableLoopExtraction &&
539 ExtractLoops(BD, TestFn, MiscompiledFunctions)) {
540 // Okay, we extracted some loops and the problem still appears. See if we
541 // can eliminate some of the created functions from being candidates.
543 // Loop extraction can introduce functions with the same name (foo_code).
544 // Make sure to disambiguate the symbols so that when the program is split
545 // apart that we can link it back together again.
546 DisambiguateGlobalSymbols(BD.getProgram());
548 // Do the reduction...
549 if (!BugpointIsInterrupted)
550 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
552 std::cout << "\n*** The following function"
553 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
554 << " being miscompiled: ";
555 PrintFunctionList(MiscompiledFunctions);
559 if (!BugpointIsInterrupted &&
560 ExtractBlocks(BD, TestFn, MiscompiledFunctions)) {
561 // Okay, we extracted some blocks and the problem still appears. See if we
562 // can eliminate some of the created functions from being candidates.
564 // Block extraction can introduce functions with the same name (foo_code).
565 // Make sure to disambiguate the symbols so that when the program is split
566 // apart that we can link it back together again.
567 DisambiguateGlobalSymbols(BD.getProgram());
569 // Do the reduction...
570 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
572 std::cout << "\n*** The following function"
573 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
574 << " being miscompiled: ";
575 PrintFunctionList(MiscompiledFunctions);
579 return MiscompiledFunctions;
582 /// TestOptimizer - This is the predicate function used to check to see if the
583 /// "Test" portion of the program is misoptimized. If so, return true. In any
584 /// case, both module arguments are deleted.
586 static bool TestOptimizer(BugDriver &BD, Module *Test, Module *Safe) {
587 // Run the optimization passes on ToOptimize, producing a transformed version
588 // of the functions being tested.
589 std::cout << " Optimizing functions being tested: ";
590 Module *Optimized = BD.runPassesOn(Test, BD.getPassesToRun(),
591 /*AutoDebugCrashes*/true);
592 std::cout << "done.\n";
595 std::cout << " Checking to see if the merged program executes correctly: ";
596 bool Broken = TestMergedProgram(BD, Optimized, Safe, true);
597 std::cout << (Broken ? " nope.\n" : " yup.\n");
602 /// debugMiscompilation - This method is used when the passes selected are not
603 /// crashing, but the generated output is semantically different from the
606 bool BugDriver::debugMiscompilation() {
607 // Make sure something was miscompiled...
608 if (!BugpointIsInterrupted)
609 if (!ReduceMiscompilingPasses(*this).reduceList(PassesToRun)) {
610 errs() << "*** Optimized program matches reference output! No problem"
611 << " detected...\nbugpoint can't help you with your problem!\n";
615 std::cout << "\n*** Found miscompiling pass"
616 << (getPassesToRun().size() == 1 ? "" : "es") << ": "
617 << getPassesString(getPassesToRun()) << '\n';
618 EmitProgressBitcode("passinput");
620 std::vector<Function*> MiscompiledFunctions =
621 DebugAMiscompilation(*this, TestOptimizer);
623 // Output a bunch of bitcode files for the user...
624 std::cout << "Outputting reduced bitcode files which expose the problem:\n";
625 DenseMap<const Value*, Value*> ValueMap;
626 Module *ToNotOptimize = CloneModule(getProgram(), ValueMap);
627 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
628 MiscompiledFunctions,
631 std::cout << " Non-optimized portion: ";
632 ToNotOptimize = swapProgramIn(ToNotOptimize);
633 EmitProgressBitcode("tonotoptimize", true);
634 setNewProgram(ToNotOptimize); // Delete hacked module.
636 std::cout << " Portion that is input to optimizer: ";
637 ToOptimize = swapProgramIn(ToOptimize);
638 EmitProgressBitcode("tooptimize");
639 setNewProgram(ToOptimize); // Delete hacked module.
644 /// CleanupAndPrepareModules - Get the specified modules ready for code
645 /// generator testing.
647 static void CleanupAndPrepareModules(BugDriver &BD, Module *&Test,
649 LLVMContext &Context = BD.getContext();
651 // Clean up the modules, removing extra cruft that we don't need anymore...
652 Test = BD.performFinalCleanups(Test);
654 // If we are executing the JIT, we have several nasty issues to take care of.
655 if (!BD.isExecutingJIT()) return;
657 // First, if the main function is in the Safe module, we must add a stub to
658 // the Test module to call into it. Thus, we create a new function `main'
659 // which just calls the old one.
660 if (Function *oldMain = Safe->getFunction("main"))
661 if (!oldMain->isDeclaration()) {
663 oldMain->setName("llvm_bugpoint_old_main");
664 // Create a NEW `main' function with same type in the test module.
665 Function *newMain = Function::Create(oldMain->getFunctionType(),
666 GlobalValue::ExternalLinkage,
668 // Create an `oldmain' prototype in the test module, which will
669 // corresponds to the real main function in the same module.
670 Function *oldMainProto = Function::Create(oldMain->getFunctionType(),
671 GlobalValue::ExternalLinkage,
672 oldMain->getName(), Test);
673 // Set up and remember the argument list for the main function.
674 std::vector<Value*> args;
675 for (Function::arg_iterator
676 I = newMain->arg_begin(), E = newMain->arg_end(),
677 OI = oldMain->arg_begin(); I != E; ++I, ++OI) {
678 I->setName(OI->getName()); // Copy argument names from oldMain
682 // Call the old main function and return its result
683 BasicBlock *BB = BasicBlock::Create("entry", newMain);
684 CallInst *call = CallInst::Create(oldMainProto, args.begin(), args.end(),
687 // If the type of old function wasn't void, return value of call
688 ReturnInst::Create(call, BB);
691 // The second nasty issue we must deal with in the JIT is that the Safe
692 // module cannot directly reference any functions defined in the test
693 // module. Instead, we use a JIT API call to dynamically resolve the
696 // Add the resolver to the Safe module.
697 // Prototype: void *getPointerToNamedFunction(const char* Name)
698 Constant *resolverFunc =
699 Safe->getOrInsertFunction("getPointerToNamedFunction",
700 Context.getPointerTypeUnqual(Type::Int8Ty),
701 Context.getPointerTypeUnqual(Type::Int8Ty), (Type *)0);
703 // Use the function we just added to get addresses of functions we need.
704 for (Module::iterator F = Safe->begin(), E = Safe->end(); F != E; ++F) {
705 if (F->isDeclaration() && !F->use_empty() && &*F != resolverFunc &&
706 !F->isIntrinsic() /* ignore intrinsics */) {
707 Function *TestFn = Test->getFunction(F->getName());
709 // Don't forward functions which are external in the test module too.
710 if (TestFn && !TestFn->isDeclaration()) {
711 // 1. Add a string constant with its name to the global file
712 Constant *InitArray = Context.getConstantArray(F->getName());
713 GlobalVariable *funcName =
714 new GlobalVariable(*Safe, InitArray->getType(), true /*isConstant*/,
715 GlobalValue::InternalLinkage, InitArray,
716 F->getName() + "_name");
718 // 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an
719 // sbyte* so it matches the signature of the resolver function.
721 // GetElementPtr *funcName, ulong 0, ulong 0
722 std::vector<Constant*> GEPargs(2, Context.getNullValue(Type::Int32Ty));
724 Context.getConstantExprGetElementPtr(funcName, &GEPargs[0], 2);
725 std::vector<Value*> ResolverArgs;
726 ResolverArgs.push_back(GEP);
728 // Rewrite uses of F in global initializers, etc. to uses of a wrapper
729 // function that dynamically resolves the calls to F via our JIT API
730 if (!F->use_empty()) {
731 // Create a new global to hold the cached function pointer.
732 Constant *NullPtr = Context.getConstantPointerNull(F->getType());
733 GlobalVariable *Cache =
734 new GlobalVariable(*F->getParent(), F->getType(),
735 false, GlobalValue::InternalLinkage,
736 NullPtr,F->getName()+".fpcache");
738 // Construct a new stub function that will re-route calls to F
739 const FunctionType *FuncTy = F->getFunctionType();
740 Function *FuncWrapper = Function::Create(FuncTy,
741 GlobalValue::InternalLinkage,
742 F->getName() + "_wrapper",
744 BasicBlock *EntryBB = BasicBlock::Create("entry", FuncWrapper);
745 BasicBlock *DoCallBB = BasicBlock::Create("usecache", FuncWrapper);
746 BasicBlock *LookupBB = BasicBlock::Create("lookupfp", FuncWrapper);
748 // Check to see if we already looked up the value.
749 Value *CachedVal = new LoadInst(Cache, "fpcache", EntryBB);
750 Value *IsNull = new ICmpInst(*EntryBB, ICmpInst::ICMP_EQ, CachedVal,
752 BranchInst::Create(LookupBB, DoCallBB, IsNull, EntryBB);
754 // Resolve the call to function F via the JIT API:
756 // call resolver(GetElementPtr...)
758 CallInst::Create(resolverFunc, ResolverArgs.begin(),
759 ResolverArgs.end(), "resolver", LookupBB);
761 // Cast the result from the resolver to correctly-typed function.
762 CastInst *CastedResolver =
763 new BitCastInst(Resolver,
764 Context.getPointerTypeUnqual(F->getFunctionType()),
765 "resolverCast", LookupBB);
767 // Save the value in our cache.
768 new StoreInst(CastedResolver, Cache, LookupBB);
769 BranchInst::Create(DoCallBB, LookupBB);
771 PHINode *FuncPtr = PHINode::Create(NullPtr->getType(),
773 FuncPtr->addIncoming(CastedResolver, LookupBB);
774 FuncPtr->addIncoming(CachedVal, EntryBB);
776 // Save the argument list.
777 std::vector<Value*> Args;
778 for (Function::arg_iterator i = FuncWrapper->arg_begin(),
779 e = FuncWrapper->arg_end(); i != e; ++i)
782 // Pass on the arguments to the real function, return its result
783 if (F->getReturnType() == Type::VoidTy) {
784 CallInst::Create(FuncPtr, Args.begin(), Args.end(), "", DoCallBB);
785 ReturnInst::Create(DoCallBB);
787 CallInst *Call = CallInst::Create(FuncPtr, Args.begin(), Args.end(),
789 ReturnInst::Create(Call, DoCallBB);
792 // Use the wrapper function instead of the old function
793 F->replaceAllUsesWith(FuncWrapper);
799 if (verifyModule(*Test) || verifyModule(*Safe)) {
800 errs() << "Bugpoint has a bug, which corrupted a module!!\n";
807 /// TestCodeGenerator - This is the predicate function used to check to see if
808 /// the "Test" portion of the program is miscompiled by the code generator under
809 /// test. If so, return true. In any case, both module arguments are deleted.
811 static bool TestCodeGenerator(BugDriver &BD, Module *Test, Module *Safe) {
812 CleanupAndPrepareModules(BD, Test, Safe);
814 sys::Path TestModuleBC("bugpoint.test.bc");
816 if (TestModuleBC.makeUnique(true, &ErrMsg)) {
817 errs() << BD.getToolName() << "Error making unique filename: "
821 if (BD.writeProgramToFile(TestModuleBC.toString(), Test)) {
822 errs() << "Error writing bitcode to `" << TestModuleBC << "'\nExiting.";
827 // Make the shared library
828 sys::Path SafeModuleBC("bugpoint.safe.bc");
829 if (SafeModuleBC.makeUnique(true, &ErrMsg)) {
830 errs() << BD.getToolName() << "Error making unique filename: "
835 if (BD.writeProgramToFile(SafeModuleBC.toString(), Safe)) {
836 errs() << "Error writing bitcode to `" << SafeModuleBC << "'\nExiting.";
839 std::string SharedObject = BD.compileSharedObject(SafeModuleBC.toString());
842 // Run the code generator on the `Test' code, loading the shared library.
843 // The function returns whether or not the new output differs from reference.
844 int Result = BD.diffProgram(TestModuleBC.toString(), SharedObject, false);
847 errs() << ": still failing!\n";
849 errs() << ": didn't fail.\n";
850 TestModuleBC.eraseFromDisk();
851 SafeModuleBC.eraseFromDisk();
852 sys::Path(SharedObject).eraseFromDisk();
858 /// debugCodeGenerator - debug errors in LLC, LLI, or CBE.
860 bool BugDriver::debugCodeGenerator() {
861 if ((void*)SafeInterpreter == (void*)Interpreter) {
862 std::string Result = executeProgramSafely("bugpoint.safe.out");
863 std::cout << "\n*** The \"safe\" i.e. 'known good' backend cannot match "
864 << "the reference diff. This may be due to a\n front-end "
865 << "bug or a bug in the original program, but this can also "
866 << "happen if bugpoint isn't running the program with the "
867 << "right flags or input.\n I left the result of executing "
868 << "the program with the \"safe\" backend in this file for "
874 DisambiguateGlobalSymbols(Program);
876 std::vector<Function*> Funcs = DebugAMiscompilation(*this, TestCodeGenerator);
878 // Split the module into the two halves of the program we want.
879 DenseMap<const Value*, Value*> ValueMap;
880 Module *ToNotCodeGen = CloneModule(getProgram(), ValueMap);
881 Module *ToCodeGen = SplitFunctionsOutOfModule(ToNotCodeGen, Funcs, ValueMap);
883 // Condition the modules
884 CleanupAndPrepareModules(*this, ToCodeGen, ToNotCodeGen);
886 sys::Path TestModuleBC("bugpoint.test.bc");
888 if (TestModuleBC.makeUnique(true, &ErrMsg)) {
889 errs() << getToolName() << "Error making unique filename: "
894 if (writeProgramToFile(TestModuleBC.toString(), ToCodeGen)) {
895 errs() << "Error writing bitcode to `" << TestModuleBC << "'\nExiting.";
900 // Make the shared library
901 sys::Path SafeModuleBC("bugpoint.safe.bc");
902 if (SafeModuleBC.makeUnique(true, &ErrMsg)) {
903 errs() << getToolName() << "Error making unique filename: "
908 if (writeProgramToFile(SafeModuleBC.toString(), ToNotCodeGen)) {
909 errs() << "Error writing bitcode to `" << SafeModuleBC << "'\nExiting.";
912 std::string SharedObject = compileSharedObject(SafeModuleBC.toString());
915 std::cout << "You can reproduce the problem with the command line: \n";
916 if (isExecutingJIT()) {
917 std::cout << " lli -load " << SharedObject << " " << TestModuleBC;
919 std::cout << " llc -f " << TestModuleBC << " -o " << TestModuleBC<< ".s\n";
920 std::cout << " gcc " << SharedObject << " " << TestModuleBC
921 << ".s -o " << TestModuleBC << ".exe";
922 #if defined (HAVE_LINK_R)
923 std::cout << " -Wl,-R.";
926 std::cout << " " << TestModuleBC << ".exe";
928 for (unsigned i=0, e = InputArgv.size(); i != e; ++i)
929 std::cout << " " << InputArgv[i];
931 std::cout << "The shared object was created with:\n llc -march=c "
932 << SafeModuleBC << " -o temporary.c\n"
933 << " gcc -xc temporary.c -O2 -o " << SharedObject
934 #if defined(sparc) || defined(__sparc__) || defined(__sparcv9)
935 << " -G" // Compile a shared library, `-G' for Sparc
937 << " -fPIC -shared" // `-shared' for Linux/X86, maybe others
939 << " -fno-strict-aliasing\n";