InlineFunction.cpp revision 009c4d86c14bb2f46f9473f8f517393dabab7e9e
1ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner//===- InlineFunction.cpp - Code to perform function inlining -------------===//
2fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman//
3b576c94c15af9a440f69d9d03c2afead7971118cJohn Criswell//                     The LLVM Compiler Infrastructure
4b576c94c15af9a440f69d9d03c2afead7971118cJohn Criswell//
54ee451de366474b9c228b4e5fa573795a715216dChris Lattner// This file is distributed under the University of Illinois Open Source
64ee451de366474b9c228b4e5fa573795a715216dChris Lattner// License. See LICENSE.TXT for details.
7fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman//
8b576c94c15af9a440f69d9d03c2afead7971118cJohn Criswell//===----------------------------------------------------------------------===//
9ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner//
10ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner// This file implements inlining of a function into a call site, resolving
11ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner// parameters and the return value as appropriate.
12ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner//
13ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner//===----------------------------------------------------------------------===//
14ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner
15ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner#include "llvm/Transforms/Utils/Cloning.h"
1606cb8ed00696eb14d1b831921452e50ec0568ea2Chandler Carruth#include "llvm/Attributes.h"
173787e765facfad5ea62753922d940bcdd52afd57Chris Lattner#include "llvm/Constants.h"
180bcbd1df7a204e1e512f1a27066d725309de1b13Bill Wendling#include "llvm/DebugInfo.h"
197152c237b46a920b29d5605af934766b8f9a07a1Chris Lattner#include "llvm/DerivedTypes.h"
2006cb8ed00696eb14d1b831921452e50ec0568ea2Chandler Carruth#include "llvm/IRBuilder.h"
2180a38d245359cb0a3be8f78f5d7d911232886b9aChris Lattner#include "llvm/Instructions.h"
22517576d6f96a0acde9bab79553d89f4ceba20cf6Devang Patel#include "llvm/IntrinsicInst.h"
2380a38d245359cb0a3be8f78f5d7d911232886b9aChris Lattner#include "llvm/Intrinsics.h"
2406cb8ed00696eb14d1b831921452e50ec0568ea2Chandler Carruth#include "llvm/Module.h"
2506cb8ed00696eb14d1b831921452e50ec0568ea2Chandler Carruth#include "llvm/ADT/SmallVector.h"
2606cb8ed00696eb14d1b831921452e50ec0568ea2Chandler Carruth#include "llvm/ADT/StringExtras.h"
27468fb1df7db466e5682ee44341c3990b599e8d6aChris Lattner#include "llvm/Analysis/CallGraph.h"
286fb881c036c32728c4a128d81b6083457e534e09Duncan Sands#include "llvm/Analysis/InstructionSimplify.h"
2906cb8ed00696eb14d1b831921452e50ec0568ea2Chandler Carruth#include "llvm/Support/CallSite.h"
303574eca1b02600bac4e625297f4ecf745f4c4f32Micah Villmow#include "llvm/DataLayout.h"
317569d79de1bd97a6a17b81340ea6ce97d8a3c279Chris Lattner#include "llvm/Transforms/Utils/Local.h"
32f7703df4968084c18c248c1feea9961c19a32e6aChris Lattnerusing namespace llvm;
33ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner
34373c2d37072026e82f9b307eb40cf12baafd5f93Eric Christopherbool llvm::InlineFunction(CallInst *CI, InlineFunctionInfo &IFI,
35373c2d37072026e82f9b307eb40cf12baafd5f93Eric Christopher                          bool InsertLifetime) {
36fa086f1f00a8b75ab2e2208bd7a028e62f9854dbChad Rosier  return InlineFunction(CallSite(CI), IFI, InsertLifetime);
37468fb1df7db466e5682ee44341c3990b599e8d6aChris Lattner}
38373c2d37072026e82f9b307eb40cf12baafd5f93Eric Christopherbool llvm::InlineFunction(InvokeInst *II, InlineFunctionInfo &IFI,
39373c2d37072026e82f9b307eb40cf12baafd5f93Eric Christopher                          bool InsertLifetime) {
40fa086f1f00a8b75ab2e2208bd7a028e62f9854dbChad Rosier  return InlineFunction(CallSite(II), IFI, InsertLifetime);
41468fb1df7db466e5682ee44341c3990b599e8d6aChris Lattner}
4280a38d245359cb0a3be8f78f5d7d911232886b9aChris Lattner
43a3de16bc8f36638d5444e3e7b0112998af54f826John McCallnamespace {
44a3de16bc8f36638d5444e3e7b0112998af54f826John McCall  /// A class for recording information about inlining through an invoke.
45a3de16bc8f36638d5444e3e7b0112998af54f826John McCall  class InvokeInliningInfo {
4677592fe39c404f3c48b06fae48b965058b3a5ee8Dmitri Gribenko    BasicBlock *OuterResumeDest; ///< Destination of the invoke's unwind.
4777592fe39c404f3c48b06fae48b965058b3a5ee8Dmitri Gribenko    BasicBlock *InnerResumeDest; ///< Destination for the callee's resume.
4877592fe39c404f3c48b06fae48b965058b3a5ee8Dmitri Gribenko    LandingPadInst *CallerLPad;  ///< LandingPadInst associated with the invoke.
4977592fe39c404f3c48b06fae48b965058b3a5ee8Dmitri Gribenko    PHINode *InnerEHValuesPHI;   ///< PHI for EH values from landingpad insts.
504dbd9b8ebfddb845c5675bbf2567a4d0e04871e7Bill Wendling    SmallVector<Value*, 8> UnwindDestPHIValues;
51fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling
522bf84c15d24bb373987d9dbc6308092eac1b8324Bill Wendling  public:
53fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling    InvokeInliningInfo(InvokeInst *II)
5408d01462d13fdfac756a8bd0f38bbfbceb247403Bill Wendling      : OuterResumeDest(II->getUnwindDest()), InnerResumeDest(0),
55fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling        CallerLPad(0), InnerEHValuesPHI(0) {
56fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling      // If there are PHI nodes in the unwind destination block, we need to keep
57fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling      // track of which values came into them from the invoke before removing
58fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling      // the edge from this block.
59fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling      llvm::BasicBlock *InvokeBB = II->getParent();
6008d01462d13fdfac756a8bd0f38bbfbceb247403Bill Wendling      BasicBlock::iterator I = OuterResumeDest->begin();
61fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling      for (; isa<PHINode>(I); ++I) {
62a3de16bc8f36638d5444e3e7b0112998af54f826John McCall        // Save the value to use for this edge.
63fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling        PHINode *PHI = cast<PHINode>(I);
64fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling        UnwindDestPHIValues.push_back(PHI->getIncomingValueForBlock(InvokeBB));
65fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling      }
66fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling
6727b5658affba5b12b396048d2cc598c70719bfc5Bill Wendling      CallerLPad = cast<LandingPadInst>(I);
68a3de16bc8f36638d5444e3e7b0112998af54f826John McCall    }
69a3de16bc8f36638d5444e3e7b0112998af54f826John McCall
7008d01462d13fdfac756a8bd0f38bbfbceb247403Bill Wendling    /// getOuterResumeDest - The outer unwind destination is the target of
7108d01462d13fdfac756a8bd0f38bbfbceb247403Bill Wendling    /// unwind edges introduced for calls within the inlined function.
724dbd9b8ebfddb845c5675bbf2567a4d0e04871e7Bill Wendling    BasicBlock *getOuterResumeDest() const {
7308d01462d13fdfac756a8bd0f38bbfbceb247403Bill Wendling      return OuterResumeDest;
74a3de16bc8f36638d5444e3e7b0112998af54f826John McCall    }
75a3de16bc8f36638d5444e3e7b0112998af54f826John McCall
7613b1c31412372ef3790934ca213546fec595fbbcBill Wendling    BasicBlock *getInnerResumeDest();
77fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling
78fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling    LandingPadInst *getLandingPadInst() const { return CallerLPad; }
79fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling
80fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling    /// forwardResume - Forward the 'resume' instruction to the caller's landing
81fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling    /// pad block. When the landing pad block has only one predecessor, this is
82fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling    /// a simple branch. When there is more than one predecessor, we need to
83fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling    /// split the landing pad block after the landingpad instruction and jump
84fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling    /// to there.
85fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling    void forwardResume(ResumeInst *RI);
86fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling
87fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling    /// addIncomingPHIValuesFor - Add incoming-PHI values to the unwind
88fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling    /// destination block for the given basic block, using the values for the
89fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling    /// original invoke's source block.
90a3de16bc8f36638d5444e3e7b0112998af54f826John McCall    void addIncomingPHIValuesFor(BasicBlock *BB) const {
9108d01462d13fdfac756a8bd0f38bbfbceb247403Bill Wendling      addIncomingPHIValuesForInto(BB, OuterResumeDest);
92d7c10862016939c9850cadfe5e1c35513c0adf28John McCall    }
9310c6d12a9fd4dab411091f64db4db69670b88850Bill Wendling
94d7c10862016939c9850cadfe5e1c35513c0adf28John McCall    void addIncomingPHIValuesForInto(BasicBlock *src, BasicBlock *dest) const {
95d7c10862016939c9850cadfe5e1c35513c0adf28John McCall      BasicBlock::iterator I = dest->begin();
96a3de16bc8f36638d5444e3e7b0112998af54f826John McCall      for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
9710c6d12a9fd4dab411091f64db4db69670b88850Bill Wendling        PHINode *phi = cast<PHINode>(I);
9810c6d12a9fd4dab411091f64db4db69670b88850Bill Wendling        phi->addIncoming(UnwindDestPHIValues[i], src);
99a3de16bc8f36638d5444e3e7b0112998af54f826John McCall      }
100a3de16bc8f36638d5444e3e7b0112998af54f826John McCall    }
101a3de16bc8f36638d5444e3e7b0112998af54f826John McCall  };
102a3de16bc8f36638d5444e3e7b0112998af54f826John McCall}
103a3de16bc8f36638d5444e3e7b0112998af54f826John McCall
10413b1c31412372ef3790934ca213546fec595fbbcBill Wendling/// getInnerResumeDest - Get or create a target for the branch from ResumeInsts.
10513b1c31412372ef3790934ca213546fec595fbbcBill WendlingBasicBlock *InvokeInliningInfo::getInnerResumeDest() {
106fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling  if (InnerResumeDest) return InnerResumeDest;
107fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling
108fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling  // Split the landing pad.
109fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling  BasicBlock::iterator SplitPoint = CallerLPad; ++SplitPoint;
110fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling  InnerResumeDest =
111fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling    OuterResumeDest->splitBasicBlock(SplitPoint,
112fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling                                     OuterResumeDest->getName() + ".body");
113fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling
114fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling  // The number of incoming edges we expect to the inner landing pad.
115fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling  const unsigned PHICapacity = 2;
116fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling
117fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling  // Create corresponding new PHIs for all the PHIs in the outer landing pad.
118fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling  BasicBlock::iterator InsertPoint = InnerResumeDest->begin();
119fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling  BasicBlock::iterator I = OuterResumeDest->begin();
120fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling  for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
121fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling    PHINode *OuterPHI = cast<PHINode>(I);
122fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling    PHINode *InnerPHI = PHINode::Create(OuterPHI->getType(), PHICapacity,
123fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling                                        OuterPHI->getName() + ".lpad-body",
124fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling                                        InsertPoint);
125fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling    OuterPHI->replaceAllUsesWith(InnerPHI);
126fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling    InnerPHI->addIncoming(OuterPHI, OuterResumeDest);
127fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling  }
128fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling
129fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling  // Create a PHI for the exception values.
130fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling  InnerEHValuesPHI = PHINode::Create(CallerLPad->getType(), PHICapacity,
131fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling                                     "eh.lpad-body", InsertPoint);
132fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling  CallerLPad->replaceAllUsesWith(InnerEHValuesPHI);
133fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling  InnerEHValuesPHI->addIncoming(CallerLPad, OuterResumeDest);
134fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling
135fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling  // All done.
136fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling  return InnerResumeDest;
137fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling}
138fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling
139fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling/// forwardResume - Forward the 'resume' instruction to the caller's landing pad
140fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling/// block. When the landing pad block has only one predecessor, this is a simple
141fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling/// branch. When there is more than one predecessor, we need to split the
142fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling/// landing pad block after the landingpad instruction and jump to there.
143fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendlingvoid InvokeInliningInfo::forwardResume(ResumeInst *RI) {
14413b1c31412372ef3790934ca213546fec595fbbcBill Wendling  BasicBlock *Dest = getInnerResumeDest();
145fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling  BasicBlock *Src = RI->getParent();
146fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling
147fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling  BranchInst::Create(Dest, Src);
148fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling
149fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling  // Update the PHIs in the destination. They were inserted in an order which
150fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling  // makes this work.
151fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling  addIncomingPHIValuesForInto(Src, Dest);
152fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling
153fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling  InnerEHValuesPHI->addIncoming(RI->getOperand(0), Src);
154fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling  RI->eraseFromParent();
155fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling}
156fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling
157135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner/// HandleCallsInBlockInlinedThroughInvoke - When we inline a basic block into
158f61f89ae14cf332a014a598153137113af34002fEric Christopher/// an invoke, we have to turn all of the calls that can throw into
159135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner/// invokes.  This function analyze BB to see if there are any calls, and if so,
160135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner/// it rewrites them to be invokes that jump to InvokeDest and fills in the PHI
16181dfb3885252fbf621b080827a080099864415f8Chris Lattner/// nodes in that block with the values specified in InvokeDestPHIValues.
162135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner///
163a3de16bc8f36638d5444e3e7b0112998af54f826John McCall/// Returns true to indicate that the next block should be skipped.
164a3de16bc8f36638d5444e3e7b0112998af54f826John McCallstatic bool HandleCallsInBlockInlinedThroughInvoke(BasicBlock *BB,
165a3de16bc8f36638d5444e3e7b0112998af54f826John McCall                                                   InvokeInliningInfo &Invoke) {
166fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling  LandingPadInst *LPI = Invoke.getLandingPadInst();
167fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling
168135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner  for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
169135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner    Instruction *I = BBI++;
170fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling
17127b5658affba5b12b396048d2cc598c70719bfc5Bill Wendling    if (LandingPadInst *L = dyn_cast<LandingPadInst>(I)) {
17227b5658affba5b12b396048d2cc598c70719bfc5Bill Wendling      unsigned NumClauses = LPI->getNumClauses();
17327b5658affba5b12b396048d2cc598c70719bfc5Bill Wendling      L->reserveClauses(NumClauses);
17427b5658affba5b12b396048d2cc598c70719bfc5Bill Wendling      for (unsigned i = 0; i != NumClauses; ++i)
17527b5658affba5b12b396048d2cc598c70719bfc5Bill Wendling        L->addClause(LPI->getClause(i));
17627b5658affba5b12b396048d2cc598c70719bfc5Bill Wendling    }
177fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling
178135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner    // We only need to check for function calls: inlined invoke
179135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner    // instructions require no special handling.
180135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner    CallInst *CI = dyn_cast<CallInst>(I);
181675f63886944d72e05e5210c36838c797364a0aaBill Wendling
182135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner    // If this call cannot unwind, don't convert it to an invoke.
183675f63886944d72e05e5210c36838c797364a0aaBill Wendling    if (!CI || CI->doesNotThrow())
184135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner      continue;
185675f63886944d72e05e5210c36838c797364a0aaBill Wendling
186675f63886944d72e05e5210c36838c797364a0aaBill Wendling    // Convert this function call into an invoke instruction.  First, split the
187675f63886944d72e05e5210c36838c797364a0aaBill Wendling    // basic block.
188135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner    BasicBlock *Split = BB->splitBasicBlock(CI, CI->getName()+".noexc");
189a3de16bc8f36638d5444e3e7b0112998af54f826John McCall
190d7c10862016939c9850cadfe5e1c35513c0adf28John McCall    // Delete the unconditional branch inserted by splitBasicBlock
191d7c10862016939c9850cadfe5e1c35513c0adf28John McCall    BB->getInstList().pop_back();
192a3de16bc8f36638d5444e3e7b0112998af54f826John McCall
1939e9a34c5688500eee47d6a7800c6e9ef93b90684Bill Wendling    // Create the new invoke instruction.
194d7c10862016939c9850cadfe5e1c35513c0adf28John McCall    ImmutableCallSite CS(CI);
195d7c10862016939c9850cadfe5e1c35513c0adf28John McCall    SmallVector<Value*, 8> InvokeArgs(CS.arg_begin(), CS.arg_end());
19606881e8734b1758fb0666f4e47a91bc58c6383beBill Wendling    InvokeInst *II = InvokeInst::Create(CI->getCalledValue(), Split,
1974dbd9b8ebfddb845c5675bbf2567a4d0e04871e7Bill Wendling                                        Invoke.getOuterResumeDest(),
19806881e8734b1758fb0666f4e47a91bc58c6383beBill Wendling                                        InvokeArgs, CI->getName(), BB);
199d7c10862016939c9850cadfe5e1c35513c0adf28John McCall    II->setCallingConv(CI->getCallingConv());
200d7c10862016939c9850cadfe5e1c35513c0adf28John McCall    II->setAttributes(CI->getAttributes());
201135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner
202d7c10862016939c9850cadfe5e1c35513c0adf28John McCall    // Make sure that anything using the call now uses the invoke!  This also
203d7c10862016939c9850cadfe5e1c35513c0adf28John McCall    // updates the CallGraph if present, because it uses a WeakVH.
204d7c10862016939c9850cadfe5e1c35513c0adf28John McCall    CI->replaceAllUsesWith(II);
205d7c10862016939c9850cadfe5e1c35513c0adf28John McCall
20606881e8734b1758fb0666f4e47a91bc58c6383beBill Wendling    // Delete the original call
20706881e8734b1758fb0666f4e47a91bc58c6383beBill Wendling    Split->getInstList().pop_front();
208a3de16bc8f36638d5444e3e7b0112998af54f826John McCall
20906881e8734b1758fb0666f4e47a91bc58c6383beBill Wendling    // Update any PHI nodes in the exceptional block to indicate that there is
21006881e8734b1758fb0666f4e47a91bc58c6383beBill Wendling    // now a new entry in them.
211a3de16bc8f36638d5444e3e7b0112998af54f826John McCall    Invoke.addIncomingPHIValuesFor(BB);
212d7c10862016939c9850cadfe5e1c35513c0adf28John McCall    return false;
213135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner  }
214a3de16bc8f36638d5444e3e7b0112998af54f826John McCall
215a3de16bc8f36638d5444e3e7b0112998af54f826John McCall  return false;
216135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner}
217135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner
218cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner/// HandleInlinedInvoke - If we inlined an invoke site, we need to convert calls
2198833ef03b9ceaa52063116819fff8b3d16fd8933Bill Wendling/// in the body of the inlined function into invokes.
220cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner///
221dac5c4b10b387b55c2394cd98a64f3f1394df2e8Nick Lewycky/// II is the invoke instruction being inlined.  FirstNewBlock is the first
222cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner/// block of the inlined code (the last block is the end of the function),
223cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner/// and InlineCodeInfo is information about the code that got inlined.
224cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattnerstatic void HandleInlinedInvoke(InvokeInst *II, BasicBlock *FirstNewBlock,
22581dfb3885252fbf621b080827a080099864415f8Chris Lattner                                ClonedCodeInfo &InlinedCodeInfo) {
226cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner  BasicBlock *InvokeDest = II->getUnwindDest();
227cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner
228cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner  Function *Caller = FirstNewBlock->getParent();
229a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands
230cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner  // The inlined code is currently at the end of the function, scan from the
231cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner  // start of the inlined code to its end, checking for stuff we need to
232135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner  // rewrite.  If the code doesn't have calls or unwinds, we know there is
233135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner  // nothing to rewrite.
2348833ef03b9ceaa52063116819fff8b3d16fd8933Bill Wendling  if (!InlinedCodeInfo.ContainsCalls) {
235135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner    // Now that everything is happy, we have one final detail.  The PHI nodes in
236135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner    // the exception destination block still have entries due to the original
237135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner    // invoke instruction.  Eliminate these entries (which might even delete the
238135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner    // PHI node) now.
239135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner    InvokeDest->removePredecessor(II->getParent());
240135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner    return;
241135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner  }
242a3de16bc8f36638d5444e3e7b0112998af54f826John McCall
243a3de16bc8f36638d5444e3e7b0112998af54f826John McCall  InvokeInliningInfo Invoke(II);
244135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner
245135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner  for (Function::iterator BB = FirstNewBlock, E = Caller->end(); BB != E; ++BB){
246135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner    if (InlinedCodeInfo.ContainsCalls)
247a3de16bc8f36638d5444e3e7b0112998af54f826John McCall      if (HandleCallsInBlockInlinedThroughInvoke(BB, Invoke)) {
2488833ef03b9ceaa52063116819fff8b3d16fd8933Bill Wendling        // Honor a request to skip the next block.
249a3de16bc8f36638d5444e3e7b0112998af54f826John McCall        ++BB;
250a3de16bc8f36638d5444e3e7b0112998af54f826John McCall        continue;
251a3de16bc8f36638d5444e3e7b0112998af54f826John McCall      }
252135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner
2539e9a34c5688500eee47d6a7800c6e9ef93b90684Bill Wendling    if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator()))
254fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling      Invoke.forwardResume(RI);
255cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner  }
256cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner
257cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner  // Now that everything is happy, we have one final detail.  The PHI nodes in
258cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner  // the exception destination block still have entries due to the original
259cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner  // invoke instruction.  Eliminate these entries (which might even delete the
260cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner  // PHI node) now.
261cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner  InvokeDest->removePredecessor(II->getParent());
262cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner}
263cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner
264d85340f4ec587e22b0239617f3b747a6df113894Chris Lattner/// UpdateCallGraphAfterInlining - Once we have cloned code over from a callee
265d85340f4ec587e22b0239617f3b747a6df113894Chris Lattner/// into the caller, update the specified callgraph to reflect the changes we
266d85340f4ec587e22b0239617f3b747a6df113894Chris Lattner/// made.  Note that it's possible that not all code was copied over, so only
267d7b9851c4e634ed3599b1a4c70b1c76c90a11686Duncan Sands/// some edges of the callgraph may remain.
268d7b9851c4e634ed3599b1a4c70b1c76c90a11686Duncan Sandsstatic void UpdateCallGraphAfterInlining(CallSite CS,
269d85340f4ec587e22b0239617f3b747a6df113894Chris Lattner                                         Function::iterator FirstNewBlock,
2701ed219a9d2279ce5a5bbcf16d9b7ccc05cce638cRafael Espindola                                         ValueToValueMapTy &VMap,
271fe9af3b1f7e5d68ecc330bdf4f047d76838f8cc3Chris Lattner                                         InlineFunctionInfo &IFI) {
272fe9af3b1f7e5d68ecc330bdf4f047d76838f8cc3Chris Lattner  CallGraph &CG = *IFI.CG;
273d7b9851c4e634ed3599b1a4c70b1c76c90a11686Duncan Sands  const Function *Caller = CS.getInstruction()->getParent()->getParent();
274d7b9851c4e634ed3599b1a4c70b1c76c90a11686Duncan Sands  const Function *Callee = CS.getCalledFunction();
275468fb1df7db466e5682ee44341c3990b599e8d6aChris Lattner  CallGraphNode *CalleeNode = CG[Callee];
276468fb1df7db466e5682ee44341c3990b599e8d6aChris Lattner  CallGraphNode *CallerNode = CG[Caller];
277a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands
278d85340f4ec587e22b0239617f3b747a6df113894Chris Lattner  // Since we inlined some uninlined call sites in the callee into the caller,
279468fb1df7db466e5682ee44341c3990b599e8d6aChris Lattner  // add edges from the caller to all of the callees of the callee.
280c478e52bf4c12691037856ee103c66946afeab6cGabor Greif  CallGraphNode::iterator I = CalleeNode->begin(), E = CalleeNode->end();
281c478e52bf4c12691037856ee103c66946afeab6cGabor Greif
282c478e52bf4c12691037856ee103c66946afeab6cGabor Greif  // Consider the case where CalleeNode == CallerNode.
283125329891f97baedef21e4b464ba70182c3fb45eGabor Greif  CallGraphNode::CalledFunctionsVector CallCache;
284c478e52bf4c12691037856ee103c66946afeab6cGabor Greif  if (CalleeNode == CallerNode) {
285c478e52bf4c12691037856ee103c66946afeab6cGabor Greif    CallCache.assign(I, E);
286c478e52bf4c12691037856ee103c66946afeab6cGabor Greif    I = CallCache.begin();
287c478e52bf4c12691037856ee103c66946afeab6cGabor Greif    E = CallCache.end();
288c478e52bf4c12691037856ee103c66946afeab6cGabor Greif  }
289c478e52bf4c12691037856ee103c66946afeab6cGabor Greif
290c478e52bf4c12691037856ee103c66946afeab6cGabor Greif  for (; I != E; ++I) {
291a541b0fde2ab6b8b037edf113d42da41a2c5aae9Chris Lattner    const Value *OrigCall = I->first;
292a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands
2931ed219a9d2279ce5a5bbcf16d9b7ccc05cce638cRafael Espindola    ValueToValueMapTy::iterator VMI = VMap.find(OrigCall);
294981418bf1562d0b5b470ddc7d0034c9f3297b893Chris Lattner    // Only copy the edge if the call was inlined!
29529d3dd8a64791031eea00ffbae51843dc9982df9Devang Patel    if (VMI == VMap.end() || VMI->second == 0)
296135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner      continue;
297135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner
298135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner    // If the call was inlined, but then constant folded, there is no edge to
299135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner    // add.  Check for this case.
300b957a5e41ed6288f4d033167f6413621a09655eeChris Lattner    Instruction *NewCall = dyn_cast<Instruction>(VMI->second);
301b957a5e41ed6288f4d033167f6413621a09655eeChris Lattner    if (NewCall == 0) continue;
3020ca2f28458ae9122f413a4092ddcee33a9dd21c6Chris Lattner
3030ca2f28458ae9122f413a4092ddcee33a9dd21c6Chris Lattner    // Remember that this call site got inlined for the client of
3040ca2f28458ae9122f413a4092ddcee33a9dd21c6Chris Lattner    // InlineFunction.
3050ca2f28458ae9122f413a4092ddcee33a9dd21c6Chris Lattner    IFI.InlinedCalls.push_back(NewCall);
3060ca2f28458ae9122f413a4092ddcee33a9dd21c6Chris Lattner
307b957a5e41ed6288f4d033167f6413621a09655eeChris Lattner    // It's possible that inlining the callsite will cause it to go from an
308b957a5e41ed6288f4d033167f6413621a09655eeChris Lattner    // indirect to a direct call by resolving a function pointer.  If this
309b957a5e41ed6288f4d033167f6413621a09655eeChris Lattner    // happens, set the callee of the new call site to a more precise
310b957a5e41ed6288f4d033167f6413621a09655eeChris Lattner    // destination.  This can also happen if the call graph node of the caller
311b957a5e41ed6288f4d033167f6413621a09655eeChris Lattner    // was just unnecessarily imprecise.
312b957a5e41ed6288f4d033167f6413621a09655eeChris Lattner    if (I->second->getFunction() == 0)
313b957a5e41ed6288f4d033167f6413621a09655eeChris Lattner      if (Function *F = CallSite(NewCall).getCalledFunction()) {
314b957a5e41ed6288f4d033167f6413621a09655eeChris Lattner        // Indirect call site resolved to direct call.
31586099345db95fdce6960ab62fbd9cb0cf96875f7Gabor Greif        CallerNode->addCalledFunction(CallSite(NewCall), CG[F]);
31686099345db95fdce6960ab62fbd9cb0cf96875f7Gabor Greif
317b957a5e41ed6288f4d033167f6413621a09655eeChris Lattner        continue;
318b957a5e41ed6288f4d033167f6413621a09655eeChris Lattner      }
31986099345db95fdce6960ab62fbd9cb0cf96875f7Gabor Greif
32086099345db95fdce6960ab62fbd9cb0cf96875f7Gabor Greif    CallerNode->addCalledFunction(CallSite(NewCall), I->second);
321d85340f4ec587e22b0239617f3b747a6df113894Chris Lattner  }
322135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner
32339fa32403e0b5e163f4f05566d6cde65e6c11095Dale Johannesen  // Update the call graph by deleting the edge from Callee to Caller.  We must
32439fa32403e0b5e163f4f05566d6cde65e6c11095Dale Johannesen  // do this after the loop above in case Caller and Callee are the same.
32539fa32403e0b5e163f4f05566d6cde65e6c11095Dale Johannesen  CallerNode->removeCallEdgeFor(CS);
326468fb1df7db466e5682ee44341c3990b599e8d6aChris Lattner}
327468fb1df7db466e5682ee44341c3990b599e8d6aChris Lattner
3280b66f63a26387f5c0360a4324fc3c31e0599a6e0Chris Lattner/// HandleByValArgument - When inlining a call site that has a byval argument,
3290b66f63a26387f5c0360a4324fc3c31e0599a6e0Chris Lattner/// we have to make the implicit memcpy explicit by adding it.
330e7ae705c32906979a527926864345016e76867b9Chris Lattnerstatic Value *HandleByValArgument(Value *Arg, Instruction *TheCall,
331e7ae705c32906979a527926864345016e76867b9Chris Lattner                                  const Function *CalledFunc,
332e7ae705c32906979a527926864345016e76867b9Chris Lattner                                  InlineFunctionInfo &IFI,
333e7ae705c32906979a527926864345016e76867b9Chris Lattner                                  unsigned ByValAlignment) {
334db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *AggTy = cast<PointerType>(Arg->getType())->getElementType();
3350b66f63a26387f5c0360a4324fc3c31e0599a6e0Chris Lattner
3360b66f63a26387f5c0360a4324fc3c31e0599a6e0Chris Lattner  // If the called function is readonly, then it could not mutate the caller's
3370b66f63a26387f5c0360a4324fc3c31e0599a6e0Chris Lattner  // copy of the byval'd memory.  In this case, it is safe to elide the copy and
3380b66f63a26387f5c0360a4324fc3c31e0599a6e0Chris Lattner  // temporary.
3390b66f63a26387f5c0360a4324fc3c31e0599a6e0Chris Lattner  if (CalledFunc->onlyReadsMemory()) {
3400b66f63a26387f5c0360a4324fc3c31e0599a6e0Chris Lattner    // If the byval argument has a specified alignment that is greater than the
3410b66f63a26387f5c0360a4324fc3c31e0599a6e0Chris Lattner    // passed in pointer, then we either have to round up the input pointer or
3420b66f63a26387f5c0360a4324fc3c31e0599a6e0Chris Lattner    // give up on this transformation.
3430b66f63a26387f5c0360a4324fc3c31e0599a6e0Chris Lattner    if (ByValAlignment <= 1)  // 0 = unspecified, 1 = no particular alignment.
3440b66f63a26387f5c0360a4324fc3c31e0599a6e0Chris Lattner      return Arg;
3450b66f63a26387f5c0360a4324fc3c31e0599a6e0Chris Lattner
3467569d79de1bd97a6a17b81340ea6ce97d8a3c279Chris Lattner    // If the pointer is already known to be sufficiently aligned, or if we can
3477569d79de1bd97a6a17b81340ea6ce97d8a3c279Chris Lattner    // round it up to a larger alignment, then we don't need a temporary.
3487569d79de1bd97a6a17b81340ea6ce97d8a3c279Chris Lattner    if (getOrEnforceKnownAlignment(Arg, ByValAlignment,
3497569d79de1bd97a6a17b81340ea6ce97d8a3c279Chris Lattner                                   IFI.TD) >= ByValAlignment)
3507569d79de1bd97a6a17b81340ea6ce97d8a3c279Chris Lattner      return Arg;
3510b66f63a26387f5c0360a4324fc3c31e0599a6e0Chris Lattner
3527569d79de1bd97a6a17b81340ea6ce97d8a3c279Chris Lattner    // Otherwise, we have to make a memcpy to get a safe alignment.  This is bad
3537569d79de1bd97a6a17b81340ea6ce97d8a3c279Chris Lattner    // for code quality, but rarely happens and is required for correctness.
3540b66f63a26387f5c0360a4324fc3c31e0599a6e0Chris Lattner  }
355e7ae705c32906979a527926864345016e76867b9Chris Lattner
356e7ae705c32906979a527926864345016e76867b9Chris Lattner  LLVMContext &Context = Arg->getContext();
357e7ae705c32906979a527926864345016e76867b9Chris Lattner
3585fdd6c8793462549e3593890ec61573da06e3346Jay Foad  Type *VoidPtrTy = Type::getInt8PtrTy(Context);
359e7ae705c32906979a527926864345016e76867b9Chris Lattner
3603574eca1b02600bac4e625297f4ecf745f4c4f32Micah Villmow  // Create the alloca.  If we have DataLayout, use nice alignment.
361e7ae705c32906979a527926864345016e76867b9Chris Lattner  unsigned Align = 1;
362e7ae705c32906979a527926864345016e76867b9Chris Lattner  if (IFI.TD)
363e7ae705c32906979a527926864345016e76867b9Chris Lattner    Align = IFI.TD->getPrefTypeAlignment(AggTy);
364e7ae705c32906979a527926864345016e76867b9Chris Lattner
365e7ae705c32906979a527926864345016e76867b9Chris Lattner  // If the byval had an alignment specified, we *must* use at least that
366e7ae705c32906979a527926864345016e76867b9Chris Lattner  // alignment, as it is required by the byval argument (and uses of the
367e7ae705c32906979a527926864345016e76867b9Chris Lattner  // pointer inside the callee).
368e7ae705c32906979a527926864345016e76867b9Chris Lattner  Align = std::max(Align, ByValAlignment);
369e7ae705c32906979a527926864345016e76867b9Chris Lattner
370e7ae705c32906979a527926864345016e76867b9Chris Lattner  Function *Caller = TheCall->getParent()->getParent();
371e7ae705c32906979a527926864345016e76867b9Chris Lattner
372e7ae705c32906979a527926864345016e76867b9Chris Lattner  Value *NewAlloca = new AllocaInst(AggTy, 0, Align, Arg->getName(),
373e7ae705c32906979a527926864345016e76867b9Chris Lattner                                    &*Caller->begin()->begin());
374e7ae705c32906979a527926864345016e76867b9Chris Lattner  // Emit a memcpy.
3755fdd6c8793462549e3593890ec61573da06e3346Jay Foad  Type *Tys[3] = {VoidPtrTy, VoidPtrTy, Type::getInt64Ty(Context)};
376e7ae705c32906979a527926864345016e76867b9Chris Lattner  Function *MemCpyFn = Intrinsic::getDeclaration(Caller->getParent(),
377e7ae705c32906979a527926864345016e76867b9Chris Lattner                                                 Intrinsic::memcpy,
378eb9a85f09e18b3fe88499710404b38d3a9128f62Benjamin Kramer                                                 Tys);
379e7ae705c32906979a527926864345016e76867b9Chris Lattner  Value *DestCast = new BitCastInst(NewAlloca, VoidPtrTy, "tmp", TheCall);
380e7ae705c32906979a527926864345016e76867b9Chris Lattner  Value *SrcCast = new BitCastInst(Arg, VoidPtrTy, "tmp", TheCall);
381e7ae705c32906979a527926864345016e76867b9Chris Lattner
382e7ae705c32906979a527926864345016e76867b9Chris Lattner  Value *Size;
383e7ae705c32906979a527926864345016e76867b9Chris Lattner  if (IFI.TD == 0)
384e7ae705c32906979a527926864345016e76867b9Chris Lattner    Size = ConstantExpr::getSizeOf(AggTy);
385e7ae705c32906979a527926864345016e76867b9Chris Lattner  else
386e7ae705c32906979a527926864345016e76867b9Chris Lattner    Size = ConstantInt::get(Type::getInt64Ty(Context),
387e7ae705c32906979a527926864345016e76867b9Chris Lattner                            IFI.TD->getTypeStoreSize(AggTy));
388e7ae705c32906979a527926864345016e76867b9Chris Lattner
389e7ae705c32906979a527926864345016e76867b9Chris Lattner  // Always generate a memcpy of alignment 1 here because we don't know
390e7ae705c32906979a527926864345016e76867b9Chris Lattner  // the alignment of the src pointer.  Other optimizations can infer
391e7ae705c32906979a527926864345016e76867b9Chris Lattner  // better alignment.
392e7ae705c32906979a527926864345016e76867b9Chris Lattner  Value *CallArgs[] = {
393e7ae705c32906979a527926864345016e76867b9Chris Lattner    DestCast, SrcCast, Size,
394e7ae705c32906979a527926864345016e76867b9Chris Lattner    ConstantInt::get(Type::getInt32Ty(Context), 1),
395e7ae705c32906979a527926864345016e76867b9Chris Lattner    ConstantInt::getFalse(Context) // isVolatile
396e7ae705c32906979a527926864345016e76867b9Chris Lattner  };
397a3efbb15ddd5aa9006564cd79086723640084878Jay Foad  IRBuilder<>(TheCall).CreateCall(MemCpyFn, CallArgs);
398e7ae705c32906979a527926864345016e76867b9Chris Lattner
399e7ae705c32906979a527926864345016e76867b9Chris Lattner  // Uses of the argument in the function should use our new alloca
400e7ae705c32906979a527926864345016e76867b9Chris Lattner  // instead.
401e7ae705c32906979a527926864345016e76867b9Chris Lattner  return NewAlloca;
402e7ae705c32906979a527926864345016e76867b9Chris Lattner}
403e7ae705c32906979a527926864345016e76867b9Chris Lattner
4046d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky// isUsedByLifetimeMarker - Check whether this Value is used by a lifetime
4056d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky// intrinsic.
4066d55f2269e20298a1d6a683be72d9552482156a9Nick Lewyckystatic bool isUsedByLifetimeMarker(Value *V) {
4076d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky  for (Value::use_iterator UI = V->use_begin(), UE = V->use_end(); UI != UE;
4086d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky       ++UI) {
4096d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky    if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(*UI)) {
4106d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky      switch (II->getIntrinsicID()) {
4116d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky      default: break;
4126d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky      case Intrinsic::lifetime_start:
4136d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky      case Intrinsic::lifetime_end:
4146d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky        return true;
4156d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky      }
4166d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky    }
4176d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky  }
4186d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky  return false;
4196d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky}
4206d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky
4216d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky// hasLifetimeMarkers - Check whether the given alloca already has
4226d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky// lifetime.start or lifetime.end intrinsics.
4236d55f2269e20298a1d6a683be72d9552482156a9Nick Lewyckystatic bool hasLifetimeMarkers(AllocaInst *AI) {
424db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *Int8PtrTy = Type::getInt8PtrTy(AI->getType()->getContext());
4256d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky  if (AI->getType() == Int8PtrTy)
4266d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky    return isUsedByLifetimeMarker(AI);
4276d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky
428708c1ac077fbc0cb73d489b4f4df3b2718566b05Nick Lewycky  // Do a scan to find all the casts to i8*.
4296d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky  for (Value::use_iterator I = AI->use_begin(), E = AI->use_end(); I != E;
4306d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky       ++I) {
4316d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky    if (I->getType() != Int8PtrTy) continue;
432708c1ac077fbc0cb73d489b4f4df3b2718566b05Nick Lewycky    if (I->stripPointerCasts() != AI) continue;
4336d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky    if (isUsedByLifetimeMarker(*I))
4346d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky      return true;
4356d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky  }
4366d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky  return false;
4376d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky}
4386d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky
439373c2d37072026e82f9b307eb40cf12baafd5f93Eric Christopher/// updateInlinedAtInfo - Helper function used by fixupLineNumbers to
440373c2d37072026e82f9b307eb40cf12baafd5f93Eric Christopher/// recursively update InlinedAtEntry of a DebugLoc.
4412cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patelstatic DebugLoc updateInlinedAtInfo(const DebugLoc &DL,
4422cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patel                                    const DebugLoc &InlinedAtDL,
4432cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patel                                    LLVMContext &Ctx) {
4442cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patel  if (MDNode *IA = DL.getInlinedAt(Ctx)) {
4452cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patel    DebugLoc NewInlinedAtDL
4462cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patel      = updateInlinedAtInfo(DebugLoc::getFromDILocation(IA), InlinedAtDL, Ctx);
4472cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patel    return DebugLoc::get(DL.getLine(), DL.getCol(), DL.getScope(Ctx),
4482cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patel                         NewInlinedAtDL.getAsMDNode(Ctx));
4492cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patel  }
450373c2d37072026e82f9b307eb40cf12baafd5f93Eric Christopher
4512cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patel  return DebugLoc::get(DL.getLine(), DL.getCol(), DL.getScope(Ctx),
4522cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patel                       InlinedAtDL.getAsMDNode(Ctx));
4532cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patel}
4542cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patel
4552cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patel/// fixupLineNumbers - Update inlined instructions' line numbers to
4562cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patel/// to encode location where these instructions are inlined.
4572cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patelstatic void fixupLineNumbers(Function *Fn, Function::iterator FI,
4587d8eb711e4608dcca9366141be22941af8d1eff8Eric Christopher                             Instruction *TheCall) {
4592cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patel  DebugLoc TheCallDL = TheCall->getDebugLoc();
4602cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patel  if (TheCallDL.isUnknown())
4612cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patel    return;
4622cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patel
4632cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patel  for (; FI != Fn->end(); ++FI) {
4642cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patel    for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
4652cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patel         BI != BE; ++BI) {
4662cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patel      DebugLoc DL = BI->getDebugLoc();
467b549bcfe6c19dbb24162c75bbcc06d4a5fa90cb8Devang Patel      if (!DL.isUnknown()) {
4682cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patel        BI->setDebugLoc(updateInlinedAtInfo(DL, TheCallDL, BI->getContext()));
469b549bcfe6c19dbb24162c75bbcc06d4a5fa90cb8Devang Patel        if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(BI)) {
470b549bcfe6c19dbb24162c75bbcc06d4a5fa90cb8Devang Patel          LLVMContext &Ctx = BI->getContext();
471b549bcfe6c19dbb24162c75bbcc06d4a5fa90cb8Devang Patel          MDNode *InlinedAt = BI->getDebugLoc().getInlinedAt(Ctx);
472b549bcfe6c19dbb24162c75bbcc06d4a5fa90cb8Devang Patel          DVI->setOperand(2, createInlinedVariable(DVI->getVariable(),
473b549bcfe6c19dbb24162c75bbcc06d4a5fa90cb8Devang Patel                                                   InlinedAt, Ctx));
474b549bcfe6c19dbb24162c75bbcc06d4a5fa90cb8Devang Patel        }
475b549bcfe6c19dbb24162c75bbcc06d4a5fa90cb8Devang Patel      }
4762cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patel    }
4772cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patel  }
4782cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patel}
4792cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patel
48006881e8734b1758fb0666f4e47a91bc58c6383beBill Wendling/// InlineFunction - This function inlines the called function into the basic
48106881e8734b1758fb0666f4e47a91bc58c6383beBill Wendling/// block of the caller.  This returns false if it is not possible to inline
48206881e8734b1758fb0666f4e47a91bc58c6383beBill Wendling/// this call.  The program is still in a well defined state if this occurs
48306881e8734b1758fb0666f4e47a91bc58c6383beBill Wendling/// though.
48406881e8734b1758fb0666f4e47a91bc58c6383beBill Wendling///
48506881e8734b1758fb0666f4e47a91bc58c6383beBill Wendling/// Note that this only does one level of inlining.  For example, if the
48606881e8734b1758fb0666f4e47a91bc58c6383beBill Wendling/// instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
48706881e8734b1758fb0666f4e47a91bc58c6383beBill Wendling/// exists in the instruction stream.  Similarly this will inline a recursive
48806881e8734b1758fb0666f4e47a91bc58c6383beBill Wendling/// function by one level.
489373c2d37072026e82f9b307eb40cf12baafd5f93Eric Christopherbool llvm::InlineFunction(CallSite CS, InlineFunctionInfo &IFI,
490373c2d37072026e82f9b307eb40cf12baafd5f93Eric Christopher                          bool InsertLifetime) {
49180a38d245359cb0a3be8f78f5d7d911232886b9aChris Lattner  Instruction *TheCall = CS.getInstruction();
49280a38d245359cb0a3be8f78f5d7d911232886b9aChris Lattner  assert(TheCall->getParent() && TheCall->getParent()->getParent() &&
49380a38d245359cb0a3be8f78f5d7d911232886b9aChris Lattner         "Instruction not in function!");
494ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner
49560915146f4d35e12f10dcdaa155596fac79184daChris Lattner  // If IFI has any state in it, zap it before we fill it in.
49660915146f4d35e12f10dcdaa155596fac79184daChris Lattner  IFI.reset();
49760915146f4d35e12f10dcdaa155596fac79184daChris Lattner
49880a38d245359cb0a3be8f78f5d7d911232886b9aChris Lattner  const Function *CalledFunc = CS.getCalledFunction();
499ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner  if (CalledFunc == 0 ||          // Can't inline external function or indirect
5005cbf985dcbc89fba3208e7baf8b6f488b06d3ec9Reid Spencer      CalledFunc->isDeclaration() || // call, or call to a vararg function!
5010623e90398153be61226ad19f1b40d3817874526Eric Christopher      CalledFunc->getFunctionType()->isVarArg()) return false;
502ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner
503af9985c6b9d066cb70a0363fed699022d0ec196cChris Lattner  // If the call to the callee is not a tail call, we must clear the 'tail'
5041b49141821e98e4321bfe6234c7001c836b2a289Chris Lattner  // flags on any calls that we inline.
5051b49141821e98e4321bfe6234c7001c836b2a289Chris Lattner  bool MustClearTailCallFlags =
506af9985c6b9d066cb70a0363fed699022d0ec196cChris Lattner    !(isa<CallInst>(TheCall) && cast<CallInst>(TheCall)->isTailCall());
5071b49141821e98e4321bfe6234c7001c836b2a289Chris Lattner
508f0c3354d998507515ab39e26b5292ea0ceb06aefDuncan Sands  // If the call to the callee cannot throw, set the 'nounwind' flag on any
509f0c3354d998507515ab39e26b5292ea0ceb06aefDuncan Sands  // calls that we inline.
510f0c3354d998507515ab39e26b5292ea0ceb06aefDuncan Sands  bool MarkNoUnwind = CS.doesNotThrow();
511f0c3354d998507515ab39e26b5292ea0ceb06aefDuncan Sands
51280a38d245359cb0a3be8f78f5d7d911232886b9aChris Lattner  BasicBlock *OrigBB = TheCall->getParent();
513ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner  Function *Caller = OrigBB->getParent();
514ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner
5150e13821c96937830ec817f08095c3cef1fdcac8dGordon Henriksen  // GC poses two hazards to inlining, which only occur when the callee has GC:
5160e13821c96937830ec817f08095c3cef1fdcac8dGordon Henriksen  //  1. If the caller has no GC, then the callee's GC must be propagated to the
5170e13821c96937830ec817f08095c3cef1fdcac8dGordon Henriksen  //     caller.
5180e13821c96937830ec817f08095c3cef1fdcac8dGordon Henriksen  //  2. If the caller has a differing GC, it is invalid to inline.
5195eca075b74d62c621b160aa216b4cd50829a2cc7Gordon Henriksen  if (CalledFunc->hasGC()) {
5205eca075b74d62c621b160aa216b4cd50829a2cc7Gordon Henriksen    if (!Caller->hasGC())
5215eca075b74d62c621b160aa216b4cd50829a2cc7Gordon Henriksen      Caller->setGC(CalledFunc->getGC());
5225eca075b74d62c621b160aa216b4cd50829a2cc7Gordon Henriksen    else if (CalledFunc->getGC() != Caller->getGC())
5230e13821c96937830ec817f08095c3cef1fdcac8dGordon Henriksen      return false;
5240e13821c96937830ec817f08095c3cef1fdcac8dGordon Henriksen  }
525a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands
52630fe1ae20d02ac8e12cec9d767d855946546a030Benjamin Kramer  // Get the personality function from the callee if it contains a landing pad.
52730fe1ae20d02ac8e12cec9d767d855946546a030Benjamin Kramer  Value *CalleePersonality = 0;
52830fe1ae20d02ac8e12cec9d767d855946546a030Benjamin Kramer  for (Function::const_iterator I = CalledFunc->begin(), E = CalledFunc->end();
52930fe1ae20d02ac8e12cec9d767d855946546a030Benjamin Kramer       I != E; ++I)
530fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling    if (const InvokeInst *II = dyn_cast<InvokeInst>(I->getTerminator())) {
531fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling      const BasicBlock *BB = II->getUnwindDest();
53227b5658affba5b12b396048d2cc598c70719bfc5Bill Wendling      const LandingPadInst *LP = BB->getLandingPadInst();
53327b5658affba5b12b396048d2cc598c70719bfc5Bill Wendling      CalleePersonality = LP->getPersonalityFn();
534fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling      break;
535fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling    }
536fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling
53730fe1ae20d02ac8e12cec9d767d855946546a030Benjamin Kramer  // Find the personality function used by the landing pads of the caller. If it
53830fe1ae20d02ac8e12cec9d767d855946546a030Benjamin Kramer  // exists, then check to see that it matches the personality function used in
53930fe1ae20d02ac8e12cec9d767d855946546a030Benjamin Kramer  // the callee.
54006881e8734b1758fb0666f4e47a91bc58c6383beBill Wendling  if (CalleePersonality) {
54130fe1ae20d02ac8e12cec9d767d855946546a030Benjamin Kramer    for (Function::const_iterator I = Caller->begin(), E = Caller->end();
54230fe1ae20d02ac8e12cec9d767d855946546a030Benjamin Kramer         I != E; ++I)
54330fe1ae20d02ac8e12cec9d767d855946546a030Benjamin Kramer      if (const InvokeInst *II = dyn_cast<InvokeInst>(I->getTerminator())) {
54430fe1ae20d02ac8e12cec9d767d855946546a030Benjamin Kramer        const BasicBlock *BB = II->getUnwindDest();
54527b5658affba5b12b396048d2cc598c70719bfc5Bill Wendling        const LandingPadInst *LP = BB->getLandingPadInst();
54630fe1ae20d02ac8e12cec9d767d855946546a030Benjamin Kramer
54730fe1ae20d02ac8e12cec9d767d855946546a030Benjamin Kramer        // If the personality functions match, then we can perform the
54830fe1ae20d02ac8e12cec9d767d855946546a030Benjamin Kramer        // inlining. Otherwise, we can't inline.
54930fe1ae20d02ac8e12cec9d767d855946546a030Benjamin Kramer        // TODO: This isn't 100% true. Some personality functions are proper
55030fe1ae20d02ac8e12cec9d767d855946546a030Benjamin Kramer        //       supersets of others and can be used in place of the other.
55130fe1ae20d02ac8e12cec9d767d855946546a030Benjamin Kramer        if (LP->getPersonalityFn() != CalleePersonality)
55230fe1ae20d02ac8e12cec9d767d855946546a030Benjamin Kramer          return false;
55330fe1ae20d02ac8e12cec9d767d855946546a030Benjamin Kramer
55430fe1ae20d02ac8e12cec9d767d855946546a030Benjamin Kramer        break;
55530fe1ae20d02ac8e12cec9d767d855946546a030Benjamin Kramer      }
55606881e8734b1758fb0666f4e47a91bc58c6383beBill Wendling  }
55730fe1ae20d02ac8e12cec9d767d855946546a030Benjamin Kramer
5585052c911ec1be51ecb36e7f025c26412e9f1bfacChris Lattner  // Get an iterator to the last basic block in the function, which will have
5595052c911ec1be51ecb36e7f025c26412e9f1bfacChris Lattner  // the new function inlined after it.
5605052c911ec1be51ecb36e7f025c26412e9f1bfacChris Lattner  Function::iterator LastBlock = &Caller->back();
5615052c911ec1be51ecb36e7f025c26412e9f1bfacChris Lattner
5625e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner  // Make sure to capture all of the return instructions from the cloned
5635e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner  // function.
564ec1bea0d94372985a0a5eb283e644c6d0dd345dcChris Lattner  SmallVector<ReturnInst*, 8> Returns;
565cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner  ClonedCodeInfo InlinedFunctionInfo;
5660744f09efc53d3352ac1caffc61f6e8239201c3bDale Johannesen  Function::iterator FirstNewBlock;
567f0c3354d998507515ab39e26b5292ea0ceb06aefDuncan Sands
56829d3dd8a64791031eea00ffbae51843dc9982df9Devang Patel  { // Scope to destroy VMap after cloning.
5691ed219a9d2279ce5a5bbcf16d9b7ccc05cce638cRafael Espindola    ValueToValueMapTy VMap;
5705b5bc3032f97cfa7bfa3e22282d3a9c1ed05eec6Chris Lattner
5719614fcc640eb628cc5dfddb277ebae9f6cb61014Dan Gohman    assert(CalledFunc->arg_size() == CS.arg_size() &&
5725e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner           "No varargs calls can be inlined!");
573a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands
574c93adca35856d0eaae088e52ba30cfefbd7ad910Chris Lattner    // Calculate the vector of arguments to pass into the function cloner, which
575c93adca35856d0eaae088e52ba30cfefbd7ad910Chris Lattner    // matches up the formal to the actual argument values.
5765e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner    CallSite::arg_iterator AI = CS.arg_begin();
577c93adca35856d0eaae088e52ba30cfefbd7ad910Chris Lattner    unsigned ArgNo = 0;
578e4d5c441e04bdc00ccf1804744af670655123b07Chris Lattner    for (Function::const_arg_iterator I = CalledFunc->arg_begin(),
579c93adca35856d0eaae088e52ba30cfefbd7ad910Chris Lattner         E = CalledFunc->arg_end(); I != E; ++I, ++AI, ++ArgNo) {
580c93adca35856d0eaae088e52ba30cfefbd7ad910Chris Lattner      Value *ActualArg = *AI;
581a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands
582d82375c1c43db7f823dd4660d3495e76566699e3Duncan Sands      // When byval arguments actually inlined, we need to make the copy implied
583d82375c1c43db7f823dd4660d3495e76566699e3Duncan Sands      // by them explicit.  However, we don't do this if the callee is readonly
584d82375c1c43db7f823dd4660d3495e76566699e3Duncan Sands      // or readnone, because the copy would be unneeded: the callee doesn't
585d82375c1c43db7f823dd4660d3495e76566699e3Duncan Sands      // modify the struct.
586173862e5468fbcf4b022b9088d2c81b25c2d60c5Nick Lewycky      if (CS.isByValArgument(ArgNo)) {
587e7ae705c32906979a527926864345016e76867b9Chris Lattner        ActualArg = HandleByValArgument(ActualArg, TheCall, CalledFunc, IFI,
588e7ae705c32906979a527926864345016e76867b9Chris Lattner                                        CalledFunc->getParamAlignment(ArgNo+1));
589e7ae705c32906979a527926864345016e76867b9Chris Lattner
5902914ba6ec793e2bb0e9ca5891af1d29ee2fee28eDuncan Sands        // Calls that we inline may use the new alloca, so we need to clear
591e7ae705c32906979a527926864345016e76867b9Chris Lattner        // their 'tail' flags if HandleByValArgument introduced a new alloca and
592e7ae705c32906979a527926864345016e76867b9Chris Lattner        // the callee has calls.
593e7ae705c32906979a527926864345016e76867b9Chris Lattner        MustClearTailCallFlags |= ActualArg != *AI;
594c93adca35856d0eaae088e52ba30cfefbd7ad910Chris Lattner      }
595a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands
59629d3dd8a64791031eea00ffbae51843dc9982df9Devang Patel      VMap[I] = ActualArg;
597c93adca35856d0eaae088e52ba30cfefbd7ad910Chris Lattner    }
598fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
5995b5bc3032f97cfa7bfa3e22282d3a9c1ed05eec6Chris Lattner    // We want the inliner to prune the code as it copies.  We would LOVE to
6005b5bc3032f97cfa7bfa3e22282d3a9c1ed05eec6Chris Lattner    // have no dead or constant instructions leftover after inlining occurs
6015b5bc3032f97cfa7bfa3e22282d3a9c1ed05eec6Chris Lattner    // (which can happen, e.g., because an argument was constant), but we'll be
6025b5bc3032f97cfa7bfa3e22282d3a9c1ed05eec6Chris Lattner    // happy with whatever the cloner can do.
6036cb8c23db1c3becdce6dfbf1b7f1677faca4251eDan Gohman    CloneAndPruneFunctionInto(Caller, CalledFunc, VMap,
6046cb8c23db1c3becdce6dfbf1b7f1677faca4251eDan Gohman                              /*ModuleLevelChanges=*/false, Returns, ".i",
60560915146f4d35e12f10dcdaa155596fac79184daChris Lattner                              &InlinedFunctionInfo, IFI.TD, TheCall);
606a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands
607d85340f4ec587e22b0239617f3b747a6df113894Chris Lattner    // Remember the first block that is newly cloned over.
608d85340f4ec587e22b0239617f3b747a6df113894Chris Lattner    FirstNewBlock = LastBlock; ++FirstNewBlock;
609a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands
610d85340f4ec587e22b0239617f3b747a6df113894Chris Lattner    // Update the callgraph if requested.
61160915146f4d35e12f10dcdaa155596fac79184daChris Lattner    if (IFI.CG)
61229d3dd8a64791031eea00ffbae51843dc9982df9Devang Patel      UpdateCallGraphAfterInlining(CS, FirstNewBlock, VMap, IFI);
6132cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patel
6142cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patel    // Update inlined instructions' line number information.
6152cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patel    fixupLineNumbers(Caller, FirstNewBlock, TheCall);
616fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman  }
617a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands
618ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner  // If there are any alloca instructions in the block that used to be the entry
619ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner  // block for the callee, move them to the entry block of the caller.  First
620ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner  // calculate which instruction they should be inserted before.  We insert the
621ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner  // instructions at the end of the current alloca list.
62221f20558d629f7ff8f64c20746d890d29328a544Chris Lattner  {
62380a38d245359cb0a3be8f78f5d7d911232886b9aChris Lattner    BasicBlock::iterator InsertPoint = Caller->begin()->begin();
6245e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner    for (BasicBlock::iterator I = FirstNewBlock->begin(),
625135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner         E = FirstNewBlock->end(); I != E; ) {
626135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner      AllocaInst *AI = dyn_cast<AllocaInst>(I++);
627135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner      if (AI == 0) continue;
628135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner
629135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner      // If the alloca is now dead, remove it.  This often occurs due to code
630135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner      // specialization.
631135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner      if (AI->use_empty()) {
632135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner        AI->eraseFromParent();
633135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner        continue;
63433bb3c8be355d179ece8e751f6e0f0978d0dd038Chris Lattner      }
635135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner
636135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner      if (!isa<Constant>(AI->getArraySize()))
637135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner        continue;
638135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner
63939add23dc54a1580983b1901384688d6622daa3bChris Lattner      // Keep track of the static allocas that we inline into the caller.
64060915146f4d35e12f10dcdaa155596fac79184daChris Lattner      IFI.StaticAllocas.push_back(AI);
6418f2718fbef6177966ff807af0732eb2431bd9a5fChris Lattner
642135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner      // Scan for the block of allocas that we can move over, and move them
643135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner      // all at once.
644135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner      while (isa<AllocaInst>(I) &&
6458f2718fbef6177966ff807af0732eb2431bd9a5fChris Lattner             isa<Constant>(cast<AllocaInst>(I)->getArraySize())) {
64660915146f4d35e12f10dcdaa155596fac79184daChris Lattner        IFI.StaticAllocas.push_back(cast<AllocaInst>(I));
647135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner        ++I;
6488f2718fbef6177966ff807af0732eb2431bd9a5fChris Lattner      }
649135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner
650135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner      // Transfer all of the allocas over in a block.  Using splice means
651135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner      // that the instructions aren't removed from the symbol table, then
652135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner      // reinserted.
653135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner      Caller->getEntryBlock().getInstList().splice(InsertPoint,
654135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner                                                   FirstNewBlock->getInstList(),
655135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner                                                   AI, I);
656135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner    }
65780a38d245359cb0a3be8f78f5d7d911232886b9aChris Lattner  }
65880a38d245359cb0a3be8f78f5d7d911232886b9aChris Lattner
6596d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky  // Leave lifetime markers for the static alloca's, scoping them to the
6606d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky  // function we just inlined.
661fa086f1f00a8b75ab2e2208bd7a028e62f9854dbChad Rosier  if (InsertLifetime && !IFI.StaticAllocas.empty()) {
6626d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky    IRBuilder<> builder(FirstNewBlock->begin());
6636d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky    for (unsigned ai = 0, ae = IFI.StaticAllocas.size(); ai != ae; ++ai) {
6646d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky      AllocaInst *AI = IFI.StaticAllocas[ai];
6656d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky
6666d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky      // If the alloca is already scoped to something smaller than the whole
6676d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky      // function then there's no need to add redundant, less accurate markers.
6686d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky      if (hasLifetimeMarkers(AI))
6696d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky        continue;
6706d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky
671009c4d86c14bb2f46f9473f8f517393dabab7e9eAlexey Samsonov      // Try to determine the size of the allocation.
672009c4d86c14bb2f46f9473f8f517393dabab7e9eAlexey Samsonov      ConstantInt *AllocaSize = 0;
673009c4d86c14bb2f46f9473f8f517393dabab7e9eAlexey Samsonov      if (ConstantInt *AIArraySize =
674009c4d86c14bb2f46f9473f8f517393dabab7e9eAlexey Samsonov          dyn_cast<ConstantInt>(AI->getArraySize())) {
675009c4d86c14bb2f46f9473f8f517393dabab7e9eAlexey Samsonov        if (IFI.TD) {
676009c4d86c14bb2f46f9473f8f517393dabab7e9eAlexey Samsonov          Type *AllocaType = AI->getAllocatedType();
677009c4d86c14bb2f46f9473f8f517393dabab7e9eAlexey Samsonov          uint64_t AllocaTypeSize = IFI.TD->getTypeAllocSize(AllocaType);
678009c4d86c14bb2f46f9473f8f517393dabab7e9eAlexey Samsonov          uint64_t AllocaArraySize = AIArraySize->getLimitedValue();
679009c4d86c14bb2f46f9473f8f517393dabab7e9eAlexey Samsonov          assert(AllocaArraySize > 0 && "array size of AllocaInst is zero");
680009c4d86c14bb2f46f9473f8f517393dabab7e9eAlexey Samsonov          // Check that array size doesn't saturate uint64_t and doesn't
681009c4d86c14bb2f46f9473f8f517393dabab7e9eAlexey Samsonov          // overflow when it's multiplied by type size.
682009c4d86c14bb2f46f9473f8f517393dabab7e9eAlexey Samsonov          if (AllocaArraySize != ~0ULL &&
683009c4d86c14bb2f46f9473f8f517393dabab7e9eAlexey Samsonov              UINT64_MAX / AllocaArraySize >= AllocaTypeSize) {
684009c4d86c14bb2f46f9473f8f517393dabab7e9eAlexey Samsonov            AllocaSize = ConstantInt::get(Type::getInt64Ty(AI->getContext()),
685009c4d86c14bb2f46f9473f8f517393dabab7e9eAlexey Samsonov                                          AllocaArraySize * AllocaTypeSize);
686009c4d86c14bb2f46f9473f8f517393dabab7e9eAlexey Samsonov          }
687009c4d86c14bb2f46f9473f8f517393dabab7e9eAlexey Samsonov        }
688009c4d86c14bb2f46f9473f8f517393dabab7e9eAlexey Samsonov      }
689009c4d86c14bb2f46f9473f8f517393dabab7e9eAlexey Samsonov
690009c4d86c14bb2f46f9473f8f517393dabab7e9eAlexey Samsonov      builder.CreateLifetimeStart(AI, AllocaSize);
6916d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky      for (unsigned ri = 0, re = Returns.size(); ri != re; ++ri) {
6926d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky        IRBuilder<> builder(Returns[ri]);
693009c4d86c14bb2f46f9473f8f517393dabab7e9eAlexey Samsonov        builder.CreateLifetimeEnd(AI, AllocaSize);
6946d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky      }
6956d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky    }
6966d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky  }
6976d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky
698bf229f488a7541abd979cc3fbe9c3ce1c100e5c0Chris Lattner  // If the inlined code contained dynamic alloca instructions, wrap the inlined
699bf229f488a7541abd979cc3fbe9c3ce1c100e5c0Chris Lattner  // code with llvm.stacksave/llvm.stackrestore intrinsics.
700bf229f488a7541abd979cc3fbe9c3ce1c100e5c0Chris Lattner  if (InlinedFunctionInfo.ContainsDynamicAllocas) {
701bf229f488a7541abd979cc3fbe9c3ce1c100e5c0Chris Lattner    Module *M = Caller->getParent();
702bf229f488a7541abd979cc3fbe9c3ce1c100e5c0Chris Lattner    // Get the two intrinsics we care about.
7036128df525501c333a650d097703c18d7e878f5e8Chris Lattner    Function *StackSave = Intrinsic::getDeclaration(M, Intrinsic::stacksave);
7046128df525501c333a650d097703c18d7e878f5e8Chris Lattner    Function *StackRestore=Intrinsic::getDeclaration(M,Intrinsic::stackrestore);
705d85340f4ec587e22b0239617f3b747a6df113894Chris Lattner
706bf229f488a7541abd979cc3fbe9c3ce1c100e5c0Chris Lattner    // Insert the llvm.stacksave.
707c975a51ac042eb15bcb04a293cb737810ff40a00John McCall    CallInst *SavedPtr = IRBuilder<>(FirstNewBlock, FirstNewBlock->begin())
708c975a51ac042eb15bcb04a293cb737810ff40a00John McCall      .CreateCall(StackSave, "savedstack");
709a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands
710bf229f488a7541abd979cc3fbe9c3ce1c100e5c0Chris Lattner    // Insert a call to llvm.stackrestore before any return instructions in the
711bf229f488a7541abd979cc3fbe9c3ce1c100e5c0Chris Lattner    // inlined function.
712d85340f4ec587e22b0239617f3b747a6df113894Chris Lattner    for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
713c975a51ac042eb15bcb04a293cb737810ff40a00John McCall      IRBuilder<>(Returns[i]).CreateCall(StackRestore, SavedPtr);
714d85340f4ec587e22b0239617f3b747a6df113894Chris Lattner    }
715bf229f488a7541abd979cc3fbe9c3ce1c100e5c0Chris Lattner  }
716bf229f488a7541abd979cc3fbe9c3ce1c100e5c0Chris Lattner
717a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands  // If we are inlining tail call instruction through a call site that isn't
7181fdf4a859f03ce5aa4ce9acba29ce321c847388eChris Lattner  // marked 'tail', we must remove the tail marker for any calls in the inlined
719f0c3354d998507515ab39e26b5292ea0ceb06aefDuncan Sands  // code.  Also, calls inlined through a 'nounwind' call site should be marked
720f0c3354d998507515ab39e26b5292ea0ceb06aefDuncan Sands  // 'nounwind'.
721f0c3354d998507515ab39e26b5292ea0ceb06aefDuncan Sands  if (InlinedFunctionInfo.ContainsCalls &&
722f0c3354d998507515ab39e26b5292ea0ceb06aefDuncan Sands      (MustClearTailCallFlags || MarkNoUnwind)) {
7231b49141821e98e4321bfe6234c7001c836b2a289Chris Lattner    for (Function::iterator BB = FirstNewBlock, E = Caller->end();
7241b49141821e98e4321bfe6234c7001c836b2a289Chris Lattner         BB != E; ++BB)
7251b49141821e98e4321bfe6234c7001c836b2a289Chris Lattner      for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
726f0c3354d998507515ab39e26b5292ea0ceb06aefDuncan Sands        if (CallInst *CI = dyn_cast<CallInst>(I)) {
727f0c3354d998507515ab39e26b5292ea0ceb06aefDuncan Sands          if (MustClearTailCallFlags)
728f0c3354d998507515ab39e26b5292ea0ceb06aefDuncan Sands            CI->setTailCall(false);
729f0c3354d998507515ab39e26b5292ea0ceb06aefDuncan Sands          if (MarkNoUnwind)
730f0c3354d998507515ab39e26b5292ea0ceb06aefDuncan Sands            CI->setDoesNotThrow();
731f0c3354d998507515ab39e26b5292ea0ceb06aefDuncan Sands        }
7321b49141821e98e4321bfe6234c7001c836b2a289Chris Lattner  }
7331b49141821e98e4321bfe6234c7001c836b2a289Chris Lattner
7345e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner  // If we are inlining for an invoke instruction, we must make sure to rewrite
7358833ef03b9ceaa52063116819fff8b3d16fd8933Bill Wendling  // any call instructions into invoke instructions.
736cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner  if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
73781dfb3885252fbf621b080827a080099864415f8Chris Lattner    HandleInlinedInvoke(II, FirstNewBlock, InlinedFunctionInfo);
7385e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner
73944a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner  // If we cloned in _exactly one_ basic block, and if that block ends in a
74044a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner  // return instruction, we splice the body of the inlined callee directly into
74144a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner  // the calling basic block.
74244a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner  if (Returns.size() == 1 && std::distance(FirstNewBlock, Caller->end()) == 1) {
74344a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner    // Move all of the instructions right before the call.
74444a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner    OrigBB->getInstList().splice(TheCall, FirstNewBlock->getInstList(),
74544a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner                                 FirstNewBlock->begin(), FirstNewBlock->end());
74644a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner    // Remove the cloned basic block.
74744a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner    Caller->getBasicBlockList().pop_back();
748fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
74944a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner    // If the call site was an invoke instruction, add a branch to the normal
75044a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner    // destination.
75144a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner    if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
752051a950000e21935165db56695e35bade668193bGabor Greif      BranchInst::Create(II->getNormalDest(), TheCall);
75344a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner
75444a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner    // If the return instruction returned a value, replace uses of the call with
75544a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner    // uses of the returned value.
756dc00d42bb18a6748f43c365d9bd30c1ed0e800acDevang Patel    if (!TheCall->use_empty()) {
757dc00d42bb18a6748f43c365d9bd30c1ed0e800acDevang Patel      ReturnInst *R = Returns[0];
7585877ad7e90de2179c15914ff9e8f1c72152cac30Eli Friedman      if (TheCall == R->getReturnValue())
7599e9a0d5fc26878e51a58a8b57900fcbf952c2691Owen Anderson        TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
7605877ad7e90de2179c15914ff9e8f1c72152cac30Eli Friedman      else
7615877ad7e90de2179c15914ff9e8f1c72152cac30Eli Friedman        TheCall->replaceAllUsesWith(R->getReturnValue());
762dc00d42bb18a6748f43c365d9bd30c1ed0e800acDevang Patel    }
76344a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner    // Since we are now done with the Call/Invoke, we can delete it.
7641adec83ae84031bfa9f0bf209c5ee6c64906a1ffDan Gohman    TheCall->eraseFromParent();
76544a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner
76644a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner    // Since we are now done with the return instruction, delete it also.
7671adec83ae84031bfa9f0bf209c5ee6c64906a1ffDan Gohman    Returns[0]->eraseFromParent();
76844a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner
76944a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner    // We are now done with the inlining.
77044a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner    return true;
77144a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner  }
77244a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner
77344a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner  // Otherwise, we have the normal case, of more than one block to inline or
77444a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner  // multiple return sites.
77544a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner
7765e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner  // We want to clone the entire callee function into the hole between the
7775e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner  // "starter" and "ender" blocks.  How we accomplish this depends on whether
7785e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner  // this is an invoke instruction or a call instruction.
7795e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner  BasicBlock *AfterCallBB;
7805e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner  if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
781fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
7825e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner    // Add an unconditional branch to make this look like the CallInst case...
783051a950000e21935165db56695e35bade668193bGabor Greif    BranchInst *NewBr = BranchInst::Create(II->getNormalDest(), TheCall);
784fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
7855e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner    // Split the basic block.  This guarantees that no PHI nodes will have to be
7865e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner    // updated due to new incoming edges, and make the invoke case more
7875e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner    // symmetric to the call case.
7885e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner    AfterCallBB = OrigBB->splitBasicBlock(NewBr,
789284d1b88273eb1967c8faef407f1167791c760e0Chris Lattner                                          CalledFunc->getName()+".exit");
790fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
7915e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner  } else {  // It's a call
79244a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner    // If this is a call instruction, we need to split the basic block that
79344a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner    // the call lives in.
7945e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner    //
7955e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner    AfterCallBB = OrigBB->splitBasicBlock(TheCall,
796284d1b88273eb1967c8faef407f1167791c760e0Chris Lattner                                          CalledFunc->getName()+".exit");
7975e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner  }
7985e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner
79944a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner  // Change the branch that used to go to AfterCallBB to branch to the first
80044a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner  // basic block of the inlined function.
80144a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner  //
80244a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner  TerminatorInst *Br = OrigBB->getTerminator();
803fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman  assert(Br && Br->getOpcode() == Instruction::Br &&
80444a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner         "splitBasicBlock broken!");
80544a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner  Br->setOperand(0, FirstNewBlock);
80644a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner
80744a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner
80844a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner  // Now that the function is correct, make it a little bit nicer.  In
80944a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner  // particular, move the basic blocks inserted from the end of the function
81044a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner  // into the space made by splitting the source basic block.
81144a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner  Caller->getBasicBlockList().splice(AfterCallBB, Caller->getBasicBlockList(),
81244a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner                                     FirstNewBlock, Caller->end());
81344a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner
8145e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner  // Handle all of the return instructions that we just cloned in, and eliminate
8155e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner  // any users of the original call/invoke instruction.
816db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *RTy = CalledFunc->getReturnType();
8172c31750cd0ebdc83a890ace97dbb6249b3abe44eDan Gohman
8186fb881c036c32728c4a128d81b6083457e534e09Duncan Sands  PHINode *PHI = 0;
819fc74abfba5128544a750fce22fdf13eb0403e3ceDan Gohman  if (Returns.size() > 1) {
8205e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner    // The PHI node should go at the front of the new basic block to merge all
8215e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner    // possible incoming values.
8225e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner    if (!TheCall->use_empty()) {
8233ecfc861b4365f341c5c969b40e1afccde676e6fJay Foad      PHI = PHINode::Create(RTy, Returns.size(), TheCall->getName(),
824fc74abfba5128544a750fce22fdf13eb0403e3ceDan Gohman                            AfterCallBB->begin());
825fc74abfba5128544a750fce22fdf13eb0403e3ceDan Gohman      // Anything that used the result of the function call should now use the
826fc74abfba5128544a750fce22fdf13eb0403e3ceDan Gohman      // PHI node as their operand.
827a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands      TheCall->replaceAllUsesWith(PHI);
8285e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner    }
829fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
830c478e52bf4c12691037856ee103c66946afeab6cGabor Greif    // Loop over all of the return instructions adding entries to the PHI node
831c478e52bf4c12691037856ee103c66946afeab6cGabor Greif    // as appropriate.
832fc74abfba5128544a750fce22fdf13eb0403e3ceDan Gohman    if (PHI) {
833fc74abfba5128544a750fce22fdf13eb0403e3ceDan Gohman      for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
834fc74abfba5128544a750fce22fdf13eb0403e3ceDan Gohman        ReturnInst *RI = Returns[i];
835fc74abfba5128544a750fce22fdf13eb0403e3ceDan Gohman        assert(RI->getReturnValue()->getType() == PHI->getType() &&
836fc74abfba5128544a750fce22fdf13eb0403e3ceDan Gohman               "Ret value not consistent in function!");
837fc74abfba5128544a750fce22fdf13eb0403e3ceDan Gohman        PHI->addIncoming(RI->getReturnValue(), RI->getParent());
8385e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner      }
83912a466b9d0e27be453cfa05cff18acc9d7c1cfbaDevang Patel    }
840fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
841c581acbbba3cb1af6a08e17314b26344333f9267Chris Lattner
842de62aeaec49ddcf4a4c61fbbb3a22d3a4dd448f0Gabor Greif    // Add a branch to the merge points and remove return instructions.
84312a466b9d0e27be453cfa05cff18acc9d7c1cfbaDevang Patel    for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
84412a466b9d0e27be453cfa05cff18acc9d7c1cfbaDevang Patel      ReturnInst *RI = Returns[i];
8450744f09efc53d3352ac1caffc61f6e8239201c3bDale Johannesen      BranchInst::Create(AfterCallBB, RI);
846b8f198af1b62f2ed48dcb914973a9d211dcba38bDevang Patel      RI->eraseFromParent();
8475e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner    }
848b8f198af1b62f2ed48dcb914973a9d211dcba38bDevang Patel  } else if (!Returns.empty()) {
849b8f198af1b62f2ed48dcb914973a9d211dcba38bDevang Patel    // Otherwise, if there is exactly one return value, just replace anything
850b8f198af1b62f2ed48dcb914973a9d211dcba38bDevang Patel    // using the return value of the call with the computed value.
8515877ad7e90de2179c15914ff9e8f1c72152cac30Eli Friedman    if (!TheCall->use_empty()) {
8525877ad7e90de2179c15914ff9e8f1c72152cac30Eli Friedman      if (TheCall == Returns[0]->getReturnValue())
8539e9a0d5fc26878e51a58a8b57900fcbf952c2691Owen Anderson        TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
8545877ad7e90de2179c15914ff9e8f1c72152cac30Eli Friedman      else
8555877ad7e90de2179c15914ff9e8f1c72152cac30Eli Friedman        TheCall->replaceAllUsesWith(Returns[0]->getReturnValue());
8565877ad7e90de2179c15914ff9e8f1c72152cac30Eli Friedman    }
857a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands
85895c3e48f9557adb6064d580684bb14cacec2f826Jay Foad    // Update PHI nodes that use the ReturnBB to use the AfterCallBB.
85995c3e48f9557adb6064d580684bb14cacec2f826Jay Foad    BasicBlock *ReturnBB = Returns[0]->getParent();
86095c3e48f9557adb6064d580684bb14cacec2f826Jay Foad    ReturnBB->replaceAllUsesWith(AfterCallBB);
86195c3e48f9557adb6064d580684bb14cacec2f826Jay Foad
862b8f198af1b62f2ed48dcb914973a9d211dcba38bDevang Patel    // Splice the code from the return block into the block that it will return
863b8f198af1b62f2ed48dcb914973a9d211dcba38bDevang Patel    // to, which contains the code that was after the call.
864b8f198af1b62f2ed48dcb914973a9d211dcba38bDevang Patel    AfterCallBB->getInstList().splice(AfterCallBB->begin(),
865b8f198af1b62f2ed48dcb914973a9d211dcba38bDevang Patel                                      ReturnBB->getInstList());
866a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands
867b8f198af1b62f2ed48dcb914973a9d211dcba38bDevang Patel    // Delete the return instruction now and empty ReturnBB now.
868b8f198af1b62f2ed48dcb914973a9d211dcba38bDevang Patel    Returns[0]->eraseFromParent();
869b8f198af1b62f2ed48dcb914973a9d211dcba38bDevang Patel    ReturnBB->eraseFromParent();
8703787e765facfad5ea62753922d940bcdd52afd57Chris Lattner  } else if (!TheCall->use_empty()) {
8713787e765facfad5ea62753922d940bcdd52afd57Chris Lattner    // No returns, but something is using the return value of the call.  Just
8723787e765facfad5ea62753922d940bcdd52afd57Chris Lattner    // nuke the result.
8739e9a0d5fc26878e51a58a8b57900fcbf952c2691Owen Anderson    TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
8745e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner  }
875fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
8765e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner  // Since we are now done with the Call/Invoke, we can delete it.
8773787e765facfad5ea62753922d940bcdd52afd57Chris Lattner  TheCall->eraseFromParent();
878ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner
8797152c237b46a920b29d5605af934766b8f9a07a1Chris Lattner  // We should always be able to fold the entry block of the function into the
8807152c237b46a920b29d5605af934766b8f9a07a1Chris Lattner  // single predecessor of the block...
881cd01ae5c7071fb99a665b2bbea7428d769792ab8Chris Lattner  assert(cast<BranchInst>(Br)->isUnconditional() && "splitBasicBlock broken!");
8827152c237b46a920b29d5605af934766b8f9a07a1Chris Lattner  BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0);
88344a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner
884cd01ae5c7071fb99a665b2bbea7428d769792ab8Chris Lattner  // Splice the code entry block into calling block, right before the
885cd01ae5c7071fb99a665b2bbea7428d769792ab8Chris Lattner  // unconditional branch.
886e59fbc04ad343435705c28b3cf7038d65fe4af0aEric Christopher  CalleeEntry->replaceAllUsesWith(OrigBB);  // Update PHI nodes
88795c3e48f9557adb6064d580684bb14cacec2f826Jay Foad  OrigBB->getInstList().splice(Br, CalleeEntry->getInstList());
888cd01ae5c7071fb99a665b2bbea7428d769792ab8Chris Lattner
889cd01ae5c7071fb99a665b2bbea7428d769792ab8Chris Lattner  // Remove the unconditional branch.
890cd01ae5c7071fb99a665b2bbea7428d769792ab8Chris Lattner  OrigBB->getInstList().erase(Br);
891cd01ae5c7071fb99a665b2bbea7428d769792ab8Chris Lattner
892cd01ae5c7071fb99a665b2bbea7428d769792ab8Chris Lattner  // Now we can remove the CalleeEntry block, which is now empty.
893cd01ae5c7071fb99a665b2bbea7428d769792ab8Chris Lattner  Caller->getBasicBlockList().erase(CalleeEntry);
894a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands
8956fb881c036c32728c4a128d81b6083457e534e09Duncan Sands  // If we inserted a phi node, check to see if it has a single value (e.g. all
8966fb881c036c32728c4a128d81b6083457e534e09Duncan Sands  // the entries are the same or undef).  If so, remove the PHI so it doesn't
8976fb881c036c32728c4a128d81b6083457e534e09Duncan Sands  // block other optimizations.
89806881e8734b1758fb0666f4e47a91bc58c6383beBill Wendling  if (PHI) {
8996fb881c036c32728c4a128d81b6083457e534e09Duncan Sands    if (Value *V = SimplifyInstruction(PHI, IFI.TD)) {
9006fb881c036c32728c4a128d81b6083457e534e09Duncan Sands      PHI->replaceAllUsesWith(V);
9016fb881c036c32728c4a128d81b6083457e534e09Duncan Sands      PHI->eraseFromParent();
9026fb881c036c32728c4a128d81b6083457e534e09Duncan Sands    }
90306881e8734b1758fb0666f4e47a91bc58c6383beBill Wendling  }
9046fb881c036c32728c4a128d81b6083457e534e09Duncan Sands
905ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner  return true;
906ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner}
907