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"
16d04a8d4b33ff316ca4cf961e06c9e312eff8e64fChandler Carruth#include "llvm/ADT/SmallVector.h"
17d04a8d4b33ff316ca4cf961e06c9e312eff8e64fChandler Carruth#include "llvm/ADT/StringExtras.h"
18d04a8d4b33ff316ca4cf961e06c9e312eff8e64fChandler Carruth#include "llvm/Analysis/CallGraph.h"
19d04a8d4b33ff316ca4cf961e06c9e312eff8e64fChandler Carruth#include "llvm/Analysis/InstructionSimplify.h"
200b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/Attributes.h"
2136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines#include "llvm/IR/CallSite.h"
22dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines#include "llvm/IR/CFG.h"
230b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/Constants.h"
240b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/DataLayout.h"
2536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines#include "llvm/IR/DebugInfo.h"
260b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/DerivedTypes.h"
270b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/IRBuilder.h"
280b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/Instructions.h"
290b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/IntrinsicInst.h"
300b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/Intrinsics.h"
310b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/Module.h"
327569d79de1bd97a6a17b81340ea6ce97d8a3c279Chris Lattner#include "llvm/Transforms/Utils/Local.h"
33f7703df4968084c18c248c1feea9961c19a32e6aChris Lattnerusing namespace llvm;
34ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner
35373c2d37072026e82f9b307eb40cf12baafd5f93Eric Christopherbool llvm::InlineFunction(CallInst *CI, InlineFunctionInfo &IFI,
36373c2d37072026e82f9b307eb40cf12baafd5f93Eric Christopher                          bool InsertLifetime) {
37fa086f1f00a8b75ab2e2208bd7a028e62f9854dbChad Rosier  return InlineFunction(CallSite(CI), IFI, InsertLifetime);
38468fb1df7db466e5682ee44341c3990b599e8d6aChris Lattner}
39373c2d37072026e82f9b307eb40cf12baafd5f93Eric Christopherbool llvm::InlineFunction(InvokeInst *II, InlineFunctionInfo &IFI,
40373c2d37072026e82f9b307eb40cf12baafd5f93Eric Christopher                          bool InsertLifetime) {
41fa086f1f00a8b75ab2e2208bd7a028e62f9854dbChad Rosier  return InlineFunction(CallSite(II), IFI, InsertLifetime);
42468fb1df7db466e5682ee44341c3990b599e8d6aChris Lattner}
4380a38d245359cb0a3be8f78f5d7d911232886b9aChris Lattner
44a3de16bc8f36638d5444e3e7b0112998af54f826John McCallnamespace {
45a3de16bc8f36638d5444e3e7b0112998af54f826John McCall  /// A class for recording information about inlining through an invoke.
46a3de16bc8f36638d5444e3e7b0112998af54f826John McCall  class InvokeInliningInfo {
4777592fe39c404f3c48b06fae48b965058b3a5ee8Dmitri Gribenko    BasicBlock *OuterResumeDest; ///< Destination of the invoke's unwind.
4877592fe39c404f3c48b06fae48b965058b3a5ee8Dmitri Gribenko    BasicBlock *InnerResumeDest; ///< Destination for the callee's resume.
4977592fe39c404f3c48b06fae48b965058b3a5ee8Dmitri Gribenko    LandingPadInst *CallerLPad;  ///< LandingPadInst associated with the invoke.
5077592fe39c404f3c48b06fae48b965058b3a5ee8Dmitri Gribenko    PHINode *InnerEHValuesPHI;   ///< PHI for EH values from landingpad insts.
514dbd9b8ebfddb845c5675bbf2567a4d0e04871e7Bill Wendling    SmallVector<Value*, 8> UnwindDestPHIValues;
52fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling
532bf84c15d24bb373987d9dbc6308092eac1b8324Bill Wendling  public:
54fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling    InvokeInliningInfo(InvokeInst *II)
55dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      : OuterResumeDest(II->getUnwindDest()), InnerResumeDest(nullptr),
56dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines        CallerLPad(nullptr), InnerEHValuesPHI(nullptr) {
57fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling      // If there are PHI nodes in the unwind destination block, we need to keep
58fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling      // track of which values came into them from the invoke before removing
59fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling      // the edge from this block.
60fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling      llvm::BasicBlock *InvokeBB = II->getParent();
6108d01462d13fdfac756a8bd0f38bbfbceb247403Bill Wendling      BasicBlock::iterator I = OuterResumeDest->begin();
62fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling      for (; isa<PHINode>(I); ++I) {
63a3de16bc8f36638d5444e3e7b0112998af54f826John McCall        // Save the value to use for this edge.
64fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling        PHINode *PHI = cast<PHINode>(I);
65fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling        UnwindDestPHIValues.push_back(PHI->getIncomingValueForBlock(InvokeBB));
66fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling      }
67fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling
6827b5658affba5b12b396048d2cc598c70719bfc5Bill Wendling      CallerLPad = cast<LandingPadInst>(I);
69a3de16bc8f36638d5444e3e7b0112998af54f826John McCall    }
70a3de16bc8f36638d5444e3e7b0112998af54f826John McCall
7108d01462d13fdfac756a8bd0f38bbfbceb247403Bill Wendling    /// getOuterResumeDest - The outer unwind destination is the target of
7208d01462d13fdfac756a8bd0f38bbfbceb247403Bill Wendling    /// unwind edges introduced for calls within the inlined function.
734dbd9b8ebfddb845c5675bbf2567a4d0e04871e7Bill Wendling    BasicBlock *getOuterResumeDest() const {
7408d01462d13fdfac756a8bd0f38bbfbceb247403Bill Wendling      return OuterResumeDest;
75a3de16bc8f36638d5444e3e7b0112998af54f826John McCall    }
76a3de16bc8f36638d5444e3e7b0112998af54f826John McCall
7713b1c31412372ef3790934ca213546fec595fbbcBill Wendling    BasicBlock *getInnerResumeDest();
78fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling
79fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling    LandingPadInst *getLandingPadInst() const { return CallerLPad; }
80fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling
81fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling    /// forwardResume - Forward the 'resume' instruction to the caller's landing
82fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling    /// pad block. When the landing pad block has only one predecessor, this is
83fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling    /// a simple branch. When there is more than one predecessor, we need to
84fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling    /// split the landing pad block after the landingpad instruction and jump
85fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling    /// to there.
864c6250247053810d44119d2e34eb4f07ba56d035Bill Wendling    void forwardResume(ResumeInst *RI,
874c6250247053810d44119d2e34eb4f07ba56d035Bill Wendling                       SmallPtrSet<LandingPadInst*, 16> &InlinedLPads);
88fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling
89fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling    /// addIncomingPHIValuesFor - Add incoming-PHI values to the unwind
90fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling    /// destination block for the given basic block, using the values for the
91fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling    /// original invoke's source block.
92a3de16bc8f36638d5444e3e7b0112998af54f826John McCall    void addIncomingPHIValuesFor(BasicBlock *BB) const {
9308d01462d13fdfac756a8bd0f38bbfbceb247403Bill Wendling      addIncomingPHIValuesForInto(BB, OuterResumeDest);
94d7c10862016939c9850cadfe5e1c35513c0adf28John McCall    }
9510c6d12a9fd4dab411091f64db4db69670b88850Bill Wendling
96d7c10862016939c9850cadfe5e1c35513c0adf28John McCall    void addIncomingPHIValuesForInto(BasicBlock *src, BasicBlock *dest) const {
97d7c10862016939c9850cadfe5e1c35513c0adf28John McCall      BasicBlock::iterator I = dest->begin();
98a3de16bc8f36638d5444e3e7b0112998af54f826John McCall      for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
9910c6d12a9fd4dab411091f64db4db69670b88850Bill Wendling        PHINode *phi = cast<PHINode>(I);
10010c6d12a9fd4dab411091f64db4db69670b88850Bill Wendling        phi->addIncoming(UnwindDestPHIValues[i], src);
101a3de16bc8f36638d5444e3e7b0112998af54f826John McCall      }
102a3de16bc8f36638d5444e3e7b0112998af54f826John McCall    }
103a3de16bc8f36638d5444e3e7b0112998af54f826John McCall  };
104a3de16bc8f36638d5444e3e7b0112998af54f826John McCall}
105a3de16bc8f36638d5444e3e7b0112998af54f826John McCall
10613b1c31412372ef3790934ca213546fec595fbbcBill Wendling/// getInnerResumeDest - Get or create a target for the branch from ResumeInsts.
10713b1c31412372ef3790934ca213546fec595fbbcBill WendlingBasicBlock *InvokeInliningInfo::getInnerResumeDest() {
108fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling  if (InnerResumeDest) return InnerResumeDest;
109fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling
110fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling  // Split the landing pad.
111fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling  BasicBlock::iterator SplitPoint = CallerLPad; ++SplitPoint;
112fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling  InnerResumeDest =
113fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling    OuterResumeDest->splitBasicBlock(SplitPoint,
114fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling                                     OuterResumeDest->getName() + ".body");
115fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling
116fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling  // The number of incoming edges we expect to the inner landing pad.
117fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling  const unsigned PHICapacity = 2;
118fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling
119fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling  // Create corresponding new PHIs for all the PHIs in the outer landing pad.
120fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling  BasicBlock::iterator InsertPoint = InnerResumeDest->begin();
121fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling  BasicBlock::iterator I = OuterResumeDest->begin();
122fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling  for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
123fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling    PHINode *OuterPHI = cast<PHINode>(I);
124fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling    PHINode *InnerPHI = PHINode::Create(OuterPHI->getType(), PHICapacity,
125fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling                                        OuterPHI->getName() + ".lpad-body",
126fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling                                        InsertPoint);
127fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling    OuterPHI->replaceAllUsesWith(InnerPHI);
128fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling    InnerPHI->addIncoming(OuterPHI, OuterResumeDest);
129fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling  }
130fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling
131fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling  // Create a PHI for the exception values.
132fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling  InnerEHValuesPHI = PHINode::Create(CallerLPad->getType(), PHICapacity,
133fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling                                     "eh.lpad-body", InsertPoint);
134fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling  CallerLPad->replaceAllUsesWith(InnerEHValuesPHI);
135fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling  InnerEHValuesPHI->addIncoming(CallerLPad, OuterResumeDest);
136fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling
137fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling  // All done.
138fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling  return InnerResumeDest;
139fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling}
140fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling
141fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling/// forwardResume - Forward the 'resume' instruction to the caller's landing pad
142fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling/// block. When the landing pad block has only one predecessor, this is a simple
143fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling/// branch. When there is more than one predecessor, we need to split the
144fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling/// landing pad block after the landingpad instruction and jump to there.
145d9ff8c83d137586d8c06f98bdf8adbf0d1fa79caBill Wendlingvoid InvokeInliningInfo::forwardResume(ResumeInst *RI,
1464c6250247053810d44119d2e34eb4f07ba56d035Bill Wendling                               SmallPtrSet<LandingPadInst*, 16> &InlinedLPads) {
14713b1c31412372ef3790934ca213546fec595fbbcBill Wendling  BasicBlock *Dest = getInnerResumeDest();
148fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling  BasicBlock *Src = RI->getParent();
149fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling
150fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling  BranchInst::Create(Dest, Src);
151fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling
152fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling  // Update the PHIs in the destination. They were inserted in an order which
153fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling  // makes this work.
154fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling  addIncomingPHIValuesForInto(Src, Dest);
155fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling
156fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling  InnerEHValuesPHI->addIncoming(RI->getOperand(0), Src);
157fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling  RI->eraseFromParent();
158fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling}
159fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling
160135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner/// HandleCallsInBlockInlinedThroughInvoke - When we inline a basic block into
161f61f89ae14cf332a014a598153137113af34002fEric Christopher/// an invoke, we have to turn all of the calls that can throw into
162135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner/// invokes.  This function analyze BB to see if there are any calls, and if so,
163135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner/// it rewrites them to be invokes that jump to InvokeDest and fills in the PHI
16481dfb3885252fbf621b080827a080099864415f8Chris Lattner/// nodes in that block with the values specified in InvokeDestPHIValues.
16536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hinesstatic void HandleCallsInBlockInlinedThroughInvoke(BasicBlock *BB,
166a3de16bc8f36638d5444e3e7b0112998af54f826John McCall                                                   InvokeInliningInfo &Invoke) {
167135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner  for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
168135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner    Instruction *I = BBI++;
169fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling
170135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner    // We only need to check for function calls: inlined invoke
171135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner    // instructions require no special handling.
172135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner    CallInst *CI = dyn_cast<CallInst>(I);
173675f63886944d72e05e5210c36838c797364a0aaBill Wendling
174135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner    // If this call cannot unwind, don't convert it to an invoke.
175ef34496b3fc197fe03da6fd86214d5e9b37d4368Manman Ren    // Inline asm calls cannot throw.
176ef34496b3fc197fe03da6fd86214d5e9b37d4368Manman Ren    if (!CI || CI->doesNotThrow() || isa<InlineAsm>(CI->getCalledValue()))
177135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner      continue;
178675f63886944d72e05e5210c36838c797364a0aaBill Wendling
179675f63886944d72e05e5210c36838c797364a0aaBill Wendling    // Convert this function call into an invoke instruction.  First, split the
180675f63886944d72e05e5210c36838c797364a0aaBill Wendling    // basic block.
181135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner    BasicBlock *Split = BB->splitBasicBlock(CI, CI->getName()+".noexc");
182a3de16bc8f36638d5444e3e7b0112998af54f826John McCall
183d7c10862016939c9850cadfe5e1c35513c0adf28John McCall    // Delete the unconditional branch inserted by splitBasicBlock
184d7c10862016939c9850cadfe5e1c35513c0adf28John McCall    BB->getInstList().pop_back();
185a3de16bc8f36638d5444e3e7b0112998af54f826John McCall
1869e9a34c5688500eee47d6a7800c6e9ef93b90684Bill Wendling    // Create the new invoke instruction.
187d7c10862016939c9850cadfe5e1c35513c0adf28John McCall    ImmutableCallSite CS(CI);
188d7c10862016939c9850cadfe5e1c35513c0adf28John McCall    SmallVector<Value*, 8> InvokeArgs(CS.arg_begin(), CS.arg_end());
18906881e8734b1758fb0666f4e47a91bc58c6383beBill Wendling    InvokeInst *II = InvokeInst::Create(CI->getCalledValue(), Split,
1904dbd9b8ebfddb845c5675bbf2567a4d0e04871e7Bill Wendling                                        Invoke.getOuterResumeDest(),
19106881e8734b1758fb0666f4e47a91bc58c6383beBill Wendling                                        InvokeArgs, CI->getName(), BB);
192cd81d94322a39503e4a3e87b6ee03d4fcb3465fbStephen Hines    II->setDebugLoc(CI->getDebugLoc());
193d7c10862016939c9850cadfe5e1c35513c0adf28John McCall    II->setCallingConv(CI->getCallingConv());
194d7c10862016939c9850cadfe5e1c35513c0adf28John McCall    II->setAttributes(CI->getAttributes());
195135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner
196d7c10862016939c9850cadfe5e1c35513c0adf28John McCall    // Make sure that anything using the call now uses the invoke!  This also
197d7c10862016939c9850cadfe5e1c35513c0adf28John McCall    // updates the CallGraph if present, because it uses a WeakVH.
198d7c10862016939c9850cadfe5e1c35513c0adf28John McCall    CI->replaceAllUsesWith(II);
199d7c10862016939c9850cadfe5e1c35513c0adf28John McCall
20006881e8734b1758fb0666f4e47a91bc58c6383beBill Wendling    // Delete the original call
20106881e8734b1758fb0666f4e47a91bc58c6383beBill Wendling    Split->getInstList().pop_front();
202a3de16bc8f36638d5444e3e7b0112998af54f826John McCall
20306881e8734b1758fb0666f4e47a91bc58c6383beBill Wendling    // Update any PHI nodes in the exceptional block to indicate that there is
20406881e8734b1758fb0666f4e47a91bc58c6383beBill Wendling    // now a new entry in them.
205a3de16bc8f36638d5444e3e7b0112998af54f826John McCall    Invoke.addIncomingPHIValuesFor(BB);
20636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    return;
207135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner  }
208135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner}
209135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner
210cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner/// HandleInlinedInvoke - If we inlined an invoke site, we need to convert calls
2118833ef03b9ceaa52063116819fff8b3d16fd8933Bill Wendling/// in the body of the inlined function into invokes.
212cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner///
213dac5c4b10b387b55c2394cd98a64f3f1394df2e8Nick Lewycky/// II is the invoke instruction being inlined.  FirstNewBlock is the first
214cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner/// block of the inlined code (the last block is the end of the function),
215cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner/// and InlineCodeInfo is information about the code that got inlined.
216cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattnerstatic void HandleInlinedInvoke(InvokeInst *II, BasicBlock *FirstNewBlock,
21781dfb3885252fbf621b080827a080099864415f8Chris Lattner                                ClonedCodeInfo &InlinedCodeInfo) {
218cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner  BasicBlock *InvokeDest = II->getUnwindDest();
219cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner
220cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner  Function *Caller = FirstNewBlock->getParent();
221a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands
222cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner  // The inlined code is currently at the end of the function, scan from the
223cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner  // start of the inlined code to its end, checking for stuff we need to
224d9ff8c83d137586d8c06f98bdf8adbf0d1fa79caBill Wendling  // rewrite.
225a3de16bc8f36638d5444e3e7b0112998af54f826John McCall  InvokeInliningInfo Invoke(II);
226d9ff8c83d137586d8c06f98bdf8adbf0d1fa79caBill Wendling
2274c6250247053810d44119d2e34eb4f07ba56d035Bill Wendling  // Get all of the inlined landing pad instructions.
2284c6250247053810d44119d2e34eb4f07ba56d035Bill Wendling  SmallPtrSet<LandingPadInst*, 16> InlinedLPads;
2294c6250247053810d44119d2e34eb4f07ba56d035Bill Wendling  for (Function::iterator I = FirstNewBlock, E = Caller->end(); I != E; ++I)
2304c6250247053810d44119d2e34eb4f07ba56d035Bill Wendling    if (InvokeInst *II = dyn_cast<InvokeInst>(I->getTerminator()))
2314c6250247053810d44119d2e34eb4f07ba56d035Bill Wendling      InlinedLPads.insert(II->getLandingPadInst());
2324c6250247053810d44119d2e34eb4f07ba56d035Bill Wendling
23336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  // Append the clauses from the outer landing pad instruction into the inlined
23436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  // landing pad instructions.
23536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  LandingPadInst *OuterLPad = Invoke.getLandingPadInst();
23636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  for (SmallPtrSet<LandingPadInst*, 16>::iterator I = InlinedLPads.begin(),
23736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines         E = InlinedLPads.end(); I != E; ++I) {
23836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    LandingPadInst *InlinedLPad = *I;
23936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    unsigned OuterNum = OuterLPad->getNumClauses();
24036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    InlinedLPad->reserveClauses(OuterNum);
24136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    for (unsigned OuterIdx = 0; OuterIdx != OuterNum; ++OuterIdx)
24236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      InlinedLPad->addClause(OuterLPad->getClause(OuterIdx));
24336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    if (OuterLPad->isCleanup())
24436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      InlinedLPad->setCleanup(true);
24536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  }
24636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
247135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner  for (Function::iterator BB = FirstNewBlock, E = Caller->end(); BB != E; ++BB){
248135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner    if (InlinedCodeInfo.ContainsCalls)
24936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      HandleCallsInBlockInlinedThroughInvoke(BB, Invoke);
250135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner
251d9ff8c83d137586d8c06f98bdf8adbf0d1fa79caBill Wendling    // Forward any resumes that are remaining here.
2529e9a34c5688500eee47d6a7800c6e9ef93b90684Bill Wendling    if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator()))
2534c6250247053810d44119d2e34eb4f07ba56d035Bill Wendling      Invoke.forwardResume(RI, InlinedLPads);
254cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner  }
255cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner
256cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner  // Now that everything is happy, we have one final detail.  The PHI nodes in
257cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner  // the exception destination block still have entries due to the original
258d9ff8c83d137586d8c06f98bdf8adbf0d1fa79caBill Wendling  // invoke instruction. Eliminate these entries (which might even delete the
259cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner  // PHI node) now.
260cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner  InvokeDest->removePredecessor(II->getParent());
261cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner}
262cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner
263d85340f4ec587e22b0239617f3b747a6df113894Chris Lattner/// UpdateCallGraphAfterInlining - Once we have cloned code over from a callee
264d85340f4ec587e22b0239617f3b747a6df113894Chris Lattner/// into the caller, update the specified callgraph to reflect the changes we
265d85340f4ec587e22b0239617f3b747a6df113894Chris Lattner/// made.  Note that it's possible that not all code was copied over, so only
266d7b9851c4e634ed3599b1a4c70b1c76c90a11686Duncan Sands/// some edges of the callgraph may remain.
267d7b9851c4e634ed3599b1a4c70b1c76c90a11686Duncan Sandsstatic void UpdateCallGraphAfterInlining(CallSite CS,
268d85340f4ec587e22b0239617f3b747a6df113894Chris Lattner                                         Function::iterator FirstNewBlock,
2691ed219a9d2279ce5a5bbcf16d9b7ccc05cce638cRafael Espindola                                         ValueToValueMapTy &VMap,
270fe9af3b1f7e5d68ecc330bdf4f047d76838f8cc3Chris Lattner                                         InlineFunctionInfo &IFI) {
271fe9af3b1f7e5d68ecc330bdf4f047d76838f8cc3Chris Lattner  CallGraph &CG = *IFI.CG;
272d7b9851c4e634ed3599b1a4c70b1c76c90a11686Duncan Sands  const Function *Caller = CS.getInstruction()->getParent()->getParent();
273d7b9851c4e634ed3599b1a4c70b1c76c90a11686Duncan Sands  const Function *Callee = CS.getCalledFunction();
274468fb1df7db466e5682ee44341c3990b599e8d6aChris Lattner  CallGraphNode *CalleeNode = CG[Callee];
275468fb1df7db466e5682ee44341c3990b599e8d6aChris Lattner  CallGraphNode *CallerNode = CG[Caller];
276a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands
277d85340f4ec587e22b0239617f3b747a6df113894Chris Lattner  // Since we inlined some uninlined call sites in the callee into the caller,
278468fb1df7db466e5682ee44341c3990b599e8d6aChris Lattner  // add edges from the caller to all of the callees of the callee.
279c478e52bf4c12691037856ee103c66946afeab6cGabor Greif  CallGraphNode::iterator I = CalleeNode->begin(), E = CalleeNode->end();
280c478e52bf4c12691037856ee103c66946afeab6cGabor Greif
281c478e52bf4c12691037856ee103c66946afeab6cGabor Greif  // Consider the case where CalleeNode == CallerNode.
282125329891f97baedef21e4b464ba70182c3fb45eGabor Greif  CallGraphNode::CalledFunctionsVector CallCache;
283c478e52bf4c12691037856ee103c66946afeab6cGabor Greif  if (CalleeNode == CallerNode) {
284c478e52bf4c12691037856ee103c66946afeab6cGabor Greif    CallCache.assign(I, E);
285c478e52bf4c12691037856ee103c66946afeab6cGabor Greif    I = CallCache.begin();
286c478e52bf4c12691037856ee103c66946afeab6cGabor Greif    E = CallCache.end();
287c478e52bf4c12691037856ee103c66946afeab6cGabor Greif  }
288c478e52bf4c12691037856ee103c66946afeab6cGabor Greif
289c478e52bf4c12691037856ee103c66946afeab6cGabor Greif  for (; I != E; ++I) {
290a541b0fde2ab6b8b037edf113d42da41a2c5aae9Chris Lattner    const Value *OrigCall = I->first;
291a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands
2921ed219a9d2279ce5a5bbcf16d9b7ccc05cce638cRafael Espindola    ValueToValueMapTy::iterator VMI = VMap.find(OrigCall);
293981418bf1562d0b5b470ddc7d0034c9f3297b893Chris Lattner    // Only copy the edge if the call was inlined!
294dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    if (VMI == VMap.end() || VMI->second == nullptr)
295135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner      continue;
296135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner
297135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner    // If the call was inlined, but then constant folded, there is no edge to
298135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner    // add.  Check for this case.
299b957a5e41ed6288f4d033167f6413621a09655eeChris Lattner    Instruction *NewCall = dyn_cast<Instruction>(VMI->second);
300dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    if (!NewCall) continue;
3010ca2f28458ae9122f413a4092ddcee33a9dd21c6Chris Lattner
3020ca2f28458ae9122f413a4092ddcee33a9dd21c6Chris Lattner    // Remember that this call site got inlined for the client of
3030ca2f28458ae9122f413a4092ddcee33a9dd21c6Chris Lattner    // InlineFunction.
3040ca2f28458ae9122f413a4092ddcee33a9dd21c6Chris Lattner    IFI.InlinedCalls.push_back(NewCall);
3050ca2f28458ae9122f413a4092ddcee33a9dd21c6Chris Lattner
306b957a5e41ed6288f4d033167f6413621a09655eeChris Lattner    // It's possible that inlining the callsite will cause it to go from an
307b957a5e41ed6288f4d033167f6413621a09655eeChris Lattner    // indirect to a direct call by resolving a function pointer.  If this
308b957a5e41ed6288f4d033167f6413621a09655eeChris Lattner    // happens, set the callee of the new call site to a more precise
309b957a5e41ed6288f4d033167f6413621a09655eeChris Lattner    // destination.  This can also happen if the call graph node of the caller
310b957a5e41ed6288f4d033167f6413621a09655eeChris Lattner    // was just unnecessarily imprecise.
311dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    if (!I->second->getFunction())
312b957a5e41ed6288f4d033167f6413621a09655eeChris Lattner      if (Function *F = CallSite(NewCall).getCalledFunction()) {
313b957a5e41ed6288f4d033167f6413621a09655eeChris Lattner        // Indirect call site resolved to direct call.
31486099345db95fdce6960ab62fbd9cb0cf96875f7Gabor Greif        CallerNode->addCalledFunction(CallSite(NewCall), CG[F]);
31586099345db95fdce6960ab62fbd9cb0cf96875f7Gabor Greif
316b957a5e41ed6288f4d033167f6413621a09655eeChris Lattner        continue;
317b957a5e41ed6288f4d033167f6413621a09655eeChris Lattner      }
31886099345db95fdce6960ab62fbd9cb0cf96875f7Gabor Greif
31986099345db95fdce6960ab62fbd9cb0cf96875f7Gabor Greif    CallerNode->addCalledFunction(CallSite(NewCall), I->second);
320d85340f4ec587e22b0239617f3b747a6df113894Chris Lattner  }
321135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner
32239fa32403e0b5e163f4f05566d6cde65e6c11095Dale Johannesen  // Update the call graph by deleting the edge from Callee to Caller.  We must
32339fa32403e0b5e163f4f05566d6cde65e6c11095Dale Johannesen  // do this after the loop above in case Caller and Callee are the same.
32439fa32403e0b5e163f4f05566d6cde65e6c11095Dale Johannesen  CallerNode->removeCallEdgeFor(CS);
325468fb1df7db466e5682ee44341c3990b599e8d6aChris Lattner}
326468fb1df7db466e5682ee44341c3990b599e8d6aChris Lattner
327dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hinesstatic void HandleByValArgumentInit(Value *Dst, Value *Src, Module *M,
328dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines                                    BasicBlock *InsertBlock,
329dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines                                    InlineFunctionInfo &IFI) {
330dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  LLVMContext &Context = Src->getContext();
331dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  Type *VoidPtrTy = Type::getInt8PtrTy(Context);
332dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  Type *AggTy = cast<PointerType>(Src->getType())->getElementType();
333dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  Type *Tys[3] = { VoidPtrTy, VoidPtrTy, Type::getInt64Ty(Context) };
334dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  Function *MemCpyFn = Intrinsic::getDeclaration(M, Intrinsic::memcpy, Tys);
335dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  IRBuilder<> builder(InsertBlock->begin());
336dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  Value *DstCast = builder.CreateBitCast(Dst, VoidPtrTy, "tmp");
337dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  Value *SrcCast = builder.CreateBitCast(Src, VoidPtrTy, "tmp");
338dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines
339dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  Value *Size;
340dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  if (IFI.DL == nullptr)
341dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    Size = ConstantExpr::getSizeOf(AggTy);
342dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  else
343dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    Size = ConstantInt::get(Type::getInt64Ty(Context),
344dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines                            IFI.DL->getTypeStoreSize(AggTy));
345dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines
346dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  // Always generate a memcpy of alignment 1 here because we don't know
347dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  // the alignment of the src pointer.  Other optimizations can infer
348dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  // better alignment.
349dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  Value *CallArgs[] = {
350dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    DstCast, SrcCast, Size,
351dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    ConstantInt::get(Type::getInt32Ty(Context), 1),
352dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    ConstantInt::getFalse(Context) // isVolatile
353dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  };
354dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  builder.CreateCall(MemCpyFn, CallArgs);
355dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines}
356dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines
3570b66f63a26387f5c0360a4324fc3c31e0599a6e0Chris Lattner/// HandleByValArgument - When inlining a call site that has a byval argument,
3580b66f63a26387f5c0360a4324fc3c31e0599a6e0Chris Lattner/// we have to make the implicit memcpy explicit by adding it.
35916d10987184281aff35c80542a3c02e7dcb7b59bDavid Majnemerstatic Value *HandleByValArgument(Value *Arg, Instruction *TheCall,
360e7ae705c32906979a527926864345016e76867b9Chris Lattner                                  const Function *CalledFunc,
361e7ae705c32906979a527926864345016e76867b9Chris Lattner                                  InlineFunctionInfo &IFI,
362e7ae705c32906979a527926864345016e76867b9Chris Lattner                                  unsigned ByValAlignment) {
363dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  PointerType *ArgTy = cast<PointerType>(Arg->getType());
364dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  Type *AggTy = ArgTy->getElementType();
3650b66f63a26387f5c0360a4324fc3c31e0599a6e0Chris Lattner
3660b66f63a26387f5c0360a4324fc3c31e0599a6e0Chris Lattner  // If the called function is readonly, then it could not mutate the caller's
3670b66f63a26387f5c0360a4324fc3c31e0599a6e0Chris Lattner  // copy of the byval'd memory.  In this case, it is safe to elide the copy and
3680b66f63a26387f5c0360a4324fc3c31e0599a6e0Chris Lattner  // temporary.
36916d10987184281aff35c80542a3c02e7dcb7b59bDavid Majnemer  if (CalledFunc->onlyReadsMemory()) {
3700b66f63a26387f5c0360a4324fc3c31e0599a6e0Chris Lattner    // If the byval argument has a specified alignment that is greater than the
3710b66f63a26387f5c0360a4324fc3c31e0599a6e0Chris Lattner    // passed in pointer, then we either have to round up the input pointer or
3720b66f63a26387f5c0360a4324fc3c31e0599a6e0Chris Lattner    // give up on this transformation.
3730b66f63a26387f5c0360a4324fc3c31e0599a6e0Chris Lattner    if (ByValAlignment <= 1)  // 0 = unspecified, 1 = no particular alignment.
37416d10987184281aff35c80542a3c02e7dcb7b59bDavid Majnemer      return Arg;
3750b66f63a26387f5c0360a4324fc3c31e0599a6e0Chris Lattner
3767569d79de1bd97a6a17b81340ea6ce97d8a3c279Chris Lattner    // If the pointer is already known to be sufficiently aligned, or if we can
3777569d79de1bd97a6a17b81340ea6ce97d8a3c279Chris Lattner    // round it up to a larger alignment, then we don't need a temporary.
37816d10987184281aff35c80542a3c02e7dcb7b59bDavid Majnemer    if (getOrEnforceKnownAlignment(Arg, ByValAlignment,
37936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines                                   IFI.DL) >= ByValAlignment)
38016d10987184281aff35c80542a3c02e7dcb7b59bDavid Majnemer      return Arg;
3810b66f63a26387f5c0360a4324fc3c31e0599a6e0Chris Lattner
3827569d79de1bd97a6a17b81340ea6ce97d8a3c279Chris Lattner    // Otherwise, we have to make a memcpy to get a safe alignment.  This is bad
3837569d79de1bd97a6a17b81340ea6ce97d8a3c279Chris Lattner    // for code quality, but rarely happens and is required for correctness.
3840b66f63a26387f5c0360a4324fc3c31e0599a6e0Chris Lattner  }
385e7ae705c32906979a527926864345016e76867b9Chris Lattner
3863574eca1b02600bac4e625297f4ecf745f4c4f32Micah Villmow  // Create the alloca.  If we have DataLayout, use nice alignment.
387e7ae705c32906979a527926864345016e76867b9Chris Lattner  unsigned Align = 1;
38836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  if (IFI.DL)
38936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    Align = IFI.DL->getPrefTypeAlignment(AggTy);
390e7ae705c32906979a527926864345016e76867b9Chris Lattner
391e7ae705c32906979a527926864345016e76867b9Chris Lattner  // If the byval had an alignment specified, we *must* use at least that
392e7ae705c32906979a527926864345016e76867b9Chris Lattner  // alignment, as it is required by the byval argument (and uses of the
393e7ae705c32906979a527926864345016e76867b9Chris Lattner  // pointer inside the callee).
394e7ae705c32906979a527926864345016e76867b9Chris Lattner  Align = std::max(Align, ByValAlignment);
395e7ae705c32906979a527926864345016e76867b9Chris Lattner
396e7ae705c32906979a527926864345016e76867b9Chris Lattner  Function *Caller = TheCall->getParent()->getParent();
397e7ae705c32906979a527926864345016e76867b9Chris Lattner
398dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  Value *NewAlloca = new AllocaInst(AggTy, nullptr, Align, Arg->getName(),
399e7ae705c32906979a527926864345016e76867b9Chris Lattner                                    &*Caller->begin()->begin());
400dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  IFI.StaticAllocas.push_back(cast<AllocaInst>(NewAlloca));
401e7ae705c32906979a527926864345016e76867b9Chris Lattner
402e7ae705c32906979a527926864345016e76867b9Chris Lattner  // Uses of the argument in the function should use our new alloca
403e7ae705c32906979a527926864345016e76867b9Chris Lattner  // instead.
404e7ae705c32906979a527926864345016e76867b9Chris Lattner  return NewAlloca;
405e7ae705c32906979a527926864345016e76867b9Chris Lattner}
406e7ae705c32906979a527926864345016e76867b9Chris Lattner
4076d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky// isUsedByLifetimeMarker - Check whether this Value is used by a lifetime
4086d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky// intrinsic.
4096d55f2269e20298a1d6a683be72d9552482156a9Nick Lewyckystatic bool isUsedByLifetimeMarker(Value *V) {
41036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  for (User *U : V->users()) {
41136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) {
4126d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky      switch (II->getIntrinsicID()) {
4136d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky      default: break;
4146d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky      case Intrinsic::lifetime_start:
4156d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky      case Intrinsic::lifetime_end:
4166d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky        return true;
4176d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky      }
4186d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky    }
4196d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky  }
4206d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky  return false;
4216d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky}
4226d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky
4236d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky// hasLifetimeMarkers - Check whether the given alloca already has
4246d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky// lifetime.start or lifetime.end intrinsics.
4256d55f2269e20298a1d6a683be72d9552482156a9Nick Lewyckystatic bool hasLifetimeMarkers(AllocaInst *AI) {
426dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  Type *Ty = AI->getType();
427dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  Type *Int8PtrTy = Type::getInt8PtrTy(Ty->getContext(),
428dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines                                       Ty->getPointerAddressSpace());
429dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  if (Ty == Int8PtrTy)
4306d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky    return isUsedByLifetimeMarker(AI);
4316d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky
432708c1ac077fbc0cb73d489b4f4df3b2718566b05Nick Lewycky  // Do a scan to find all the casts to i8*.
43336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  for (User *U : AI->users()) {
43436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    if (U->getType() != Int8PtrTy) continue;
43536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    if (U->stripPointerCasts() != AI) continue;
43636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    if (isUsedByLifetimeMarker(U))
4376d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky      return true;
4386d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky  }
4396d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky  return false;
4406d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky}
4416d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky
442373c2d37072026e82f9b307eb40cf12baafd5f93Eric Christopher/// updateInlinedAtInfo - Helper function used by fixupLineNumbers to
443373c2d37072026e82f9b307eb40cf12baafd5f93Eric Christopher/// recursively update InlinedAtEntry of a DebugLoc.
4442cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patelstatic DebugLoc updateInlinedAtInfo(const DebugLoc &DL,
4452cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patel                                    const DebugLoc &InlinedAtDL,
4462cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patel                                    LLVMContext &Ctx) {
4472cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patel  if (MDNode *IA = DL.getInlinedAt(Ctx)) {
4482cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patel    DebugLoc NewInlinedAtDL
4492cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patel      = updateInlinedAtInfo(DebugLoc::getFromDILocation(IA), InlinedAtDL, Ctx);
4502cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patel    return DebugLoc::get(DL.getLine(), DL.getCol(), DL.getScope(Ctx),
4512cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patel                         NewInlinedAtDL.getAsMDNode(Ctx));
4522cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patel  }
453373c2d37072026e82f9b307eb40cf12baafd5f93Eric Christopher
4542cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patel  return DebugLoc::get(DL.getLine(), DL.getCol(), DL.getScope(Ctx),
4552cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patel                       InlinedAtDL.getAsMDNode(Ctx));
4562cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patel}
4572cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patel
4582cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patel/// fixupLineNumbers - Update inlined instructions' line numbers to
4592cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patel/// to encode location where these instructions are inlined.
4602cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patelstatic void fixupLineNumbers(Function *Fn, Function::iterator FI,
4617d8eb711e4608dcca9366141be22941af8d1eff8Eric Christopher                             Instruction *TheCall) {
4622cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patel  DebugLoc TheCallDL = TheCall->getDebugLoc();
4632cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patel  if (TheCallDL.isUnknown())
4642cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patel    return;
4652cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patel
4662cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patel  for (; FI != Fn->end(); ++FI) {
4672cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patel    for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
4682cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patel         BI != BE; ++BI) {
4692cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patel      DebugLoc DL = BI->getDebugLoc();
470cd81d94322a39503e4a3e87b6ee03d4fcb3465fbStephen Hines      if (DL.isUnknown()) {
471cd81d94322a39503e4a3e87b6ee03d4fcb3465fbStephen Hines        // If the inlined instruction has no line number, make it look as if it
472cd81d94322a39503e4a3e87b6ee03d4fcb3465fbStephen Hines        // originates from the call location. This is important for
473cd81d94322a39503e4a3e87b6ee03d4fcb3465fbStephen Hines        // ((__always_inline__, __nodebug__)) functions which must use caller
474cd81d94322a39503e4a3e87b6ee03d4fcb3465fbStephen Hines        // location for all instructions in their function body.
475cd81d94322a39503e4a3e87b6ee03d4fcb3465fbStephen Hines        BI->setDebugLoc(TheCallDL);
476cd81d94322a39503e4a3e87b6ee03d4fcb3465fbStephen Hines      } else {
4772cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patel        BI->setDebugLoc(updateInlinedAtInfo(DL, TheCallDL, BI->getContext()));
478b549bcfe6c19dbb24162c75bbcc06d4a5fa90cb8Devang Patel        if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(BI)) {
479b549bcfe6c19dbb24162c75bbcc06d4a5fa90cb8Devang Patel          LLVMContext &Ctx = BI->getContext();
480b549bcfe6c19dbb24162c75bbcc06d4a5fa90cb8Devang Patel          MDNode *InlinedAt = BI->getDebugLoc().getInlinedAt(Ctx);
481b549bcfe6c19dbb24162c75bbcc06d4a5fa90cb8Devang Patel          DVI->setOperand(2, createInlinedVariable(DVI->getVariable(),
482b549bcfe6c19dbb24162c75bbcc06d4a5fa90cb8Devang Patel                                                   InlinedAt, Ctx));
483b549bcfe6c19dbb24162c75bbcc06d4a5fa90cb8Devang Patel        }
484b549bcfe6c19dbb24162c75bbcc06d4a5fa90cb8Devang Patel      }
4852cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patel    }
4862cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patel  }
4872cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patel}
4882cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patel
489dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines/// Returns a musttail call instruction if one immediately precedes the given
490dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines/// return instruction with an optional bitcast instruction between them.
491dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hinesstatic CallInst *getPrecedingMustTailCall(ReturnInst *RI) {
492dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  Instruction *Prev = RI->getPrevNode();
493dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  if (!Prev)
494dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    return nullptr;
495dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines
496dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  if (Value *RV = RI->getReturnValue()) {
497dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    if (RV != Prev)
498dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      return nullptr;
499dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines
500dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    // Look through the optional bitcast.
501dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    if (auto *BI = dyn_cast<BitCastInst>(Prev)) {
502dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      RV = BI->getOperand(0);
503dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      Prev = BI->getPrevNode();
504dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      if (!Prev || RV != Prev)
505dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines        return nullptr;
506dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    }
507dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  }
508dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines
509dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  if (auto *CI = dyn_cast<CallInst>(Prev)) {
510dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    if (CI->isMustTailCall())
511dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      return CI;
512dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  }
513dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  return nullptr;
514dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines}
515dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines
51606881e8734b1758fb0666f4e47a91bc58c6383beBill Wendling/// InlineFunction - This function inlines the called function into the basic
51706881e8734b1758fb0666f4e47a91bc58c6383beBill Wendling/// block of the caller.  This returns false if it is not possible to inline
51806881e8734b1758fb0666f4e47a91bc58c6383beBill Wendling/// this call.  The program is still in a well defined state if this occurs
51906881e8734b1758fb0666f4e47a91bc58c6383beBill Wendling/// though.
52006881e8734b1758fb0666f4e47a91bc58c6383beBill Wendling///
52106881e8734b1758fb0666f4e47a91bc58c6383beBill Wendling/// Note that this only does one level of inlining.  For example, if the
52206881e8734b1758fb0666f4e47a91bc58c6383beBill Wendling/// instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
52306881e8734b1758fb0666f4e47a91bc58c6383beBill Wendling/// exists in the instruction stream.  Similarly this will inline a recursive
52406881e8734b1758fb0666f4e47a91bc58c6383beBill Wendling/// function by one level.
525373c2d37072026e82f9b307eb40cf12baafd5f93Eric Christopherbool llvm::InlineFunction(CallSite CS, InlineFunctionInfo &IFI,
526373c2d37072026e82f9b307eb40cf12baafd5f93Eric Christopher                          bool InsertLifetime) {
52780a38d245359cb0a3be8f78f5d7d911232886b9aChris Lattner  Instruction *TheCall = CS.getInstruction();
52880a38d245359cb0a3be8f78f5d7d911232886b9aChris Lattner  assert(TheCall->getParent() && TheCall->getParent()->getParent() &&
52980a38d245359cb0a3be8f78f5d7d911232886b9aChris Lattner         "Instruction not in function!");
530ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner
53160915146f4d35e12f10dcdaa155596fac79184daChris Lattner  // If IFI has any state in it, zap it before we fill it in.
53260915146f4d35e12f10dcdaa155596fac79184daChris Lattner  IFI.reset();
53360915146f4d35e12f10dcdaa155596fac79184daChris Lattner
53480a38d245359cb0a3be8f78f5d7d911232886b9aChris Lattner  const Function *CalledFunc = CS.getCalledFunction();
535dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  if (!CalledFunc ||              // Can't inline external function or indirect
5365cbf985dcbc89fba3208e7baf8b6f488b06d3ec9Reid Spencer      CalledFunc->isDeclaration() || // call, or call to a vararg function!
5370623e90398153be61226ad19f1b40d3817874526Eric Christopher      CalledFunc->getFunctionType()->isVarArg()) return false;
538ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner
539f0c3354d998507515ab39e26b5292ea0ceb06aefDuncan Sands  // If the call to the callee cannot throw, set the 'nounwind' flag on any
540f0c3354d998507515ab39e26b5292ea0ceb06aefDuncan Sands  // calls that we inline.
541f0c3354d998507515ab39e26b5292ea0ceb06aefDuncan Sands  bool MarkNoUnwind = CS.doesNotThrow();
542f0c3354d998507515ab39e26b5292ea0ceb06aefDuncan Sands
54380a38d245359cb0a3be8f78f5d7d911232886b9aChris Lattner  BasicBlock *OrigBB = TheCall->getParent();
544ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner  Function *Caller = OrigBB->getParent();
545ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner
5460e13821c96937830ec817f08095c3cef1fdcac8dGordon Henriksen  // GC poses two hazards to inlining, which only occur when the callee has GC:
5470e13821c96937830ec817f08095c3cef1fdcac8dGordon Henriksen  //  1. If the caller has no GC, then the callee's GC must be propagated to the
5480e13821c96937830ec817f08095c3cef1fdcac8dGordon Henriksen  //     caller.
5490e13821c96937830ec817f08095c3cef1fdcac8dGordon Henriksen  //  2. If the caller has a differing GC, it is invalid to inline.
5505eca075b74d62c621b160aa216b4cd50829a2cc7Gordon Henriksen  if (CalledFunc->hasGC()) {
5515eca075b74d62c621b160aa216b4cd50829a2cc7Gordon Henriksen    if (!Caller->hasGC())
5525eca075b74d62c621b160aa216b4cd50829a2cc7Gordon Henriksen      Caller->setGC(CalledFunc->getGC());
5535eca075b74d62c621b160aa216b4cd50829a2cc7Gordon Henriksen    else if (CalledFunc->getGC() != Caller->getGC())
5540e13821c96937830ec817f08095c3cef1fdcac8dGordon Henriksen      return false;
5550e13821c96937830ec817f08095c3cef1fdcac8dGordon Henriksen  }
556a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands
55730fe1ae20d02ac8e12cec9d767d855946546a030Benjamin Kramer  // Get the personality function from the callee if it contains a landing pad.
558dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  Value *CalleePersonality = nullptr;
55930fe1ae20d02ac8e12cec9d767d855946546a030Benjamin Kramer  for (Function::const_iterator I = CalledFunc->begin(), E = CalledFunc->end();
56030fe1ae20d02ac8e12cec9d767d855946546a030Benjamin Kramer       I != E; ++I)
561fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling    if (const InvokeInst *II = dyn_cast<InvokeInst>(I->getTerminator())) {
562fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling      const BasicBlock *BB = II->getUnwindDest();
56327b5658affba5b12b396048d2cc598c70719bfc5Bill Wendling      const LandingPadInst *LP = BB->getLandingPadInst();
56427b5658affba5b12b396048d2cc598c70719bfc5Bill Wendling      CalleePersonality = LP->getPersonalityFn();
565fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling      break;
566fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling    }
567fe7a071a19ca6781c774c392c82341bdf14df104Bill Wendling
56830fe1ae20d02ac8e12cec9d767d855946546a030Benjamin Kramer  // Find the personality function used by the landing pads of the caller. If it
56930fe1ae20d02ac8e12cec9d767d855946546a030Benjamin Kramer  // exists, then check to see that it matches the personality function used in
57030fe1ae20d02ac8e12cec9d767d855946546a030Benjamin Kramer  // the callee.
57106881e8734b1758fb0666f4e47a91bc58c6383beBill Wendling  if (CalleePersonality) {
57230fe1ae20d02ac8e12cec9d767d855946546a030Benjamin Kramer    for (Function::const_iterator I = Caller->begin(), E = Caller->end();
57330fe1ae20d02ac8e12cec9d767d855946546a030Benjamin Kramer         I != E; ++I)
57430fe1ae20d02ac8e12cec9d767d855946546a030Benjamin Kramer      if (const InvokeInst *II = dyn_cast<InvokeInst>(I->getTerminator())) {
57530fe1ae20d02ac8e12cec9d767d855946546a030Benjamin Kramer        const BasicBlock *BB = II->getUnwindDest();
57627b5658affba5b12b396048d2cc598c70719bfc5Bill Wendling        const LandingPadInst *LP = BB->getLandingPadInst();
57730fe1ae20d02ac8e12cec9d767d855946546a030Benjamin Kramer
57830fe1ae20d02ac8e12cec9d767d855946546a030Benjamin Kramer        // If the personality functions match, then we can perform the
57930fe1ae20d02ac8e12cec9d767d855946546a030Benjamin Kramer        // inlining. Otherwise, we can't inline.
58030fe1ae20d02ac8e12cec9d767d855946546a030Benjamin Kramer        // TODO: This isn't 100% true. Some personality functions are proper
58130fe1ae20d02ac8e12cec9d767d855946546a030Benjamin Kramer        //       supersets of others and can be used in place of the other.
58230fe1ae20d02ac8e12cec9d767d855946546a030Benjamin Kramer        if (LP->getPersonalityFn() != CalleePersonality)
58330fe1ae20d02ac8e12cec9d767d855946546a030Benjamin Kramer          return false;
58430fe1ae20d02ac8e12cec9d767d855946546a030Benjamin Kramer
58530fe1ae20d02ac8e12cec9d767d855946546a030Benjamin Kramer        break;
58630fe1ae20d02ac8e12cec9d767d855946546a030Benjamin Kramer      }
58706881e8734b1758fb0666f4e47a91bc58c6383beBill Wendling  }
58830fe1ae20d02ac8e12cec9d767d855946546a030Benjamin Kramer
5895052c911ec1be51ecb36e7f025c26412e9f1bfacChris Lattner  // Get an iterator to the last basic block in the function, which will have
5905052c911ec1be51ecb36e7f025c26412e9f1bfacChris Lattner  // the new function inlined after it.
5915052c911ec1be51ecb36e7f025c26412e9f1bfacChris Lattner  Function::iterator LastBlock = &Caller->back();
5925052c911ec1be51ecb36e7f025c26412e9f1bfacChris Lattner
5935e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner  // Make sure to capture all of the return instructions from the cloned
5945e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner  // function.
595ec1bea0d94372985a0a5eb283e644c6d0dd345dcChris Lattner  SmallVector<ReturnInst*, 8> Returns;
596cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner  ClonedCodeInfo InlinedFunctionInfo;
5970744f09efc53d3352ac1caffc61f6e8239201c3bDale Johannesen  Function::iterator FirstNewBlock;
598f0c3354d998507515ab39e26b5292ea0ceb06aefDuncan Sands
59929d3dd8a64791031eea00ffbae51843dc9982df9Devang Patel  { // Scope to destroy VMap after cloning.
6001ed219a9d2279ce5a5bbcf16d9b7ccc05cce638cRafael Espindola    ValueToValueMapTy VMap;
601dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    // Keep a list of pair (dst, src) to emit byval initializations.
602dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    SmallVector<std::pair<Value*, Value*>, 4> ByValInit;
6035b5bc3032f97cfa7bfa3e22282d3a9c1ed05eec6Chris Lattner
6049614fcc640eb628cc5dfddb277ebae9f6cb61014Dan Gohman    assert(CalledFunc->arg_size() == CS.arg_size() &&
6055e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner           "No varargs calls can be inlined!");
606a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands
607c93adca35856d0eaae088e52ba30cfefbd7ad910Chris Lattner    // Calculate the vector of arguments to pass into the function cloner, which
608c93adca35856d0eaae088e52ba30cfefbd7ad910Chris Lattner    // matches up the formal to the actual argument values.
6095e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner    CallSite::arg_iterator AI = CS.arg_begin();
610c93adca35856d0eaae088e52ba30cfefbd7ad910Chris Lattner    unsigned ArgNo = 0;
611e4d5c441e04bdc00ccf1804744af670655123b07Chris Lattner    for (Function::const_arg_iterator I = CalledFunc->arg_begin(),
612c93adca35856d0eaae088e52ba30cfefbd7ad910Chris Lattner         E = CalledFunc->arg_end(); I != E; ++I, ++AI, ++ArgNo) {
613c93adca35856d0eaae088e52ba30cfefbd7ad910Chris Lattner      Value *ActualArg = *AI;
614a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands
615d82375c1c43db7f823dd4660d3495e76566699e3Duncan Sands      // When byval arguments actually inlined, we need to make the copy implied
616d82375c1c43db7f823dd4660d3495e76566699e3Duncan Sands      // by them explicit.  However, we don't do this if the callee is readonly
617d82375c1c43db7f823dd4660d3495e76566699e3Duncan Sands      // or readnone, because the copy would be unneeded: the callee doesn't
618d82375c1c43db7f823dd4660d3495e76566699e3Duncan Sands      // modify the struct.
619173862e5468fbcf4b022b9088d2c81b25c2d60c5Nick Lewycky      if (CS.isByValArgument(ArgNo)) {
62016d10987184281aff35c80542a3c02e7dcb7b59bDavid Majnemer        ActualArg = HandleByValArgument(ActualArg, TheCall, CalledFunc, IFI,
621e7ae705c32906979a527926864345016e76867b9Chris Lattner                                        CalledFunc->getParamAlignment(ArgNo+1));
622dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines        if (ActualArg != *AI)
623dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines          ByValInit.push_back(std::make_pair(ActualArg, (Value*) *AI));
624c93adca35856d0eaae088e52ba30cfefbd7ad910Chris Lattner      }
625a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands
62629d3dd8a64791031eea00ffbae51843dc9982df9Devang Patel      VMap[I] = ActualArg;
627c93adca35856d0eaae088e52ba30cfefbd7ad910Chris Lattner    }
628fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
6295b5bc3032f97cfa7bfa3e22282d3a9c1ed05eec6Chris Lattner    // We want the inliner to prune the code as it copies.  We would LOVE to
6305b5bc3032f97cfa7bfa3e22282d3a9c1ed05eec6Chris Lattner    // have no dead or constant instructions leftover after inlining occurs
6315b5bc3032f97cfa7bfa3e22282d3a9c1ed05eec6Chris Lattner    // (which can happen, e.g., because an argument was constant), but we'll be
6325b5bc3032f97cfa7bfa3e22282d3a9c1ed05eec6Chris Lattner    // happy with whatever the cloner can do.
6336cb8c23db1c3becdce6dfbf1b7f1677faca4251eDan Gohman    CloneAndPruneFunctionInto(Caller, CalledFunc, VMap,
6346cb8c23db1c3becdce6dfbf1b7f1677faca4251eDan Gohman                              /*ModuleLevelChanges=*/false, Returns, ".i",
63536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines                              &InlinedFunctionInfo, IFI.DL, TheCall);
636a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands
637d85340f4ec587e22b0239617f3b747a6df113894Chris Lattner    // Remember the first block that is newly cloned over.
638d85340f4ec587e22b0239617f3b747a6df113894Chris Lattner    FirstNewBlock = LastBlock; ++FirstNewBlock;
639a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands
640dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    // Inject byval arguments initialization.
641dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    for (std::pair<Value*, Value*> &Init : ByValInit)
642dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      HandleByValArgumentInit(Init.first, Init.second, Caller->getParent(),
643dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines                              FirstNewBlock, IFI);
644dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines
645d85340f4ec587e22b0239617f3b747a6df113894Chris Lattner    // Update the callgraph if requested.
64660915146f4d35e12f10dcdaa155596fac79184daChris Lattner    if (IFI.CG)
64729d3dd8a64791031eea00ffbae51843dc9982df9Devang Patel      UpdateCallGraphAfterInlining(CS, FirstNewBlock, VMap, IFI);
6482cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patel
6492cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patel    // Update inlined instructions' line number information.
6502cf158ec4bf78f236976f07e09d7b1fe6be13994Devang Patel    fixupLineNumbers(Caller, FirstNewBlock, TheCall);
651fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman  }
652a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands
653ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner  // If there are any alloca instructions in the block that used to be the entry
654ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner  // block for the callee, move them to the entry block of the caller.  First
655ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner  // calculate which instruction they should be inserted before.  We insert the
656ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner  // instructions at the end of the current alloca list.
65721f20558d629f7ff8f64c20746d890d29328a544Chris Lattner  {
65880a38d245359cb0a3be8f78f5d7d911232886b9aChris Lattner    BasicBlock::iterator InsertPoint = Caller->begin()->begin();
6595e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner    for (BasicBlock::iterator I = FirstNewBlock->begin(),
660135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner         E = FirstNewBlock->end(); I != E; ) {
661135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner      AllocaInst *AI = dyn_cast<AllocaInst>(I++);
662dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      if (!AI) continue;
663135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner
664135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner      // If the alloca is now dead, remove it.  This often occurs due to code
665135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner      // specialization.
666135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner      if (AI->use_empty()) {
667135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner        AI->eraseFromParent();
668135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner        continue;
66933bb3c8be355d179ece8e751f6e0f0978d0dd038Chris Lattner      }
670135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner
671135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner      if (!isa<Constant>(AI->getArraySize()))
672135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner        continue;
673135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner
67439add23dc54a1580983b1901384688d6622daa3bChris Lattner      // Keep track of the static allocas that we inline into the caller.
67560915146f4d35e12f10dcdaa155596fac79184daChris Lattner      IFI.StaticAllocas.push_back(AI);
6768f2718fbef6177966ff807af0732eb2431bd9a5fChris Lattner
677135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner      // Scan for the block of allocas that we can move over, and move them
678135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner      // all at once.
679135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner      while (isa<AllocaInst>(I) &&
6808f2718fbef6177966ff807af0732eb2431bd9a5fChris Lattner             isa<Constant>(cast<AllocaInst>(I)->getArraySize())) {
68160915146f4d35e12f10dcdaa155596fac79184daChris Lattner        IFI.StaticAllocas.push_back(cast<AllocaInst>(I));
682135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner        ++I;
6838f2718fbef6177966ff807af0732eb2431bd9a5fChris Lattner      }
684135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner
685135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner      // Transfer all of the allocas over in a block.  Using splice means
686135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner      // that the instructions aren't removed from the symbol table, then
687135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner      // reinserted.
688135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner      Caller->getEntryBlock().getInstList().splice(InsertPoint,
689135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner                                                   FirstNewBlock->getInstList(),
690135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner                                                   AI, I);
691135755dae4c3fa8003b76150689d5064aa4612eeChris Lattner    }
69280a38d245359cb0a3be8f78f5d7d911232886b9aChris Lattner  }
69380a38d245359cb0a3be8f78f5d7d911232886b9aChris Lattner
694dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  bool InlinedMustTailCalls = false;
695dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  if (InlinedFunctionInfo.ContainsCalls) {
696dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    CallInst::TailCallKind CallSiteTailKind = CallInst::TCK_None;
697dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    if (CallInst *CI = dyn_cast<CallInst>(TheCall))
698dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      CallSiteTailKind = CI->getTailCallKind();
699dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines
700dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    for (Function::iterator BB = FirstNewBlock, E = Caller->end(); BB != E;
701dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines         ++BB) {
702dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      for (Instruction &I : *BB) {
703dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines        CallInst *CI = dyn_cast<CallInst>(&I);
704dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines        if (!CI)
705dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines          continue;
706dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines
707dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines        // We need to reduce the strength of any inlined tail calls.  For
708dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines        // musttail, we have to avoid introducing potential unbounded stack
709dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines        // growth.  For example, if functions 'f' and 'g' are mutually recursive
710dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines        // with musttail, we can inline 'g' into 'f' so long as we preserve
711dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines        // musttail on the cloned call to 'f'.  If either the inlined call site
712dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines        // or the cloned call site is *not* musttail, the program already has
713dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines        // one frame of stack growth, so it's safe to remove musttail.  Here is
714dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines        // a table of example transformations:
715dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines        //
716dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines        //    f -> musttail g -> musttail f  ==>  f -> musttail f
717dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines        //    f -> musttail g ->     tail f  ==>  f ->     tail f
718dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines        //    f ->          g -> musttail f  ==>  f ->          f
719dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines        //    f ->          g ->     tail f  ==>  f ->          f
720dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines        CallInst::TailCallKind ChildTCK = CI->getTailCallKind();
721dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines        ChildTCK = std::min(CallSiteTailKind, ChildTCK);
722dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines        CI->setTailCallKind(ChildTCK);
723dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines        InlinedMustTailCalls |= CI->isMustTailCall();
724dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines
725dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines        // Calls inlined through a 'nounwind' call site should be marked
726dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines        // 'nounwind'.
727dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines        if (MarkNoUnwind)
728dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines          CI->setDoesNotThrow();
729dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      }
730dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    }
731dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  }
732dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines
7336d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky  // Leave lifetime markers for the static alloca's, scoping them to the
7346d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky  // function we just inlined.
735fa086f1f00a8b75ab2e2208bd7a028e62f9854dbChad Rosier  if (InsertLifetime && !IFI.StaticAllocas.empty()) {
7366d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky    IRBuilder<> builder(FirstNewBlock->begin());
7376d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky    for (unsigned ai = 0, ae = IFI.StaticAllocas.size(); ai != ae; ++ai) {
7386d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky      AllocaInst *AI = IFI.StaticAllocas[ai];
7396d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky
7406d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky      // If the alloca is already scoped to something smaller than the whole
7416d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky      // function then there's no need to add redundant, less accurate markers.
7426d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky      if (hasLifetimeMarkers(AI))
7436d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky        continue;
7446d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky
745009c4d86c14bb2f46f9473f8f517393dabab7e9eAlexey Samsonov      // Try to determine the size of the allocation.
746dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      ConstantInt *AllocaSize = nullptr;
747009c4d86c14bb2f46f9473f8f517393dabab7e9eAlexey Samsonov      if (ConstantInt *AIArraySize =
748009c4d86c14bb2f46f9473f8f517393dabab7e9eAlexey Samsonov          dyn_cast<ConstantInt>(AI->getArraySize())) {
74936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines        if (IFI.DL) {
750009c4d86c14bb2f46f9473f8f517393dabab7e9eAlexey Samsonov          Type *AllocaType = AI->getAllocatedType();
75136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines          uint64_t AllocaTypeSize = IFI.DL->getTypeAllocSize(AllocaType);
752009c4d86c14bb2f46f9473f8f517393dabab7e9eAlexey Samsonov          uint64_t AllocaArraySize = AIArraySize->getLimitedValue();
753009c4d86c14bb2f46f9473f8f517393dabab7e9eAlexey Samsonov          assert(AllocaArraySize > 0 && "array size of AllocaInst is zero");
754009c4d86c14bb2f46f9473f8f517393dabab7e9eAlexey Samsonov          // Check that array size doesn't saturate uint64_t and doesn't
755009c4d86c14bb2f46f9473f8f517393dabab7e9eAlexey Samsonov          // overflow when it's multiplied by type size.
756009c4d86c14bb2f46f9473f8f517393dabab7e9eAlexey Samsonov          if (AllocaArraySize != ~0ULL &&
757009c4d86c14bb2f46f9473f8f517393dabab7e9eAlexey Samsonov              UINT64_MAX / AllocaArraySize >= AllocaTypeSize) {
758009c4d86c14bb2f46f9473f8f517393dabab7e9eAlexey Samsonov            AllocaSize = ConstantInt::get(Type::getInt64Ty(AI->getContext()),
759009c4d86c14bb2f46f9473f8f517393dabab7e9eAlexey Samsonov                                          AllocaArraySize * AllocaTypeSize);
760009c4d86c14bb2f46f9473f8f517393dabab7e9eAlexey Samsonov          }
761009c4d86c14bb2f46f9473f8f517393dabab7e9eAlexey Samsonov        }
762009c4d86c14bb2f46f9473f8f517393dabab7e9eAlexey Samsonov      }
763009c4d86c14bb2f46f9473f8f517393dabab7e9eAlexey Samsonov
764009c4d86c14bb2f46f9473f8f517393dabab7e9eAlexey Samsonov      builder.CreateLifetimeStart(AI, AllocaSize);
765dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      for (ReturnInst *RI : Returns) {
766dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines        // Don't insert llvm.lifetime.end calls between a musttail call and a
767dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines        // return.  The return kills all local allocas.
768dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines        if (InlinedMustTailCalls && getPrecedingMustTailCall(RI))
769dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines          continue;
770dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines        IRBuilder<>(RI).CreateLifetimeEnd(AI, AllocaSize);
7716d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky      }
7726d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky    }
7736d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky  }
7746d55f2269e20298a1d6a683be72d9552482156a9Nick Lewycky
775bf229f488a7541abd979cc3fbe9c3ce1c100e5c0Chris Lattner  // If the inlined code contained dynamic alloca instructions, wrap the inlined
776bf229f488a7541abd979cc3fbe9c3ce1c100e5c0Chris Lattner  // code with llvm.stacksave/llvm.stackrestore intrinsics.
777bf229f488a7541abd979cc3fbe9c3ce1c100e5c0Chris Lattner  if (InlinedFunctionInfo.ContainsDynamicAllocas) {
778bf229f488a7541abd979cc3fbe9c3ce1c100e5c0Chris Lattner    Module *M = Caller->getParent();
779bf229f488a7541abd979cc3fbe9c3ce1c100e5c0Chris Lattner    // Get the two intrinsics we care about.
7806128df525501c333a650d097703c18d7e878f5e8Chris Lattner    Function *StackSave = Intrinsic::getDeclaration(M, Intrinsic::stacksave);
7816128df525501c333a650d097703c18d7e878f5e8Chris Lattner    Function *StackRestore=Intrinsic::getDeclaration(M,Intrinsic::stackrestore);
782d85340f4ec587e22b0239617f3b747a6df113894Chris Lattner
783bf229f488a7541abd979cc3fbe9c3ce1c100e5c0Chris Lattner    // Insert the llvm.stacksave.
784c975a51ac042eb15bcb04a293cb737810ff40a00John McCall    CallInst *SavedPtr = IRBuilder<>(FirstNewBlock, FirstNewBlock->begin())
785c975a51ac042eb15bcb04a293cb737810ff40a00John McCall      .CreateCall(StackSave, "savedstack");
786a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands
787bf229f488a7541abd979cc3fbe9c3ce1c100e5c0Chris Lattner    // Insert a call to llvm.stackrestore before any return instructions in the
788bf229f488a7541abd979cc3fbe9c3ce1c100e5c0Chris Lattner    // inlined function.
789dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    for (ReturnInst *RI : Returns) {
790dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      // Don't insert llvm.stackrestore calls between a musttail call and a
791dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      // return.  The return will restore the stack pointer.
792dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      if (InlinedMustTailCalls && getPrecedingMustTailCall(RI))
793dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines        continue;
794dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      IRBuilder<>(RI).CreateCall(StackRestore, SavedPtr);
795d85340f4ec587e22b0239617f3b747a6df113894Chris Lattner    }
796bf229f488a7541abd979cc3fbe9c3ce1c100e5c0Chris Lattner  }
797bf229f488a7541abd979cc3fbe9c3ce1c100e5c0Chris Lattner
7985e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner  // If we are inlining for an invoke instruction, we must make sure to rewrite
7998833ef03b9ceaa52063116819fff8b3d16fd8933Bill Wendling  // any call instructions into invoke instructions.
800cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner  if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
80181dfb3885252fbf621b080827a080099864415f8Chris Lattner    HandleInlinedInvoke(II, FirstNewBlock, InlinedFunctionInfo);
8025e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner
803dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  // Handle any inlined musttail call sites.  In order for a new call site to be
804dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  // musttail, the source of the clone and the inlined call site must have been
805dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  // musttail.  Therefore it's safe to return without merging control into the
806dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  // phi below.
807dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  if (InlinedMustTailCalls) {
808dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    // Check if we need to bitcast the result of any musttail calls.
809dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    Type *NewRetTy = Caller->getReturnType();
810dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    bool NeedBitCast = !TheCall->use_empty() && TheCall->getType() != NewRetTy;
811dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines
812dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    // Handle the returns preceded by musttail calls separately.
813dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    SmallVector<ReturnInst *, 8> NormalReturns;
814dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    for (ReturnInst *RI : Returns) {
815dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      CallInst *ReturnedMustTail = getPrecedingMustTailCall(RI);
816dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      if (!ReturnedMustTail) {
817dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines        NormalReturns.push_back(RI);
818dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines        continue;
819dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      }
820dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      if (!NeedBitCast)
821dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines        continue;
822dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines
823dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      // Delete the old return and any preceding bitcast.
824dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      BasicBlock *CurBB = RI->getParent();
825dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      auto *OldCast = dyn_cast_or_null<BitCastInst>(RI->getReturnValue());
826dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      RI->eraseFromParent();
827dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      if (OldCast)
828dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines        OldCast->eraseFromParent();
829dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines
830dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      // Insert a new bitcast and return with the right type.
831dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      IRBuilder<> Builder(CurBB);
832dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      Builder.CreateRet(Builder.CreateBitCast(ReturnedMustTail, NewRetTy));
833dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    }
834dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines
835dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    // Leave behind the normal returns so we can merge control flow.
836dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    std::swap(Returns, NormalReturns);
837dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  }
838dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines
83944a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner  // If we cloned in _exactly one_ basic block, and if that block ends in a
84044a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner  // return instruction, we splice the body of the inlined callee directly into
84144a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner  // the calling basic block.
84244a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner  if (Returns.size() == 1 && std::distance(FirstNewBlock, Caller->end()) == 1) {
84344a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner    // Move all of the instructions right before the call.
84444a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner    OrigBB->getInstList().splice(TheCall, FirstNewBlock->getInstList(),
84544a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner                                 FirstNewBlock->begin(), FirstNewBlock->end());
84644a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner    // Remove the cloned basic block.
84744a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner    Caller->getBasicBlockList().pop_back();
848fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
84944a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner    // If the call site was an invoke instruction, add a branch to the normal
85044a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner    // destination.
851f48509787acfcfc3f9eee2fb3084c2e8c7b4a009Adrian Prantl    if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
852f48509787acfcfc3f9eee2fb3084c2e8c7b4a009Adrian Prantl      BranchInst *NewBr = BranchInst::Create(II->getNormalDest(), TheCall);
853f48509787acfcfc3f9eee2fb3084c2e8c7b4a009Adrian Prantl      NewBr->setDebugLoc(Returns[0]->getDebugLoc());
854f48509787acfcfc3f9eee2fb3084c2e8c7b4a009Adrian Prantl    }
85544a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner
85644a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner    // If the return instruction returned a value, replace uses of the call with
85744a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner    // uses of the returned value.
858dc00d42bb18a6748f43c365d9bd30c1ed0e800acDevang Patel    if (!TheCall->use_empty()) {
859dc00d42bb18a6748f43c365d9bd30c1ed0e800acDevang Patel      ReturnInst *R = Returns[0];
8605877ad7e90de2179c15914ff9e8f1c72152cac30Eli Friedman      if (TheCall == R->getReturnValue())
8619e9a0d5fc26878e51a58a8b57900fcbf952c2691Owen Anderson        TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
8625877ad7e90de2179c15914ff9e8f1c72152cac30Eli Friedman      else
8635877ad7e90de2179c15914ff9e8f1c72152cac30Eli Friedman        TheCall->replaceAllUsesWith(R->getReturnValue());
864dc00d42bb18a6748f43c365d9bd30c1ed0e800acDevang Patel    }
86544a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner    // Since we are now done with the Call/Invoke, we can delete it.
8661adec83ae84031bfa9f0bf209c5ee6c64906a1ffDan Gohman    TheCall->eraseFromParent();
86744a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner
86844a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner    // Since we are now done with the return instruction, delete it also.
8691adec83ae84031bfa9f0bf209c5ee6c64906a1ffDan Gohman    Returns[0]->eraseFromParent();
87044a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner
87144a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner    // We are now done with the inlining.
87244a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner    return true;
87344a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner  }
87444a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner
87544a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner  // Otherwise, we have the normal case, of more than one block to inline or
87644a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner  // multiple return sites.
87744a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner
8785e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner  // We want to clone the entire callee function into the hole between the
8795e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner  // "starter" and "ender" blocks.  How we accomplish this depends on whether
8805e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner  // this is an invoke instruction or a call instruction.
8815e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner  BasicBlock *AfterCallBB;
882dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  BranchInst *CreatedBranchToNormalDest = nullptr;
8835e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner  if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
884fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
8855e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner    // Add an unconditional branch to make this look like the CallInst case...
886f48509787acfcfc3f9eee2fb3084c2e8c7b4a009Adrian Prantl    CreatedBranchToNormalDest = BranchInst::Create(II->getNormalDest(), TheCall);
887fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
8885e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner    // Split the basic block.  This guarantees that no PHI nodes will have to be
8895e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner    // updated due to new incoming edges, and make the invoke case more
8905e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner    // symmetric to the call case.
891f48509787acfcfc3f9eee2fb3084c2e8c7b4a009Adrian Prantl    AfterCallBB = OrigBB->splitBasicBlock(CreatedBranchToNormalDest,
892284d1b88273eb1967c8faef407f1167791c760e0Chris Lattner                                          CalledFunc->getName()+".exit");
893fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
8945e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner  } else {  // It's a call
89544a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner    // If this is a call instruction, we need to split the basic block that
89644a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner    // the call lives in.
8975e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner    //
8985e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner    AfterCallBB = OrigBB->splitBasicBlock(TheCall,
899284d1b88273eb1967c8faef407f1167791c760e0Chris Lattner                                          CalledFunc->getName()+".exit");
9005e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner  }
9015e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner
90244a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner  // Change the branch that used to go to AfterCallBB to branch to the first
90344a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner  // basic block of the inlined function.
90444a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner  //
90544a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner  TerminatorInst *Br = OrigBB->getTerminator();
906fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman  assert(Br && Br->getOpcode() == Instruction::Br &&
90744a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner         "splitBasicBlock broken!");
90844a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner  Br->setOperand(0, FirstNewBlock);
90944a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner
91044a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner
91144a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner  // Now that the function is correct, make it a little bit nicer.  In
91244a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner  // particular, move the basic blocks inserted from the end of the function
91344a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner  // into the space made by splitting the source basic block.
91444a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner  Caller->getBasicBlockList().splice(AfterCallBB, Caller->getBasicBlockList(),
91544a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner                                     FirstNewBlock, Caller->end());
91644a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner
9175e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner  // Handle all of the return instructions that we just cloned in, and eliminate
9185e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner  // any users of the original call/invoke instruction.
919db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *RTy = CalledFunc->getReturnType();
9202c31750cd0ebdc83a890ace97dbb6249b3abe44eDan Gohman
921dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  PHINode *PHI = nullptr;
922fc74abfba5128544a750fce22fdf13eb0403e3ceDan Gohman  if (Returns.size() > 1) {
9235e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner    // The PHI node should go at the front of the new basic block to merge all
9245e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner    // possible incoming values.
9255e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner    if (!TheCall->use_empty()) {
9263ecfc861b4365f341c5c969b40e1afccde676e6fJay Foad      PHI = PHINode::Create(RTy, Returns.size(), TheCall->getName(),
927fc74abfba5128544a750fce22fdf13eb0403e3ceDan Gohman                            AfterCallBB->begin());
928fc74abfba5128544a750fce22fdf13eb0403e3ceDan Gohman      // Anything that used the result of the function call should now use the
929fc74abfba5128544a750fce22fdf13eb0403e3ceDan Gohman      // PHI node as their operand.
930a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands      TheCall->replaceAllUsesWith(PHI);
9315e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner    }
932fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
933c478e52bf4c12691037856ee103c66946afeab6cGabor Greif    // Loop over all of the return instructions adding entries to the PHI node
934c478e52bf4c12691037856ee103c66946afeab6cGabor Greif    // as appropriate.
935fc74abfba5128544a750fce22fdf13eb0403e3ceDan Gohman    if (PHI) {
936fc74abfba5128544a750fce22fdf13eb0403e3ceDan Gohman      for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
937fc74abfba5128544a750fce22fdf13eb0403e3ceDan Gohman        ReturnInst *RI = Returns[i];
938fc74abfba5128544a750fce22fdf13eb0403e3ceDan Gohman        assert(RI->getReturnValue()->getType() == PHI->getType() &&
939fc74abfba5128544a750fce22fdf13eb0403e3ceDan Gohman               "Ret value not consistent in function!");
940fc74abfba5128544a750fce22fdf13eb0403e3ceDan Gohman        PHI->addIncoming(RI->getReturnValue(), RI->getParent());
9415e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner      }
94212a466b9d0e27be453cfa05cff18acc9d7c1cfbaDevang Patel    }
943fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
944c581acbbba3cb1af6a08e17314b26344333f9267Chris Lattner
945de62aeaec49ddcf4a4c61fbbb3a22d3a4dd448f0Gabor Greif    // Add a branch to the merge points and remove return instructions.
9468e229c24ed8b8a9a3866947a709e616b33780f1fRichard Trieu    DebugLoc Loc;
94712a466b9d0e27be453cfa05cff18acc9d7c1cfbaDevang Patel    for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
9488e229c24ed8b8a9a3866947a709e616b33780f1fRichard Trieu      ReturnInst *RI = Returns[i];
9498b11e89b93542a465b4b23197283cc7bbceaaa9aAdrian Prantl      BranchInst* BI = BranchInst::Create(AfterCallBB, RI);
9508e229c24ed8b8a9a3866947a709e616b33780f1fRichard Trieu      Loc = RI->getDebugLoc();
9518e229c24ed8b8a9a3866947a709e616b33780f1fRichard Trieu      BI->setDebugLoc(Loc);
952b8f198af1b62f2ed48dcb914973a9d211dcba38bDevang Patel      RI->eraseFromParent();
9535e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner    }
9548b11e89b93542a465b4b23197283cc7bbceaaa9aAdrian Prantl    // We need to set the debug location to *somewhere* inside the
9558960a5c63db0d4f1e6ad794ea626c68de9313dbfAdrian Prantl    // inlined function. The line number may be nonsensical, but the
9568b11e89b93542a465b4b23197283cc7bbceaaa9aAdrian Prantl    // instruction will at least be associated with the right
9578b11e89b93542a465b4b23197283cc7bbceaaa9aAdrian Prantl    // function.
9588b11e89b93542a465b4b23197283cc7bbceaaa9aAdrian Prantl    if (CreatedBranchToNormalDest)
9598e229c24ed8b8a9a3866947a709e616b33780f1fRichard Trieu      CreatedBranchToNormalDest->setDebugLoc(Loc);
960b8f198af1b62f2ed48dcb914973a9d211dcba38bDevang Patel  } else if (!Returns.empty()) {
961b8f198af1b62f2ed48dcb914973a9d211dcba38bDevang Patel    // Otherwise, if there is exactly one return value, just replace anything
962b8f198af1b62f2ed48dcb914973a9d211dcba38bDevang Patel    // using the return value of the call with the computed value.
9635877ad7e90de2179c15914ff9e8f1c72152cac30Eli Friedman    if (!TheCall->use_empty()) {
9645877ad7e90de2179c15914ff9e8f1c72152cac30Eli Friedman      if (TheCall == Returns[0]->getReturnValue())
9659e9a0d5fc26878e51a58a8b57900fcbf952c2691Owen Anderson        TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
9665877ad7e90de2179c15914ff9e8f1c72152cac30Eli Friedman      else
9675877ad7e90de2179c15914ff9e8f1c72152cac30Eli Friedman        TheCall->replaceAllUsesWith(Returns[0]->getReturnValue());
9685877ad7e90de2179c15914ff9e8f1c72152cac30Eli Friedman    }
969a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands
97095c3e48f9557adb6064d580684bb14cacec2f826Jay Foad    // Update PHI nodes that use the ReturnBB to use the AfterCallBB.
97195c3e48f9557adb6064d580684bb14cacec2f826Jay Foad    BasicBlock *ReturnBB = Returns[0]->getParent();
97295c3e48f9557adb6064d580684bb14cacec2f826Jay Foad    ReturnBB->replaceAllUsesWith(AfterCallBB);
97395c3e48f9557adb6064d580684bb14cacec2f826Jay Foad
974b8f198af1b62f2ed48dcb914973a9d211dcba38bDevang Patel    // Splice the code from the return block into the block that it will return
975b8f198af1b62f2ed48dcb914973a9d211dcba38bDevang Patel    // to, which contains the code that was after the call.
976b8f198af1b62f2ed48dcb914973a9d211dcba38bDevang Patel    AfterCallBB->getInstList().splice(AfterCallBB->begin(),
977b8f198af1b62f2ed48dcb914973a9d211dcba38bDevang Patel                                      ReturnBB->getInstList());
978a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands
979f48509787acfcfc3f9eee2fb3084c2e8c7b4a009Adrian Prantl    if (CreatedBranchToNormalDest)
980f48509787acfcfc3f9eee2fb3084c2e8c7b4a009Adrian Prantl      CreatedBranchToNormalDest->setDebugLoc(Returns[0]->getDebugLoc());
981f48509787acfcfc3f9eee2fb3084c2e8c7b4a009Adrian Prantl
982b8f198af1b62f2ed48dcb914973a9d211dcba38bDevang Patel    // Delete the return instruction now and empty ReturnBB now.
983b8f198af1b62f2ed48dcb914973a9d211dcba38bDevang Patel    Returns[0]->eraseFromParent();
984b8f198af1b62f2ed48dcb914973a9d211dcba38bDevang Patel    ReturnBB->eraseFromParent();
9853787e765facfad5ea62753922d940bcdd52afd57Chris Lattner  } else if (!TheCall->use_empty()) {
9863787e765facfad5ea62753922d940bcdd52afd57Chris Lattner    // No returns, but something is using the return value of the call.  Just
9873787e765facfad5ea62753922d940bcdd52afd57Chris Lattner    // nuke the result.
9889e9a0d5fc26878e51a58a8b57900fcbf952c2691Owen Anderson    TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
9895e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner  }
990fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
9915e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner  // Since we are now done with the Call/Invoke, we can delete it.
9923787e765facfad5ea62753922d940bcdd52afd57Chris Lattner  TheCall->eraseFromParent();
993ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner
994dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  // If we inlined any musttail calls and the original return is now
995dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  // unreachable, delete it.  It can only contain a bitcast and ret.
996dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  if (InlinedMustTailCalls && pred_begin(AfterCallBB) == pred_end(AfterCallBB))
997dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    AfterCallBB->eraseFromParent();
998dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines
9997152c237b46a920b29d5605af934766b8f9a07a1Chris Lattner  // We should always be able to fold the entry block of the function into the
10007152c237b46a920b29d5605af934766b8f9a07a1Chris Lattner  // single predecessor of the block...
1001cd01ae5c7071fb99a665b2bbea7428d769792ab8Chris Lattner  assert(cast<BranchInst>(Br)->isUnconditional() && "splitBasicBlock broken!");
10027152c237b46a920b29d5605af934766b8f9a07a1Chris Lattner  BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0);
100344a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner
1004cd01ae5c7071fb99a665b2bbea7428d769792ab8Chris Lattner  // Splice the code entry block into calling block, right before the
1005cd01ae5c7071fb99a665b2bbea7428d769792ab8Chris Lattner  // unconditional branch.
1006e59fbc04ad343435705c28b3cf7038d65fe4af0aEric Christopher  CalleeEntry->replaceAllUsesWith(OrigBB);  // Update PHI nodes
100795c3e48f9557adb6064d580684bb14cacec2f826Jay Foad  OrigBB->getInstList().splice(Br, CalleeEntry->getInstList());
1008cd01ae5c7071fb99a665b2bbea7428d769792ab8Chris Lattner
1009cd01ae5c7071fb99a665b2bbea7428d769792ab8Chris Lattner  // Remove the unconditional branch.
1010cd01ae5c7071fb99a665b2bbea7428d769792ab8Chris Lattner  OrigBB->getInstList().erase(Br);
1011cd01ae5c7071fb99a665b2bbea7428d769792ab8Chris Lattner
1012cd01ae5c7071fb99a665b2bbea7428d769792ab8Chris Lattner  // Now we can remove the CalleeEntry block, which is now empty.
1013cd01ae5c7071fb99a665b2bbea7428d769792ab8Chris Lattner  Caller->getBasicBlockList().erase(CalleeEntry);
1014a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands
10156fb881c036c32728c4a128d81b6083457e534e09Duncan Sands  // If we inserted a phi node, check to see if it has a single value (e.g. all
10166fb881c036c32728c4a128d81b6083457e534e09Duncan Sands  // the entries are the same or undef).  If so, remove the PHI so it doesn't
10176fb881c036c32728c4a128d81b6083457e534e09Duncan Sands  // block other optimizations.
101806881e8734b1758fb0666f4e47a91bc58c6383beBill Wendling  if (PHI) {
101936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    if (Value *V = SimplifyInstruction(PHI, IFI.DL)) {
10206fb881c036c32728c4a128d81b6083457e534e09Duncan Sands      PHI->replaceAllUsesWith(V);
10216fb881c036c32728c4a128d81b6083457e534e09Duncan Sands      PHI->eraseFromParent();
10226fb881c036c32728c4a128d81b6083457e534e09Duncan Sands    }
102306881e8734b1758fb0666f4e47a91bc58c6383beBill Wendling  }
10246fb881c036c32728c4a128d81b6083457e534e09Duncan Sands
1025ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner  return true;
1026ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner}
1027