InlineFunction.cpp [plain text]
#include "llvm/Transforms/Utils/Cloning.h"
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Module.h"
#include "llvm/Instructions.h"
#include "llvm/IntrinsicInst.h"
#include "llvm/Intrinsics.h"
#include "llvm/Attributes.h"
#include "llvm/Analysis/CallGraph.h"
#include "llvm/Analysis/DebugInfo.h"
#include "llvm/Target/TargetData.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/CallSite.h"
using namespace llvm;
bool llvm::InlineFunction(CallInst *CI, CallGraph *CG, const TargetData *TD) {
return InlineFunction(CallSite(CI), CG, TD);
}
bool llvm::InlineFunction(InvokeInst *II, CallGraph *CG, const TargetData *TD) {
return InlineFunction(CallSite(II), CG, TD);
}
static void HandleInlinedInvoke(InvokeInst *II, BasicBlock *FirstNewBlock,
ClonedCodeInfo &InlinedCodeInfo,
CallGraph *CG) {
BasicBlock *InvokeDest = II->getUnwindDest();
std::vector<Value*> InvokeDestPHIValues;
BasicBlock *InvokeBlock = II->getParent();
for (BasicBlock::iterator I = InvokeDest->begin(); isa<PHINode>(I); ++I) {
PHINode *PN = cast<PHINode>(I);
InvokeDestPHIValues.push_back(PN->getIncomingValueForBlock(InvokeBlock));
}
Function *Caller = FirstNewBlock->getParent();
if (InlinedCodeInfo.ContainsCalls || InlinedCodeInfo.ContainsUnwinds) {
for (Function::iterator BB = FirstNewBlock, E = Caller->end();
BB != E; ++BB) {
if (InlinedCodeInfo.ContainsCalls) {
for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ){
Instruction *I = BBI++;
if (!isa<CallInst>(I)) continue;
CallInst *CI = cast<CallInst>(I);
if (CI->doesNotThrow())
continue;
BasicBlock *Split = BB->splitBasicBlock(CI, CI->getName()+".noexc");
SmallVector<Value*, 8> InvokeArgs(CI->op_begin()+1, CI->op_end());
InvokeInst *II =
InvokeInst::Create(CI->getCalledValue(), Split, InvokeDest,
InvokeArgs.begin(), InvokeArgs.end(),
CI->getName(), BB->getTerminator());
II->setCallingConv(CI->getCallingConv());
II->setAttributes(CI->getAttributes());
CI->replaceAllUsesWith(II);
if (CG) {
CallGraphNode *CGN = (*CG)[Caller];
for (CallGraphNode::iterator NI = CGN->begin(), NE = CGN->end();
NI != NE; ++NI) {
if (NI->first == CI) {
NI->first = II;
break;
}
}
}
BB->getInstList().pop_back();
Split->getInstList().pop_front();
unsigned i = 0;
for (BasicBlock::iterator I = InvokeDest->begin();
isa<PHINode>(I); ++I, ++i) {
PHINode *PN = cast<PHINode>(I);
PN->addIncoming(InvokeDestPHIValues[i], BB);
}
break;
}
}
if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
BranchInst::Create(InvokeDest, UI);
UI->eraseFromParent();
unsigned i = 0;
for (BasicBlock::iterator I = InvokeDest->begin();
isa<PHINode>(I); ++I, ++i) {
PHINode *PN = cast<PHINode>(I);
PN->addIncoming(InvokeDestPHIValues[i], BB);
}
}
}
}
InvokeDest->removePredecessor(II->getParent());
}
static void UpdateCallGraphAfterInlining(CallSite CS,
Function::iterator FirstNewBlock,
DenseMap<const Value*, Value*> &ValueMap,
CallGraph &CG) {
const Function *Caller = CS.getInstruction()->getParent()->getParent();
const Function *Callee = CS.getCalledFunction();
CallGraphNode *CalleeNode = CG[Callee];
CallGraphNode *CallerNode = CG[Caller];
CallGraphNode::iterator I = CalleeNode->begin(), E = CalleeNode->end();
CallGraphNode::CalledFunctionsVector CallCache;
if (CalleeNode == CallerNode) {
CallCache.assign(I, E);
I = CallCache.begin();
E = CallCache.end();
}
for (; I != E; ++I) {
const Instruction *OrigCall = I->first.getInstruction();
DenseMap<const Value*, Value*>::iterator VMI = ValueMap.find(OrigCall);
if (VMI != ValueMap.end() && VMI->second) {
if (Instruction *NewCall = dyn_cast<Instruction>(VMI->second))
CallerNode->addCalledFunction(CallSite::get(NewCall), I->second);
}
}
CallerNode->removeCallEdgeFor(CS);
}
static const DbgRegionEndInst *findFnRegionEndMarker(const Function *F) {
GlobalVariable *FnStart = NULL;
const DbgRegionEndInst *FnEnd = NULL;
for (Function::const_iterator FI = F->begin(), FE =F->end(); FI != FE; ++FI)
for (BasicBlock::const_iterator BI = FI->begin(), BE = FI->end(); BI != BE;
++BI) {
if (FnStart == NULL) {
if (const DbgFuncStartInst *FSI = dyn_cast<DbgFuncStartInst>(BI)) {
DISubprogram SP(cast<GlobalVariable>(FSI->getSubprogram()));
assert (SP.isNull() == false && "Invalid llvm.dbg.func.start");
if (SP.describes(F))
FnStart = SP.getGV();
}
} else {
if (const DbgRegionEndInst *REI = dyn_cast<DbgRegionEndInst>(BI))
if (REI->getContext() == FnStart)
FnEnd = REI;
}
}
return FnEnd;
}
bool llvm::InlineFunction(CallSite CS, CallGraph *CG, const TargetData *TD) {
Instruction *TheCall = CS.getInstruction();
assert(TheCall->getParent() && TheCall->getParent()->getParent() &&
"Instruction not in function!");
const Function *CalledFunc = CS.getCalledFunction();
if (CalledFunc == 0 || CalledFunc->isDeclaration() || CalledFunc->getFunctionType()->isVarArg()) return false;
bool MustClearTailCallFlags =
!(isa<CallInst>(TheCall) && cast<CallInst>(TheCall)->isTailCall());
bool MarkNoUnwind = CS.doesNotThrow();
BasicBlock *OrigBB = TheCall->getParent();
Function *Caller = OrigBB->getParent();
if (CalledFunc->hasGC()) {
if (!Caller->hasGC())
Caller->setGC(CalledFunc->getGC());
else if (CalledFunc->getGC() != Caller->getGC())
return false;
}
Function::iterator LastBlock = &Caller->back();
std::vector<ReturnInst*> Returns;
ClonedCodeInfo InlinedFunctionInfo;
Function::iterator FirstNewBlock;
{ DenseMap<const Value*, Value*> ValueMap;
assert(CalledFunc->arg_size() == CS.arg_size() &&
"No varargs calls can be inlined!");
CallSite::arg_iterator AI = CS.arg_begin();
unsigned ArgNo = 0;
for (Function::const_arg_iterator I = CalledFunc->arg_begin(),
E = CalledFunc->arg_end(); I != E; ++I, ++AI, ++ArgNo) {
Value *ActualArg = *AI;
if (CalledFunc->paramHasAttr(ArgNo+1, Attribute::ByVal) &&
!CalledFunc->onlyReadsMemory()) {
const Type *AggTy = cast<PointerType>(I->getType())->getElementType();
const Type *VoidPtrTy = PointerType::getUnqual(Type::Int8Ty);
unsigned Align = 1;
if (TD) Align = TD->getPrefTypeAlignment(AggTy);
Value *NewAlloca = new AllocaInst(AggTy, 0, Align, I->getName(),
Caller->begin()->begin());
const Type *Tys[] = { Type::Int64Ty };
Function *MemCpyFn = Intrinsic::getDeclaration(Caller->getParent(),
Intrinsic::memcpy,
Tys, 1);
Value *DestCast = new BitCastInst(NewAlloca, VoidPtrTy, "tmp", TheCall);
Value *SrcCast = new BitCastInst(*AI, VoidPtrTy, "tmp", TheCall);
Value *Size;
if (TD == 0)
Size = ConstantExpr::getSizeOf(AggTy);
else
Size = ConstantInt::get(Type::Int64Ty, TD->getTypeStoreSize(AggTy));
Value *CallArgs[] = {
DestCast, SrcCast, Size, ConstantInt::get(Type::Int32Ty, 1)
};
CallInst *TheMemCpy =
CallInst::Create(MemCpyFn, CallArgs, CallArgs+4, "", TheCall);
if (CG) {
CallGraphNode *MemCpyCGN = CG->getOrInsertFunction(MemCpyFn);
CallGraphNode *CallerNode = (*CG)[Caller];
CallerNode->addCalledFunction(TheMemCpy, MemCpyCGN);
}
ActualArg = NewAlloca;
}
ValueMap[I] = ActualArg;
}
const DbgRegionEndInst *DREI = findFnRegionEndMarker(CalledFunc);
if (DREI) {
for (BasicBlock::iterator BI = TheCall,
BE = TheCall->getParent()->end(); BI != BE; ++BI) {
if (DbgStopPointInst *DSPI = dyn_cast<DbgStopPointInst>(BI)) {
if (DbgRegionEndInst *NewDREI =
dyn_cast<DbgRegionEndInst>(DREI->clone()))
NewDREI->insertAfter(DSPI);
break;
}
}
}
CloneAndPruneFunctionInto(Caller, CalledFunc, ValueMap, Returns, ".i",
&InlinedFunctionInfo, TD);
FirstNewBlock = LastBlock; ++FirstNewBlock;
if (CG)
UpdateCallGraphAfterInlining(CS, FirstNewBlock, ValueMap, *CG);
}
{
BasicBlock::iterator InsertPoint = Caller->begin()->begin();
for (BasicBlock::iterator I = FirstNewBlock->begin(),
E = FirstNewBlock->end(); I != E; )
if (AllocaInst *AI = dyn_cast<AllocaInst>(I++)) {
if (AI->use_empty()) {
AI->eraseFromParent();
continue;
}
if (isa<Constant>(AI->getArraySize())) {
while (isa<AllocaInst>(I) &&
isa<Constant>(cast<AllocaInst>(I)->getArraySize()))
++I;
Caller->getEntryBlock().getInstList().splice(
InsertPoint,
FirstNewBlock->getInstList(),
AI, I);
}
}
}
if (InlinedFunctionInfo.ContainsDynamicAllocas) {
Module *M = Caller->getParent();
Constant *StackSave, *StackRestore;
StackSave = Intrinsic::getDeclaration(M, Intrinsic::stacksave);
StackRestore = Intrinsic::getDeclaration(M, Intrinsic::stackrestore);
CallGraphNode *StackSaveCGN = 0, *StackRestoreCGN = 0, *CallerNode = 0;
if (CG) {
StackSaveCGN = CG->getOrInsertFunction(cast<Function>(StackSave));
StackRestoreCGN = CG->getOrInsertFunction(cast<Function>(StackRestore));
CallerNode = (*CG)[Caller];
}
CallInst *SavedPtr = CallInst::Create(StackSave, "savedstack",
FirstNewBlock->begin());
if (CG) CallerNode->addCalledFunction(SavedPtr, StackSaveCGN);
for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
CallInst *CI = CallInst::Create(StackRestore, SavedPtr, "", Returns[i]);
if (CG) CallerNode->addCalledFunction(CI, StackRestoreCGN);
}
unsigned NumStackRestores = Returns.size();
if (InlinedFunctionInfo.ContainsUnwinds && isa<InvokeInst>(TheCall)) {
for (Function::iterator BB = FirstNewBlock, E = Caller->end();
BB != E; ++BB)
if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
CallInst::Create(StackRestore, SavedPtr, "", UI);
++NumStackRestores;
}
}
}
if (InlinedFunctionInfo.ContainsCalls &&
(MustClearTailCallFlags || MarkNoUnwind)) {
for (Function::iterator BB = FirstNewBlock, E = Caller->end();
BB != E; ++BB)
for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
if (CallInst *CI = dyn_cast<CallInst>(I)) {
if (MustClearTailCallFlags)
CI->setTailCall(false);
if (MarkNoUnwind)
CI->setDoesNotThrow();
}
}
if (InlinedFunctionInfo.ContainsUnwinds && MarkNoUnwind)
for (Function::iterator BB = FirstNewBlock, E = Caller->end();
BB != E; ++BB) {
TerminatorInst *Term = BB->getTerminator();
if (isa<UnwindInst>(Term)) {
new UnreachableInst(Term);
BB->getInstList().erase(Term);
}
}
if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
HandleInlinedInvoke(II, FirstNewBlock, InlinedFunctionInfo, CG);
if (Returns.size() == 1 && std::distance(FirstNewBlock, Caller->end()) == 1) {
OrigBB->getInstList().splice(TheCall, FirstNewBlock->getInstList(),
FirstNewBlock->begin(), FirstNewBlock->end());
Caller->getBasicBlockList().pop_back();
if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
BranchInst::Create(II->getNormalDest(), TheCall);
if (!TheCall->use_empty()) {
ReturnInst *R = Returns[0];
TheCall->replaceAllUsesWith(R->getReturnValue());
}
TheCall->eraseFromParent();
Returns[0]->eraseFromParent();
return true;
}
BasicBlock *AfterCallBB;
if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
BranchInst *NewBr = BranchInst::Create(II->getNormalDest(), TheCall);
AfterCallBB = OrigBB->splitBasicBlock(NewBr,
CalledFunc->getName()+".exit");
} else { AfterCallBB = OrigBB->splitBasicBlock(TheCall,
CalledFunc->getName()+".exit");
}
TerminatorInst *Br = OrigBB->getTerminator();
assert(Br && Br->getOpcode() == Instruction::Br &&
"splitBasicBlock broken!");
Br->setOperand(0, FirstNewBlock);
Caller->getBasicBlockList().splice(AfterCallBB, Caller->getBasicBlockList(),
FirstNewBlock, Caller->end());
const Type *RTy = CalledFunc->getReturnType();
if (Returns.size() > 1) {
PHINode *PHI = 0;
if (!TheCall->use_empty()) {
PHI = PHINode::Create(RTy, TheCall->getName(),
AfterCallBB->begin());
TheCall->replaceAllUsesWith(PHI);
}
if (PHI) {
for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
ReturnInst *RI = Returns[i];
assert(RI->getReturnValue()->getType() == PHI->getType() &&
"Ret value not consistent in function!");
PHI->addIncoming(RI->getReturnValue(), RI->getParent());
}
}
for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
ReturnInst *RI = Returns[i];
BranchInst::Create(AfterCallBB, RI);
RI->eraseFromParent();
}
} else if (!Returns.empty()) {
if (!TheCall->use_empty())
TheCall->replaceAllUsesWith(Returns[0]->getReturnValue());
BasicBlock *ReturnBB = Returns[0]->getParent();
AfterCallBB->getInstList().splice(AfterCallBB->begin(),
ReturnBB->getInstList());
ReturnBB->replaceAllUsesWith(AfterCallBB);
Returns[0]->eraseFromParent();
ReturnBB->eraseFromParent();
} else if (!TheCall->use_empty()) {
TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
}
TheCall->eraseFromParent();
assert(cast<BranchInst>(Br)->isUnconditional() && "splitBasicBlock broken!");
BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0);
OrigBB->getInstList().splice(Br, CalleeEntry->getInstList());
CalleeEntry->replaceAllUsesWith(OrigBB);
OrigBB->getInstList().erase(Br);
Caller->getBasicBlockList().erase(CalleeEntry);
return true;
}