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 class ReduceMiscompilingPasses : public ListReducer<const PassInfo*> {
39 ReduceMiscompilingPasses(BugDriver &bd) : BD(bd) {}
41 virtual TestResult doTest(std::vector<const PassInfo*> &Prefix,
42 std::vector<const PassInfo*> &Suffix);
46 /// TestResult - After passes have been split into a test group and a control
47 /// group, see if they still break the program.
49 ReduceMiscompilingPasses::TestResult
50 ReduceMiscompilingPasses::doTest(std::vector<const PassInfo*> &Prefix,
51 std::vector<const PassInfo*> &Suffix) {
52 // First, run the program with just the Suffix passes. If it is still broken
53 // with JUST the kept passes, discard the prefix passes.
54 std::cout << "Checking to see if '" << getPassesString(Suffix)
55 << "' compile correctly: ";
57 std::string BytecodeResult;
58 if (BD.runPasses(Suffix, BytecodeResult, false/*delete*/, true/*quiet*/)) {
59 std::cerr << " Error running this sequence of passes"
60 << " on the input program!\n";
61 BD.setPassesToRun(Suffix);
62 BD.EmitProgressBytecode("pass-error", false);
63 exit(BD.debugOptimizerCrash());
66 // Check to see if the finished program matches the reference output...
67 if (BD.diffProgram(BytecodeResult, "", true /*delete bytecode*/)) {
68 std::cout << " nope.\n";
70 std::cerr << BD.getToolName() << ": I'm confused: the test fails when "
71 << "no passes are run, nondeterministic program?\n";
74 return KeepSuffix; // Miscompilation detected!
76 std::cout << " yup.\n"; // No miscompilation!
78 if (Prefix.empty()) return NoFailure;
80 // Next, see if the program is broken if we run the "prefix" passes first,
81 // then separately run the "kept" passes.
82 std::cout << "Checking to see if '" << getPassesString(Prefix)
83 << "' compile correctly: ";
85 // If it is not broken with the kept passes, it's possible that the prefix
86 // passes must be run before the kept passes to break it. If the program
87 // WORKS after the prefix passes, but then fails if running the prefix AND
88 // kept passes, we can update our bytecode file to include the result of the
89 // prefix passes, then discard the prefix passes.
91 if (BD.runPasses(Prefix, BytecodeResult, false/*delete*/, true/*quiet*/)) {
92 std::cerr << " Error running this sequence of passes"
93 << " on the input program!\n";
94 BD.setPassesToRun(Prefix);
95 BD.EmitProgressBytecode("pass-error", false);
96 exit(BD.debugOptimizerCrash());
99 // If the prefix maintains the predicate by itself, only keep the prefix!
100 if (BD.diffProgram(BytecodeResult)) {
101 std::cout << " nope.\n";
102 sys::Path(BytecodeResult).destroyFile();
105 std::cout << " yup.\n"; // No miscompilation!
107 // Ok, so now we know that the prefix passes work, try running the suffix
108 // passes on the result of the prefix passes.
110 Module *PrefixOutput = ParseInputFile(BytecodeResult);
111 if (PrefixOutput == 0) {
112 std::cerr << BD.getToolName() << ": Error reading bytecode file '"
113 << BytecodeResult << "'!\n";
116 sys::Path(BytecodeResult).destroyFile(); // No longer need the file on disk
118 // Don't check if there are no passes in the suffix.
122 std::cout << "Checking to see if '" << getPassesString(Suffix)
123 << "' passes compile correctly after the '"
124 << getPassesString(Prefix) << "' passes: ";
126 Module *OriginalInput = BD.swapProgramIn(PrefixOutput);
127 if (BD.runPasses(Suffix, BytecodeResult, false/*delete*/, true/*quiet*/)) {
128 std::cerr << " Error running this sequence of passes"
129 << " on the input program!\n";
130 BD.setPassesToRun(Suffix);
131 BD.EmitProgressBytecode("pass-error", false);
132 exit(BD.debugOptimizerCrash());
136 if (BD.diffProgram(BytecodeResult, "", true/*delete bytecode*/)) {
137 std::cout << " nope.\n";
138 delete OriginalInput; // We pruned down the original input...
142 // Otherwise, we must not be running the bad pass anymore.
143 std::cout << " yup.\n"; // No miscompilation!
144 delete BD.swapProgramIn(OriginalInput); // Restore orig program & free test
149 class ReduceMiscompilingFunctions : public ListReducer<Function*> {
151 bool (*TestFn)(BugDriver &, Module *, Module *);
153 ReduceMiscompilingFunctions(BugDriver &bd,
154 bool (*F)(BugDriver &, Module *, Module *))
155 : BD(bd), TestFn(F) {}
157 virtual TestResult doTest(std::vector<Function*> &Prefix,
158 std::vector<Function*> &Suffix) {
159 if (!Suffix.empty() && TestFuncs(Suffix))
161 if (!Prefix.empty() && TestFuncs(Prefix))
166 bool TestFuncs(const std::vector<Function*> &Prefix);
170 /// TestMergedProgram - Given two modules, link them together and run the
171 /// program, checking to see if the program matches the diff. If the diff
172 /// matches, return false, otherwise return true. If the DeleteInputs argument
173 /// is set to true then this function deletes both input modules before it
176 static bool TestMergedProgram(BugDriver &BD, Module *M1, Module *M2,
178 // Link the two portions of the program back to together.
179 std::string ErrorMsg;
181 M1 = CloneModule(M1);
182 M2 = CloneModule(M2);
184 if (Linker::LinkModules(M1, M2, &ErrorMsg)) {
185 std::cerr << BD.getToolName() << ": Error linking modules together:"
189 delete M2; // We are done with this module.
191 Module *OldProgram = BD.swapProgramIn(M1);
193 // Execute the program. If it does not match the expected output, we must
195 bool Broken = BD.diffProgram();
197 // Delete the linked module & restore the original
198 BD.swapProgramIn(OldProgram);
203 /// TestFuncs - split functions in a Module into two groups: those that are
204 /// under consideration for miscompilation vs. those that are not, and test
205 /// accordingly. Each group of functions becomes a separate Module.
207 bool ReduceMiscompilingFunctions::TestFuncs(const std::vector<Function*>&Funcs){
208 // Test to see if the function is misoptimized if we ONLY run it on the
209 // functions listed in Funcs.
210 std::cout << "Checking to see if the program is misoptimized when "
211 << (Funcs.size()==1 ? "this function is" : "these functions are")
212 << " run through the pass"
213 << (BD.getPassesToRun().size() == 1 ? "" : "es") << ":";
214 PrintFunctionList(Funcs);
217 // Split the module into the two halves of the program we want.
218 Module *ToNotOptimize = CloneModule(BD.getProgram());
219 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize, Funcs);
221 // Run the predicate, not that the predicate will delete both input modules.
222 return TestFn(BD, ToOptimize, ToNotOptimize);
225 /// DisambiguateGlobalSymbols - Mangle symbols to guarantee uniqueness by
226 /// modifying predominantly internal symbols rather than external ones.
228 static void DisambiguateGlobalSymbols(Module *M) {
229 // Try not to cause collisions by minimizing chances of renaming an
230 // already-external symbol, so take in external globals and functions as-is.
231 // The code should work correctly without disambiguation (assuming the same
232 // mangler is used by the two code generators), but having symbols with the
233 // same name causes warnings to be emitted by the code generator.
235 for (Module::global_iterator I = M->global_begin(), E = M->global_end(); I != E; ++I)
236 I->setName(Mang.getValueName(I));
237 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
238 I->setName(Mang.getValueName(I));
241 /// ExtractLoops - Given a reduced list of functions that still exposed the bug,
242 /// check to see if we can extract the loops in the region without obscuring the
243 /// bug. If so, it reduces the amount of code identified.
245 static bool ExtractLoops(BugDriver &BD,
246 bool (*TestFn)(BugDriver &, Module *, Module *),
247 std::vector<Function*> &MiscompiledFunctions) {
248 bool MadeChange = false;
250 Module *ToNotOptimize = CloneModule(BD.getProgram());
251 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
252 MiscompiledFunctions);
253 Module *ToOptimizeLoopExtracted = BD.ExtractLoop(ToOptimize);
254 if (!ToOptimizeLoopExtracted) {
255 // If the loop extractor crashed or if there were no extractible loops,
256 // then this chapter of our odyssey is over with.
257 delete ToNotOptimize;
262 std::cerr << "Extracted a loop from the breaking portion of the program.\n";
265 // Bugpoint is intentionally not very trusting of LLVM transformations. In
266 // particular, we're not going to assume that the loop extractor works, so
267 // we're going to test the newly loop extracted program to make sure nothing
268 // has broken. If something broke, then we'll inform the user and stop
270 AbstractInterpreter *AI = BD.switchToCBE();
271 if (TestMergedProgram(BD, ToOptimizeLoopExtracted, ToNotOptimize, false)) {
272 BD.switchToInterpreter(AI);
274 // Merged program doesn't work anymore!
275 std::cerr << " *** ERROR: Loop extraction broke the program. :("
276 << " Please report a bug!\n";
277 std::cerr << " Continuing on with un-loop-extracted version.\n";
278 delete ToNotOptimize;
279 delete ToOptimizeLoopExtracted;
282 BD.switchToInterpreter(AI);
284 std::cout << " Testing after loop extraction:\n";
285 // Clone modules, the tester function will free them.
286 Module *TOLEBackup = CloneModule(ToOptimizeLoopExtracted);
287 Module *TNOBackup = CloneModule(ToNotOptimize);
288 if (!TestFn(BD, ToOptimizeLoopExtracted, ToNotOptimize)) {
289 std::cout << "*** Loop extraction masked the problem. Undoing.\n";
290 // If the program is not still broken, then loop extraction did something
291 // that masked the error. Stop loop extraction now.
296 ToOptimizeLoopExtracted = TOLEBackup;
297 ToNotOptimize = TNOBackup;
299 std::cout << "*** Loop extraction successful!\n";
301 std::vector<std::pair<std::string, const FunctionType*> > MisCompFunctions;
302 for (Module::iterator I = ToOptimizeLoopExtracted->begin(),
303 E = ToOptimizeLoopExtracted->end(); I != E; ++I)
304 if (!I->isExternal())
305 MisCompFunctions.push_back(std::make_pair(I->getName(),
306 I->getFunctionType()));
308 // Okay, great! Now we know that we extracted a loop and that loop
309 // extraction both didn't break the program, and didn't mask the problem.
310 // Replace the current program with the loop extracted version, and try to
311 // extract another loop.
312 std::string ErrorMsg;
313 if (Linker::LinkModules(ToNotOptimize, ToOptimizeLoopExtracted, &ErrorMsg)){
314 std::cerr << BD.getToolName() << ": Error linking modules together:"
318 delete ToOptimizeLoopExtracted;
320 // All of the Function*'s in the MiscompiledFunctions list are in the old
321 // module. Update this list to include all of the functions in the
322 // optimized and loop extracted module.
323 MiscompiledFunctions.clear();
324 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
325 Function *NewF = ToNotOptimize->getFunction(MisCompFunctions[i].first,
326 MisCompFunctions[i].second);
327 assert(NewF && "Function not found??");
328 MiscompiledFunctions.push_back(NewF);
331 BD.setNewProgram(ToNotOptimize);
337 class ReduceMiscompiledBlocks : public ListReducer<BasicBlock*> {
339 bool (*TestFn)(BugDriver &, Module *, Module *);
340 std::vector<Function*> FunctionsBeingTested;
342 ReduceMiscompiledBlocks(BugDriver &bd,
343 bool (*F)(BugDriver &, Module *, Module *),
344 const std::vector<Function*> &Fns)
345 : BD(bd), TestFn(F), FunctionsBeingTested(Fns) {}
347 virtual TestResult doTest(std::vector<BasicBlock*> &Prefix,
348 std::vector<BasicBlock*> &Suffix) {
349 if (!Suffix.empty() && TestFuncs(Suffix))
351 if (TestFuncs(Prefix))
356 bool TestFuncs(const std::vector<BasicBlock*> &Prefix);
360 /// TestFuncs - Extract all blocks for the miscompiled functions except for the
361 /// specified blocks. If the problem still exists, return true.
363 bool ReduceMiscompiledBlocks::TestFuncs(const std::vector<BasicBlock*> &BBs) {
364 // Test to see if the function is misoptimized if we ONLY run it on the
365 // functions listed in Funcs.
366 std::cout << "Checking to see if the program is misoptimized when all ";
368 std::cout << "but these " << BBs.size() << " blocks are extracted: ";
369 for (unsigned i = 0, e = BBs.size() < 10 ? BBs.size() : 10; i != e; ++i)
370 std::cout << BBs[i]->getName() << " ";
371 if (BBs.size() > 10) std::cout << "...";
373 std::cout << "blocks are extracted.";
377 // Split the module into the two halves of the program we want.
378 Module *ToNotOptimize = CloneModule(BD.getProgram());
379 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
380 FunctionsBeingTested);
382 // Try the extraction. If it doesn't work, then the block extractor crashed
383 // or something, in which case bugpoint can't chase down this possibility.
384 if (Module *New = BD.ExtractMappedBlocksFromModule(BBs, ToOptimize)) {
386 // Run the predicate, not that the predicate will delete both input modules.
387 return TestFn(BD, New, ToNotOptimize);
390 delete ToNotOptimize;
395 /// ExtractBlocks - Given a reduced list of functions that still expose the bug,
396 /// extract as many basic blocks from the region as possible without obscuring
399 static bool ExtractBlocks(BugDriver &BD,
400 bool (*TestFn)(BugDriver &, Module *, Module *),
401 std::vector<Function*> &MiscompiledFunctions) {
402 std::vector<BasicBlock*> Blocks;
403 for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
404 for (Function::iterator I = MiscompiledFunctions[i]->begin(),
405 E = MiscompiledFunctions[i]->end(); I != E; ++I)
408 // Use the list reducer to identify blocks that can be extracted without
409 // obscuring the bug. The Blocks list will end up containing blocks that must
410 // be retained from the original program.
411 unsigned OldSize = Blocks.size();
413 // Check to see if all blocks are extractible first.
414 if (ReduceMiscompiledBlocks(BD, TestFn,
415 MiscompiledFunctions).TestFuncs(std::vector<BasicBlock*>())) {
418 ReduceMiscompiledBlocks(BD, TestFn,MiscompiledFunctions).reduceList(Blocks);
419 if (Blocks.size() == OldSize)
423 Module *ProgClone = CloneModule(BD.getProgram());
424 Module *ToExtract = SplitFunctionsOutOfModule(ProgClone,
425 MiscompiledFunctions);
426 Module *Extracted = BD.ExtractMappedBlocksFromModule(Blocks, ToExtract);
427 if (Extracted == 0) {
428 // Weird, extraction should have worked.
429 std::cerr << "Nondeterministic problem extracting blocks??\n";
435 // Otherwise, block extraction succeeded. Link the two program fragments back
439 std::vector<std::pair<std::string, const FunctionType*> > MisCompFunctions;
440 for (Module::iterator I = Extracted->begin(), E = Extracted->end();
442 if (!I->isExternal())
443 MisCompFunctions.push_back(std::make_pair(I->getName(),
444 I->getFunctionType()));
446 std::string ErrorMsg;
447 if (Linker::LinkModules(ProgClone, Extracted, &ErrorMsg)) {
448 std::cerr << BD.getToolName() << ": Error linking modules together:"
454 // Set the new program and delete the old one.
455 BD.setNewProgram(ProgClone);
457 // Update the list of miscompiled functions.
458 MiscompiledFunctions.clear();
460 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
461 Function *NewF = ProgClone->getFunction(MisCompFunctions[i].first,
462 MisCompFunctions[i].second);
463 assert(NewF && "Function not found??");
464 MiscompiledFunctions.push_back(NewF);
471 /// DebugAMiscompilation - This is a generic driver to narrow down
472 /// miscompilations, either in an optimization or a code generator.
474 static std::vector<Function*>
475 DebugAMiscompilation(BugDriver &BD,
476 bool (*TestFn)(BugDriver &, Module *, Module *)) {
477 // Okay, now that we have reduced the list of passes which are causing the
478 // failure, see if we can pin down which functions are being
479 // miscompiled... first build a list of all of the non-external functions in
481 std::vector<Function*> MiscompiledFunctions;
482 Module *Prog = BD.getProgram();
483 for (Module::iterator I = Prog->begin(), E = Prog->end(); I != E; ++I)
484 if (!I->isExternal())
485 MiscompiledFunctions.push_back(I);
487 // Do the reduction...
488 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
490 std::cout << "\n*** The following function"
491 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
492 << " being miscompiled: ";
493 PrintFunctionList(MiscompiledFunctions);
496 // See if we can rip any loops out of the miscompiled functions and still
497 // trigger the problem.
498 if (ExtractLoops(BD, TestFn, MiscompiledFunctions)) {
499 // Okay, we extracted some loops and the problem still appears. See if we
500 // can eliminate some of the created functions from being candidates.
502 // Loop extraction can introduce functions with the same name (foo_code).
503 // Make sure to disambiguate the symbols so that when the program is split
504 // apart that we can link it back together again.
505 DisambiguateGlobalSymbols(BD.getProgram());
507 // Do the reduction...
508 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
510 std::cout << "\n*** The following function"
511 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
512 << " being miscompiled: ";
513 PrintFunctionList(MiscompiledFunctions);
517 if (ExtractBlocks(BD, TestFn, MiscompiledFunctions)) {
518 // Okay, we extracted some blocks and the problem still appears. See if we
519 // can eliminate some of the created functions from being candidates.
521 // Block extraction can introduce functions with the same name (foo_code).
522 // Make sure to disambiguate the symbols so that when the program is split
523 // apart that we can link it back together again.
524 DisambiguateGlobalSymbols(BD.getProgram());
526 // Do the reduction...
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);
536 return MiscompiledFunctions;
539 /// TestOptimizer - This is the predicate function used to check to see if the
540 /// "Test" portion of the program is misoptimized. If so, return true. In any
541 /// case, both module arguments are deleted.
543 static bool TestOptimizer(BugDriver &BD, Module *Test, Module *Safe) {
544 // Run the optimization passes on ToOptimize, producing a transformed version
545 // of the functions being tested.
546 std::cout << " Optimizing functions being tested: ";
547 Module *Optimized = BD.runPassesOn(Test, BD.getPassesToRun(),
548 /*AutoDebugCrashes*/true);
549 std::cout << "done.\n";
552 std::cout << " Checking to see if the merged program executes correctly: ";
553 bool Broken = TestMergedProgram(BD, Optimized, Safe, true);
554 std::cout << (Broken ? " nope.\n" : " yup.\n");
559 /// debugMiscompilation - This method is used when the passes selected are not
560 /// crashing, but the generated output is semantically different from the
563 bool BugDriver::debugMiscompilation() {
564 // Make sure something was miscompiled...
565 if (!ReduceMiscompilingPasses(*this).reduceList(PassesToRun)) {
566 std::cerr << "*** Optimized program matches reference output! No problem "
567 << "detected...\nbugpoint can't help you with your problem!\n";
571 std::cout << "\n*** Found miscompiling pass"
572 << (getPassesToRun().size() == 1 ? "" : "es") << ": "
573 << getPassesString(getPassesToRun()) << '\n';
574 EmitProgressBytecode("passinput");
576 std::vector<Function*> MiscompiledFunctions =
577 DebugAMiscompilation(*this, TestOptimizer);
579 // Output a bunch of bytecode files for the user...
580 std::cout << "Outputting reduced bytecode files which expose the problem:\n";
581 Module *ToNotOptimize = CloneModule(getProgram());
582 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
583 MiscompiledFunctions);
585 std::cout << " Non-optimized portion: ";
586 ToNotOptimize = swapProgramIn(ToNotOptimize);
587 EmitProgressBytecode("tonotoptimize", true);
588 setNewProgram(ToNotOptimize); // Delete hacked module.
590 std::cout << " Portion that is input to optimizer: ";
591 ToOptimize = swapProgramIn(ToOptimize);
592 EmitProgressBytecode("tooptimize");
593 setNewProgram(ToOptimize); // Delete hacked module.
598 /// CleanupAndPrepareModules - Get the specified modules ready for code
599 /// generator testing.
601 static void CleanupAndPrepareModules(BugDriver &BD, Module *&Test,
603 // Clean up the modules, removing extra cruft that we don't need anymore...
604 Test = BD.performFinalCleanups(Test);
606 // If we are executing the JIT, we have several nasty issues to take care of.
607 if (!BD.isExecutingJIT()) return;
609 // First, if the main function is in the Safe module, we must add a stub to
610 // the Test module to call into it. Thus, we create a new function `main'
611 // which just calls the old one.
612 if (Function *oldMain = Safe->getNamedFunction("main"))
613 if (!oldMain->isExternal()) {
615 oldMain->setName("llvm_bugpoint_old_main");
616 // Create a NEW `main' function with same type in the test module.
617 Function *newMain = new Function(oldMain->getFunctionType(),
618 GlobalValue::ExternalLinkage,
620 // Create an `oldmain' prototype in the test module, which will
621 // corresponds to the real main function in the same module.
622 Function *oldMainProto = new Function(oldMain->getFunctionType(),
623 GlobalValue::ExternalLinkage,
624 oldMain->getName(), Test);
625 // Set up and remember the argument list for the main function.
626 std::vector<Value*> args;
627 for (Function::arg_iterator
628 I = newMain->arg_begin(), E = newMain->arg_end(),
629 OI = oldMain->arg_begin(); I != E; ++I, ++OI) {
630 I->setName(OI->getName()); // Copy argument names from oldMain
634 // Call the old main function and return its result
635 BasicBlock *BB = new BasicBlock("entry", newMain);
636 CallInst *call = new CallInst(oldMainProto, args, "", BB);
638 // If the type of old function wasn't void, return value of call
639 new ReturnInst(call, BB);
642 // The second nasty issue we must deal with in the JIT is that the Safe
643 // module cannot directly reference any functions defined in the test
644 // module. Instead, we use a JIT API call to dynamically resolve the
647 // Add the resolver to the Safe module.
648 // Prototype: void *getPointerToNamedFunction(const char* Name)
649 Function *resolverFunc =
650 Safe->getOrInsertFunction("getPointerToNamedFunction",
651 PointerType::get(Type::SByteTy),
652 PointerType::get(Type::SByteTy), 0);
654 // Use the function we just added to get addresses of functions we need.
655 for (Module::iterator F = Safe->begin(), E = Safe->end(); F != E; ++F) {
656 if (F->isExternal() && !F->use_empty() && &*F != resolverFunc &&
657 F->getIntrinsicID() == 0 /* ignore intrinsics */) {
658 Function *TestFn = Test->getFunction(F->getName(), F->getFunctionType());
660 // Don't forward functions which are external in the test module too.
661 if (TestFn && !TestFn->isExternal()) {
662 // 1. Add a string constant with its name to the global file
663 Constant *InitArray = ConstantArray::get(F->getName());
664 GlobalVariable *funcName =
665 new GlobalVariable(InitArray->getType(), true /*isConstant*/,
666 GlobalValue::InternalLinkage, InitArray,
667 F->getName() + "_name", Safe);
669 // 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an
670 // sbyte* so it matches the signature of the resolver function.
672 // GetElementPtr *funcName, ulong 0, ulong 0
673 std::vector<Constant*> GEPargs(2,Constant::getNullValue(Type::IntTy));
675 ConstantExpr::getGetElementPtr(funcName, GEPargs);
676 std::vector<Value*> ResolverArgs;
677 ResolverArgs.push_back(GEP);
679 // Rewrite uses of F in global initializers, etc. to uses of a wrapper
680 // function that dynamically resolves the calls to F via our JIT API
681 if (F->use_begin() != F->use_end()) {
682 // Construct a new stub function that will re-route calls to F
683 const FunctionType *FuncTy = F->getFunctionType();
684 Function *FuncWrapper = new Function(FuncTy,
685 GlobalValue::InternalLinkage,
686 F->getName() + "_wrapper",
688 BasicBlock *Header = new BasicBlock("header", FuncWrapper);
690 // Resolve the call to function F via the JIT API:
692 // call resolver(GetElementPtr...)
693 CallInst *resolve = new CallInst(resolverFunc, ResolverArgs,
695 Header->getInstList().push_back(resolve);
696 // cast the result from the resolver to correctly-typed function
697 CastInst *castResolver =
698 new CastInst(resolve, PointerType::get(F->getFunctionType()),
700 Header->getInstList().push_back(castResolver);
702 // Save the argument list
703 std::vector<Value*> Args;
704 for (Function::arg_iterator i = FuncWrapper->arg_begin(),
705 e = FuncWrapper->arg_end(); i != e; ++i)
708 // Pass on the arguments to the real function, return its result
709 if (F->getReturnType() == Type::VoidTy) {
710 CallInst *Call = new CallInst(castResolver, Args);
711 Header->getInstList().push_back(Call);
712 ReturnInst *Ret = new ReturnInst();
713 Header->getInstList().push_back(Ret);
715 CallInst *Call = new CallInst(castResolver, Args, "redir");
716 Header->getInstList().push_back(Call);
717 ReturnInst *Ret = new ReturnInst(Call);
718 Header->getInstList().push_back(Ret);
721 // Use the wrapper function instead of the old function
722 F->replaceAllUsesWith(FuncWrapper);
728 if (verifyModule(*Test) || verifyModule(*Safe)) {
729 std::cerr << "Bugpoint has a bug, which corrupted a module!!\n";
736 /// TestCodeGenerator - This is the predicate function used to check to see if
737 /// the "Test" portion of the program is miscompiled by the code generator under
738 /// test. If so, return true. In any case, both module arguments are deleted.
740 static bool TestCodeGenerator(BugDriver &BD, Module *Test, Module *Safe) {
741 CleanupAndPrepareModules(BD, Test, Safe);
743 sys::Path TestModuleBC("bugpoint.test.bc");
744 TestModuleBC.makeUnique();
745 if (BD.writeProgramToFile(TestModuleBC.toString(), Test)) {
746 std::cerr << "Error writing bytecode to `" << TestModuleBC << "'\nExiting.";
751 // Make the shared library
752 sys::Path SafeModuleBC("bugpoint.safe.bc");
753 SafeModuleBC.makeUnique();
755 if (BD.writeProgramToFile(SafeModuleBC.toString(), Safe)) {
756 std::cerr << "Error writing bytecode to `" << SafeModuleBC << "'\nExiting.";
759 std::string SharedObject = BD.compileSharedObject(SafeModuleBC.toString());
762 // Run the code generator on the `Test' code, loading the shared library.
763 // The function returns whether or not the new output differs from reference.
764 int Result = BD.diffProgram(TestModuleBC.toString(), SharedObject, false);
767 std::cerr << ": still failing!\n";
769 std::cerr << ": didn't fail.\n";
770 TestModuleBC.destroyFile();
771 SafeModuleBC.destroyFile();
772 sys::Path(SharedObject).destroyFile();
778 /// debugCodeGenerator - debug errors in LLC, LLI, or CBE.
780 bool BugDriver::debugCodeGenerator() {
781 if ((void*)cbe == (void*)Interpreter) {
782 std::string Result = executeProgramWithCBE("bugpoint.cbe.out");
783 std::cout << "\n*** The C backend cannot match the reference diff, but it "
784 << "is used as the 'known good'\n code generator, so I can't"
785 << " debug it. Perhaps you have a front-end problem?\n As a"
786 << " sanity check, I left the result of executing the program "
787 << "with the C backend\n in this file for you: '"
792 DisambiguateGlobalSymbols(Program);
794 std::vector<Function*> Funcs = DebugAMiscompilation(*this, TestCodeGenerator);
796 // Split the module into the two halves of the program we want.
797 Module *ToNotCodeGen = CloneModule(getProgram());
798 Module *ToCodeGen = SplitFunctionsOutOfModule(ToNotCodeGen, Funcs);
800 // Condition the modules
801 CleanupAndPrepareModules(*this, ToCodeGen, ToNotCodeGen);
803 sys::Path TestModuleBC("bugpoint.test.bc");
804 TestModuleBC.makeUnique();
806 if (writeProgramToFile(TestModuleBC.toString(), ToCodeGen)) {
807 std::cerr << "Error writing bytecode to `" << TestModuleBC << "'\nExiting.";
812 // Make the shared library
813 sys::Path SafeModuleBC("bugpoint.safe.bc");
814 SafeModuleBC.makeUnique();
816 if (writeProgramToFile(SafeModuleBC.toString(), ToNotCodeGen)) {
817 std::cerr << "Error writing bytecode to `" << SafeModuleBC << "'\nExiting.";
820 std::string SharedObject = compileSharedObject(SafeModuleBC.toString());
823 std::cout << "You can reproduce the problem with the command line: \n";
824 if (isExecutingJIT()) {
825 std::cout << " lli -load " << SharedObject << " " << TestModuleBC;
827 std::cout << " llc -f " << TestModuleBC << " -o " << TestModuleBC<< ".s\n";
828 std::cout << " gcc " << SharedObject << " " << TestModuleBC
829 << ".s -o " << TestModuleBC << ".exe";
830 #if defined (HAVE_LINK_R)
831 std::cout << "-Wl,-R.";
834 std::cout << " " << TestModuleBC << ".exe";
836 for (unsigned i=0, e = InputArgv.size(); i != e; ++i)
837 std::cout << " " << InputArgv[i];
839 std::cout << "The shared object was created with:\n llc -march=c "
840 << SafeModuleBC << " -o temporary.c\n"
841 << " gcc -xc temporary.c -O2 -o " << SharedObject
842 #if defined(sparc) || defined(__sparc__) || defined(__sparcv9)
843 << " -G" // Compile a shared library, `-G' for Sparc
845 << " -shared" // `-shared' for Linux/X86, maybe others
847 << " -fno-strict-aliasing\n";