1 //===- Miscompilation.cpp - Debug program miscompilations -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
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
32 extern cl::list<std::string> InputArgv;
36 static llvm::cl::opt<bool>
37 DisableLoopExtraction("disable-loop-extraction",
38 cl::desc("Don't extract loops when searching for miscompilations"),
41 class ReduceMiscompilingPasses : public ListReducer<const PassInfo*> {
44 ReduceMiscompilingPasses(BugDriver &bd) : BD(bd) {}
46 virtual TestResult doTest(std::vector<const PassInfo*> &Prefix,
47 std::vector<const PassInfo*> &Suffix);
51 /// TestResult - After passes have been split into a test group and a control
52 /// group, see if they still break the program.
54 ReduceMiscompilingPasses::TestResult
55 ReduceMiscompilingPasses::doTest(std::vector<const PassInfo*> &Prefix,
56 std::vector<const PassInfo*> &Suffix) {
57 // First, run the program with just the Suffix passes. If it is still broken
58 // with JUST the kept passes, discard the prefix passes.
59 std::cout << "Checking to see if '" << getPassesString(Suffix)
60 << "' compile correctly: ";
62 std::string BytecodeResult;
63 if (BD.runPasses(Suffix, BytecodeResult, false/*delete*/, true/*quiet*/)) {
64 std::cerr << " Error running this sequence of passes"
65 << " on the input program!\n";
66 BD.setPassesToRun(Suffix);
67 BD.EmitProgressBytecode("pass-error", false);
68 exit(BD.debugOptimizerCrash());
71 // Check to see if the finished program matches the reference output...
72 if (BD.diffProgram(BytecodeResult, "", true /*delete bytecode*/)) {
73 std::cout << " nope.\n";
75 std::cerr << BD.getToolName() << ": I'm confused: the test fails when "
76 << "no passes are run, nondeterministic program?\n";
79 return KeepSuffix; // Miscompilation detected!
81 std::cout << " yup.\n"; // No miscompilation!
83 if (Prefix.empty()) return NoFailure;
85 // Next, see if the program is broken if we run the "prefix" passes first,
86 // then separately run the "kept" passes.
87 std::cout << "Checking to see if '" << getPassesString(Prefix)
88 << "' compile correctly: ";
90 // If it is not broken with the kept passes, it's possible that the prefix
91 // passes must be run before the kept passes to break it. If the program
92 // WORKS after the prefix passes, but then fails if running the prefix AND
93 // kept passes, we can update our bytecode file to include the result of the
94 // prefix passes, then discard the prefix passes.
96 if (BD.runPasses(Prefix, BytecodeResult, false/*delete*/, true/*quiet*/)) {
97 std::cerr << " Error running this sequence of passes"
98 << " on the input program!\n";
99 BD.setPassesToRun(Prefix);
100 BD.EmitProgressBytecode("pass-error", false);
101 exit(BD.debugOptimizerCrash());
104 // If the prefix maintains the predicate by itself, only keep the prefix!
105 if (BD.diffProgram(BytecodeResult)) {
106 std::cout << " nope.\n";
107 sys::Path(BytecodeResult).eraseFromDisk();
110 std::cout << " yup.\n"; // No miscompilation!
112 // Ok, so now we know that the prefix passes work, try running the suffix
113 // passes on the result of the prefix passes.
115 Module *PrefixOutput = ParseInputFile(BytecodeResult);
116 if (PrefixOutput == 0) {
117 std::cerr << BD.getToolName() << ": Error reading bytecode file '"
118 << BytecodeResult << "'!\n";
121 sys::Path(BytecodeResult).eraseFromDisk(); // No longer need the file on disk
123 // Don't check if there are no passes in the suffix.
127 std::cout << "Checking to see if '" << getPassesString(Suffix)
128 << "' passes compile correctly after the '"
129 << getPassesString(Prefix) << "' passes: ";
131 Module *OriginalInput = BD.swapProgramIn(PrefixOutput);
132 if (BD.runPasses(Suffix, BytecodeResult, false/*delete*/, true/*quiet*/)) {
133 std::cerr << " Error running this sequence of passes"
134 << " on the input program!\n";
135 BD.setPassesToRun(Suffix);
136 BD.EmitProgressBytecode("pass-error", false);
137 exit(BD.debugOptimizerCrash());
141 if (BD.diffProgram(BytecodeResult, "", true/*delete bytecode*/)) {
142 std::cout << " nope.\n";
143 delete OriginalInput; // We pruned down the original input...
147 // Otherwise, we must not be running the bad pass anymore.
148 std::cout << " yup.\n"; // No miscompilation!
149 delete BD.swapProgramIn(OriginalInput); // Restore orig program & free test
154 class ReduceMiscompilingFunctions : public ListReducer<Function*> {
156 bool (*TestFn)(BugDriver &, Module *, Module *);
158 ReduceMiscompilingFunctions(BugDriver &bd,
159 bool (*F)(BugDriver &, Module *, Module *))
160 : BD(bd), TestFn(F) {}
162 virtual TestResult doTest(std::vector<Function*> &Prefix,
163 std::vector<Function*> &Suffix) {
164 if (!Suffix.empty() && TestFuncs(Suffix))
166 if (!Prefix.empty() && TestFuncs(Prefix))
171 bool TestFuncs(const std::vector<Function*> &Prefix);
175 /// TestMergedProgram - Given two modules, link them together and run the
176 /// program, checking to see if the program matches the diff. If the diff
177 /// matches, return false, otherwise return true. If the DeleteInputs argument
178 /// is set to true then this function deletes both input modules before it
181 static bool TestMergedProgram(BugDriver &BD, Module *M1, Module *M2,
183 // Link the two portions of the program back to together.
184 std::string ErrorMsg;
186 M1 = CloneModule(M1);
187 M2 = CloneModule(M2);
189 if (Linker::LinkModules(M1, M2, &ErrorMsg)) {
190 std::cerr << BD.getToolName() << ": Error linking modules together:"
194 delete M2; // We are done with this module.
196 Module *OldProgram = BD.swapProgramIn(M1);
198 // Execute the program. If it does not match the expected output, we must
200 bool Broken = BD.diffProgram();
202 // Delete the linked module & restore the original
203 BD.swapProgramIn(OldProgram);
208 /// TestFuncs - split functions in a Module into two groups: those that are
209 /// under consideration for miscompilation vs. those that are not, and test
210 /// accordingly. Each group of functions becomes a separate Module.
212 bool ReduceMiscompilingFunctions::TestFuncs(const std::vector<Function*>&Funcs){
213 // Test to see if the function is misoptimized if we ONLY run it on the
214 // functions listed in Funcs.
215 std::cout << "Checking to see if the program is misoptimized when "
216 << (Funcs.size()==1 ? "this function is" : "these functions are")
217 << " run through the pass"
218 << (BD.getPassesToRun().size() == 1 ? "" : "es") << ":";
219 PrintFunctionList(Funcs);
222 // Split the module into the two halves of the program we want.
223 Module *ToNotOptimize = CloneModule(BD.getProgram());
224 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize, Funcs);
226 // Run the predicate, not that the predicate will delete both input modules.
227 return TestFn(BD, ToOptimize, ToNotOptimize);
230 /// DisambiguateGlobalSymbols - Mangle symbols to guarantee uniqueness by
231 /// modifying predominantly internal symbols rather than external ones.
233 static void DisambiguateGlobalSymbols(Module *M) {
234 // Try not to cause collisions by minimizing chances of renaming an
235 // already-external symbol, so take in external globals and functions as-is.
236 // The code should work correctly without disambiguation (assuming the same
237 // mangler is used by the two code generators), but having symbols with the
238 // same name causes warnings to be emitted by the code generator.
240 // Agree with the CBE on symbol naming
241 Mang.markCharUnacceptable('.');
242 Mang.setPreserveAsmNames(true);
243 for (Module::global_iterator I = M->global_begin(), E = M->global_end();
245 I->setName(Mang.getValueName(I));
246 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
247 I->setName(Mang.getValueName(I));
250 /// ExtractLoops - Given a reduced list of functions that still exposed the bug,
251 /// check to see if we can extract the loops in the region without obscuring the
252 /// bug. If so, it reduces the amount of code identified.
254 static bool ExtractLoops(BugDriver &BD,
255 bool (*TestFn)(BugDriver &, Module *, Module *),
256 std::vector<Function*> &MiscompiledFunctions) {
257 bool MadeChange = false;
259 if (BugpointIsInterrupted) return MadeChange;
261 Module *ToNotOptimize = CloneModule(BD.getProgram());
262 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
263 MiscompiledFunctions);
264 Module *ToOptimizeLoopExtracted = BD.ExtractLoop(ToOptimize);
265 if (!ToOptimizeLoopExtracted) {
266 // If the loop extractor crashed or if there were no extractible loops,
267 // then this chapter of our odyssey is over with.
268 delete ToNotOptimize;
273 std::cerr << "Extracted a loop from the breaking portion of the program.\n";
275 // Bugpoint is intentionally not very trusting of LLVM transformations. In
276 // particular, we're not going to assume that the loop extractor works, so
277 // we're going to test the newly loop extracted program to make sure nothing
278 // has broken. If something broke, then we'll inform the user and stop
280 AbstractInterpreter *AI = BD.switchToCBE();
281 if (TestMergedProgram(BD, ToOptimizeLoopExtracted, ToNotOptimize, false)) {
282 BD.switchToInterpreter(AI);
284 // Merged program doesn't work anymore!
285 std::cerr << " *** ERROR: Loop extraction broke the program. :("
286 << " Please report a bug!\n";
287 std::cerr << " Continuing on with un-loop-extracted version.\n";
289 BD.writeProgramToFile("bugpoint-loop-extract-fail-tno.bc", ToNotOptimize);
290 BD.writeProgramToFile("bugpoint-loop-extract-fail-to.bc", ToOptimize);
291 BD.writeProgramToFile("bugpoint-loop-extract-fail-to-le.bc",
292 ToOptimizeLoopExtracted);
294 std::cerr << "Please submit the bugpoint-loop-extract-fail-*.bc files.\n";
296 delete ToNotOptimize;
297 delete ToOptimizeLoopExtracted;
301 BD.switchToInterpreter(AI);
303 std::cout << " Testing after loop extraction:\n";
304 // Clone modules, the tester function will free them.
305 Module *TOLEBackup = CloneModule(ToOptimizeLoopExtracted);
306 Module *TNOBackup = CloneModule(ToNotOptimize);
307 if (!TestFn(BD, ToOptimizeLoopExtracted, ToNotOptimize)) {
308 std::cout << "*** Loop extraction masked the problem. Undoing.\n";
309 // If the program is not still broken, then loop extraction did something
310 // that masked the error. Stop loop extraction now.
315 ToOptimizeLoopExtracted = TOLEBackup;
316 ToNotOptimize = TNOBackup;
318 std::cout << "*** Loop extraction successful!\n";
320 std::vector<std::pair<std::string, const FunctionType*> > MisCompFunctions;
321 for (Module::iterator I = ToOptimizeLoopExtracted->begin(),
322 E = ToOptimizeLoopExtracted->end(); I != E; ++I)
323 if (!I->isExternal())
324 MisCompFunctions.push_back(std::make_pair(I->getName(),
325 I->getFunctionType()));
327 // Okay, great! Now we know that we extracted a loop and that loop
328 // extraction both didn't break the program, and didn't mask the problem.
329 // Replace the current program with the loop extracted version, and try to
330 // extract another loop.
331 std::string ErrorMsg;
332 if (Linker::LinkModules(ToNotOptimize, ToOptimizeLoopExtracted, &ErrorMsg)){
333 std::cerr << BD.getToolName() << ": Error linking modules together:"
337 delete ToOptimizeLoopExtracted;
339 // All of the Function*'s in the MiscompiledFunctions list are in the old
340 // module. Update this list to include all of the functions in the
341 // optimized and loop extracted module.
342 MiscompiledFunctions.clear();
343 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
344 Function *NewF = ToNotOptimize->getFunction(MisCompFunctions[i].first,
345 MisCompFunctions[i].second);
346 assert(NewF && "Function not found??");
347 MiscompiledFunctions.push_back(NewF);
350 BD.setNewProgram(ToNotOptimize);
356 class ReduceMiscompiledBlocks : public ListReducer<BasicBlock*> {
358 bool (*TestFn)(BugDriver &, Module *, Module *);
359 std::vector<Function*> FunctionsBeingTested;
361 ReduceMiscompiledBlocks(BugDriver &bd,
362 bool (*F)(BugDriver &, Module *, Module *),
363 const std::vector<Function*> &Fns)
364 : BD(bd), TestFn(F), FunctionsBeingTested(Fns) {}
366 virtual TestResult doTest(std::vector<BasicBlock*> &Prefix,
367 std::vector<BasicBlock*> &Suffix) {
368 if (!Suffix.empty() && TestFuncs(Suffix))
370 if (TestFuncs(Prefix))
375 bool TestFuncs(const std::vector<BasicBlock*> &Prefix);
379 /// TestFuncs - Extract all blocks for the miscompiled functions except for the
380 /// specified blocks. If the problem still exists, return true.
382 bool ReduceMiscompiledBlocks::TestFuncs(const std::vector<BasicBlock*> &BBs) {
383 // Test to see if the function is misoptimized if we ONLY run it on the
384 // functions listed in Funcs.
385 std::cout << "Checking to see if the program is misoptimized when all ";
387 std::cout << "but these " << BBs.size() << " blocks are extracted: ";
388 for (unsigned i = 0, e = BBs.size() < 10 ? BBs.size() : 10; i != e; ++i)
389 std::cout << BBs[i]->getName() << " ";
390 if (BBs.size() > 10) std::cout << "...";
392 std::cout << "blocks are extracted.";
396 // Split the module into the two halves of the program we want.
397 Module *ToNotOptimize = CloneModule(BD.getProgram());
398 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
399 FunctionsBeingTested);
401 // Try the extraction. If it doesn't work, then the block extractor crashed
402 // or something, in which case bugpoint can't chase down this possibility.
403 if (Module *New = BD.ExtractMappedBlocksFromModule(BBs, ToOptimize)) {
405 // Run the predicate, not that the predicate will delete both input modules.
406 return TestFn(BD, New, ToNotOptimize);
409 delete ToNotOptimize;
414 /// ExtractBlocks - Given a reduced list of functions that still expose the bug,
415 /// extract as many basic blocks from the region as possible without obscuring
418 static bool ExtractBlocks(BugDriver &BD,
419 bool (*TestFn)(BugDriver &, Module *, Module *),
420 std::vector<Function*> &MiscompiledFunctions) {
421 if (BugpointIsInterrupted) return false;
423 std::vector<BasicBlock*> Blocks;
424 for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
425 for (Function::iterator I = MiscompiledFunctions[i]->begin(),
426 E = MiscompiledFunctions[i]->end(); I != E; ++I)
429 // Use the list reducer to identify blocks that can be extracted without
430 // obscuring the bug. The Blocks list will end up containing blocks that must
431 // be retained from the original program.
432 unsigned OldSize = Blocks.size();
434 // Check to see if all blocks are extractible first.
435 if (ReduceMiscompiledBlocks(BD, TestFn,
436 MiscompiledFunctions).TestFuncs(std::vector<BasicBlock*>())) {
439 ReduceMiscompiledBlocks(BD, TestFn,MiscompiledFunctions).reduceList(Blocks);
440 if (Blocks.size() == OldSize)
444 Module *ProgClone = CloneModule(BD.getProgram());
445 Module *ToExtract = SplitFunctionsOutOfModule(ProgClone,
446 MiscompiledFunctions);
447 Module *Extracted = BD.ExtractMappedBlocksFromModule(Blocks, ToExtract);
448 if (Extracted == 0) {
449 // Weird, extraction should have worked.
450 std::cerr << "Nondeterministic problem extracting blocks??\n";
456 // Otherwise, block extraction succeeded. Link the two program fragments back
460 std::vector<std::pair<std::string, const FunctionType*> > MisCompFunctions;
461 for (Module::iterator I = Extracted->begin(), E = Extracted->end();
463 if (!I->isExternal())
464 MisCompFunctions.push_back(std::make_pair(I->getName(),
465 I->getFunctionType()));
467 std::string ErrorMsg;
468 if (Linker::LinkModules(ProgClone, Extracted, &ErrorMsg)) {
469 std::cerr << BD.getToolName() << ": Error linking modules together:"
475 // Set the new program and delete the old one.
476 BD.setNewProgram(ProgClone);
478 // Update the list of miscompiled functions.
479 MiscompiledFunctions.clear();
481 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
482 Function *NewF = ProgClone->getFunction(MisCompFunctions[i].first,
483 MisCompFunctions[i].second);
484 assert(NewF && "Function not found??");
485 MiscompiledFunctions.push_back(NewF);
492 /// DebugAMiscompilation - This is a generic driver to narrow down
493 /// miscompilations, either in an optimization or a code generator.
495 static std::vector<Function*>
496 DebugAMiscompilation(BugDriver &BD,
497 bool (*TestFn)(BugDriver &, Module *, Module *)) {
498 // Okay, now that we have reduced the list of passes which are causing the
499 // failure, see if we can pin down which functions are being
500 // miscompiled... first build a list of all of the non-external functions in
502 std::vector<Function*> MiscompiledFunctions;
503 Module *Prog = BD.getProgram();
504 for (Module::iterator I = Prog->begin(), E = Prog->end(); I != E; ++I)
505 if (!I->isExternal())
506 MiscompiledFunctions.push_back(I);
508 // Do the reduction...
509 if (!BugpointIsInterrupted)
510 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
512 std::cout << "\n*** The following function"
513 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
514 << " being miscompiled: ";
515 PrintFunctionList(MiscompiledFunctions);
518 // See if we can rip any loops out of the miscompiled functions and still
519 // trigger the problem.
521 if (!BugpointIsInterrupted && !DisableLoopExtraction &&
522 ExtractLoops(BD, TestFn, MiscompiledFunctions)) {
523 // Okay, we extracted some loops and the problem still appears. See if we
524 // can eliminate some of the created functions from being candidates.
526 // Loop extraction can introduce functions with the same name (foo_code).
527 // Make sure to disambiguate the symbols so that when the program is split
528 // apart that we can link it back together again.
529 DisambiguateGlobalSymbols(BD.getProgram());
531 // Do the reduction...
532 if (!BugpointIsInterrupted)
533 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
535 std::cout << "\n*** The following function"
536 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
537 << " being miscompiled: ";
538 PrintFunctionList(MiscompiledFunctions);
542 if (!BugpointIsInterrupted &&
543 ExtractBlocks(BD, TestFn, MiscompiledFunctions)) {
544 // Okay, we extracted some blocks and the problem still appears. See if we
545 // can eliminate some of the created functions from being candidates.
547 // Block extraction can introduce functions with the same name (foo_code).
548 // Make sure to disambiguate the symbols so that when the program is split
549 // apart that we can link it back together again.
550 DisambiguateGlobalSymbols(BD.getProgram());
552 // Do the reduction...
553 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
555 std::cout << "\n*** The following function"
556 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
557 << " being miscompiled: ";
558 PrintFunctionList(MiscompiledFunctions);
562 return MiscompiledFunctions;
565 /// TestOptimizer - This is the predicate function used to check to see if the
566 /// "Test" portion of the program is misoptimized. If so, return true. In any
567 /// case, both module arguments are deleted.
569 static bool TestOptimizer(BugDriver &BD, Module *Test, Module *Safe) {
570 // Run the optimization passes on ToOptimize, producing a transformed version
571 // of the functions being tested.
572 std::cout << " Optimizing functions being tested: ";
573 Module *Optimized = BD.runPassesOn(Test, BD.getPassesToRun(),
574 /*AutoDebugCrashes*/true);
575 std::cout << "done.\n";
578 std::cout << " Checking to see if the merged program executes correctly: ";
579 bool Broken = TestMergedProgram(BD, Optimized, Safe, true);
580 std::cout << (Broken ? " nope.\n" : " yup.\n");
585 /// debugMiscompilation - This method is used when the passes selected are not
586 /// crashing, but the generated output is semantically different from the
589 bool BugDriver::debugMiscompilation() {
590 // Make sure something was miscompiled...
591 if (!BugpointIsInterrupted)
592 if (!ReduceMiscompilingPasses(*this).reduceList(PassesToRun)) {
593 std::cerr << "*** Optimized program matches reference output! No problem"
594 << " detected...\nbugpoint can't help you with your problem!\n";
598 std::cout << "\n*** Found miscompiling pass"
599 << (getPassesToRun().size() == 1 ? "" : "es") << ": "
600 << getPassesString(getPassesToRun()) << '\n';
601 EmitProgressBytecode("passinput");
603 std::vector<Function*> MiscompiledFunctions =
604 DebugAMiscompilation(*this, TestOptimizer);
606 // Output a bunch of bytecode files for the user...
607 std::cout << "Outputting reduced bytecode files which expose the problem:\n";
608 Module *ToNotOptimize = CloneModule(getProgram());
609 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
610 MiscompiledFunctions);
612 std::cout << " Non-optimized portion: ";
613 ToNotOptimize = swapProgramIn(ToNotOptimize);
614 EmitProgressBytecode("tonotoptimize", true);
615 setNewProgram(ToNotOptimize); // Delete hacked module.
617 std::cout << " Portion that is input to optimizer: ";
618 ToOptimize = swapProgramIn(ToOptimize);
619 EmitProgressBytecode("tooptimize");
620 setNewProgram(ToOptimize); // Delete hacked module.
625 /// CleanupAndPrepareModules - Get the specified modules ready for code
626 /// generator testing.
628 static void CleanupAndPrepareModules(BugDriver &BD, Module *&Test,
630 // Clean up the modules, removing extra cruft that we don't need anymore...
631 Test = BD.performFinalCleanups(Test);
633 // If we are executing the JIT, we have several nasty issues to take care of.
634 if (!BD.isExecutingJIT()) return;
636 // First, if the main function is in the Safe module, we must add a stub to
637 // the Test module to call into it. Thus, we create a new function `main'
638 // which just calls the old one.
639 if (Function *oldMain = Safe->getNamedFunction("main"))
640 if (!oldMain->isExternal()) {
642 oldMain->setName("llvm_bugpoint_old_main");
643 // Create a NEW `main' function with same type in the test module.
644 Function *newMain = new Function(oldMain->getFunctionType(),
645 GlobalValue::ExternalLinkage,
647 // Create an `oldmain' prototype in the test module, which will
648 // corresponds to the real main function in the same module.
649 Function *oldMainProto = new Function(oldMain->getFunctionType(),
650 GlobalValue::ExternalLinkage,
651 oldMain->getName(), Test);
652 // Set up and remember the argument list for the main function.
653 std::vector<Value*> args;
654 for (Function::arg_iterator
655 I = newMain->arg_begin(), E = newMain->arg_end(),
656 OI = oldMain->arg_begin(); I != E; ++I, ++OI) {
657 I->setName(OI->getName()); // Copy argument names from oldMain
661 // Call the old main function and return its result
662 BasicBlock *BB = new BasicBlock("entry", newMain);
663 CallInst *call = new CallInst(oldMainProto, args, "", BB);
665 // If the type of old function wasn't void, return value of call
666 new ReturnInst(call, BB);
669 // The second nasty issue we must deal with in the JIT is that the Safe
670 // module cannot directly reference any functions defined in the test
671 // module. Instead, we use a JIT API call to dynamically resolve the
674 // Add the resolver to the Safe module.
675 // Prototype: void *getPointerToNamedFunction(const char* Name)
676 Function *resolverFunc =
677 Safe->getOrInsertFunction("getPointerToNamedFunction",
678 PointerType::get(Type::SByteTy),
679 PointerType::get(Type::SByteTy), (Type *)0);
681 // Use the function we just added to get addresses of functions we need.
682 for (Module::iterator F = Safe->begin(), E = Safe->end(); F != E; ++F) {
683 if (F->isExternal() && !F->use_empty() && &*F != resolverFunc &&
684 F->getIntrinsicID() == 0 /* ignore intrinsics */) {
685 Function *TestFn = Test->getNamedFunction(F->getName());
687 // Don't forward functions which are external in the test module too.
688 if (TestFn && !TestFn->isExternal()) {
689 // 1. Add a string constant with its name to the global file
690 Constant *InitArray = ConstantArray::get(F->getName());
691 GlobalVariable *funcName =
692 new GlobalVariable(InitArray->getType(), true /*isConstant*/,
693 GlobalValue::InternalLinkage, InitArray,
694 F->getName() + "_name", Safe);
696 // 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an
697 // sbyte* so it matches the signature of the resolver function.
699 // GetElementPtr *funcName, ulong 0, ulong 0
700 std::vector<Constant*> GEPargs(2,Constant::getNullValue(Type::IntTy));
702 ConstantExpr::getGetElementPtr(funcName, GEPargs);
703 std::vector<Value*> ResolverArgs;
704 ResolverArgs.push_back(GEP);
706 // Rewrite uses of F in global initializers, etc. to uses of a wrapper
707 // function that dynamically resolves the calls to F via our JIT API
708 if (!F->use_empty()) {
709 // Create a new global to hold the cached function pointer.
710 Constant *NullPtr = ConstantPointerNull::get(F->getType());
711 GlobalVariable *Cache =
712 new GlobalVariable(F->getType(), false,GlobalValue::InternalLinkage,
713 NullPtr,F->getName()+".fpcache", F->getParent());
715 // Construct a new stub function that will re-route calls to F
716 const FunctionType *FuncTy = F->getFunctionType();
717 Function *FuncWrapper = new Function(FuncTy,
718 GlobalValue::InternalLinkage,
719 F->getName() + "_wrapper",
721 BasicBlock *EntryBB = new BasicBlock("entry", FuncWrapper);
722 BasicBlock *DoCallBB = new BasicBlock("usecache", FuncWrapper);
723 BasicBlock *LookupBB = new BasicBlock("lookupfp", FuncWrapper);
725 // Check to see if we already looked up the value.
726 Value *CachedVal = new LoadInst(Cache, "fpcache", EntryBB);
727 Value *IsNull = new SetCondInst(Instruction::SetEQ, CachedVal,
728 NullPtr, "isNull", EntryBB);
729 new BranchInst(LookupBB, DoCallBB, IsNull, EntryBB);
731 // Resolve the call to function F via the JIT API:
733 // call resolver(GetElementPtr...)
734 CallInst *Resolver = new CallInst(resolverFunc, ResolverArgs,
735 "resolver", LookupBB);
736 // cast the result from the resolver to correctly-typed function
737 CastInst *CastedResolver = new BitCastInst(Resolver,
738 PointerType::get(F->getFunctionType()), "resolverCast", LookupBB);
740 // Save the value in our cache.
741 new StoreInst(CastedResolver, Cache, LookupBB);
742 new BranchInst(DoCallBB, LookupBB);
744 PHINode *FuncPtr = new PHINode(NullPtr->getType(), "fp", DoCallBB);
745 FuncPtr->addIncoming(CastedResolver, LookupBB);
746 FuncPtr->addIncoming(CachedVal, EntryBB);
748 // Save the argument list.
749 std::vector<Value*> Args;
750 for (Function::arg_iterator i = FuncWrapper->arg_begin(),
751 e = FuncWrapper->arg_end(); i != e; ++i)
754 // Pass on the arguments to the real function, return its result
755 if (F->getReturnType() == Type::VoidTy) {
756 new CallInst(FuncPtr, Args, "", DoCallBB);
757 new ReturnInst(DoCallBB);
759 CallInst *Call = new CallInst(FuncPtr, Args, "retval", DoCallBB);
760 new ReturnInst(Call, DoCallBB);
763 // Use the wrapper function instead of the old function
764 F->replaceAllUsesWith(FuncWrapper);
770 if (verifyModule(*Test) || verifyModule(*Safe)) {
771 std::cerr << "Bugpoint has a bug, which corrupted a module!!\n";
778 /// TestCodeGenerator - This is the predicate function used to check to see if
779 /// the "Test" portion of the program is miscompiled by the code generator under
780 /// test. If so, return true. In any case, both module arguments are deleted.
782 static bool TestCodeGenerator(BugDriver &BD, Module *Test, Module *Safe) {
783 CleanupAndPrepareModules(BD, Test, Safe);
785 sys::Path TestModuleBC("bugpoint.test.bc");
787 if (TestModuleBC.makeUnique(true, &ErrMsg)) {
788 std::cerr << BD.getToolName() << "Error making unique filename: "
792 if (BD.writeProgramToFile(TestModuleBC.toString(), Test)) {
793 std::cerr << "Error writing bytecode to `" << TestModuleBC << "'\nExiting.";
798 // Make the shared library
799 sys::Path SafeModuleBC("bugpoint.safe.bc");
800 if (SafeModuleBC.makeUnique(true, &ErrMsg)) {
801 std::cerr << BD.getToolName() << "Error making unique filename: "
806 if (BD.writeProgramToFile(SafeModuleBC.toString(), Safe)) {
807 std::cerr << "Error writing bytecode to `" << SafeModuleBC << "'\nExiting.";
810 std::string SharedObject = BD.compileSharedObject(SafeModuleBC.toString());
813 // Run the code generator on the `Test' code, loading the shared library.
814 // The function returns whether or not the new output differs from reference.
815 int Result = BD.diffProgram(TestModuleBC.toString(), SharedObject, false);
818 std::cerr << ": still failing!\n";
820 std::cerr << ": didn't fail.\n";
821 TestModuleBC.eraseFromDisk();
822 SafeModuleBC.eraseFromDisk();
823 sys::Path(SharedObject).eraseFromDisk();
829 /// debugCodeGenerator - debug errors in LLC, LLI, or CBE.
831 bool BugDriver::debugCodeGenerator() {
832 if ((void*)cbe == (void*)Interpreter) {
833 std::string Result = executeProgramWithCBE("bugpoint.cbe.out");
834 std::cout << "\n*** The C backend cannot match the reference diff, but it "
835 << "is used as the 'known good'\n code generator, so I can't"
836 << " debug it. Perhaps you have a front-end problem?\n As a"
837 << " sanity check, I left the result of executing the program "
838 << "with the C backend\n in this file for you: '"
843 DisambiguateGlobalSymbols(Program);
845 std::vector<Function*> Funcs = DebugAMiscompilation(*this, TestCodeGenerator);
847 // Split the module into the two halves of the program we want.
848 Module *ToNotCodeGen = CloneModule(getProgram());
849 Module *ToCodeGen = SplitFunctionsOutOfModule(ToNotCodeGen, Funcs);
851 // Condition the modules
852 CleanupAndPrepareModules(*this, ToCodeGen, ToNotCodeGen);
854 sys::Path TestModuleBC("bugpoint.test.bc");
856 if (TestModuleBC.makeUnique(true, &ErrMsg)) {
857 std::cerr << getToolName() << "Error making unique filename: "
862 if (writeProgramToFile(TestModuleBC.toString(), ToCodeGen)) {
863 std::cerr << "Error writing bytecode to `" << TestModuleBC << "'\nExiting.";
868 // Make the shared library
869 sys::Path SafeModuleBC("bugpoint.safe.bc");
870 if (SafeModuleBC.makeUnique(true, &ErrMsg)) {
871 std::cerr << getToolName() << "Error making unique filename: "
876 if (writeProgramToFile(SafeModuleBC.toString(), ToNotCodeGen)) {
877 std::cerr << "Error writing bytecode to `" << SafeModuleBC << "'\nExiting.";
880 std::string SharedObject = compileSharedObject(SafeModuleBC.toString());
883 std::cout << "You can reproduce the problem with the command line: \n";
884 if (isExecutingJIT()) {
885 std::cout << " lli -load " << SharedObject << " " << TestModuleBC;
887 std::cout << " llc -f " << TestModuleBC << " -o " << TestModuleBC<< ".s\n";
888 std::cout << " gcc " << SharedObject << " " << TestModuleBC
889 << ".s -o " << TestModuleBC << ".exe";
890 #if defined (HAVE_LINK_R)
891 std::cout << " -Wl,-R.";
894 std::cout << " " << TestModuleBC << ".exe";
896 for (unsigned i=0, e = InputArgv.size(); i != e; ++i)
897 std::cout << " " << InputArgv[i];
899 std::cout << "The shared object was created with:\n llc -march=c "
900 << SafeModuleBC << " -o temporary.c\n"
901 << " gcc -xc temporary.c -O2 -o " << SharedObject
902 #if defined(sparc) || defined(__sparc__) || defined(__sparcv9)
903 << " -G" // Compile a shared library, `-G' for Sparc
905 << " -shared" // `-shared' for Linux/X86, maybe others
907 << " -fno-strict-aliasing\n";