Miscompilation.cpp [plain text]
#include "BugDriver.h"
#include "ListReducer.h"
#include "ToolRunner.h"
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Instructions.h"
#include "llvm/Linker.h"
#include "llvm/Module.h"
#include "llvm/Pass.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/Transforms/Utils/Cloning.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileUtilities.h"
#include "llvm/Config/config.h" // for HAVE_LINK_R
using namespace llvm;
namespace llvm {
extern cl::opt<std::string> OutputPrefix;
extern cl::list<std::string> InputArgv;
}
namespace {
static llvm::cl::opt<bool>
DisableLoopExtraction("disable-loop-extraction",
cl::desc("Don't extract loops when searching for miscompilations"),
cl::init(false));
static llvm::cl::opt<bool>
DisableBlockExtraction("disable-block-extraction",
cl::desc("Don't extract blocks when searching for miscompilations"),
cl::init(false));
class ReduceMiscompilingPasses : public ListReducer<std::string> {
BugDriver &BD;
public:
ReduceMiscompilingPasses(BugDriver &bd) : BD(bd) {}
virtual TestResult doTest(std::vector<std::string> &Prefix,
std::vector<std::string> &Suffix,
std::string &Error);
};
}
ReduceMiscompilingPasses::TestResult
ReduceMiscompilingPasses::doTest(std::vector<std::string> &Prefix,
std::vector<std::string> &Suffix,
std::string &Error) {
outs() << "Checking to see if '" << getPassesString(Suffix)
<< "' compiles correctly: ";
std::string BitcodeResult;
if (BD.runPasses(BD.getProgram(), Suffix, BitcodeResult, false,
true)) {
errs() << " Error running this sequence of passes"
<< " on the input program!\n";
BD.setPassesToRun(Suffix);
BD.EmitProgressBitcode(BD.getProgram(), "pass-error", false);
exit(BD.debugOptimizerCrash());
}
bool Diff = BD.diffProgram(BD.getProgram(), BitcodeResult, "",
true , &Error);
if (!Error.empty())
return InternalError;
if (Diff) {
outs() << " nope.\n";
if (Suffix.empty()) {
errs() << BD.getToolName() << ": I'm confused: the test fails when "
<< "no passes are run, nondeterministic program?\n";
exit(1);
}
return KeepSuffix; }
outs() << " yup.\n";
if (Prefix.empty()) return NoFailure;
outs() << "Checking to see if '" << getPassesString(Prefix)
<< "' compiles correctly: ";
if (BD.runPasses(BD.getProgram(), Prefix, BitcodeResult, false,
true)) {
errs() << " Error running this sequence of passes"
<< " on the input program!\n";
BD.setPassesToRun(Prefix);
BD.EmitProgressBitcode(BD.getProgram(), "pass-error", false);
exit(BD.debugOptimizerCrash());
}
Diff = BD.diffProgram(BD.getProgram(), BitcodeResult, "", false, &Error);
if (!Error.empty())
return InternalError;
if (Diff) {
outs() << " nope.\n";
sys::Path(BitcodeResult).eraseFromDisk();
return KeepPrefix;
}
outs() << " yup.\n";
OwningPtr<Module> PrefixOutput(ParseInputFile(BitcodeResult,
BD.getContext()));
if (PrefixOutput == 0) {
errs() << BD.getToolName() << ": Error reading bitcode file '"
<< BitcodeResult << "'!\n";
exit(1);
}
sys::Path(BitcodeResult).eraseFromDisk();
if (Suffix.empty())
return NoFailure;
outs() << "Checking to see if '" << getPassesString(Suffix)
<< "' passes compile correctly after the '"
<< getPassesString(Prefix) << "' passes: ";
OwningPtr<Module> OriginalInput(BD.swapProgramIn(PrefixOutput.take()));
if (BD.runPasses(BD.getProgram(), Suffix, BitcodeResult, false,
true)) {
errs() << " Error running this sequence of passes"
<< " on the input program!\n";
BD.setPassesToRun(Suffix);
BD.EmitProgressBitcode(BD.getProgram(), "pass-error", false);
exit(BD.debugOptimizerCrash());
}
Diff = BD.diffProgram(BD.getProgram(), BitcodeResult, "",
true , &Error);
if (!Error.empty())
return InternalError;
if (Diff) {
outs() << " nope.\n";
return KeepSuffix;
}
outs() << " yup.\n"; delete BD.swapProgramIn(OriginalInput.take());
return NoFailure;
}
namespace {
class ReduceMiscompilingFunctions : public ListReducer<Function*> {
BugDriver &BD;
bool (*TestFn)(BugDriver &, Module *, Module *, std::string &);
public:
ReduceMiscompilingFunctions(BugDriver &bd,
bool (*F)(BugDriver &, Module *, Module *,
std::string &))
: BD(bd), TestFn(F) {}
virtual TestResult doTest(std::vector<Function*> &Prefix,
std::vector<Function*> &Suffix,
std::string &Error) {
if (!Suffix.empty()) {
bool Ret = TestFuncs(Suffix, Error);
if (!Error.empty())
return InternalError;
if (Ret)
return KeepSuffix;
}
if (!Prefix.empty()) {
bool Ret = TestFuncs(Prefix, Error);
if (!Error.empty())
return InternalError;
if (Ret)
return KeepPrefix;
}
return NoFailure;
}
bool TestFuncs(const std::vector<Function*> &Prefix, std::string &Error);
};
}
static Module *TestMergedProgram(const BugDriver &BD, Module *M1, Module *M2,
bool DeleteInputs, std::string &Error,
bool &Broken) {
std::string ErrorMsg;
if (!DeleteInputs) {
M1 = CloneModule(M1);
M2 = CloneModule(M2);
}
if (Linker::LinkModules(M1, M2, Linker::DestroySource, &ErrorMsg)) {
errs() << BD.getToolName() << ": Error linking modules together:"
<< ErrorMsg << '\n';
exit(1);
}
delete M2;
Broken = BD.diffProgram(M1, "", "", false, &Error);
if (!Error.empty()) {
delete M1;
return NULL;
}
return M1;
}
bool ReduceMiscompilingFunctions::TestFuncs(const std::vector<Function*> &Funcs,
std::string &Error) {
outs() << "Checking to see if the program is misoptimized when "
<< (Funcs.size()==1 ? "this function is" : "these functions are")
<< " run through the pass"
<< (BD.getPassesToRun().size() == 1 ? "" : "es") << ":";
PrintFunctionList(Funcs);
outs() << '\n';
ValueToValueMapTy VMap;
Module *Clone = CloneModule(BD.getProgram(), VMap);
Module *Orig = BD.swapProgramIn(Clone);
std::vector<Function*> FuncsOnClone;
for (unsigned i = 0, e = Funcs.size(); i != e; ++i) {
Function *F = cast<Function>(VMap[Funcs[i]]);
FuncsOnClone.push_back(F);
}
VMap.clear();
Module *ToNotOptimize = CloneModule(BD.getProgram(), VMap);
Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize, FuncsOnClone,
VMap);
bool Broken = TestFn(BD, ToOptimize, ToNotOptimize, Error);
delete BD.swapProgramIn(Orig);
return Broken;
}
static void DisambiguateGlobalSymbols(Module *M) {
for (Module::global_iterator I = M->global_begin(), E = M->global_end();
I != E; ++I)
if (!I->hasName())
I->setName("anon_global");
for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
if (!I->hasName())
I->setName("anon_fn");
}
static bool ExtractLoops(BugDriver &BD,
bool (*TestFn)(BugDriver &, Module *, Module *,
std::string &),
std::vector<Function*> &MiscompiledFunctions,
std::string &Error) {
bool MadeChange = false;
while (1) {
if (BugpointIsInterrupted) return MadeChange;
ValueToValueMapTy VMap;
Module *ToNotOptimize = CloneModule(BD.getProgram(), VMap);
Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
MiscompiledFunctions,
VMap);
Module *ToOptimizeLoopExtracted = BD.ExtractLoop(ToOptimize);
if (!ToOptimizeLoopExtracted) {
delete ToNotOptimize;
delete ToOptimize;
return MadeChange;
}
errs() << "Extracted a loop from the breaking portion of the program.\n";
AbstractInterpreter *AI = BD.switchToSafeInterpreter();
bool Failure;
Module *New = TestMergedProgram(BD, ToOptimizeLoopExtracted, ToNotOptimize,
false, Error, Failure);
if (!New)
return false;
delete BD.swapProgramIn(New);
if (Failure) {
BD.switchToInterpreter(AI);
errs() << " *** ERROR: Loop extraction broke the program. :("
<< " Please report a bug!\n";
errs() << " Continuing on with un-loop-extracted version.\n";
BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-tno.bc",
ToNotOptimize);
BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-to.bc",
ToOptimize);
BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-to-le.bc",
ToOptimizeLoopExtracted);
errs() << "Please submit the "
<< OutputPrefix << "-loop-extract-fail-*.bc files.\n";
delete ToOptimize;
delete ToNotOptimize;
delete ToOptimizeLoopExtracted;
return MadeChange;
}
delete ToOptimize;
BD.switchToInterpreter(AI);
outs() << " Testing after loop extraction:\n";
Module *TOLEBackup = CloneModule(ToOptimizeLoopExtracted);
Module *TNOBackup = CloneModule(ToNotOptimize);
Failure = TestFn(BD, ToOptimizeLoopExtracted, ToNotOptimize, Error);
if (!Error.empty())
return false;
if (!Failure) {
outs() << "*** Loop extraction masked the problem. Undoing.\n";
delete TOLEBackup;
delete TNOBackup;
return MadeChange;
}
ToOptimizeLoopExtracted = TOLEBackup;
ToNotOptimize = TNOBackup;
outs() << "*** Loop extraction successful!\n";
std::vector<std::pair<std::string, FunctionType*> > MisCompFunctions;
for (Module::iterator I = ToOptimizeLoopExtracted->begin(),
E = ToOptimizeLoopExtracted->end(); I != E; ++I)
if (!I->isDeclaration())
MisCompFunctions.push_back(std::make_pair(I->getName(),
I->getFunctionType()));
std::string ErrorMsg;
if (Linker::LinkModules(ToNotOptimize, ToOptimizeLoopExtracted,
Linker::DestroySource, &ErrorMsg)){
errs() << BD.getToolName() << ": Error linking modules together:"
<< ErrorMsg << '\n';
exit(1);
}
delete ToOptimizeLoopExtracted;
MiscompiledFunctions.clear();
for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
Function *NewF = ToNotOptimize->getFunction(MisCompFunctions[i].first);
assert(NewF && "Function not found??");
MiscompiledFunctions.push_back(NewF);
}
BD.setNewProgram(ToNotOptimize);
MadeChange = true;
}
}
namespace {
class ReduceMiscompiledBlocks : public ListReducer<BasicBlock*> {
BugDriver &BD;
bool (*TestFn)(BugDriver &, Module *, Module *, std::string &);
std::vector<Function*> FunctionsBeingTested;
public:
ReduceMiscompiledBlocks(BugDriver &bd,
bool (*F)(BugDriver &, Module *, Module *,
std::string &),
const std::vector<Function*> &Fns)
: BD(bd), TestFn(F), FunctionsBeingTested(Fns) {}
virtual TestResult doTest(std::vector<BasicBlock*> &Prefix,
std::vector<BasicBlock*> &Suffix,
std::string &Error) {
if (!Suffix.empty()) {
bool Ret = TestFuncs(Suffix, Error);
if (!Error.empty())
return InternalError;
if (Ret)
return KeepSuffix;
}
if (!Prefix.empty()) {
bool Ret = TestFuncs(Prefix, Error);
if (!Error.empty())
return InternalError;
if (Ret)
return KeepPrefix;
}
return NoFailure;
}
bool TestFuncs(const std::vector<BasicBlock*> &BBs, std::string &Error);
};
}
bool ReduceMiscompiledBlocks::TestFuncs(const std::vector<BasicBlock*> &BBs,
std::string &Error) {
outs() << "Checking to see if the program is misoptimized when all ";
if (!BBs.empty()) {
outs() << "but these " << BBs.size() << " blocks are extracted: ";
for (unsigned i = 0, e = BBs.size() < 10 ? BBs.size() : 10; i != e; ++i)
outs() << BBs[i]->getName() << " ";
if (BBs.size() > 10) outs() << "...";
} else {
outs() << "blocks are extracted.";
}
outs() << '\n';
ValueToValueMapTy VMap;
Module *Clone = CloneModule(BD.getProgram(), VMap);
Module *Orig = BD.swapProgramIn(Clone);
std::vector<Function*> FuncsOnClone;
std::vector<BasicBlock*> BBsOnClone;
for (unsigned i = 0, e = FunctionsBeingTested.size(); i != e; ++i) {
Function *F = cast<Function>(VMap[FunctionsBeingTested[i]]);
FuncsOnClone.push_back(F);
}
for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
BasicBlock *BB = cast<BasicBlock>(VMap[BBs[i]]);
BBsOnClone.push_back(BB);
}
VMap.clear();
Module *ToNotOptimize = CloneModule(BD.getProgram(), VMap);
Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
FuncsOnClone,
VMap);
if (Module *New = BD.ExtractMappedBlocksFromModule(BBsOnClone, ToOptimize)) {
delete ToOptimize;
bool Ret = TestFn(BD, New, ToNotOptimize, Error);
delete BD.swapProgramIn(Orig);
return Ret;
}
delete BD.swapProgramIn(Orig);
delete ToOptimize;
delete ToNotOptimize;
return false;
}
static bool ExtractBlocks(BugDriver &BD,
bool (*TestFn)(BugDriver &, Module *, Module *,
std::string &),
std::vector<Function*> &MiscompiledFunctions,
std::string &Error) {
if (BugpointIsInterrupted) return false;
std::vector<BasicBlock*> Blocks;
for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
for (Function::iterator I = MiscompiledFunctions[i]->begin(),
E = MiscompiledFunctions[i]->end(); I != E; ++I)
Blocks.push_back(I);
unsigned OldSize = Blocks.size();
bool Ret = ReduceMiscompiledBlocks(BD, TestFn, MiscompiledFunctions)
.TestFuncs(std::vector<BasicBlock*>(), Error);
if (!Error.empty())
return false;
if (Ret) {
Blocks.clear();
} else {
ReduceMiscompiledBlocks(BD, TestFn,
MiscompiledFunctions).reduceList(Blocks, Error);
if (!Error.empty())
return false;
if (Blocks.size() == OldSize)
return false;
}
ValueToValueMapTy VMap;
Module *ProgClone = CloneModule(BD.getProgram(), VMap);
Module *ToExtract = SplitFunctionsOutOfModule(ProgClone,
MiscompiledFunctions,
VMap);
Module *Extracted = BD.ExtractMappedBlocksFromModule(Blocks, ToExtract);
if (Extracted == 0) {
errs() << "Nondeterministic problem extracting blocks??\n";
delete ProgClone;
delete ToExtract;
return false;
}
delete ToExtract;
std::vector<std::pair<std::string, FunctionType*> > MisCompFunctions;
for (Module::iterator I = Extracted->begin(), E = Extracted->end();
I != E; ++I)
if (!I->isDeclaration())
MisCompFunctions.push_back(std::make_pair(I->getName(),
I->getFunctionType()));
std::string ErrorMsg;
if (Linker::LinkModules(ProgClone, Extracted, Linker::DestroySource,
&ErrorMsg)) {
errs() << BD.getToolName() << ": Error linking modules together:"
<< ErrorMsg << '\n';
exit(1);
}
delete Extracted;
BD.setNewProgram(ProgClone);
MiscompiledFunctions.clear();
for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
Function *NewF = ProgClone->getFunction(MisCompFunctions[i].first);
assert(NewF && "Function not found??");
MiscompiledFunctions.push_back(NewF);
}
return true;
}
static std::vector<Function*>
DebugAMiscompilation(BugDriver &BD,
bool (*TestFn)(BugDriver &, Module *, Module *,
std::string &),
std::string &Error) {
std::vector<Function*> MiscompiledFunctions;
Module *Prog = BD.getProgram();
for (Module::iterator I = Prog->begin(), E = Prog->end(); I != E; ++I)
if (!I->isDeclaration())
MiscompiledFunctions.push_back(I);
if (!BugpointIsInterrupted)
ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions,
Error);
if (!Error.empty()) {
errs() << "\n***Cannot reduce functions: ";
return MiscompiledFunctions;
}
outs() << "\n*** The following function"
<< (MiscompiledFunctions.size() == 1 ? " is" : "s are")
<< " being miscompiled: ";
PrintFunctionList(MiscompiledFunctions);
outs() << '\n';
if (!BugpointIsInterrupted && !DisableLoopExtraction) {
bool Ret = ExtractLoops(BD, TestFn, MiscompiledFunctions, Error);
if (!Error.empty())
return MiscompiledFunctions;
if (Ret) {
DisambiguateGlobalSymbols(BD.getProgram());
if (!BugpointIsInterrupted)
ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions,
Error);
if (!Error.empty())
return MiscompiledFunctions;
outs() << "\n*** The following function"
<< (MiscompiledFunctions.size() == 1 ? " is" : "s are")
<< " being miscompiled: ";
PrintFunctionList(MiscompiledFunctions);
outs() << '\n';
}
}
if (!BugpointIsInterrupted && !DisableBlockExtraction) {
bool Ret = ExtractBlocks(BD, TestFn, MiscompiledFunctions, Error);
if (!Error.empty())
return MiscompiledFunctions;
if (Ret) {
DisambiguateGlobalSymbols(BD.getProgram());
ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions,
Error);
if (!Error.empty())
return MiscompiledFunctions;
outs() << "\n*** The following function"
<< (MiscompiledFunctions.size() == 1 ? " is" : "s are")
<< " being miscompiled: ";
PrintFunctionList(MiscompiledFunctions);
outs() << '\n';
}
}
return MiscompiledFunctions;
}
static bool TestOptimizer(BugDriver &BD, Module *Test, Module *Safe,
std::string &Error) {
outs() << " Optimizing functions being tested: ";
Module *Optimized = BD.runPassesOn(Test, BD.getPassesToRun(),
true);
outs() << "done.\n";
delete Test;
outs() << " Checking to see if the merged program executes correctly: ";
bool Broken;
Module *New = TestMergedProgram(BD, Optimized, Safe, true, Error, Broken);
if (New) {
outs() << (Broken ? " nope.\n" : " yup.\n");
delete BD.swapProgramIn(New);
}
return Broken;
}
void BugDriver::debugMiscompilation(std::string *Error) {
if (!BugpointIsInterrupted)
if (!ReduceMiscompilingPasses(*this).reduceList(PassesToRun, *Error)) {
if (Error->empty())
errs() << "*** Optimized program matches reference output! No problem"
<< " detected...\nbugpoint can't help you with your problem!\n";
return;
}
outs() << "\n*** Found miscompiling pass"
<< (getPassesToRun().size() == 1 ? "" : "es") << ": "
<< getPassesString(getPassesToRun()) << '\n';
EmitProgressBitcode(Program, "passinput");
std::vector<Function *> MiscompiledFunctions =
DebugAMiscompilation(*this, TestOptimizer, *Error);
if (!Error->empty())
return;
outs() << "Outputting reduced bitcode files which expose the problem:\n";
ValueToValueMapTy VMap;
Module *ToNotOptimize = CloneModule(getProgram(), VMap);
Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
MiscompiledFunctions,
VMap);
outs() << " Non-optimized portion: ";
EmitProgressBitcode(ToNotOptimize, "tonotoptimize", true);
delete ToNotOptimize;
outs() << " Portion that is input to optimizer: ";
EmitProgressBitcode(ToOptimize, "tooptimize");
delete ToOptimize;
return;
}
static void CleanupAndPrepareModules(BugDriver &BD, Module *&Test,
Module *Safe) {
Test = BD.performFinalCleanups(Test);
if (!BD.isExecutingJIT()) return;
if (Function *oldMain = Safe->getFunction("main"))
if (!oldMain->isDeclaration()) {
oldMain->setName("llvm_bugpoint_old_main");
Function *newMain = Function::Create(oldMain->getFunctionType(),
GlobalValue::ExternalLinkage,
"main", Test);
Function *oldMainProto = Function::Create(oldMain->getFunctionType(),
GlobalValue::ExternalLinkage,
oldMain->getName(), Test);
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()); args.push_back(I);
}
BasicBlock *BB = BasicBlock::Create(Safe->getContext(), "entry", newMain);
CallInst *call = CallInst::Create(oldMainProto, args, "", BB);
ReturnInst::Create(Safe->getContext(), call, BB);
}
Constant *resolverFunc =
Safe->getOrInsertFunction("getPointerToNamedFunction",
Type::getInt8PtrTy(Safe->getContext()),
Type::getInt8PtrTy(Safe->getContext()),
(Type *)0);
for (Module::iterator F = Safe->begin(), E = Safe->end(); F != E; ++F) {
if (F->isDeclaration() && !F->use_empty() && &*F != resolverFunc &&
!F->isIntrinsic() ) {
Function *TestFn = Test->getFunction(F->getName());
if (TestFn && !TestFn->isDeclaration()) {
Constant *InitArray =
ConstantDataArray::getString(F->getContext(), F->getName());
GlobalVariable *funcName =
new GlobalVariable(*Safe, InitArray->getType(), true ,
GlobalValue::InternalLinkage, InitArray,
F->getName() + "_name");
std::vector<Constant*> GEPargs(2,
Constant::getNullValue(Type::getInt32Ty(F->getContext())));
Value *GEP = ConstantExpr::getGetElementPtr(funcName, GEPargs);
std::vector<Value*> ResolverArgs;
ResolverArgs.push_back(GEP);
if (!F->use_empty()) {
Constant *NullPtr = ConstantPointerNull::get(F->getType());
GlobalVariable *Cache =
new GlobalVariable(*F->getParent(), F->getType(),
false, GlobalValue::InternalLinkage,
NullPtr,F->getName()+".fpcache");
FunctionType *FuncTy = F->getFunctionType();
Function *FuncWrapper = Function::Create(FuncTy,
GlobalValue::InternalLinkage,
F->getName() + "_wrapper",
F->getParent());
BasicBlock *EntryBB = BasicBlock::Create(F->getContext(),
"entry", FuncWrapper);
BasicBlock *DoCallBB = BasicBlock::Create(F->getContext(),
"usecache", FuncWrapper);
BasicBlock *LookupBB = BasicBlock::Create(F->getContext(),
"lookupfp", FuncWrapper);
Value *CachedVal = new LoadInst(Cache, "fpcache", EntryBB);
Value *IsNull = new ICmpInst(*EntryBB, ICmpInst::ICMP_EQ, CachedVal,
NullPtr, "isNull");
BranchInst::Create(LookupBB, DoCallBB, IsNull, EntryBB);
CallInst *Resolver =
CallInst::Create(resolverFunc, ResolverArgs, "resolver", LookupBB);
CastInst *CastedResolver =
new BitCastInst(Resolver,
PointerType::getUnqual(F->getFunctionType()),
"resolverCast", LookupBB);
new StoreInst(CastedResolver, Cache, LookupBB);
BranchInst::Create(DoCallBB, LookupBB);
PHINode *FuncPtr = PHINode::Create(NullPtr->getType(), 2,
"fp", DoCallBB);
FuncPtr->addIncoming(CastedResolver, LookupBB);
FuncPtr->addIncoming(CachedVal, EntryBB);
std::vector<Value*> Args;
for (Function::arg_iterator i = FuncWrapper->arg_begin(),
e = FuncWrapper->arg_end(); i != e; ++i)
Args.push_back(i);
if (F->getReturnType()->isVoidTy()) {
CallInst::Create(FuncPtr, Args, "", DoCallBB);
ReturnInst::Create(F->getContext(), DoCallBB);
} else {
CallInst *Call = CallInst::Create(FuncPtr, Args,
"retval", DoCallBB);
ReturnInst::Create(F->getContext(),Call, DoCallBB);
}
F->replaceAllUsesWith(FuncWrapper);
}
}
}
}
if (verifyModule(*Test) || verifyModule(*Safe)) {
errs() << "Bugpoint has a bug, which corrupted a module!!\n";
abort();
}
}
static bool TestCodeGenerator(BugDriver &BD, Module *Test, Module *Safe,
std::string &Error) {
CleanupAndPrepareModules(BD, Test, Safe);
sys::Path TestModuleBC("bugpoint.test.bc");
std::string ErrMsg;
if (TestModuleBC.makeUnique(true, &ErrMsg)) {
errs() << BD.getToolName() << "Error making unique filename: "
<< ErrMsg << "\n";
exit(1);
}
if (BD.writeProgramToFile(TestModuleBC.str(), Test)) {
errs() << "Error writing bitcode to `" << TestModuleBC.str()
<< "'\nExiting.";
exit(1);
}
delete Test;
FileRemover TestModuleBCRemover(TestModuleBC.str(), !SaveTemps);
sys::Path SafeModuleBC("bugpoint.safe.bc");
if (SafeModuleBC.makeUnique(true, &ErrMsg)) {
errs() << BD.getToolName() << "Error making unique filename: "
<< ErrMsg << "\n";
exit(1);
}
if (BD.writeProgramToFile(SafeModuleBC.str(), Safe)) {
errs() << "Error writing bitcode to `" << SafeModuleBC.str()
<< "'\nExiting.";
exit(1);
}
FileRemover SafeModuleBCRemover(SafeModuleBC.str(), !SaveTemps);
std::string SharedObject = BD.compileSharedObject(SafeModuleBC.str(), Error);
if (!Error.empty())
return false;
delete Safe;
FileRemover SharedObjectRemover(SharedObject, !SaveTemps);
bool Result = BD.diffProgram(BD.getProgram(), TestModuleBC.str(),
SharedObject, false, &Error);
if (!Error.empty())
return false;
if (Result)
errs() << ": still failing!\n";
else
errs() << ": didn't fail.\n";
return Result;
}
bool BugDriver::debugCodeGenerator(std::string *Error) {
if ((void*)SafeInterpreter == (void*)Interpreter) {
std::string Result = executeProgramSafely(Program, "bugpoint.safe.out",
Error);
if (Error->empty()) {
outs() << "\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,
*Error);
if (!Error->empty())
return true;
ValueToValueMapTy VMap;
Module *ToNotCodeGen = CloneModule(getProgram(), VMap);
Module *ToCodeGen = SplitFunctionsOutOfModule(ToNotCodeGen, Funcs, VMap);
CleanupAndPrepareModules(*this, ToCodeGen, ToNotCodeGen);
sys::Path TestModuleBC("bugpoint.test.bc");
std::string ErrMsg;
if (TestModuleBC.makeUnique(true, &ErrMsg)) {
errs() << getToolName() << "Error making unique filename: "
<< ErrMsg << "\n";
exit(1);
}
if (writeProgramToFile(TestModuleBC.str(), ToCodeGen)) {
errs() << "Error writing bitcode to `" << TestModuleBC.str()
<< "'\nExiting.";
exit(1);
}
delete ToCodeGen;
sys::Path SafeModuleBC("bugpoint.safe.bc");
if (SafeModuleBC.makeUnique(true, &ErrMsg)) {
errs() << getToolName() << "Error making unique filename: "
<< ErrMsg << "\n";
exit(1);
}
if (writeProgramToFile(SafeModuleBC.str(), ToNotCodeGen)) {
errs() << "Error writing bitcode to `" << SafeModuleBC.str()
<< "'\nExiting.";
exit(1);
}
std::string SharedObject = compileSharedObject(SafeModuleBC.str(), *Error);
if (!Error->empty())
return true;
delete ToNotCodeGen;
outs() << "You can reproduce the problem with the command line: \n";
if (isExecutingJIT()) {
outs() << " lli -load " << SharedObject << " " << TestModuleBC.str();
} else {
outs() << " llc " << TestModuleBC.str() << " -o " << TestModuleBC.str()
<< ".s\n";
outs() << " gcc " << SharedObject << " " << TestModuleBC.str()
<< ".s -o " << TestModuleBC.str() << ".exe";
#if defined (HAVE_LINK_R)
outs() << " -Wl,-R.";
#endif
outs() << "\n";
outs() << " " << TestModuleBC.str() << ".exe";
}
for (unsigned i = 0, e = InputArgv.size(); i != e; ++i)
outs() << " " << InputArgv[i];
outs() << '\n';
outs() << "The shared object was created with:\n llc -march=c "
<< SafeModuleBC.str() << " -o temporary.c\n"
<< " gcc -xc temporary.c -O2 -o " << SharedObject;
if (TargetTriple.getArch() == Triple::sparc)
outs() << " -G"; else
outs() << " -fPIC -shared";
outs() << " -fno-strict-aliasing\n";
return false;
}