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/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Linker.h"
22 #include "llvm/Module.h"
23 #include "llvm/Pass.h"
24 #include "llvm/Analysis/Verifier.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
32 extern cl::opt<std::string> OutputPrefix;
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"),
41 static llvm::cl::opt<bool>
42 DisableBlockExtraction("disable-block-extraction",
43 cl::desc("Don't extract blocks when searching for miscompilations"),
46 class ReduceMiscompilingPasses : public ListReducer<const PassInfo*> {
49 ReduceMiscompilingPasses(BugDriver &bd) : BD(bd) {}
51 virtual TestResult doTest(std::vector<const PassInfo*> &Prefix,
52 std::vector<const PassInfo*> &Suffix);
56 /// TestResult - After passes have been split into a test group and a control
57 /// group, see if they still break the program.
59 ReduceMiscompilingPasses::TestResult
60 ReduceMiscompilingPasses::doTest(std::vector<const PassInfo*> &Prefix,
61 std::vector<const PassInfo*> &Suffix) {
62 // First, run the program with just the Suffix passes. If it is still broken
63 // with JUST the kept passes, discard the prefix passes.
64 outs() << "Checking to see if '" << getPassesString(Suffix)
65 << "' compiles correctly: ";
67 std::string BitcodeResult;
68 if (BD.runPasses(Suffix, BitcodeResult, false/*delete*/, true/*quiet*/)) {
69 errs() << " Error running this sequence of passes"
70 << " on the input program!\n";
71 BD.setPassesToRun(Suffix);
72 BD.EmitProgressBitcode("pass-error", false);
73 exit(BD.debugOptimizerCrash());
76 // Check to see if the finished program matches the reference output...
77 if (BD.diffProgram(BitcodeResult, "", true /*delete bitcode*/)) {
80 errs() << BD.getToolName() << ": I'm confused: the test fails when "
81 << "no passes are run, nondeterministic program?\n";
84 return KeepSuffix; // Miscompilation detected!
86 outs() << " yup.\n"; // No miscompilation!
88 if (Prefix.empty()) return NoFailure;
90 // Next, see if the program is broken if we run the "prefix" passes first,
91 // then separately run the "kept" passes.
92 outs() << "Checking to see if '" << getPassesString(Prefix)
93 << "' compiles correctly: ";
95 // If it is not broken with the kept passes, it's possible that the prefix
96 // passes must be run before the kept passes to break it. If the program
97 // WORKS after the prefix passes, but then fails if running the prefix AND
98 // kept passes, we can update our bitcode file to include the result of the
99 // prefix passes, then discard the prefix passes.
101 if (BD.runPasses(Prefix, BitcodeResult, false/*delete*/, true/*quiet*/)) {
102 errs() << " Error running this sequence of passes"
103 << " on the input program!\n";
104 BD.setPassesToRun(Prefix);
105 BD.EmitProgressBitcode("pass-error", false);
106 exit(BD.debugOptimizerCrash());
109 // If the prefix maintains the predicate by itself, only keep the prefix!
110 if (BD.diffProgram(BitcodeResult)) {
111 outs() << " nope.\n";
112 sys::Path(BitcodeResult).eraseFromDisk();
115 outs() << " yup.\n"; // No miscompilation!
117 // Ok, so now we know that the prefix passes work, try running the suffix
118 // passes on the result of the prefix passes.
120 Module *PrefixOutput = ParseInputFile(BitcodeResult, BD.getContext());
121 if (PrefixOutput == 0) {
122 errs() << BD.getToolName() << ": Error reading bitcode file '"
123 << BitcodeResult << "'!\n";
126 sys::Path(BitcodeResult).eraseFromDisk(); // No longer need the file on disk
128 // Don't check if there are no passes in the suffix.
132 outs() << "Checking to see if '" << getPassesString(Suffix)
133 << "' passes compile correctly after the '"
134 << getPassesString(Prefix) << "' passes: ";
136 Module *OriginalInput = BD.swapProgramIn(PrefixOutput);
137 if (BD.runPasses(Suffix, BitcodeResult, false/*delete*/, true/*quiet*/)) {
138 errs() << " Error running this sequence of passes"
139 << " on the input program!\n";
140 BD.setPassesToRun(Suffix);
141 BD.EmitProgressBitcode("pass-error", false);
142 exit(BD.debugOptimizerCrash());
146 if (BD.diffProgram(BitcodeResult, "", true/*delete bitcode*/)) {
147 outs() << " nope.\n";
148 delete OriginalInput; // We pruned down the original input...
152 // Otherwise, we must not be running the bad pass anymore.
153 outs() << " yup.\n"; // No miscompilation!
154 delete BD.swapProgramIn(OriginalInput); // Restore orig program & free test
159 class ReduceMiscompilingFunctions : public ListReducer<Function*> {
161 bool (*TestFn)(BugDriver &, Module *, Module *);
163 ReduceMiscompilingFunctions(BugDriver &bd,
164 bool (*F)(BugDriver &, Module *, Module *))
165 : BD(bd), TestFn(F) {}
167 virtual TestResult doTest(std::vector<Function*> &Prefix,
168 std::vector<Function*> &Suffix) {
169 if (!Suffix.empty() && TestFuncs(Suffix))
171 if (!Prefix.empty() && TestFuncs(Prefix))
176 bool TestFuncs(const std::vector<Function*> &Prefix);
180 /// TestMergedProgram - Given two modules, link them together and run the
181 /// program, checking to see if the program matches the diff. If the diff
182 /// matches, return false, otherwise return true. If the DeleteInputs argument
183 /// is set to true then this function deletes both input modules before it
186 static bool TestMergedProgram(BugDriver &BD, Module *M1, Module *M2,
188 // Link the two portions of the program back to together.
189 std::string ErrorMsg;
191 M1 = CloneModule(M1);
192 M2 = CloneModule(M2);
194 if (Linker::LinkModules(M1, M2, &ErrorMsg)) {
195 errs() << BD.getToolName() << ": Error linking modules together:"
199 delete M2; // We are done with this module.
201 Module *OldProgram = BD.swapProgramIn(M1);
203 // Execute the program. If it does not match the expected output, we must
205 bool Broken = BD.diffProgram();
207 // Delete the linked module & restore the original
208 BD.swapProgramIn(OldProgram);
213 /// TestFuncs - split functions in a Module into two groups: those that are
214 /// under consideration for miscompilation vs. those that are not, and test
215 /// accordingly. Each group of functions becomes a separate Module.
217 bool ReduceMiscompilingFunctions::TestFuncs(const std::vector<Function*>&Funcs){
218 // Test to see if the function is misoptimized if we ONLY run it on the
219 // functions listed in Funcs.
220 outs() << "Checking to see if the program is misoptimized when "
221 << (Funcs.size()==1 ? "this function is" : "these functions are")
222 << " run through the pass"
223 << (BD.getPassesToRun().size() == 1 ? "" : "es") << ":";
224 PrintFunctionList(Funcs);
227 // Split the module into the two halves of the program we want.
228 DenseMap<const Value*, Value*> ValueMap;
229 Module *ToNotOptimize = CloneModule(BD.getProgram(), ValueMap);
230 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize, Funcs,
233 // Run the predicate, note that the predicate will delete both input modules.
234 return TestFn(BD, ToOptimize, ToNotOptimize);
237 /// DisambiguateGlobalSymbols - Give anonymous global values names.
239 static void DisambiguateGlobalSymbols(Module *M) {
240 for (Module::global_iterator I = M->global_begin(), E = M->global_end();
243 I->setName("anon_global");
244 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
246 I->setName("anon_fn");
249 /// ExtractLoops - Given a reduced list of functions that still exposed the bug,
250 /// check to see if we can extract the loops in the region without obscuring the
251 /// bug. If so, it reduces the amount of code identified.
253 static bool ExtractLoops(BugDriver &BD,
254 bool (*TestFn)(BugDriver &, Module *, Module *),
255 std::vector<Function*> &MiscompiledFunctions) {
256 bool MadeChange = false;
258 if (BugpointIsInterrupted) return MadeChange;
260 DenseMap<const Value*, Value*> ValueMap;
261 Module *ToNotOptimize = CloneModule(BD.getProgram(), ValueMap);
262 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
263 MiscompiledFunctions,
265 Module *ToOptimizeLoopExtracted = BD.ExtractLoop(ToOptimize);
266 if (!ToOptimizeLoopExtracted) {
267 // If the loop extractor crashed or if there were no extractible loops,
268 // then this chapter of our odyssey is over with.
269 delete ToNotOptimize;
274 errs() << "Extracted a loop from the breaking portion of the program.\n";
276 // Bugpoint is intentionally not very trusting of LLVM transformations. In
277 // particular, we're not going to assume that the loop extractor works, so
278 // we're going to test the newly loop extracted program to make sure nothing
279 // has broken. If something broke, then we'll inform the user and stop
281 AbstractInterpreter *AI = BD.switchToSafeInterpreter();
282 if (TestMergedProgram(BD, ToOptimizeLoopExtracted, ToNotOptimize, false)) {
283 BD.switchToInterpreter(AI);
285 // Merged program doesn't work anymore!
286 errs() << " *** ERROR: Loop extraction broke the program. :("
287 << " Please report a bug!\n";
288 errs() << " Continuing on with un-loop-extracted version.\n";
290 BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-tno.bc",
292 BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-to.bc",
294 BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-to-le.bc",
295 ToOptimizeLoopExtracted);
297 errs() << "Please submit the "
298 << OutputPrefix << "-loop-extract-fail-*.bc files.\n";
300 delete ToNotOptimize;
301 delete ToOptimizeLoopExtracted;
305 BD.switchToInterpreter(AI);
307 outs() << " Testing after loop extraction:\n";
308 // Clone modules, the tester function will free them.
309 Module *TOLEBackup = CloneModule(ToOptimizeLoopExtracted);
310 Module *TNOBackup = CloneModule(ToNotOptimize);
311 if (!TestFn(BD, ToOptimizeLoopExtracted, ToNotOptimize)) {
312 outs() << "*** Loop extraction masked the problem. Undoing.\n";
313 // If the program is not still broken, then loop extraction did something
314 // that masked the error. Stop loop extraction now.
319 ToOptimizeLoopExtracted = TOLEBackup;
320 ToNotOptimize = TNOBackup;
322 outs() << "*** Loop extraction successful!\n";
324 std::vector<std::pair<std::string, const FunctionType*> > MisCompFunctions;
325 for (Module::iterator I = ToOptimizeLoopExtracted->begin(),
326 E = ToOptimizeLoopExtracted->end(); I != E; ++I)
327 if (!I->isDeclaration())
328 MisCompFunctions.push_back(std::make_pair(I->getName(),
329 I->getFunctionType()));
331 // Okay, great! Now we know that we extracted a loop and that loop
332 // extraction both didn't break the program, and didn't mask the problem.
333 // Replace the current program with the loop extracted version, and try to
334 // extract another loop.
335 std::string ErrorMsg;
336 if (Linker::LinkModules(ToNotOptimize, ToOptimizeLoopExtracted, &ErrorMsg)){
337 errs() << BD.getToolName() << ": Error linking modules together:"
341 delete ToOptimizeLoopExtracted;
343 // All of the Function*'s in the MiscompiledFunctions list are in the old
344 // module. Update this list to include all of the functions in the
345 // optimized and loop extracted module.
346 MiscompiledFunctions.clear();
347 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
348 Function *NewF = ToNotOptimize->getFunction(MisCompFunctions[i].first);
350 assert(NewF && "Function not found??");
351 assert(NewF->getFunctionType() == MisCompFunctions[i].second &&
352 "found wrong function type?");
353 MiscompiledFunctions.push_back(NewF);
356 BD.setNewProgram(ToNotOptimize);
362 class ReduceMiscompiledBlocks : public ListReducer<BasicBlock*> {
364 bool (*TestFn)(BugDriver &, Module *, Module *);
365 std::vector<Function*> FunctionsBeingTested;
367 ReduceMiscompiledBlocks(BugDriver &bd,
368 bool (*F)(BugDriver &, Module *, Module *),
369 const std::vector<Function*> &Fns)
370 : BD(bd), TestFn(F), FunctionsBeingTested(Fns) {}
372 virtual TestResult doTest(std::vector<BasicBlock*> &Prefix,
373 std::vector<BasicBlock*> &Suffix) {
374 if (!Suffix.empty() && TestFuncs(Suffix))
376 if (TestFuncs(Prefix))
381 bool TestFuncs(const std::vector<BasicBlock*> &Prefix);
385 /// TestFuncs - Extract all blocks for the miscompiled functions except for the
386 /// specified blocks. If the problem still exists, return true.
388 bool ReduceMiscompiledBlocks::TestFuncs(const std::vector<BasicBlock*> &BBs) {
389 // Test to see if the function is misoptimized if we ONLY run it on the
390 // functions listed in Funcs.
391 outs() << "Checking to see if the program is misoptimized when all ";
393 outs() << "but these " << BBs.size() << " blocks are extracted: ";
394 for (unsigned i = 0, e = BBs.size() < 10 ? BBs.size() : 10; i != e; ++i)
395 outs() << BBs[i]->getName() << " ";
396 if (BBs.size() > 10) outs() << "...";
398 outs() << "blocks are extracted.";
402 // Split the module into the two halves of the program we want.
403 DenseMap<const Value*, Value*> ValueMap;
404 Module *ToNotOptimize = CloneModule(BD.getProgram(), ValueMap);
405 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
406 FunctionsBeingTested,
409 // Try the extraction. If it doesn't work, then the block extractor crashed
410 // or something, in which case bugpoint can't chase down this possibility.
411 if (Module *New = BD.ExtractMappedBlocksFromModule(BBs, ToOptimize)) {
413 // Run the predicate, not that the predicate will delete both input modules.
414 return TestFn(BD, New, ToNotOptimize);
417 delete ToNotOptimize;
422 /// ExtractBlocks - Given a reduced list of functions that still expose the bug,
423 /// extract as many basic blocks from the region as possible without obscuring
426 static bool ExtractBlocks(BugDriver &BD,
427 bool (*TestFn)(BugDriver &, Module *, Module *),
428 std::vector<Function*> &MiscompiledFunctions) {
429 if (BugpointIsInterrupted) return false;
431 std::vector<BasicBlock*> Blocks;
432 for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
433 for (Function::iterator I = MiscompiledFunctions[i]->begin(),
434 E = MiscompiledFunctions[i]->end(); I != E; ++I)
437 // Use the list reducer to identify blocks that can be extracted without
438 // obscuring the bug. The Blocks list will end up containing blocks that must
439 // be retained from the original program.
440 unsigned OldSize = Blocks.size();
442 // Check to see if all blocks are extractible first.
443 if (ReduceMiscompiledBlocks(BD, TestFn,
444 MiscompiledFunctions).TestFuncs(std::vector<BasicBlock*>())) {
447 ReduceMiscompiledBlocks(BD, TestFn,MiscompiledFunctions).reduceList(Blocks);
448 if (Blocks.size() == OldSize)
452 DenseMap<const Value*, Value*> ValueMap;
453 Module *ProgClone = CloneModule(BD.getProgram(), ValueMap);
454 Module *ToExtract = SplitFunctionsOutOfModule(ProgClone,
455 MiscompiledFunctions,
457 Module *Extracted = BD.ExtractMappedBlocksFromModule(Blocks, ToExtract);
458 if (Extracted == 0) {
459 // Weird, extraction should have worked.
460 errs() << "Nondeterministic problem extracting blocks??\n";
466 // Otherwise, block extraction succeeded. Link the two program fragments back
470 std::vector<std::pair<std::string, const FunctionType*> > MisCompFunctions;
471 for (Module::iterator I = Extracted->begin(), E = Extracted->end();
473 if (!I->isDeclaration())
474 MisCompFunctions.push_back(std::make_pair(I->getName(),
475 I->getFunctionType()));
477 std::string ErrorMsg;
478 if (Linker::LinkModules(ProgClone, Extracted, &ErrorMsg)) {
479 errs() << BD.getToolName() << ": Error linking modules together:"
485 // Set the new program and delete the old one.
486 BD.setNewProgram(ProgClone);
488 // Update the list of miscompiled functions.
489 MiscompiledFunctions.clear();
491 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
492 Function *NewF = ProgClone->getFunction(MisCompFunctions[i].first);
493 assert(NewF && "Function not found??");
494 assert(NewF->getFunctionType() == MisCompFunctions[i].second &&
495 "Function has wrong type??");
496 MiscompiledFunctions.push_back(NewF);
503 /// DebugAMiscompilation - This is a generic driver to narrow down
504 /// miscompilations, either in an optimization or a code generator.
506 static std::vector<Function*>
507 DebugAMiscompilation(BugDriver &BD,
508 bool (*TestFn)(BugDriver &, Module *, Module *)) {
509 // Okay, now that we have reduced the list of passes which are causing the
510 // failure, see if we can pin down which functions are being
511 // miscompiled... first build a list of all of the non-external functions in
513 std::vector<Function*> MiscompiledFunctions;
514 Module *Prog = BD.getProgram();
515 for (Module::iterator I = Prog->begin(), E = Prog->end(); I != E; ++I)
516 if (!I->isDeclaration())
517 MiscompiledFunctions.push_back(I);
519 // Do the reduction...
520 if (!BugpointIsInterrupted)
521 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
523 outs() << "\n*** The following function"
524 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
525 << " being miscompiled: ";
526 PrintFunctionList(MiscompiledFunctions);
529 // See if we can rip any loops out of the miscompiled functions and still
530 // trigger the problem.
532 if (!BugpointIsInterrupted && !DisableLoopExtraction &&
533 ExtractLoops(BD, TestFn, MiscompiledFunctions)) {
534 // Okay, we extracted some loops and the problem still appears. See if we
535 // can eliminate some of the created functions from being candidates.
536 DisambiguateGlobalSymbols(BD.getProgram());
538 // Do the reduction...
539 if (!BugpointIsInterrupted)
540 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
542 outs() << "\n*** The following function"
543 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
544 << " being miscompiled: ";
545 PrintFunctionList(MiscompiledFunctions);
549 if (!BugpointIsInterrupted && !DisableBlockExtraction &&
550 ExtractBlocks(BD, TestFn, MiscompiledFunctions)) {
551 // Okay, we extracted some blocks and the problem still appears. See if we
552 // can eliminate some of the created functions from being candidates.
553 DisambiguateGlobalSymbols(BD.getProgram());
555 // Do the reduction...
556 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
558 outs() << "\n*** The following function"
559 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
560 << " being miscompiled: ";
561 PrintFunctionList(MiscompiledFunctions);
565 return MiscompiledFunctions;
568 /// TestOptimizer - This is the predicate function used to check to see if the
569 /// "Test" portion of the program is misoptimized. If so, return true. In any
570 /// case, both module arguments are deleted.
572 static bool TestOptimizer(BugDriver &BD, Module *Test, Module *Safe) {
573 // Run the optimization passes on ToOptimize, producing a transformed version
574 // of the functions being tested.
575 outs() << " Optimizing functions being tested: ";
576 Module *Optimized = BD.runPassesOn(Test, BD.getPassesToRun(),
577 /*AutoDebugCrashes*/true);
581 outs() << " Checking to see if the merged program executes correctly: ";
582 bool Broken = TestMergedProgram(BD, Optimized, Safe, true);
583 outs() << (Broken ? " nope.\n" : " yup.\n");
588 /// debugMiscompilation - This method is used when the passes selected are not
589 /// crashing, but the generated output is semantically different from the
592 bool BugDriver::debugMiscompilation() {
593 // Make sure something was miscompiled...
594 if (!BugpointIsInterrupted)
595 if (!ReduceMiscompilingPasses(*this).reduceList(PassesToRun)) {
596 errs() << "*** Optimized program matches reference output! No problem"
597 << " detected...\nbugpoint can't help you with your problem!\n";
601 outs() << "\n*** Found miscompiling pass"
602 << (getPassesToRun().size() == 1 ? "" : "es") << ": "
603 << getPassesString(getPassesToRun()) << '\n';
604 EmitProgressBitcode("passinput");
606 std::vector<Function*> MiscompiledFunctions =
607 DebugAMiscompilation(*this, TestOptimizer);
609 // Output a bunch of bitcode files for the user...
610 outs() << "Outputting reduced bitcode files which expose the problem:\n";
611 DenseMap<const Value*, Value*> ValueMap;
612 Module *ToNotOptimize = CloneModule(getProgram(), ValueMap);
613 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
614 MiscompiledFunctions,
617 outs() << " Non-optimized portion: ";
618 ToNotOptimize = swapProgramIn(ToNotOptimize);
619 EmitProgressBitcode("tonotoptimize", true);
620 setNewProgram(ToNotOptimize); // Delete hacked module.
622 outs() << " Portion that is input to optimizer: ";
623 ToOptimize = swapProgramIn(ToOptimize);
624 EmitProgressBitcode("tooptimize");
625 setNewProgram(ToOptimize); // Delete hacked module.
630 /// CleanupAndPrepareModules - Get the specified modules ready for code
631 /// generator testing.
633 static void CleanupAndPrepareModules(BugDriver &BD, Module *&Test,
635 // Clean up the modules, removing extra cruft that we don't need anymore...
636 Test = BD.performFinalCleanups(Test);
638 // If we are executing the JIT, we have several nasty issues to take care of.
639 if (!BD.isExecutingJIT()) return;
641 // First, if the main function is in the Safe module, we must add a stub to
642 // the Test module to call into it. Thus, we create a new function `main'
643 // which just calls the old one.
644 if (Function *oldMain = Safe->getFunction("main"))
645 if (!oldMain->isDeclaration()) {
647 oldMain->setName("llvm_bugpoint_old_main");
648 // Create a NEW `main' function with same type in the test module.
649 Function *newMain = Function::Create(oldMain->getFunctionType(),
650 GlobalValue::ExternalLinkage,
652 // Create an `oldmain' prototype in the test module, which will
653 // corresponds to the real main function in the same module.
654 Function *oldMainProto = Function::Create(oldMain->getFunctionType(),
655 GlobalValue::ExternalLinkage,
656 oldMain->getName(), Test);
657 // Set up and remember the argument list for the main function.
658 std::vector<Value*> args;
659 for (Function::arg_iterator
660 I = newMain->arg_begin(), E = newMain->arg_end(),
661 OI = oldMain->arg_begin(); I != E; ++I, ++OI) {
662 I->setName(OI->getName()); // Copy argument names from oldMain
666 // Call the old main function and return its result
667 BasicBlock *BB = BasicBlock::Create(Safe->getContext(), "entry", newMain);
668 CallInst *call = CallInst::Create(oldMainProto, args.begin(), args.end(),
671 // If the type of old function wasn't void, return value of call
672 ReturnInst::Create(Safe->getContext(), call, BB);
675 // The second nasty issue we must deal with in the JIT is that the Safe
676 // module cannot directly reference any functions defined in the test
677 // module. Instead, we use a JIT API call to dynamically resolve the
680 // Add the resolver to the Safe module.
681 // Prototype: void *getPointerToNamedFunction(const char* Name)
682 Constant *resolverFunc =
683 Safe->getOrInsertFunction("getPointerToNamedFunction",
684 Type::getInt8PtrTy(Safe->getContext()),
685 Type::getInt8PtrTy(Safe->getContext()),
688 // Use the function we just added to get addresses of functions we need.
689 for (Module::iterator F = Safe->begin(), E = Safe->end(); F != E; ++F) {
690 if (F->isDeclaration() && !F->use_empty() && &*F != resolverFunc &&
691 !F->isIntrinsic() /* ignore intrinsics */) {
692 Function *TestFn = Test->getFunction(F->getName());
694 // Don't forward functions which are external in the test module too.
695 if (TestFn && !TestFn->isDeclaration()) {
696 // 1. Add a string constant with its name to the global file
697 Constant *InitArray = ConstantArray::get(F->getContext(), F->getName());
698 GlobalVariable *funcName =
699 new GlobalVariable(*Safe, InitArray->getType(), true /*isConstant*/,
700 GlobalValue::InternalLinkage, InitArray,
701 F->getName() + "_name");
703 // 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an
704 // sbyte* so it matches the signature of the resolver function.
706 // GetElementPtr *funcName, ulong 0, ulong 0
707 std::vector<Constant*> GEPargs(2,
708 Constant::getNullValue(Type::getInt32Ty(F->getContext())));
710 ConstantExpr::getGetElementPtr(funcName, &GEPargs[0], 2);
711 std::vector<Value*> ResolverArgs;
712 ResolverArgs.push_back(GEP);
714 // Rewrite uses of F in global initializers, etc. to uses of a wrapper
715 // function that dynamically resolves the calls to F via our JIT API
716 if (!F->use_empty()) {
717 // Create a new global to hold the cached function pointer.
718 Constant *NullPtr = ConstantPointerNull::get(F->getType());
719 GlobalVariable *Cache =
720 new GlobalVariable(*F->getParent(), F->getType(),
721 false, GlobalValue::InternalLinkage,
722 NullPtr,F->getName()+".fpcache");
724 // Construct a new stub function that will re-route calls to F
725 const FunctionType *FuncTy = F->getFunctionType();
726 Function *FuncWrapper = Function::Create(FuncTy,
727 GlobalValue::InternalLinkage,
728 F->getName() + "_wrapper",
730 BasicBlock *EntryBB = BasicBlock::Create(F->getContext(),
731 "entry", FuncWrapper);
732 BasicBlock *DoCallBB = BasicBlock::Create(F->getContext(),
733 "usecache", FuncWrapper);
734 BasicBlock *LookupBB = BasicBlock::Create(F->getContext(),
735 "lookupfp", FuncWrapper);
737 // Check to see if we already looked up the value.
738 Value *CachedVal = new LoadInst(Cache, "fpcache", EntryBB);
739 Value *IsNull = new ICmpInst(*EntryBB, ICmpInst::ICMP_EQ, CachedVal,
741 BranchInst::Create(LookupBB, DoCallBB, IsNull, EntryBB);
743 // Resolve the call to function F via the JIT API:
745 // call resolver(GetElementPtr...)
747 CallInst::Create(resolverFunc, ResolverArgs.begin(),
748 ResolverArgs.end(), "resolver", LookupBB);
750 // Cast the result from the resolver to correctly-typed function.
751 CastInst *CastedResolver =
752 new BitCastInst(Resolver,
753 PointerType::getUnqual(F->getFunctionType()),
754 "resolverCast", LookupBB);
756 // Save the value in our cache.
757 new StoreInst(CastedResolver, Cache, LookupBB);
758 BranchInst::Create(DoCallBB, LookupBB);
760 PHINode *FuncPtr = PHINode::Create(NullPtr->getType(),
762 FuncPtr->addIncoming(CastedResolver, LookupBB);
763 FuncPtr->addIncoming(CachedVal, EntryBB);
765 // Save the argument list.
766 std::vector<Value*> Args;
767 for (Function::arg_iterator i = FuncWrapper->arg_begin(),
768 e = FuncWrapper->arg_end(); i != e; ++i)
771 // Pass on the arguments to the real function, return its result
772 if (F->getReturnType() == Type::getVoidTy(F->getContext())) {
773 CallInst::Create(FuncPtr, Args.begin(), Args.end(), "", DoCallBB);
774 ReturnInst::Create(F->getContext(), DoCallBB);
776 CallInst *Call = CallInst::Create(FuncPtr, Args.begin(), Args.end(),
778 ReturnInst::Create(F->getContext(),Call, DoCallBB);
781 // Use the wrapper function instead of the old function
782 F->replaceAllUsesWith(FuncWrapper);
788 if (verifyModule(*Test) || verifyModule(*Safe)) {
789 errs() << "Bugpoint has a bug, which corrupted a module!!\n";
796 /// TestCodeGenerator - This is the predicate function used to check to see if
797 /// the "Test" portion of the program is miscompiled by the code generator under
798 /// test. If so, return true. In any case, both module arguments are deleted.
800 static bool TestCodeGenerator(BugDriver &BD, Module *Test, Module *Safe) {
801 CleanupAndPrepareModules(BD, Test, Safe);
803 sys::Path TestModuleBC("bugpoint.test.bc");
805 if (TestModuleBC.makeUnique(true, &ErrMsg)) {
806 errs() << BD.getToolName() << "Error making unique filename: "
810 if (BD.writeProgramToFile(TestModuleBC.str(), Test)) {
811 errs() << "Error writing bitcode to `" << TestModuleBC.str()
817 // Make the shared library
818 sys::Path SafeModuleBC("bugpoint.safe.bc");
819 if (SafeModuleBC.makeUnique(true, &ErrMsg)) {
820 errs() << BD.getToolName() << "Error making unique filename: "
825 if (BD.writeProgramToFile(SafeModuleBC.str(), Safe)) {
826 errs() << "Error writing bitcode to `" << SafeModuleBC.str()
830 std::string SharedObject = BD.compileSharedObject(SafeModuleBC.str());
833 // Run the code generator on the `Test' code, loading the shared library.
834 // The function returns whether or not the new output differs from reference.
835 int Result = BD.diffProgram(TestModuleBC.str(), SharedObject, false);
838 errs() << ": still failing!\n";
840 errs() << ": didn't fail.\n";
841 TestModuleBC.eraseFromDisk();
842 SafeModuleBC.eraseFromDisk();
843 sys::Path(SharedObject).eraseFromDisk();
849 /// debugCodeGenerator - debug errors in LLC, LLI, or CBE.
851 bool BugDriver::debugCodeGenerator() {
852 if ((void*)SafeInterpreter == (void*)Interpreter) {
853 std::string Result = executeProgramSafely("bugpoint.safe.out");
854 outs() << "\n*** The \"safe\" i.e. 'known good' backend cannot match "
855 << "the reference diff. This may be due to a\n front-end "
856 << "bug or a bug in the original program, but this can also "
857 << "happen if bugpoint isn't running the program with the "
858 << "right flags or input.\n I left the result of executing "
859 << "the program with the \"safe\" backend in this file for "
865 DisambiguateGlobalSymbols(Program);
867 std::vector<Function*> Funcs = DebugAMiscompilation(*this, TestCodeGenerator);
869 // Split the module into the two halves of the program we want.
870 DenseMap<const Value*, Value*> ValueMap;
871 Module *ToNotCodeGen = CloneModule(getProgram(), ValueMap);
872 Module *ToCodeGen = SplitFunctionsOutOfModule(ToNotCodeGen, Funcs, ValueMap);
874 // Condition the modules
875 CleanupAndPrepareModules(*this, ToCodeGen, ToNotCodeGen);
877 sys::Path TestModuleBC("bugpoint.test.bc");
879 if (TestModuleBC.makeUnique(true, &ErrMsg)) {
880 errs() << getToolName() << "Error making unique filename: "
885 if (writeProgramToFile(TestModuleBC.str(), ToCodeGen)) {
886 errs() << "Error writing bitcode to `" << TestModuleBC.str()
892 // Make the shared library
893 sys::Path SafeModuleBC("bugpoint.safe.bc");
894 if (SafeModuleBC.makeUnique(true, &ErrMsg)) {
895 errs() << getToolName() << "Error making unique filename: "
900 if (writeProgramToFile(SafeModuleBC.str(), ToNotCodeGen)) {
901 errs() << "Error writing bitcode to `" << SafeModuleBC.str()
905 std::string SharedObject = compileSharedObject(SafeModuleBC.str());
908 outs() << "You can reproduce the problem with the command line: \n";
909 if (isExecutingJIT()) {
910 outs() << " lli -load " << SharedObject << " " << TestModuleBC.str();
912 outs() << " llc -f " << TestModuleBC.str() << " -o " << TestModuleBC.str()
914 outs() << " gcc " << SharedObject << " " << TestModuleBC.str()
915 << ".s -o " << TestModuleBC.str() << ".exe";
916 #if defined (HAVE_LINK_R)
917 outs() << " -Wl,-R.";
920 outs() << " " << TestModuleBC.str() << ".exe";
922 for (unsigned i=0, e = InputArgv.size(); i != e; ++i)
923 outs() << " " << InputArgv[i];
925 outs() << "The shared object was created with:\n llc -march=c "
926 << SafeModuleBC.str() << " -o temporary.c\n"
927 << " gcc -xc temporary.c -O2 -o " << SharedObject;
928 if (TargetTriple.getArch() == Triple::sparc)
929 outs() << " -G"; // Compile a shared library, `-G' for Sparc
931 outs() << " -fPIC -shared"; // `-shared' for Linux/X86, maybe others
933 outs() << " -fno-strict-aliasing\n";