+/// CleanupAndPrepareModules - Get the specified modules ready for code
+/// generator testing.
+///
+static void CleanupAndPrepareModules(BugDriver &BD, Module *&Test,
+ Module *Safe) {
+ // Clean up the modules, removing extra cruft that we don't need anymore...
+ Test = BD.performFinalCleanups(Test);
+
+ // If we are executing the JIT, we have several nasty issues to take care of.
+ if (!BD.isExecutingJIT()) return;
+
+ // First, if the main function is in the Safe module, we must add a stub to
+ // the Test module to call into it. Thus, we create a new function `main'
+ // which just calls the old one.
+ if (Function *oldMain = Safe->getFunction("main"))
+ if (!oldMain->isDeclaration()) {
+ // Rename it
+ oldMain->setName("llvm_bugpoint_old_main");
+ // Create a NEW `main' function with same type in the test module.
+ Function *newMain = Function::Create(oldMain->getFunctionType(),
+ GlobalValue::ExternalLinkage,
+ "main", Test);
+ // Create an `oldmain' prototype in the test module, which will
+ // corresponds to the real main function in the same module.
+ Function *oldMainProto = Function::Create(oldMain->getFunctionType(),
+ GlobalValue::ExternalLinkage,
+ oldMain->getName(), Test);
+ // Set up and remember the argument list for the main function.
+ std::vector<Value*> args;
+ for (Function::arg_iterator
+ I = newMain->arg_begin(), E = newMain->arg_end(),
+ OI = oldMain->arg_begin(); I != E; ++I, ++OI) {
+ I->setName(OI->getName()); // Copy argument names from oldMain
+ args.push_back(I);
+ }
+
+ // Call the old main function and return its result
+ BasicBlock *BB = BasicBlock::Create("entry", newMain);
+ CallInst *call = CallInst::Create(oldMainProto, args.begin(), args.end(),
+ "", BB);
+
+ // If the type of old function wasn't void, return value of call
+ ReturnInst::Create(call, BB);
+ }
+
+ // The second nasty issue we must deal with in the JIT is that the Safe
+ // module cannot directly reference any functions defined in the test
+ // module. Instead, we use a JIT API call to dynamically resolve the
+ // symbol.
+
+ // Add the resolver to the Safe module.
+ // Prototype: void *getPointerToNamedFunction(const char* Name)
+ Constant *resolverFunc =
+ Safe->getOrInsertFunction("getPointerToNamedFunction",
+ PointerType::getUnqual(Type::Int8Ty),
+ PointerType::getUnqual(Type::Int8Ty), (Type *)0);
+
+ // Use the function we just added to get addresses of functions we need.
+ for (Module::iterator F = Safe->begin(), E = Safe->end(); F != E; ++F) {
+ if (F->isDeclaration() && !F->use_empty() && &*F != resolverFunc &&
+ !F->isIntrinsic() /* ignore intrinsics */) {
+ Function *TestFn = Test->getFunction(F->getName());
+
+ // Don't forward functions which are external in the test module too.
+ if (TestFn && !TestFn->isDeclaration()) {
+ // 1. Add a string constant with its name to the global file
+ Constant *InitArray = ConstantArray::get(F->getName());
+ GlobalVariable *funcName =
+ new GlobalVariable(InitArray->getType(), true /*isConstant*/,
+ GlobalValue::InternalLinkage, InitArray,
+ F->getName() + "_name", Safe);
+
+ // 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an
+ // sbyte* so it matches the signature of the resolver function.
+
+ // GetElementPtr *funcName, ulong 0, ulong 0
+ std::vector<Constant*> GEPargs(2,Constant::getNullValue(Type::Int32Ty));
+ Value *GEP = ConstantExpr::getGetElementPtr(funcName, &GEPargs[0], 2);
+ std::vector<Value*> ResolverArgs;
+ ResolverArgs.push_back(GEP);
+
+ // Rewrite uses of F in global initializers, etc. to uses of a wrapper
+ // function that dynamically resolves the calls to F via our JIT API
+ if (!F->use_empty()) {
+ // Create a new global to hold the cached function pointer.
+ Constant *NullPtr = ConstantPointerNull::get(F->getType());
+ GlobalVariable *Cache =
+ new GlobalVariable(F->getType(), false,GlobalValue::InternalLinkage,
+ NullPtr,F->getName()+".fpcache", F->getParent());
+
+ // Construct a new stub function that will re-route calls to F
+ const FunctionType *FuncTy = F->getFunctionType();
+ Function *FuncWrapper = Function::Create(FuncTy,
+ GlobalValue::InternalLinkage,
+ F->getName() + "_wrapper",
+ F->getParent());
+ BasicBlock *EntryBB = BasicBlock::Create("entry", FuncWrapper);
+ BasicBlock *DoCallBB = BasicBlock::Create("usecache", FuncWrapper);
+ BasicBlock *LookupBB = BasicBlock::Create("lookupfp", FuncWrapper);
+
+ // Check to see if we already looked up the value.
+ Value *CachedVal = new LoadInst(Cache, "fpcache", EntryBB);
+ Value *IsNull = new ICmpInst(ICmpInst::ICMP_EQ, CachedVal,
+ NullPtr, "isNull", EntryBB);
+ BranchInst::Create(LookupBB, DoCallBB, IsNull, EntryBB);
+
+ // Resolve the call to function F via the JIT API:
+ //
+ // call resolver(GetElementPtr...)
+ CallInst *Resolver =
+ CallInst::Create(resolverFunc, ResolverArgs.begin(),
+ ResolverArgs.end(), "resolver", LookupBB);
+
+ // Cast the result from the resolver to correctly-typed function.
+ CastInst *CastedResolver =
+ new BitCastInst(Resolver,
+ PointerType::getUnqual(F->getFunctionType()),
+ "resolverCast", LookupBB);
+
+ // Save the value in our cache.
+ new StoreInst(CastedResolver, Cache, LookupBB);
+ BranchInst::Create(DoCallBB, LookupBB);
+
+ PHINode *FuncPtr = PHINode::Create(NullPtr->getType(),
+ "fp", DoCallBB);
+ FuncPtr->addIncoming(CastedResolver, LookupBB);
+ FuncPtr->addIncoming(CachedVal, EntryBB);
+
+ // Save the argument list.
+ std::vector<Value*> Args;
+ for (Function::arg_iterator i = FuncWrapper->arg_begin(),
+ e = FuncWrapper->arg_end(); i != e; ++i)
+ Args.push_back(i);
+
+ // Pass on the arguments to the real function, return its result
+ if (F->getReturnType() == Type::VoidTy) {
+ CallInst::Create(FuncPtr, Args.begin(), Args.end(), "", DoCallBB);
+ ReturnInst::Create(DoCallBB);
+ } else {
+ CallInst *Call = CallInst::Create(FuncPtr, Args.begin(), Args.end(),
+ "retval", DoCallBB);
+ ReturnInst::Create(Call, DoCallBB);
+ }
+
+ // Use the wrapper function instead of the old function
+ F->replaceAllUsesWith(FuncWrapper);
+ }
+ }
+ }
+ }
+
+ if (verifyModule(*Test) || verifyModule(*Safe)) {
+ std::cerr << "Bugpoint has a bug, which corrupted a module!!\n";
+ abort();
+ }
+}
+
+
+
+/// TestCodeGenerator - This is the predicate function used to check to see if
+/// the "Test" portion of the program is miscompiled by the code generator under
+/// test. If so, return true. In any case, both module arguments are deleted.
+///
+static bool TestCodeGenerator(BugDriver &BD, Module *Test, Module *Safe) {
+ CleanupAndPrepareModules(BD, Test, Safe);
+
+ sys::Path TestModuleBC("bugpoint.test.bc");
+ std::string ErrMsg;
+ if (TestModuleBC.makeUnique(true, &ErrMsg)) {
+ std::cerr << BD.getToolName() << "Error making unique filename: "
+ << ErrMsg << "\n";
+ exit(1);
+ }
+ if (BD.writeProgramToFile(TestModuleBC.toString(), Test)) {
+ std::cerr << "Error writing bitcode to `" << TestModuleBC << "'\nExiting.";
+ exit(1);
+ }
+ delete Test;
+
+ // Make the shared library
+ sys::Path SafeModuleBC("bugpoint.safe.bc");
+ if (SafeModuleBC.makeUnique(true, &ErrMsg)) {
+ std::cerr << BD.getToolName() << "Error making unique filename: "
+ << ErrMsg << "\n";
+ exit(1);
+ }
+
+ if (BD.writeProgramToFile(SafeModuleBC.toString(), Safe)) {
+ std::cerr << "Error writing bitcode to `" << SafeModuleBC << "'\nExiting.";
+ exit(1);
+ }
+ std::string SharedObject = BD.compileSharedObject(SafeModuleBC.toString());
+ delete Safe;
+
+ // Run the code generator on the `Test' code, loading the shared library.
+ // The function returns whether or not the new output differs from reference.
+ int Result = BD.diffProgram(TestModuleBC.toString(), SharedObject, false);
+
+ if (Result)
+ std::cerr << ": still failing!\n";
+ else
+ std::cerr << ": didn't fail.\n";
+ TestModuleBC.eraseFromDisk();
+ SafeModuleBC.eraseFromDisk();
+ sys::Path(SharedObject).eraseFromDisk();
+
+ return Result;
+}
+
+
+/// debugCodeGenerator - debug errors in LLC, LLI, or CBE.
+///
+bool BugDriver::debugCodeGenerator() {
+ if ((void*)SafeInterpreter == (void*)Interpreter) {
+ std::string Result = executeProgramSafely("bugpoint.safe.out");
+ std::cout << "\n*** The \"safe\" i.e. 'known good' backend cannot match "
+ << "the reference diff. This may be due to a\n front-end "
+ << "bug or a bug in the original program, but this can also "
+ << "happen if bugpoint isn't running the program with the "
+ << "right flags or input.\n I left the result of executing "
+ << "the program with the \"safe\" backend in this file for "
+ << "you: '"
+ << Result << "'.\n";
+ return true;
+ }
+
+ DisambiguateGlobalSymbols(Program);
+
+ std::vector<Function*> Funcs = DebugAMiscompilation(*this, TestCodeGenerator);
+
+ // Split the module into the two halves of the program we want.
+ Module *ToNotCodeGen = CloneModule(getProgram());
+ Module *ToCodeGen = SplitFunctionsOutOfModule(ToNotCodeGen, Funcs);
+
+ // Condition the modules
+ CleanupAndPrepareModules(*this, ToCodeGen, ToNotCodeGen);
+
+ sys::Path TestModuleBC("bugpoint.test.bc");
+ std::string ErrMsg;
+ if (TestModuleBC.makeUnique(true, &ErrMsg)) {
+ std::cerr << getToolName() << "Error making unique filename: "
+ << ErrMsg << "\n";
+ exit(1);
+ }
+
+ if (writeProgramToFile(TestModuleBC.toString(), ToCodeGen)) {
+ std::cerr << "Error writing bitcode to `" << TestModuleBC << "'\nExiting.";
+ exit(1);
+ }
+ delete ToCodeGen;
+
+ // Make the shared library
+ sys::Path SafeModuleBC("bugpoint.safe.bc");
+ if (SafeModuleBC.makeUnique(true, &ErrMsg)) {
+ std::cerr << getToolName() << "Error making unique filename: "
+ << ErrMsg << "\n";
+ exit(1);
+ }
+
+ if (writeProgramToFile(SafeModuleBC.toString(), ToNotCodeGen)) {
+ std::cerr << "Error writing bitcode to `" << SafeModuleBC << "'\nExiting.";
+ exit(1);
+ }
+ std::string SharedObject = compileSharedObject(SafeModuleBC.toString());
+ delete ToNotCodeGen;
+
+ std::cout << "You can reproduce the problem with the command line: \n";
+ if (isExecutingJIT()) {
+ std::cout << " lli -load " << SharedObject << " " << TestModuleBC;
+ } else {
+ std::cout << " llc -f " << TestModuleBC << " -o " << TestModuleBC<< ".s\n";
+ std::cout << " gcc " << SharedObject << " " << TestModuleBC
+ << ".s -o " << TestModuleBC << ".exe";
+#if defined (HAVE_LINK_R)
+ std::cout << " -Wl,-R.";
+#endif
+ std::cout << "\n";
+ std::cout << " " << TestModuleBC << ".exe";
+ }
+ for (unsigned i=0, e = InputArgv.size(); i != e; ++i)
+ std::cout << " " << InputArgv[i];
+ std::cout << '\n';
+ std::cout << "The shared object was created with:\n llc -march=c "
+ << SafeModuleBC << " -o temporary.c\n"
+ << " gcc -xc temporary.c -O2 -o " << SharedObject
+#if defined(sparc) || defined(__sparc__) || defined(__sparcv9)
+ << " -G" // Compile a shared library, `-G' for Sparc
+#else
+ << " -fPIC -shared" // `-shared' for Linux/X86, maybe others
+#endif
+ << " -fno-strict-aliasing\n";
+
+ return false;
+}