InlineFunction.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887
  1. //===- InlineFunction.cpp - Code to perform function inlining -------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements inlining of a function into a call site, resolving
  11. // parameters and the return value as appropriate.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/Transforms/Utils/Cloning.h"
  15. #include "llvm/Attributes.h"
  16. #include "llvm/Constants.h"
  17. #include "llvm/DebugInfo.h"
  18. #include "llvm/DerivedTypes.h"
  19. #include "llvm/IRBuilder.h"
  20. #include "llvm/Instructions.h"
  21. #include "llvm/IntrinsicInst.h"
  22. #include "llvm/Intrinsics.h"
  23. #include "llvm/Module.h"
  24. #include "llvm/ADT/SmallVector.h"
  25. #include "llvm/ADT/StringExtras.h"
  26. #include "llvm/Analysis/CallGraph.h"
  27. #include "llvm/Analysis/InstructionSimplify.h"
  28. #include "llvm/Support/CallSite.h"
  29. #include "llvm/Target/TargetData.h"
  30. #include "llvm/Transforms/Utils/Local.h"
  31. using namespace llvm;
  32. bool llvm::InlineFunction(CallInst *CI, InlineFunctionInfo &IFI,
  33. bool InsertLifetime) {
  34. return InlineFunction(CallSite(CI), IFI, InsertLifetime);
  35. }
  36. bool llvm::InlineFunction(InvokeInst *II, InlineFunctionInfo &IFI,
  37. bool InsertLifetime) {
  38. return InlineFunction(CallSite(II), IFI, InsertLifetime);
  39. }
  40. namespace {
  41. /// A class for recording information about inlining through an invoke.
  42. class InvokeInliningInfo {
  43. BasicBlock *OuterResumeDest; ///< Destination of the invoke's unwind.
  44. BasicBlock *InnerResumeDest; ///< Destination for the callee's resume.
  45. LandingPadInst *CallerLPad; ///< LandingPadInst associated with the invoke.
  46. PHINode *InnerEHValuesPHI; ///< PHI for EH values from landingpad insts.
  47. SmallVector<Value*, 8> UnwindDestPHIValues;
  48. public:
  49. InvokeInliningInfo(InvokeInst *II)
  50. : OuterResumeDest(II->getUnwindDest()), InnerResumeDest(0),
  51. CallerLPad(0), InnerEHValuesPHI(0) {
  52. // If there are PHI nodes in the unwind destination block, we need to keep
  53. // track of which values came into them from the invoke before removing
  54. // the edge from this block.
  55. llvm::BasicBlock *InvokeBB = II->getParent();
  56. BasicBlock::iterator I = OuterResumeDest->begin();
  57. for (; isa<PHINode>(I); ++I) {
  58. // Save the value to use for this edge.
  59. PHINode *PHI = cast<PHINode>(I);
  60. UnwindDestPHIValues.push_back(PHI->getIncomingValueForBlock(InvokeBB));
  61. }
  62. CallerLPad = cast<LandingPadInst>(I);
  63. }
  64. /// getOuterResumeDest - The outer unwind destination is the target of
  65. /// unwind edges introduced for calls within the inlined function.
  66. BasicBlock *getOuterResumeDest() const {
  67. return OuterResumeDest;
  68. }
  69. BasicBlock *getInnerResumeDest();
  70. LandingPadInst *getLandingPadInst() const { return CallerLPad; }
  71. /// forwardResume - Forward the 'resume' instruction to the caller's landing
  72. /// pad block. When the landing pad block has only one predecessor, this is
  73. /// a simple branch. When there is more than one predecessor, we need to
  74. /// split the landing pad block after the landingpad instruction and jump
  75. /// to there.
  76. void forwardResume(ResumeInst *RI);
  77. /// addIncomingPHIValuesFor - Add incoming-PHI values to the unwind
  78. /// destination block for the given basic block, using the values for the
  79. /// original invoke's source block.
  80. void addIncomingPHIValuesFor(BasicBlock *BB) const {
  81. addIncomingPHIValuesForInto(BB, OuterResumeDest);
  82. }
  83. void addIncomingPHIValuesForInto(BasicBlock *src, BasicBlock *dest) const {
  84. BasicBlock::iterator I = dest->begin();
  85. for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
  86. PHINode *phi = cast<PHINode>(I);
  87. phi->addIncoming(UnwindDestPHIValues[i], src);
  88. }
  89. }
  90. };
  91. }
  92. /// getInnerResumeDest - Get or create a target for the branch from ResumeInsts.
  93. BasicBlock *InvokeInliningInfo::getInnerResumeDest() {
  94. if (InnerResumeDest) return InnerResumeDest;
  95. // Split the landing pad.
  96. BasicBlock::iterator SplitPoint = CallerLPad; ++SplitPoint;
  97. InnerResumeDest =
  98. OuterResumeDest->splitBasicBlock(SplitPoint,
  99. OuterResumeDest->getName() + ".body");
  100. // The number of incoming edges we expect to the inner landing pad.
  101. const unsigned PHICapacity = 2;
  102. // Create corresponding new PHIs for all the PHIs in the outer landing pad.
  103. BasicBlock::iterator InsertPoint = InnerResumeDest->begin();
  104. BasicBlock::iterator I = OuterResumeDest->begin();
  105. for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
  106. PHINode *OuterPHI = cast<PHINode>(I);
  107. PHINode *InnerPHI = PHINode::Create(OuterPHI->getType(), PHICapacity,
  108. OuterPHI->getName() + ".lpad-body",
  109. InsertPoint);
  110. OuterPHI->replaceAllUsesWith(InnerPHI);
  111. InnerPHI->addIncoming(OuterPHI, OuterResumeDest);
  112. }
  113. // Create a PHI for the exception values.
  114. InnerEHValuesPHI = PHINode::Create(CallerLPad->getType(), PHICapacity,
  115. "eh.lpad-body", InsertPoint);
  116. CallerLPad->replaceAllUsesWith(InnerEHValuesPHI);
  117. InnerEHValuesPHI->addIncoming(CallerLPad, OuterResumeDest);
  118. // All done.
  119. return InnerResumeDest;
  120. }
  121. /// forwardResume - Forward the 'resume' instruction to the caller's landing pad
  122. /// block. When the landing pad block has only one predecessor, this is a simple
  123. /// branch. When there is more than one predecessor, we need to split the
  124. /// landing pad block after the landingpad instruction and jump to there.
  125. void InvokeInliningInfo::forwardResume(ResumeInst *RI) {
  126. BasicBlock *Dest = getInnerResumeDest();
  127. BasicBlock *Src = RI->getParent();
  128. BranchInst::Create(Dest, Src);
  129. // Update the PHIs in the destination. They were inserted in an order which
  130. // makes this work.
  131. addIncomingPHIValuesForInto(Src, Dest);
  132. InnerEHValuesPHI->addIncoming(RI->getOperand(0), Src);
  133. RI->eraseFromParent();
  134. }
  135. /// HandleCallsInBlockInlinedThroughInvoke - When we inline a basic block into
  136. /// an invoke, we have to turn all of the calls that can throw into
  137. /// invokes. This function analyze BB to see if there are any calls, and if so,
  138. /// it rewrites them to be invokes that jump to InvokeDest and fills in the PHI
  139. /// nodes in that block with the values specified in InvokeDestPHIValues.
  140. ///
  141. /// Returns true to indicate that the next block should be skipped.
  142. static bool HandleCallsInBlockInlinedThroughInvoke(BasicBlock *BB,
  143. InvokeInliningInfo &Invoke) {
  144. LandingPadInst *LPI = Invoke.getLandingPadInst();
  145. for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
  146. Instruction *I = BBI++;
  147. if (LandingPadInst *L = dyn_cast<LandingPadInst>(I)) {
  148. unsigned NumClauses = LPI->getNumClauses();
  149. L->reserveClauses(NumClauses);
  150. for (unsigned i = 0; i != NumClauses; ++i)
  151. L->addClause(LPI->getClause(i));
  152. }
  153. // We only need to check for function calls: inlined invoke
  154. // instructions require no special handling.
  155. CallInst *CI = dyn_cast<CallInst>(I);
  156. // If this call cannot unwind, don't convert it to an invoke.
  157. if (!CI || CI->doesNotThrow())
  158. continue;
  159. // Convert this function call into an invoke instruction. First, split the
  160. // basic block.
  161. BasicBlock *Split = BB->splitBasicBlock(CI, CI->getName()+".noexc");
  162. // Delete the unconditional branch inserted by splitBasicBlock
  163. BB->getInstList().pop_back();
  164. // Create the new invoke instruction.
  165. ImmutableCallSite CS(CI);
  166. SmallVector<Value*, 8> InvokeArgs(CS.arg_begin(), CS.arg_end());
  167. InvokeInst *II = InvokeInst::Create(CI->getCalledValue(), Split,
  168. Invoke.getOuterResumeDest(),
  169. InvokeArgs, CI->getName(), BB);
  170. II->setCallingConv(CI->getCallingConv());
  171. II->setAttributes(CI->getAttributes());
  172. // Make sure that anything using the call now uses the invoke! This also
  173. // updates the CallGraph if present, because it uses a WeakVH.
  174. CI->replaceAllUsesWith(II);
  175. // Delete the original call
  176. Split->getInstList().pop_front();
  177. // Update any PHI nodes in the exceptional block to indicate that there is
  178. // now a new entry in them.
  179. Invoke.addIncomingPHIValuesFor(BB);
  180. return false;
  181. }
  182. return false;
  183. }
  184. /// HandleInlinedInvoke - If we inlined an invoke site, we need to convert calls
  185. /// in the body of the inlined function into invokes.
  186. ///
  187. /// II is the invoke instruction being inlined. FirstNewBlock is the first
  188. /// block of the inlined code (the last block is the end of the function),
  189. /// and InlineCodeInfo is information about the code that got inlined.
  190. static void HandleInlinedInvoke(InvokeInst *II, BasicBlock *FirstNewBlock,
  191. ClonedCodeInfo &InlinedCodeInfo) {
  192. BasicBlock *InvokeDest = II->getUnwindDest();
  193. Function *Caller = FirstNewBlock->getParent();
  194. // The inlined code is currently at the end of the function, scan from the
  195. // start of the inlined code to its end, checking for stuff we need to
  196. // rewrite. If the code doesn't have calls or unwinds, we know there is
  197. // nothing to rewrite.
  198. if (!InlinedCodeInfo.ContainsCalls) {
  199. // Now that everything is happy, we have one final detail. The PHI nodes in
  200. // the exception destination block still have entries due to the original
  201. // invoke instruction. Eliminate these entries (which might even delete the
  202. // PHI node) now.
  203. InvokeDest->removePredecessor(II->getParent());
  204. return;
  205. }
  206. InvokeInliningInfo Invoke(II);
  207. for (Function::iterator BB = FirstNewBlock, E = Caller->end(); BB != E; ++BB){
  208. if (InlinedCodeInfo.ContainsCalls)
  209. if (HandleCallsInBlockInlinedThroughInvoke(BB, Invoke)) {
  210. // Honor a request to skip the next block.
  211. ++BB;
  212. continue;
  213. }
  214. if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator()))
  215. Invoke.forwardResume(RI);
  216. }
  217. // Now that everything is happy, we have one final detail. The PHI nodes in
  218. // the exception destination block still have entries due to the original
  219. // invoke instruction. Eliminate these entries (which might even delete the
  220. // PHI node) now.
  221. InvokeDest->removePredecessor(II->getParent());
  222. }
  223. /// UpdateCallGraphAfterInlining - Once we have cloned code over from a callee
  224. /// into the caller, update the specified callgraph to reflect the changes we
  225. /// made. Note that it's possible that not all code was copied over, so only
  226. /// some edges of the callgraph may remain.
  227. static void UpdateCallGraphAfterInlining(CallSite CS,
  228. Function::iterator FirstNewBlock,
  229. ValueToValueMapTy &VMap,
  230. InlineFunctionInfo &IFI) {
  231. CallGraph &CG = *IFI.CG;
  232. const Function *Caller = CS.getInstruction()->getParent()->getParent();
  233. const Function *Callee = CS.getCalledFunction();
  234. CallGraphNode *CalleeNode = CG[Callee];
  235. CallGraphNode *CallerNode = CG[Caller];
  236. // Since we inlined some uninlined call sites in the callee into the caller,
  237. // add edges from the caller to all of the callees of the callee.
  238. CallGraphNode::iterator I = CalleeNode->begin(), E = CalleeNode->end();
  239. // Consider the case where CalleeNode == CallerNode.
  240. CallGraphNode::CalledFunctionsVector CallCache;
  241. if (CalleeNode == CallerNode) {
  242. CallCache.assign(I, E);
  243. I = CallCache.begin();
  244. E = CallCache.end();
  245. }
  246. for (; I != E; ++I) {
  247. const Value *OrigCall = I->first;
  248. ValueToValueMapTy::iterator VMI = VMap.find(OrigCall);
  249. // Only copy the edge if the call was inlined!
  250. if (VMI == VMap.end() || VMI->second == 0)
  251. continue;
  252. // If the call was inlined, but then constant folded, there is no edge to
  253. // add. Check for this case.
  254. Instruction *NewCall = dyn_cast<Instruction>(VMI->second);
  255. if (NewCall == 0) continue;
  256. // Remember that this call site got inlined for the client of
  257. // InlineFunction.
  258. IFI.InlinedCalls.push_back(NewCall);
  259. // It's possible that inlining the callsite will cause it to go from an
  260. // indirect to a direct call by resolving a function pointer. If this
  261. // happens, set the callee of the new call site to a more precise
  262. // destination. This can also happen if the call graph node of the caller
  263. // was just unnecessarily imprecise.
  264. if (I->second->getFunction() == 0)
  265. if (Function *F = CallSite(NewCall).getCalledFunction()) {
  266. // Indirect call site resolved to direct call.
  267. CallerNode->addCalledFunction(CallSite(NewCall), CG[F]);
  268. continue;
  269. }
  270. CallerNode->addCalledFunction(CallSite(NewCall), I->second);
  271. }
  272. // Update the call graph by deleting the edge from Callee to Caller. We must
  273. // do this after the loop above in case Caller and Callee are the same.
  274. CallerNode->removeCallEdgeFor(CS);
  275. }
  276. /// HandleByValArgument - When inlining a call site that has a byval argument,
  277. /// we have to make the implicit memcpy explicit by adding it.
  278. static Value *HandleByValArgument(Value *Arg, Instruction *TheCall,
  279. const Function *CalledFunc,
  280. InlineFunctionInfo &IFI,
  281. unsigned ByValAlignment) {
  282. Type *AggTy = cast<PointerType>(Arg->getType())->getElementType();
  283. // If the called function is readonly, then it could not mutate the caller's
  284. // copy of the byval'd memory. In this case, it is safe to elide the copy and
  285. // temporary.
  286. if (CalledFunc->onlyReadsMemory()) {
  287. // If the byval argument has a specified alignment that is greater than the
  288. // passed in pointer, then we either have to round up the input pointer or
  289. // give up on this transformation.
  290. if (ByValAlignment <= 1) // 0 = unspecified, 1 = no particular alignment.
  291. return Arg;
  292. // If the pointer is already known to be sufficiently aligned, or if we can
  293. // round it up to a larger alignment, then we don't need a temporary.
  294. if (getOrEnforceKnownAlignment(Arg, ByValAlignment,
  295. IFI.TD) >= ByValAlignment)
  296. return Arg;
  297. // Otherwise, we have to make a memcpy to get a safe alignment. This is bad
  298. // for code quality, but rarely happens and is required for correctness.
  299. }
  300. LLVMContext &Context = Arg->getContext();
  301. Type *VoidPtrTy = Type::getInt8PtrTy(Context);
  302. // Create the alloca. If we have TargetData, use nice alignment.
  303. unsigned Align = 1;
  304. if (IFI.TD)
  305. Align = IFI.TD->getPrefTypeAlignment(AggTy);
  306. // If the byval had an alignment specified, we *must* use at least that
  307. // alignment, as it is required by the byval argument (and uses of the
  308. // pointer inside the callee).
  309. Align = std::max(Align, ByValAlignment);
  310. Function *Caller = TheCall->getParent()->getParent();
  311. Value *NewAlloca = new AllocaInst(AggTy, 0, Align, Arg->getName(),
  312. &*Caller->begin()->begin());
  313. // Emit a memcpy.
  314. Type *Tys[3] = {VoidPtrTy, VoidPtrTy, Type::getInt64Ty(Context)};
  315. Function *MemCpyFn = Intrinsic::getDeclaration(Caller->getParent(),
  316. Intrinsic::memcpy,
  317. Tys);
  318. Value *DestCast = new BitCastInst(NewAlloca, VoidPtrTy, "tmp", TheCall);
  319. Value *SrcCast = new BitCastInst(Arg, VoidPtrTy, "tmp", TheCall);
  320. Value *Size;
  321. if (IFI.TD == 0)
  322. Size = ConstantExpr::getSizeOf(AggTy);
  323. else
  324. Size = ConstantInt::get(Type::getInt64Ty(Context),
  325. IFI.TD->getTypeStoreSize(AggTy));
  326. // Always generate a memcpy of alignment 1 here because we don't know
  327. // the alignment of the src pointer. Other optimizations can infer
  328. // better alignment.
  329. Value *CallArgs[] = {
  330. DestCast, SrcCast, Size,
  331. ConstantInt::get(Type::getInt32Ty(Context), 1),
  332. ConstantInt::getFalse(Context) // isVolatile
  333. };
  334. IRBuilder<>(TheCall).CreateCall(MemCpyFn, CallArgs);
  335. // Uses of the argument in the function should use our new alloca
  336. // instead.
  337. return NewAlloca;
  338. }
  339. // isUsedByLifetimeMarker - Check whether this Value is used by a lifetime
  340. // intrinsic.
  341. static bool isUsedByLifetimeMarker(Value *V) {
  342. for (Value::use_iterator UI = V->use_begin(), UE = V->use_end(); UI != UE;
  343. ++UI) {
  344. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(*UI)) {
  345. switch (II->getIntrinsicID()) {
  346. default: break;
  347. case Intrinsic::lifetime_start:
  348. case Intrinsic::lifetime_end:
  349. return true;
  350. }
  351. }
  352. }
  353. return false;
  354. }
  355. // hasLifetimeMarkers - Check whether the given alloca already has
  356. // lifetime.start or lifetime.end intrinsics.
  357. static bool hasLifetimeMarkers(AllocaInst *AI) {
  358. Type *Int8PtrTy = Type::getInt8PtrTy(AI->getType()->getContext());
  359. if (AI->getType() == Int8PtrTy)
  360. return isUsedByLifetimeMarker(AI);
  361. // Do a scan to find all the casts to i8*.
  362. for (Value::use_iterator I = AI->use_begin(), E = AI->use_end(); I != E;
  363. ++I) {
  364. if (I->getType() != Int8PtrTy) continue;
  365. if (I->stripPointerCasts() != AI) continue;
  366. if (isUsedByLifetimeMarker(*I))
  367. return true;
  368. }
  369. return false;
  370. }
  371. /// updateInlinedAtInfo - Helper function used by fixupLineNumbers to
  372. /// recursively update InlinedAtEntry of a DebugLoc.
  373. static DebugLoc updateInlinedAtInfo(const DebugLoc &DL,
  374. const DebugLoc &InlinedAtDL,
  375. LLVMContext &Ctx) {
  376. if (MDNode *IA = DL.getInlinedAt(Ctx)) {
  377. DebugLoc NewInlinedAtDL
  378. = updateInlinedAtInfo(DebugLoc::getFromDILocation(IA), InlinedAtDL, Ctx);
  379. return DebugLoc::get(DL.getLine(), DL.getCol(), DL.getScope(Ctx),
  380. NewInlinedAtDL.getAsMDNode(Ctx));
  381. }
  382. return DebugLoc::get(DL.getLine(), DL.getCol(), DL.getScope(Ctx),
  383. InlinedAtDL.getAsMDNode(Ctx));
  384. }
  385. /// fixupLineNumbers - Update inlined instructions' line numbers to
  386. /// to encode location where these instructions are inlined.
  387. static void fixupLineNumbers(Function *Fn, Function::iterator FI,
  388. Instruction *TheCall) {
  389. DebugLoc TheCallDL = TheCall->getDebugLoc();
  390. if (TheCallDL.isUnknown())
  391. return;
  392. for (; FI != Fn->end(); ++FI) {
  393. for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
  394. BI != BE; ++BI) {
  395. DebugLoc DL = BI->getDebugLoc();
  396. if (!DL.isUnknown()) {
  397. BI->setDebugLoc(updateInlinedAtInfo(DL, TheCallDL, BI->getContext()));
  398. if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(BI)) {
  399. LLVMContext &Ctx = BI->getContext();
  400. MDNode *InlinedAt = BI->getDebugLoc().getInlinedAt(Ctx);
  401. DVI->setOperand(2, createInlinedVariable(DVI->getVariable(),
  402. InlinedAt, Ctx));
  403. }
  404. }
  405. }
  406. }
  407. }
  408. /// InlineFunction - This function inlines the called function into the basic
  409. /// block of the caller. This returns false if it is not possible to inline
  410. /// this call. The program is still in a well defined state if this occurs
  411. /// though.
  412. ///
  413. /// Note that this only does one level of inlining. For example, if the
  414. /// instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
  415. /// exists in the instruction stream. Similarly this will inline a recursive
  416. /// function by one level.
  417. bool llvm::InlineFunction(CallSite CS, InlineFunctionInfo &IFI,
  418. bool InsertLifetime) {
  419. Instruction *TheCall = CS.getInstruction();
  420. assert(TheCall->getParent() && TheCall->getParent()->getParent() &&
  421. "Instruction not in function!");
  422. // If IFI has any state in it, zap it before we fill it in.
  423. IFI.reset();
  424. const Function *CalledFunc = CS.getCalledFunction();
  425. if (CalledFunc == 0 || // Can't inline external function or indirect
  426. CalledFunc->isDeclaration() || // call, or call to a vararg function!
  427. CalledFunc->getFunctionType()->isVarArg()) return false;
  428. // If the call to the callee is not a tail call, we must clear the 'tail'
  429. // flags on any calls that we inline.
  430. bool MustClearTailCallFlags =
  431. !(isa<CallInst>(TheCall) && cast<CallInst>(TheCall)->isTailCall());
  432. // If the call to the callee cannot throw, set the 'nounwind' flag on any
  433. // calls that we inline.
  434. bool MarkNoUnwind = CS.doesNotThrow();
  435. BasicBlock *OrigBB = TheCall->getParent();
  436. Function *Caller = OrigBB->getParent();
  437. // GC poses two hazards to inlining, which only occur when the callee has GC:
  438. // 1. If the caller has no GC, then the callee's GC must be propagated to the
  439. // caller.
  440. // 2. If the caller has a differing GC, it is invalid to inline.
  441. if (CalledFunc->hasGC()) {
  442. if (!Caller->hasGC())
  443. Caller->setGC(CalledFunc->getGC());
  444. else if (CalledFunc->getGC() != Caller->getGC())
  445. return false;
  446. }
  447. // Get the personality function from the callee if it contains a landing pad.
  448. Value *CalleePersonality = 0;
  449. for (Function::const_iterator I = CalledFunc->begin(), E = CalledFunc->end();
  450. I != E; ++I)
  451. if (const InvokeInst *II = dyn_cast<InvokeInst>(I->getTerminator())) {
  452. const BasicBlock *BB = II->getUnwindDest();
  453. const LandingPadInst *LP = BB->getLandingPadInst();
  454. CalleePersonality = LP->getPersonalityFn();
  455. break;
  456. }
  457. // Find the personality function used by the landing pads of the caller. If it
  458. // exists, then check to see that it matches the personality function used in
  459. // the callee.
  460. if (CalleePersonality) {
  461. for (Function::const_iterator I = Caller->begin(), E = Caller->end();
  462. I != E; ++I)
  463. if (const InvokeInst *II = dyn_cast<InvokeInst>(I->getTerminator())) {
  464. const BasicBlock *BB = II->getUnwindDest();
  465. const LandingPadInst *LP = BB->getLandingPadInst();
  466. // If the personality functions match, then we can perform the
  467. // inlining. Otherwise, we can't inline.
  468. // TODO: This isn't 100% true. Some personality functions are proper
  469. // supersets of others and can be used in place of the other.
  470. if (LP->getPersonalityFn() != CalleePersonality)
  471. return false;
  472. break;
  473. }
  474. }
  475. // Get an iterator to the last basic block in the function, which will have
  476. // the new function inlined after it.
  477. Function::iterator LastBlock = &Caller->back();
  478. // Make sure to capture all of the return instructions from the cloned
  479. // function.
  480. SmallVector<ReturnInst*, 8> Returns;
  481. ClonedCodeInfo InlinedFunctionInfo;
  482. Function::iterator FirstNewBlock;
  483. { // Scope to destroy VMap after cloning.
  484. ValueToValueMapTy VMap;
  485. assert(CalledFunc->arg_size() == CS.arg_size() &&
  486. "No varargs calls can be inlined!");
  487. // Calculate the vector of arguments to pass into the function cloner, which
  488. // matches up the formal to the actual argument values.
  489. CallSite::arg_iterator AI = CS.arg_begin();
  490. unsigned ArgNo = 0;
  491. for (Function::const_arg_iterator I = CalledFunc->arg_begin(),
  492. E = CalledFunc->arg_end(); I != E; ++I, ++AI, ++ArgNo) {
  493. Value *ActualArg = *AI;
  494. // When byval arguments actually inlined, we need to make the copy implied
  495. // by them explicit. However, we don't do this if the callee is readonly
  496. // or readnone, because the copy would be unneeded: the callee doesn't
  497. // modify the struct.
  498. if (CS.isByValArgument(ArgNo)) {
  499. ActualArg = HandleByValArgument(ActualArg, TheCall, CalledFunc, IFI,
  500. CalledFunc->getParamAlignment(ArgNo+1));
  501. // Calls that we inline may use the new alloca, so we need to clear
  502. // their 'tail' flags if HandleByValArgument introduced a new alloca and
  503. // the callee has calls.
  504. MustClearTailCallFlags |= ActualArg != *AI;
  505. }
  506. VMap[I] = ActualArg;
  507. }
  508. // We want the inliner to prune the code as it copies. We would LOVE to
  509. // have no dead or constant instructions leftover after inlining occurs
  510. // (which can happen, e.g., because an argument was constant), but we'll be
  511. // happy with whatever the cloner can do.
  512. CloneAndPruneFunctionInto(Caller, CalledFunc, VMap,
  513. /*ModuleLevelChanges=*/false, Returns, ".i",
  514. &InlinedFunctionInfo, IFI.TD, TheCall);
  515. // Remember the first block that is newly cloned over.
  516. FirstNewBlock = LastBlock; ++FirstNewBlock;
  517. // Update the callgraph if requested.
  518. if (IFI.CG)
  519. UpdateCallGraphAfterInlining(CS, FirstNewBlock, VMap, IFI);
  520. // Update inlined instructions' line number information.
  521. fixupLineNumbers(Caller, FirstNewBlock, TheCall);
  522. }
  523. // If there are any alloca instructions in the block that used to be the entry
  524. // block for the callee, move them to the entry block of the caller. First
  525. // calculate which instruction they should be inserted before. We insert the
  526. // instructions at the end of the current alloca list.
  527. {
  528. BasicBlock::iterator InsertPoint = Caller->begin()->begin();
  529. for (BasicBlock::iterator I = FirstNewBlock->begin(),
  530. E = FirstNewBlock->end(); I != E; ) {
  531. AllocaInst *AI = dyn_cast<AllocaInst>(I++);
  532. if (AI == 0) continue;
  533. // If the alloca is now dead, remove it. This often occurs due to code
  534. // specialization.
  535. if (AI->use_empty()) {
  536. AI->eraseFromParent();
  537. continue;
  538. }
  539. if (!isa<Constant>(AI->getArraySize()))
  540. continue;
  541. // Keep track of the static allocas that we inline into the caller.
  542. IFI.StaticAllocas.push_back(AI);
  543. // Scan for the block of allocas that we can move over, and move them
  544. // all at once.
  545. while (isa<AllocaInst>(I) &&
  546. isa<Constant>(cast<AllocaInst>(I)->getArraySize())) {
  547. IFI.StaticAllocas.push_back(cast<AllocaInst>(I));
  548. ++I;
  549. }
  550. // Transfer all of the allocas over in a block. Using splice means
  551. // that the instructions aren't removed from the symbol table, then
  552. // reinserted.
  553. Caller->getEntryBlock().getInstList().splice(InsertPoint,
  554. FirstNewBlock->getInstList(),
  555. AI, I);
  556. }
  557. }
  558. // Leave lifetime markers for the static alloca's, scoping them to the
  559. // function we just inlined.
  560. if (InsertLifetime && !IFI.StaticAllocas.empty()) {
  561. IRBuilder<> builder(FirstNewBlock->begin());
  562. for (unsigned ai = 0, ae = IFI.StaticAllocas.size(); ai != ae; ++ai) {
  563. AllocaInst *AI = IFI.StaticAllocas[ai];
  564. // If the alloca is already scoped to something smaller than the whole
  565. // function then there's no need to add redundant, less accurate markers.
  566. if (hasLifetimeMarkers(AI))
  567. continue;
  568. builder.CreateLifetimeStart(AI);
  569. for (unsigned ri = 0, re = Returns.size(); ri != re; ++ri) {
  570. IRBuilder<> builder(Returns[ri]);
  571. builder.CreateLifetimeEnd(AI);
  572. }
  573. }
  574. }
  575. // If the inlined code contained dynamic alloca instructions, wrap the inlined
  576. // code with llvm.stacksave/llvm.stackrestore intrinsics.
  577. if (InlinedFunctionInfo.ContainsDynamicAllocas) {
  578. Module *M = Caller->getParent();
  579. // Get the two intrinsics we care about.
  580. Function *StackSave = Intrinsic::getDeclaration(M, Intrinsic::stacksave);
  581. Function *StackRestore=Intrinsic::getDeclaration(M,Intrinsic::stackrestore);
  582. // Insert the llvm.stacksave.
  583. CallInst *SavedPtr = IRBuilder<>(FirstNewBlock, FirstNewBlock->begin())
  584. .CreateCall(StackSave, "savedstack");
  585. // Insert a call to llvm.stackrestore before any return instructions in the
  586. // inlined function.
  587. for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
  588. IRBuilder<>(Returns[i]).CreateCall(StackRestore, SavedPtr);
  589. }
  590. }
  591. // If we are inlining tail call instruction through a call site that isn't
  592. // marked 'tail', we must remove the tail marker for any calls in the inlined
  593. // code. Also, calls inlined through a 'nounwind' call site should be marked
  594. // 'nounwind'.
  595. if (InlinedFunctionInfo.ContainsCalls &&
  596. (MustClearTailCallFlags || MarkNoUnwind)) {
  597. for (Function::iterator BB = FirstNewBlock, E = Caller->end();
  598. BB != E; ++BB)
  599. for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
  600. if (CallInst *CI = dyn_cast<CallInst>(I)) {
  601. if (MustClearTailCallFlags)
  602. CI->setTailCall(false);
  603. if (MarkNoUnwind)
  604. CI->setDoesNotThrow();
  605. }
  606. }
  607. // If we are inlining for an invoke instruction, we must make sure to rewrite
  608. // any call instructions into invoke instructions.
  609. if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
  610. HandleInlinedInvoke(II, FirstNewBlock, InlinedFunctionInfo);
  611. // If we cloned in _exactly one_ basic block, and if that block ends in a
  612. // return instruction, we splice the body of the inlined callee directly into
  613. // the calling basic block.
  614. if (Returns.size() == 1 && std::distance(FirstNewBlock, Caller->end()) == 1) {
  615. // Move all of the instructions right before the call.
  616. OrigBB->getInstList().splice(TheCall, FirstNewBlock->getInstList(),
  617. FirstNewBlock->begin(), FirstNewBlock->end());
  618. // Remove the cloned basic block.
  619. Caller->getBasicBlockList().pop_back();
  620. // If the call site was an invoke instruction, add a branch to the normal
  621. // destination.
  622. if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
  623. BranchInst::Create(II->getNormalDest(), TheCall);
  624. // If the return instruction returned a value, replace uses of the call with
  625. // uses of the returned value.
  626. if (!TheCall->use_empty()) {
  627. ReturnInst *R = Returns[0];
  628. if (TheCall == R->getReturnValue())
  629. TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
  630. else
  631. TheCall->replaceAllUsesWith(R->getReturnValue());
  632. }
  633. // Since we are now done with the Call/Invoke, we can delete it.
  634. TheCall->eraseFromParent();
  635. // Since we are now done with the return instruction, delete it also.
  636. Returns[0]->eraseFromParent();
  637. // We are now done with the inlining.
  638. return true;
  639. }
  640. // Otherwise, we have the normal case, of more than one block to inline or
  641. // multiple return sites.
  642. // We want to clone the entire callee function into the hole between the
  643. // "starter" and "ender" blocks. How we accomplish this depends on whether
  644. // this is an invoke instruction or a call instruction.
  645. BasicBlock *AfterCallBB;
  646. if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
  647. // Add an unconditional branch to make this look like the CallInst case...
  648. BranchInst *NewBr = BranchInst::Create(II->getNormalDest(), TheCall);
  649. // Split the basic block. This guarantees that no PHI nodes will have to be
  650. // updated due to new incoming edges, and make the invoke case more
  651. // symmetric to the call case.
  652. AfterCallBB = OrigBB->splitBasicBlock(NewBr,
  653. CalledFunc->getName()+".exit");
  654. } else { // It's a call
  655. // If this is a call instruction, we need to split the basic block that
  656. // the call lives in.
  657. //
  658. AfterCallBB = OrigBB->splitBasicBlock(TheCall,
  659. CalledFunc->getName()+".exit");
  660. }
  661. // Change the branch that used to go to AfterCallBB to branch to the first
  662. // basic block of the inlined function.
  663. //
  664. TerminatorInst *Br = OrigBB->getTerminator();
  665. assert(Br && Br->getOpcode() == Instruction::Br &&
  666. "splitBasicBlock broken!");
  667. Br->setOperand(0, FirstNewBlock);
  668. // Now that the function is correct, make it a little bit nicer. In
  669. // particular, move the basic blocks inserted from the end of the function
  670. // into the space made by splitting the source basic block.
  671. Caller->getBasicBlockList().splice(AfterCallBB, Caller->getBasicBlockList(),
  672. FirstNewBlock, Caller->end());
  673. // Handle all of the return instructions that we just cloned in, and eliminate
  674. // any users of the original call/invoke instruction.
  675. Type *RTy = CalledFunc->getReturnType();
  676. PHINode *PHI = 0;
  677. if (Returns.size() > 1) {
  678. // The PHI node should go at the front of the new basic block to merge all
  679. // possible incoming values.
  680. if (!TheCall->use_empty()) {
  681. PHI = PHINode::Create(RTy, Returns.size(), TheCall->getName(),
  682. AfterCallBB->begin());
  683. // Anything that used the result of the function call should now use the
  684. // PHI node as their operand.
  685. TheCall->replaceAllUsesWith(PHI);
  686. }
  687. // Loop over all of the return instructions adding entries to the PHI node
  688. // as appropriate.
  689. if (PHI) {
  690. for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
  691. ReturnInst *RI = Returns[i];
  692. assert(RI->getReturnValue()->getType() == PHI->getType() &&
  693. "Ret value not consistent in function!");
  694. PHI->addIncoming(RI->getReturnValue(), RI->getParent());
  695. }
  696. }
  697. // Add a branch to the merge points and remove return instructions.
  698. for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
  699. ReturnInst *RI = Returns[i];
  700. BranchInst::Create(AfterCallBB, RI);
  701. RI->eraseFromParent();
  702. }
  703. } else if (!Returns.empty()) {
  704. // Otherwise, if there is exactly one return value, just replace anything
  705. // using the return value of the call with the computed value.
  706. if (!TheCall->use_empty()) {
  707. if (TheCall == Returns[0]->getReturnValue())
  708. TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
  709. else
  710. TheCall->replaceAllUsesWith(Returns[0]->getReturnValue());
  711. }
  712. // Update PHI nodes that use the ReturnBB to use the AfterCallBB.
  713. BasicBlock *ReturnBB = Returns[0]->getParent();
  714. ReturnBB->replaceAllUsesWith(AfterCallBB);
  715. // Splice the code from the return block into the block that it will return
  716. // to, which contains the code that was after the call.
  717. AfterCallBB->getInstList().splice(AfterCallBB->begin(),
  718. ReturnBB->getInstList());
  719. // Delete the return instruction now and empty ReturnBB now.
  720. Returns[0]->eraseFromParent();
  721. ReturnBB->eraseFromParent();
  722. } else if (!TheCall->use_empty()) {
  723. // No returns, but something is using the return value of the call. Just
  724. // nuke the result.
  725. TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
  726. }
  727. // Since we are now done with the Call/Invoke, we can delete it.
  728. TheCall->eraseFromParent();
  729. // We should always be able to fold the entry block of the function into the
  730. // single predecessor of the block...
  731. assert(cast<BranchInst>(Br)->isUnconditional() && "splitBasicBlock broken!");
  732. BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0);
  733. // Splice the code entry block into calling block, right before the
  734. // unconditional branch.
  735. CalleeEntry->replaceAllUsesWith(OrigBB); // Update PHI nodes
  736. OrigBB->getInstList().splice(Br, CalleeEntry->getInstList());
  737. // Remove the unconditional branch.
  738. OrigBB->getInstList().erase(Br);
  739. // Now we can remove the CalleeEntry block, which is now empty.
  740. Caller->getBasicBlockList().erase(CalleeEntry);
  741. // If we inserted a phi node, check to see if it has a single value (e.g. all
  742. // the entries are the same or undef). If so, remove the PHI so it doesn't
  743. // block other optimizations.
  744. if (PHI) {
  745. if (Value *V = SimplifyInstruction(PHI, IFI.TD)) {
  746. PHI->replaceAllUsesWith(V);
  747. PHI->eraseFromParent();
  748. }
  749. }
  750. return true;
  751. }