1f22ef01cSRoman Divacky //===- InlineFunction.cpp - Code to perform function inlining -------------===//
2f22ef01cSRoman Divacky //
3f22ef01cSRoman Divacky //                     The LLVM Compiler Infrastructure
4f22ef01cSRoman Divacky //
5f22ef01cSRoman Divacky // This file is distributed under the University of Illinois Open Source
6f22ef01cSRoman Divacky // License. See LICENSE.TXT for details.
7f22ef01cSRoman Divacky //
8f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
9f22ef01cSRoman Divacky //
10f22ef01cSRoman Divacky // This file implements inlining of a function into a call site, resolving
11f22ef01cSRoman Divacky // parameters and the return value as appropriate.
12f22ef01cSRoman Divacky //
13f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
14f22ef01cSRoman Divacky 
152cab237bSDimitry Andric #include "llvm/ADT/DenseMap.h"
162cab237bSDimitry Andric #include "llvm/ADT/None.h"
172cab237bSDimitry Andric #include "llvm/ADT/Optional.h"
182cab237bSDimitry Andric #include "llvm/ADT/STLExtras.h"
197d523365SDimitry Andric #include "llvm/ADT/SetVector.h"
20d88c1a5aSDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
21f22ef01cSRoman Divacky #include "llvm/ADT/SmallVector.h"
22f22ef01cSRoman Divacky #include "llvm/ADT/StringExtras.h"
232cab237bSDimitry Andric #include "llvm/ADT/iterator_range.h"
2439d628a0SDimitry Andric #include "llvm/Analysis/AliasAnalysis.h"
2539d628a0SDimitry Andric #include "llvm/Analysis/AssumptionCache.h"
267a7e6055SDimitry Andric #include "llvm/Analysis/BlockFrequencyInfo.h"
277ae0e2c9SDimitry Andric #include "llvm/Analysis/CallGraph.h"
2839d628a0SDimitry Andric #include "llvm/Analysis/CaptureTracking.h"
297d523365SDimitry Andric #include "llvm/Analysis/EHPersonalities.h"
307ae0e2c9SDimitry Andric #include "llvm/Analysis/InstructionSimplify.h"
317a7e6055SDimitry Andric #include "llvm/Analysis/ProfileSummaryInfo.h"
324ba319b5SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
3339d628a0SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
34*b5893f02SDimitry Andric #include "llvm/Analysis/VectorUtils.h"
352cab237bSDimitry Andric #include "llvm/IR/Argument.h"
362cab237bSDimitry Andric #include "llvm/IR/BasicBlock.h"
3791bc56edSDimitry Andric #include "llvm/IR/CFG.h"
38db17bf38SDimitry Andric #include "llvm/IR/CallSite.h"
392cab237bSDimitry Andric #include "llvm/IR/Constant.h"
40139f7f9bSDimitry Andric #include "llvm/IR/Constants.h"
41db17bf38SDimitry Andric #include "llvm/IR/DIBuilder.h"
42139f7f9bSDimitry Andric #include "llvm/IR/DataLayout.h"
432cab237bSDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
442cab237bSDimitry Andric #include "llvm/IR/DebugLoc.h"
45139f7f9bSDimitry Andric #include "llvm/IR/DerivedTypes.h"
4639d628a0SDimitry Andric #include "llvm/IR/Dominators.h"
472cab237bSDimitry Andric #include "llvm/IR/Function.h"
48139f7f9bSDimitry Andric #include "llvm/IR/IRBuilder.h"
492cab237bSDimitry Andric #include "llvm/IR/InstrTypes.h"
502cab237bSDimitry Andric #include "llvm/IR/Instruction.h"
51139f7f9bSDimitry Andric #include "llvm/IR/Instructions.h"
52139f7f9bSDimitry Andric #include "llvm/IR/IntrinsicInst.h"
53139f7f9bSDimitry Andric #include "llvm/IR/Intrinsics.h"
542cab237bSDimitry Andric #include "llvm/IR/LLVMContext.h"
5539d628a0SDimitry Andric #include "llvm/IR/MDBuilder.h"
562cab237bSDimitry Andric #include "llvm/IR/Metadata.h"
57139f7f9bSDimitry Andric #include "llvm/IR/Module.h"
582cab237bSDimitry Andric #include "llvm/IR/Type.h"
592cab237bSDimitry Andric #include "llvm/IR/User.h"
602cab237bSDimitry Andric #include "llvm/IR/Value.h"
612cab237bSDimitry Andric #include "llvm/Support/Casting.h"
6239d628a0SDimitry Andric #include "llvm/Support/CommandLine.h"
632cab237bSDimitry Andric #include "llvm/Support/ErrorHandling.h"
64db17bf38SDimitry Andric #include "llvm/Transforms/Utils/Cloning.h"
652cab237bSDimitry Andric #include "llvm/Transforms/Utils/ValueMapper.h"
6639d628a0SDimitry Andric #include <algorithm>
672cab237bSDimitry Andric #include <cassert>
682cab237bSDimitry Andric #include <cstdint>
692cab237bSDimitry Andric #include <iterator>
702cab237bSDimitry Andric #include <limits>
712cab237bSDimitry Andric #include <string>
722cab237bSDimitry Andric #include <utility>
732cab237bSDimitry Andric #include <vector>
747d523365SDimitry Andric 
75f22ef01cSRoman Divacky using namespace llvm;
764ba319b5SDimitry Andric using ProfileCount = Function::ProfileCount;
77f22ef01cSRoman Divacky 
7839d628a0SDimitry Andric static cl::opt<bool>
7939d628a0SDimitry Andric EnableNoAliasConversion("enable-noalias-to-md-conversion", cl::init(true),
8039d628a0SDimitry Andric   cl::Hidden,
8139d628a0SDimitry Andric   cl::desc("Convert noalias attributes to metadata during inlining."));
8239d628a0SDimitry Andric 
8339d628a0SDimitry Andric static cl::opt<bool>
8439d628a0SDimitry Andric PreserveAlignmentAssumptions("preserve-alignment-assumptions-during-inlining",
8539d628a0SDimitry Andric   cl::init(true), cl::Hidden,
8639d628a0SDimitry Andric   cl::desc("Convert align attributes to assumptions during inlining."));
8739d628a0SDimitry Andric 
InlineFunction(CallInst * CI,InlineFunctionInfo & IFI,AAResults * CalleeAAR,bool InsertLifetime)88*b5893f02SDimitry Andric llvm::InlineResult llvm::InlineFunction(CallInst *CI, InlineFunctionInfo &IFI,
89*b5893f02SDimitry Andric                                         AAResults *CalleeAAR,
90*b5893f02SDimitry Andric                                         bool InsertLifetime) {
917d523365SDimitry Andric   return InlineFunction(CallSite(CI), IFI, CalleeAAR, InsertLifetime);
92f22ef01cSRoman Divacky }
932cab237bSDimitry Andric 
InlineFunction(InvokeInst * II,InlineFunctionInfo & IFI,AAResults * CalleeAAR,bool InsertLifetime)94*b5893f02SDimitry Andric llvm::InlineResult llvm::InlineFunction(InvokeInst *II, InlineFunctionInfo &IFI,
95*b5893f02SDimitry Andric                                         AAResults *CalleeAAR,
96*b5893f02SDimitry Andric                                         bool InsertLifetime) {
977d523365SDimitry Andric   return InlineFunction(CallSite(II), IFI, CalleeAAR, InsertLifetime);
98bd5abe19SDimitry Andric }
99bd5abe19SDimitry Andric 
100bd5abe19SDimitry Andric namespace {
1012cab237bSDimitry Andric 
1027d523365SDimitry Andric   /// A class for recording information about inlining a landing pad.
1037d523365SDimitry Andric   class LandingPadInliningInfo {
1042cab237bSDimitry Andric     /// Destination of the invoke's unwind.
1052cab237bSDimitry Andric     BasicBlock *OuterResumeDest;
1062cab237bSDimitry Andric 
1072cab237bSDimitry Andric     /// Destination for the callee's resume.
1082cab237bSDimitry Andric     BasicBlock *InnerResumeDest = nullptr;
1092cab237bSDimitry Andric 
1102cab237bSDimitry Andric     /// LandingPadInst associated with the invoke.
1112cab237bSDimitry Andric     LandingPadInst *CallerLPad = nullptr;
1122cab237bSDimitry Andric 
1132cab237bSDimitry Andric     /// PHI for EH values from landingpad insts.
1142cab237bSDimitry Andric     PHINode *InnerEHValuesPHI = nullptr;
1152cab237bSDimitry Andric 
116dff0c46cSDimitry Andric     SmallVector<Value*, 8> UnwindDestPHIValues;
117bd5abe19SDimitry Andric 
1186122f3e6SDimitry Andric   public:
LandingPadInliningInfo(InvokeInst * II)1197d523365SDimitry Andric     LandingPadInliningInfo(InvokeInst *II)
1202cab237bSDimitry Andric         : OuterResumeDest(II->getUnwindDest()) {
1216122f3e6SDimitry Andric       // If there are PHI nodes in the unwind destination block, we need to keep
1226122f3e6SDimitry Andric       // track of which values came into them from the invoke before removing
1236122f3e6SDimitry Andric       // the edge from this block.
1242cab237bSDimitry Andric       BasicBlock *InvokeBB = II->getParent();
125dff0c46cSDimitry Andric       BasicBlock::iterator I = OuterResumeDest->begin();
1266122f3e6SDimitry Andric       for (; isa<PHINode>(I); ++I) {
127bd5abe19SDimitry Andric         // Save the value to use for this edge.
1286122f3e6SDimitry Andric         PHINode *PHI = cast<PHINode>(I);
1296122f3e6SDimitry Andric         UnwindDestPHIValues.push_back(PHI->getIncomingValueForBlock(InvokeBB));
1306122f3e6SDimitry Andric       }
1316122f3e6SDimitry Andric 
132dff0c46cSDimitry Andric       CallerLPad = cast<LandingPadInst>(I);
133bd5abe19SDimitry Andric     }
134bd5abe19SDimitry Andric 
135ff0cc061SDimitry Andric     /// The outer unwind destination is the target of
136dff0c46cSDimitry Andric     /// unwind edges introduced for calls within the inlined function.
getOuterResumeDest() const137dff0c46cSDimitry Andric     BasicBlock *getOuterResumeDest() const {
138dff0c46cSDimitry Andric       return OuterResumeDest;
139bd5abe19SDimitry Andric     }
140bd5abe19SDimitry Andric 
141dff0c46cSDimitry Andric     BasicBlock *getInnerResumeDest();
1426122f3e6SDimitry Andric 
getLandingPadInst() const1436122f3e6SDimitry Andric     LandingPadInst *getLandingPadInst() const { return CallerLPad; }
1446122f3e6SDimitry Andric 
145ff0cc061SDimitry Andric     /// Forward the 'resume' instruction to the caller's landing pad block.
146ff0cc061SDimitry Andric     /// When the landing pad block has only one predecessor, this is
1476122f3e6SDimitry Andric     /// a simple branch. When there is more than one predecessor, we need to
1486122f3e6SDimitry Andric     /// split the landing pad block after the landingpad instruction and jump
1496122f3e6SDimitry Andric     /// to there.
150139f7f9bSDimitry Andric     void forwardResume(ResumeInst *RI,
15139d628a0SDimitry Andric                        SmallPtrSetImpl<LandingPadInst*> &InlinedLPads);
1526122f3e6SDimitry Andric 
153ff0cc061SDimitry Andric     /// Add incoming-PHI values to the unwind destination block for the given
154ff0cc061SDimitry Andric     /// basic block, using the values for the original invoke's source block.
addIncomingPHIValuesFor(BasicBlock * BB) const155bd5abe19SDimitry Andric     void addIncomingPHIValuesFor(BasicBlock *BB) const {
156dff0c46cSDimitry Andric       addIncomingPHIValuesForInto(BB, OuterResumeDest);
157bd5abe19SDimitry Andric     }
158bd5abe19SDimitry Andric 
addIncomingPHIValuesForInto(BasicBlock * src,BasicBlock * dest) const159bd5abe19SDimitry Andric     void addIncomingPHIValuesForInto(BasicBlock *src, BasicBlock *dest) const {
160bd5abe19SDimitry Andric       BasicBlock::iterator I = dest->begin();
161bd5abe19SDimitry Andric       for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
162bd5abe19SDimitry Andric         PHINode *phi = cast<PHINode>(I);
163bd5abe19SDimitry Andric         phi->addIncoming(UnwindDestPHIValues[i], src);
164bd5abe19SDimitry Andric       }
165bd5abe19SDimitry Andric     }
166bd5abe19SDimitry Andric   };
1672cab237bSDimitry Andric 
1682cab237bSDimitry Andric } // end anonymous namespace
169bd5abe19SDimitry Andric 
170ff0cc061SDimitry Andric /// Get or create a target for the branch from ResumeInsts.
getInnerResumeDest()1717d523365SDimitry Andric BasicBlock *LandingPadInliningInfo::getInnerResumeDest() {
1726122f3e6SDimitry Andric   if (InnerResumeDest) return InnerResumeDest;
1736122f3e6SDimitry Andric 
1746122f3e6SDimitry Andric   // Split the landing pad.
1757d523365SDimitry Andric   BasicBlock::iterator SplitPoint = ++CallerLPad->getIterator();
1766122f3e6SDimitry Andric   InnerResumeDest =
1776122f3e6SDimitry Andric     OuterResumeDest->splitBasicBlock(SplitPoint,
1786122f3e6SDimitry Andric                                      OuterResumeDest->getName() + ".body");
1796122f3e6SDimitry Andric 
1806122f3e6SDimitry Andric   // The number of incoming edges we expect to the inner landing pad.
1816122f3e6SDimitry Andric   const unsigned PHICapacity = 2;
1826122f3e6SDimitry Andric 
1836122f3e6SDimitry Andric   // Create corresponding new PHIs for all the PHIs in the outer landing pad.
1847d523365SDimitry Andric   Instruction *InsertPoint = &InnerResumeDest->front();
1856122f3e6SDimitry Andric   BasicBlock::iterator I = OuterResumeDest->begin();
1866122f3e6SDimitry Andric   for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
1876122f3e6SDimitry Andric     PHINode *OuterPHI = cast<PHINode>(I);
1886122f3e6SDimitry Andric     PHINode *InnerPHI = PHINode::Create(OuterPHI->getType(), PHICapacity,
1896122f3e6SDimitry Andric                                         OuterPHI->getName() + ".lpad-body",
1906122f3e6SDimitry Andric                                         InsertPoint);
1916122f3e6SDimitry Andric     OuterPHI->replaceAllUsesWith(InnerPHI);
1926122f3e6SDimitry Andric     InnerPHI->addIncoming(OuterPHI, OuterResumeDest);
1936122f3e6SDimitry Andric   }
1946122f3e6SDimitry Andric 
1956122f3e6SDimitry Andric   // Create a PHI for the exception values.
1966122f3e6SDimitry Andric   InnerEHValuesPHI = PHINode::Create(CallerLPad->getType(), PHICapacity,
1976122f3e6SDimitry Andric                                      "eh.lpad-body", InsertPoint);
1986122f3e6SDimitry Andric   CallerLPad->replaceAllUsesWith(InnerEHValuesPHI);
1996122f3e6SDimitry Andric   InnerEHValuesPHI->addIncoming(CallerLPad, OuterResumeDest);
2006122f3e6SDimitry Andric 
2016122f3e6SDimitry Andric   // All done.
2026122f3e6SDimitry Andric   return InnerResumeDest;
2036122f3e6SDimitry Andric }
2046122f3e6SDimitry Andric 
205ff0cc061SDimitry Andric /// Forward the 'resume' instruction to the caller's landing pad block.
206ff0cc061SDimitry Andric /// When the landing pad block has only one predecessor, this is a simple
2076122f3e6SDimitry Andric /// branch. When there is more than one predecessor, we need to split the
2086122f3e6SDimitry Andric /// landing pad block after the landingpad instruction and jump to there.
forwardResume(ResumeInst * RI,SmallPtrSetImpl<LandingPadInst * > & InlinedLPads)2097d523365SDimitry Andric void LandingPadInliningInfo::forwardResume(
2107d523365SDimitry Andric     ResumeInst *RI, SmallPtrSetImpl<LandingPadInst *> &InlinedLPads) {
211dff0c46cSDimitry Andric   BasicBlock *Dest = getInnerResumeDest();
2126122f3e6SDimitry Andric   BasicBlock *Src = RI->getParent();
2136122f3e6SDimitry Andric 
2146122f3e6SDimitry Andric   BranchInst::Create(Dest, Src);
2156122f3e6SDimitry Andric 
2166122f3e6SDimitry Andric   // Update the PHIs in the destination. They were inserted in an order which
2176122f3e6SDimitry Andric   // makes this work.
2186122f3e6SDimitry Andric   addIncomingPHIValuesForInto(Src, Dest);
2196122f3e6SDimitry Andric 
2206122f3e6SDimitry Andric   InnerEHValuesPHI->addIncoming(RI->getOperand(0), Src);
2216122f3e6SDimitry Andric   RI->eraseFromParent();
2226122f3e6SDimitry Andric }
2236122f3e6SDimitry Andric 
2248c24ff90SDimitry Andric /// Helper for getUnwindDestToken/getUnwindDestTokenHelper.
getParentPad(Value * EHPad)2258c24ff90SDimitry Andric static Value *getParentPad(Value *EHPad) {
2268c24ff90SDimitry Andric   if (auto *FPI = dyn_cast<FuncletPadInst>(EHPad))
2278c24ff90SDimitry Andric     return FPI->getParentPad();
2288c24ff90SDimitry Andric   return cast<CatchSwitchInst>(EHPad)->getParentPad();
2298c24ff90SDimitry Andric }
2308c24ff90SDimitry Andric 
2312cab237bSDimitry Andric using UnwindDestMemoTy = DenseMap<Instruction *, Value *>;
2328c24ff90SDimitry Andric 
2338c24ff90SDimitry Andric /// Helper for getUnwindDestToken that does the descendant-ward part of
2348c24ff90SDimitry Andric /// the search.
getUnwindDestTokenHelper(Instruction * EHPad,UnwindDestMemoTy & MemoMap)2358c24ff90SDimitry Andric static Value *getUnwindDestTokenHelper(Instruction *EHPad,
2368c24ff90SDimitry Andric                                        UnwindDestMemoTy &MemoMap) {
2378c24ff90SDimitry Andric   SmallVector<Instruction *, 8> Worklist(1, EHPad);
2388c24ff90SDimitry Andric 
2398c24ff90SDimitry Andric   while (!Worklist.empty()) {
2408c24ff90SDimitry Andric     Instruction *CurrentPad = Worklist.pop_back_val();
2418c24ff90SDimitry Andric     // We only put pads on the worklist that aren't in the MemoMap.  When
2428c24ff90SDimitry Andric     // we find an unwind dest for a pad we may update its ancestors, but
2438c24ff90SDimitry Andric     // the queue only ever contains uncles/great-uncles/etc. of CurrentPad,
2448c24ff90SDimitry Andric     // so they should never get updated while queued on the worklist.
2458c24ff90SDimitry Andric     assert(!MemoMap.count(CurrentPad));
2468c24ff90SDimitry Andric     Value *UnwindDestToken = nullptr;
2478c24ff90SDimitry Andric     if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(CurrentPad)) {
2488c24ff90SDimitry Andric       if (CatchSwitch->hasUnwindDest()) {
2498c24ff90SDimitry Andric         UnwindDestToken = CatchSwitch->getUnwindDest()->getFirstNonPHI();
2508c24ff90SDimitry Andric       } else {
2518c24ff90SDimitry Andric         // Catchswitch doesn't have a 'nounwind' variant, and one might be
2528c24ff90SDimitry Andric         // annotated as "unwinds to caller" when really it's nounwind (see
2538c24ff90SDimitry Andric         // e.g. SimplifyCFGOpt::SimplifyUnreachable), so we can't infer the
2548c24ff90SDimitry Andric         // parent's unwind dest from this.  We can check its catchpads'
2558c24ff90SDimitry Andric         // descendants, since they might include a cleanuppad with an
2568c24ff90SDimitry Andric         // "unwinds to caller" cleanupret, which can be trusted.
2578c24ff90SDimitry Andric         for (auto HI = CatchSwitch->handler_begin(),
2588c24ff90SDimitry Andric                   HE = CatchSwitch->handler_end();
2598c24ff90SDimitry Andric              HI != HE && !UnwindDestToken; ++HI) {
2608c24ff90SDimitry Andric           BasicBlock *HandlerBlock = *HI;
2618c24ff90SDimitry Andric           auto *CatchPad = cast<CatchPadInst>(HandlerBlock->getFirstNonPHI());
2628c24ff90SDimitry Andric           for (User *Child : CatchPad->users()) {
2638c24ff90SDimitry Andric             // Intentionally ignore invokes here -- since the catchswitch is
2648c24ff90SDimitry Andric             // marked "unwind to caller", it would be a verifier error if it
2658c24ff90SDimitry Andric             // contained an invoke which unwinds out of it, so any invoke we'd
2668c24ff90SDimitry Andric             // encounter must unwind to some child of the catch.
2678c24ff90SDimitry Andric             if (!isa<CleanupPadInst>(Child) && !isa<CatchSwitchInst>(Child))
2688c24ff90SDimitry Andric               continue;
2698c24ff90SDimitry Andric 
2708c24ff90SDimitry Andric             Instruction *ChildPad = cast<Instruction>(Child);
2718c24ff90SDimitry Andric             auto Memo = MemoMap.find(ChildPad);
2728c24ff90SDimitry Andric             if (Memo == MemoMap.end()) {
273d88c1a5aSDimitry Andric               // Haven't figured out this child pad yet; queue it.
2748c24ff90SDimitry Andric               Worklist.push_back(ChildPad);
2758c24ff90SDimitry Andric               continue;
2768c24ff90SDimitry Andric             }
2778c24ff90SDimitry Andric             // We've already checked this child, but might have found that
2788c24ff90SDimitry Andric             // it offers no proof either way.
2798c24ff90SDimitry Andric             Value *ChildUnwindDestToken = Memo->second;
2808c24ff90SDimitry Andric             if (!ChildUnwindDestToken)
2818c24ff90SDimitry Andric               continue;
2828c24ff90SDimitry Andric             // We already know the child's unwind dest, which can either
2838c24ff90SDimitry Andric             // be ConstantTokenNone to indicate unwind to caller, or can
2848c24ff90SDimitry Andric             // be another child of the catchpad.  Only the former indicates
2858c24ff90SDimitry Andric             // the unwind dest of the catchswitch.
2868c24ff90SDimitry Andric             if (isa<ConstantTokenNone>(ChildUnwindDestToken)) {
2878c24ff90SDimitry Andric               UnwindDestToken = ChildUnwindDestToken;
2888c24ff90SDimitry Andric               break;
2898c24ff90SDimitry Andric             }
2908c24ff90SDimitry Andric             assert(getParentPad(ChildUnwindDestToken) == CatchPad);
2918c24ff90SDimitry Andric           }
2928c24ff90SDimitry Andric         }
2938c24ff90SDimitry Andric       }
2948c24ff90SDimitry Andric     } else {
2958c24ff90SDimitry Andric       auto *CleanupPad = cast<CleanupPadInst>(CurrentPad);
2968c24ff90SDimitry Andric       for (User *U : CleanupPad->users()) {
2978c24ff90SDimitry Andric         if (auto *CleanupRet = dyn_cast<CleanupReturnInst>(U)) {
2988c24ff90SDimitry Andric           if (BasicBlock *RetUnwindDest = CleanupRet->getUnwindDest())
2998c24ff90SDimitry Andric             UnwindDestToken = RetUnwindDest->getFirstNonPHI();
3008c24ff90SDimitry Andric           else
3018c24ff90SDimitry Andric             UnwindDestToken = ConstantTokenNone::get(CleanupPad->getContext());
3028c24ff90SDimitry Andric           break;
3038c24ff90SDimitry Andric         }
3048c24ff90SDimitry Andric         Value *ChildUnwindDestToken;
3058c24ff90SDimitry Andric         if (auto *Invoke = dyn_cast<InvokeInst>(U)) {
3068c24ff90SDimitry Andric           ChildUnwindDestToken = Invoke->getUnwindDest()->getFirstNonPHI();
3078c24ff90SDimitry Andric         } else if (isa<CleanupPadInst>(U) || isa<CatchSwitchInst>(U)) {
3088c24ff90SDimitry Andric           Instruction *ChildPad = cast<Instruction>(U);
3098c24ff90SDimitry Andric           auto Memo = MemoMap.find(ChildPad);
3108c24ff90SDimitry Andric           if (Memo == MemoMap.end()) {
3118c24ff90SDimitry Andric             // Haven't resolved this child yet; queue it and keep searching.
3128c24ff90SDimitry Andric             Worklist.push_back(ChildPad);
3138c24ff90SDimitry Andric             continue;
3148c24ff90SDimitry Andric           }
3158c24ff90SDimitry Andric           // We've checked this child, but still need to ignore it if it
3168c24ff90SDimitry Andric           // had no proof either way.
3178c24ff90SDimitry Andric           ChildUnwindDestToken = Memo->second;
3188c24ff90SDimitry Andric           if (!ChildUnwindDestToken)
3198c24ff90SDimitry Andric             continue;
3208c24ff90SDimitry Andric         } else {
3218c24ff90SDimitry Andric           // Not a relevant user of the cleanuppad
3228c24ff90SDimitry Andric           continue;
3238c24ff90SDimitry Andric         }
3248c24ff90SDimitry Andric         // In a well-formed program, the child/invoke must either unwind to
3258c24ff90SDimitry Andric         // an(other) child of the cleanup, or exit the cleanup.  In the
3268c24ff90SDimitry Andric         // first case, continue searching.
3278c24ff90SDimitry Andric         if (isa<Instruction>(ChildUnwindDestToken) &&
3288c24ff90SDimitry Andric             getParentPad(ChildUnwindDestToken) == CleanupPad)
3298c24ff90SDimitry Andric           continue;
3308c24ff90SDimitry Andric         UnwindDestToken = ChildUnwindDestToken;
3318c24ff90SDimitry Andric         break;
3328c24ff90SDimitry Andric       }
3338c24ff90SDimitry Andric     }
3348c24ff90SDimitry Andric     // If we haven't found an unwind dest for CurrentPad, we may have queued its
3358c24ff90SDimitry Andric     // children, so move on to the next in the worklist.
3368c24ff90SDimitry Andric     if (!UnwindDestToken)
3378c24ff90SDimitry Andric       continue;
3388c24ff90SDimitry Andric 
3398c24ff90SDimitry Andric     // Now we know that CurrentPad unwinds to UnwindDestToken.  It also exits
3408c24ff90SDimitry Andric     // any ancestors of CurrentPad up to but not including UnwindDestToken's
3418c24ff90SDimitry Andric     // parent pad.  Record this in the memo map, and check to see if the
3428c24ff90SDimitry Andric     // original EHPad being queried is one of the ones exited.
3438c24ff90SDimitry Andric     Value *UnwindParent;
3448c24ff90SDimitry Andric     if (auto *UnwindPad = dyn_cast<Instruction>(UnwindDestToken))
3458c24ff90SDimitry Andric       UnwindParent = getParentPad(UnwindPad);
3468c24ff90SDimitry Andric     else
3478c24ff90SDimitry Andric       UnwindParent = nullptr;
3488c24ff90SDimitry Andric     bool ExitedOriginalPad = false;
3498c24ff90SDimitry Andric     for (Instruction *ExitedPad = CurrentPad;
3508c24ff90SDimitry Andric          ExitedPad && ExitedPad != UnwindParent;
3518c24ff90SDimitry Andric          ExitedPad = dyn_cast<Instruction>(getParentPad(ExitedPad))) {
3528c24ff90SDimitry Andric       // Skip over catchpads since they just follow their catchswitches.
3538c24ff90SDimitry Andric       if (isa<CatchPadInst>(ExitedPad))
3548c24ff90SDimitry Andric         continue;
3558c24ff90SDimitry Andric       MemoMap[ExitedPad] = UnwindDestToken;
3568c24ff90SDimitry Andric       ExitedOriginalPad |= (ExitedPad == EHPad);
3578c24ff90SDimitry Andric     }
3588c24ff90SDimitry Andric 
3598c24ff90SDimitry Andric     if (ExitedOriginalPad)
3608c24ff90SDimitry Andric       return UnwindDestToken;
3618c24ff90SDimitry Andric 
3628c24ff90SDimitry Andric     // Continue the search.
3638c24ff90SDimitry Andric   }
3648c24ff90SDimitry Andric 
3658c24ff90SDimitry Andric   // No definitive information is contained within this funclet.
3668c24ff90SDimitry Andric   return nullptr;
3678c24ff90SDimitry Andric }
3688c24ff90SDimitry Andric 
3698c24ff90SDimitry Andric /// Given an EH pad, find where it unwinds.  If it unwinds to an EH pad,
3708c24ff90SDimitry Andric /// return that pad instruction.  If it unwinds to caller, return
3718c24ff90SDimitry Andric /// ConstantTokenNone.  If it does not have a definitive unwind destination,
3728c24ff90SDimitry Andric /// return nullptr.
3738c24ff90SDimitry Andric ///
3748c24ff90SDimitry Andric /// This routine gets invoked for calls in funclets in inlinees when inlining
3758c24ff90SDimitry Andric /// an invoke.  Since many funclets don't have calls inside them, it's queried
3768c24ff90SDimitry Andric /// on-demand rather than building a map of pads to unwind dests up front.
3778c24ff90SDimitry Andric /// Determining a funclet's unwind dest may require recursively searching its
3788c24ff90SDimitry Andric /// descendants, and also ancestors and cousins if the descendants don't provide
3798c24ff90SDimitry Andric /// an answer.  Since most funclets will have their unwind dest immediately
3808c24ff90SDimitry Andric /// available as the unwind dest of a catchswitch or cleanupret, this routine
3818c24ff90SDimitry Andric /// searches top-down from the given pad and then up. To avoid worst-case
3828c24ff90SDimitry Andric /// quadratic run-time given that approach, it uses a memo map to avoid
3838c24ff90SDimitry Andric /// re-processing funclet trees.  The callers that rewrite the IR as they go
3848c24ff90SDimitry Andric /// take advantage of this, for correctness, by checking/forcing rewritten
3858c24ff90SDimitry Andric /// pads' entries to match the original callee view.
getUnwindDestToken(Instruction * EHPad,UnwindDestMemoTy & MemoMap)3868c24ff90SDimitry Andric static Value *getUnwindDestToken(Instruction *EHPad,
3878c24ff90SDimitry Andric                                  UnwindDestMemoTy &MemoMap) {
3888c24ff90SDimitry Andric   // Catchpads unwind to the same place as their catchswitch;
3898c24ff90SDimitry Andric   // redirct any queries on catchpads so the code below can
3908c24ff90SDimitry Andric   // deal with just catchswitches and cleanuppads.
3918c24ff90SDimitry Andric   if (auto *CPI = dyn_cast<CatchPadInst>(EHPad))
3928c24ff90SDimitry Andric     EHPad = CPI->getCatchSwitch();
3938c24ff90SDimitry Andric 
3948c24ff90SDimitry Andric   // Check if we've already determined the unwind dest for this pad.
3958c24ff90SDimitry Andric   auto Memo = MemoMap.find(EHPad);
3968c24ff90SDimitry Andric   if (Memo != MemoMap.end())
3978c24ff90SDimitry Andric     return Memo->second;
3988c24ff90SDimitry Andric 
3998c24ff90SDimitry Andric   // Search EHPad and, if necessary, its descendants.
4008c24ff90SDimitry Andric   Value *UnwindDestToken = getUnwindDestTokenHelper(EHPad, MemoMap);
4018c24ff90SDimitry Andric   assert((UnwindDestToken == nullptr) != (MemoMap.count(EHPad) != 0));
4028c24ff90SDimitry Andric   if (UnwindDestToken)
4038c24ff90SDimitry Andric     return UnwindDestToken;
4048c24ff90SDimitry Andric 
4058c24ff90SDimitry Andric   // No information is available for this EHPad from itself or any of its
4068c24ff90SDimitry Andric   // descendants.  An unwind all the way out to a pad in the caller would
4078c24ff90SDimitry Andric   // need also to agree with the unwind dest of the parent funclet, so
4088c24ff90SDimitry Andric   // search up the chain to try to find a funclet with information.  Put
4098c24ff90SDimitry Andric   // null entries in the memo map to avoid re-processing as we go up.
4108c24ff90SDimitry Andric   MemoMap[EHPad] = nullptr;
411d88c1a5aSDimitry Andric #ifndef NDEBUG
412d88c1a5aSDimitry Andric   SmallPtrSet<Instruction *, 4> TempMemos;
413d88c1a5aSDimitry Andric   TempMemos.insert(EHPad);
414d88c1a5aSDimitry Andric #endif
4158c24ff90SDimitry Andric   Instruction *LastUselessPad = EHPad;
4168c24ff90SDimitry Andric   Value *AncestorToken;
4178c24ff90SDimitry Andric   for (AncestorToken = getParentPad(EHPad);
4188c24ff90SDimitry Andric        auto *AncestorPad = dyn_cast<Instruction>(AncestorToken);
4198c24ff90SDimitry Andric        AncestorToken = getParentPad(AncestorToken)) {
4208c24ff90SDimitry Andric     // Skip over catchpads since they just follow their catchswitches.
4218c24ff90SDimitry Andric     if (isa<CatchPadInst>(AncestorPad))
4228c24ff90SDimitry Andric       continue;
423d88c1a5aSDimitry Andric     // If the MemoMap had an entry mapping AncestorPad to nullptr, since we
424d88c1a5aSDimitry Andric     // haven't yet called getUnwindDestTokenHelper for AncestorPad in this
425d88c1a5aSDimitry Andric     // call to getUnwindDestToken, that would mean that AncestorPad had no
426d88c1a5aSDimitry Andric     // information in itself, its descendants, or its ancestors.  If that
427d88c1a5aSDimitry Andric     // were the case, then we should also have recorded the lack of information
428d88c1a5aSDimitry Andric     // for the descendant that we're coming from.  So assert that we don't
429d88c1a5aSDimitry Andric     // find a null entry in the MemoMap for AncestorPad.
4308c24ff90SDimitry Andric     assert(!MemoMap.count(AncestorPad) || MemoMap[AncestorPad]);
4318c24ff90SDimitry Andric     auto AncestorMemo = MemoMap.find(AncestorPad);
4328c24ff90SDimitry Andric     if (AncestorMemo == MemoMap.end()) {
4338c24ff90SDimitry Andric       UnwindDestToken = getUnwindDestTokenHelper(AncestorPad, MemoMap);
4348c24ff90SDimitry Andric     } else {
4358c24ff90SDimitry Andric       UnwindDestToken = AncestorMemo->second;
4368c24ff90SDimitry Andric     }
4378c24ff90SDimitry Andric     if (UnwindDestToken)
4388c24ff90SDimitry Andric       break;
4398c24ff90SDimitry Andric     LastUselessPad = AncestorPad;
440d88c1a5aSDimitry Andric     MemoMap[LastUselessPad] = nullptr;
441d88c1a5aSDimitry Andric #ifndef NDEBUG
442d88c1a5aSDimitry Andric     TempMemos.insert(LastUselessPad);
443d88c1a5aSDimitry Andric #endif
4448c24ff90SDimitry Andric   }
4458c24ff90SDimitry Andric 
446d88c1a5aSDimitry Andric   // We know that getUnwindDestTokenHelper was called on LastUselessPad and
447d88c1a5aSDimitry Andric   // returned nullptr (and likewise for EHPad and any of its ancestors up to
448d88c1a5aSDimitry Andric   // LastUselessPad), so LastUselessPad has no information from below.  Since
449d88c1a5aSDimitry Andric   // getUnwindDestTokenHelper must investigate all downward paths through
450d88c1a5aSDimitry Andric   // no-information nodes to prove that a node has no information like this,
451d88c1a5aSDimitry Andric   // and since any time it finds information it records it in the MemoMap for
452d88c1a5aSDimitry Andric   // not just the immediately-containing funclet but also any ancestors also
453d88c1a5aSDimitry Andric   // exited, it must be the case that, walking downward from LastUselessPad,
454d88c1a5aSDimitry Andric   // visiting just those nodes which have not been mapped to an unwind dest
455d88c1a5aSDimitry Andric   // by getUnwindDestTokenHelper (the nullptr TempMemos notwithstanding, since
456d88c1a5aSDimitry Andric   // they are just used to keep getUnwindDestTokenHelper from repeating work),
457d88c1a5aSDimitry Andric   // any node visited must have been exhaustively searched with no information
458d88c1a5aSDimitry Andric   // for it found.
4598c24ff90SDimitry Andric   SmallVector<Instruction *, 8> Worklist(1, LastUselessPad);
4608c24ff90SDimitry Andric   while (!Worklist.empty()) {
4618c24ff90SDimitry Andric     Instruction *UselessPad = Worklist.pop_back_val();
462d88c1a5aSDimitry Andric     auto Memo = MemoMap.find(UselessPad);
463d88c1a5aSDimitry Andric     if (Memo != MemoMap.end() && Memo->second) {
464d88c1a5aSDimitry Andric       // Here the name 'UselessPad' is a bit of a misnomer, because we've found
465d88c1a5aSDimitry Andric       // that it is a funclet that does have information about unwinding to
466d88c1a5aSDimitry Andric       // a particular destination; its parent was a useless pad.
467d88c1a5aSDimitry Andric       // Since its parent has no information, the unwind edge must not escape
468d88c1a5aSDimitry Andric       // the parent, and must target a sibling of this pad.  This local unwind
469d88c1a5aSDimitry Andric       // gives us no information about EHPad.  Leave it and the subtree rooted
470d88c1a5aSDimitry Andric       // at it alone.
471d88c1a5aSDimitry Andric       assert(getParentPad(Memo->second) == getParentPad(UselessPad));
472d88c1a5aSDimitry Andric       continue;
473d88c1a5aSDimitry Andric     }
474d88c1a5aSDimitry Andric     // We know we don't have information for UselesPad.  If it has an entry in
475d88c1a5aSDimitry Andric     // the MemoMap (mapping it to nullptr), it must be one of the TempMemos
476d88c1a5aSDimitry Andric     // added on this invocation of getUnwindDestToken; if a previous invocation
477d88c1a5aSDimitry Andric     // recorded nullptr, it would have had to prove that the ancestors of
478d88c1a5aSDimitry Andric     // UselessPad, which include LastUselessPad, had no information, and that
479d88c1a5aSDimitry Andric     // in turn would have required proving that the descendants of
480d88c1a5aSDimitry Andric     // LastUselesPad, which include EHPad, have no information about
481d88c1a5aSDimitry Andric     // LastUselessPad, which would imply that EHPad was mapped to nullptr in
482d88c1a5aSDimitry Andric     // the MemoMap on that invocation, which isn't the case if we got here.
483d88c1a5aSDimitry Andric     assert(!MemoMap.count(UselessPad) || TempMemos.count(UselessPad));
484d88c1a5aSDimitry Andric     // Assert as we enumerate users that 'UselessPad' doesn't have any unwind
485d88c1a5aSDimitry Andric     // information that we'd be contradicting by making a map entry for it
486d88c1a5aSDimitry Andric     // (which is something that getUnwindDestTokenHelper must have proved for
487d88c1a5aSDimitry Andric     // us to get here).  Just assert on is direct users here; the checks in
488d88c1a5aSDimitry Andric     // this downward walk at its descendants will verify that they don't have
489d88c1a5aSDimitry Andric     // any unwind edges that exit 'UselessPad' either (i.e. they either have no
490d88c1a5aSDimitry Andric     // unwind edges or unwind to a sibling).
4918c24ff90SDimitry Andric     MemoMap[UselessPad] = UnwindDestToken;
4928c24ff90SDimitry Andric     if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(UselessPad)) {
493d88c1a5aSDimitry Andric       assert(CatchSwitch->getUnwindDest() == nullptr && "Expected useless pad");
494d88c1a5aSDimitry Andric       for (BasicBlock *HandlerBlock : CatchSwitch->handlers()) {
495d88c1a5aSDimitry Andric         auto *CatchPad = HandlerBlock->getFirstNonPHI();
496d88c1a5aSDimitry Andric         for (User *U : CatchPad->users()) {
497d88c1a5aSDimitry Andric           assert(
498d88c1a5aSDimitry Andric               (!isa<InvokeInst>(U) ||
499d88c1a5aSDimitry Andric                (getParentPad(
500d88c1a5aSDimitry Andric                     cast<InvokeInst>(U)->getUnwindDest()->getFirstNonPHI()) ==
501d88c1a5aSDimitry Andric                 CatchPad)) &&
502d88c1a5aSDimitry Andric               "Expected useless pad");
5038c24ff90SDimitry Andric           if (isa<CatchSwitchInst>(U) || isa<CleanupPadInst>(U))
5048c24ff90SDimitry Andric             Worklist.push_back(cast<Instruction>(U));
505d88c1a5aSDimitry Andric         }
506d88c1a5aSDimitry Andric       }
5078c24ff90SDimitry Andric     } else {
5088c24ff90SDimitry Andric       assert(isa<CleanupPadInst>(UselessPad));
509d88c1a5aSDimitry Andric       for (User *U : UselessPad->users()) {
510d88c1a5aSDimitry Andric         assert(!isa<CleanupReturnInst>(U) && "Expected useless pad");
511d88c1a5aSDimitry Andric         assert((!isa<InvokeInst>(U) ||
512d88c1a5aSDimitry Andric                 (getParentPad(
513d88c1a5aSDimitry Andric                      cast<InvokeInst>(U)->getUnwindDest()->getFirstNonPHI()) ==
514d88c1a5aSDimitry Andric                  UselessPad)) &&
515d88c1a5aSDimitry Andric                "Expected useless pad");
5168c24ff90SDimitry Andric         if (isa<CatchSwitchInst>(U) || isa<CleanupPadInst>(U))
5178c24ff90SDimitry Andric           Worklist.push_back(cast<Instruction>(U));
5188c24ff90SDimitry Andric       }
5198c24ff90SDimitry Andric     }
520d88c1a5aSDimitry Andric   }
5218c24ff90SDimitry Andric 
5228c24ff90SDimitry Andric   return UnwindDestToken;
5238c24ff90SDimitry Andric }
5248c24ff90SDimitry Andric 
525ff0cc061SDimitry Andric /// When we inline a basic block into an invoke,
526ff0cc061SDimitry Andric /// we have to turn all of the calls that can throw into invokes.
527ff0cc061SDimitry Andric /// This function analyze BB to see if there are any calls, and if so,
528f22ef01cSRoman Divacky /// it rewrites them to be invokes that jump to InvokeDest and fills in the PHI
529f22ef01cSRoman Divacky /// nodes in that block with the values specified in InvokeDestPHIValues.
HandleCallsInBlockInlinedThroughInvoke(BasicBlock * BB,BasicBlock * UnwindEdge,UnwindDestMemoTy * FuncletUnwindMap=nullptr)5308c24ff90SDimitry Andric static BasicBlock *HandleCallsInBlockInlinedThroughInvoke(
5318c24ff90SDimitry Andric     BasicBlock *BB, BasicBlock *UnwindEdge,
5328c24ff90SDimitry Andric     UnwindDestMemoTy *FuncletUnwindMap = nullptr) {
533f22ef01cSRoman Divacky   for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
5347d523365SDimitry Andric     Instruction *I = &*BBI++;
535f22ef01cSRoman Divacky 
536f22ef01cSRoman Divacky     // We only need to check for function calls: inlined invoke
537f22ef01cSRoman Divacky     // instructions require no special handling.
538f22ef01cSRoman Divacky     CallInst *CI = dyn_cast<CallInst>(I);
539bd5abe19SDimitry Andric 
540f785676fSDimitry Andric     if (!CI || CI->doesNotThrow() || isa<InlineAsm>(CI->getCalledValue()))
541f22ef01cSRoman Divacky       continue;
542f22ef01cSRoman Divacky 
5433ca95b02SDimitry Andric     // We do not need to (and in fact, cannot) convert possibly throwing calls
5443ca95b02SDimitry Andric     // to @llvm.experimental_deoptimize (resp. @llvm.experimental.guard) into
5453ca95b02SDimitry Andric     // invokes.  The caller's "segment" of the deoptimization continuation
5463ca95b02SDimitry Andric     // attached to the newly inlined @llvm.experimental_deoptimize
5473ca95b02SDimitry Andric     // (resp. @llvm.experimental.guard) call should contain the exception
5483ca95b02SDimitry Andric     // handling logic, if any.
5493ca95b02SDimitry Andric     if (auto *F = CI->getCalledFunction())
5503ca95b02SDimitry Andric       if (F->getIntrinsicID() == Intrinsic::experimental_deoptimize ||
5513ca95b02SDimitry Andric           F->getIntrinsicID() == Intrinsic::experimental_guard)
5523ca95b02SDimitry Andric         continue;
5533ca95b02SDimitry Andric 
5548c24ff90SDimitry Andric     if (auto FuncletBundle = CI->getOperandBundle(LLVMContext::OB_funclet)) {
5558c24ff90SDimitry Andric       // This call is nested inside a funclet.  If that funclet has an unwind
5568c24ff90SDimitry Andric       // destination within the inlinee, then unwinding out of this call would
5578c24ff90SDimitry Andric       // be UB.  Rewriting this call to an invoke which targets the inlined
5588c24ff90SDimitry Andric       // invoke's unwind dest would give the call's parent funclet multiple
5598c24ff90SDimitry Andric       // unwind destinations, which is something that subsequent EH table
5608c24ff90SDimitry Andric       // generation can't handle and that the veirifer rejects.  So when we
5618c24ff90SDimitry Andric       // see such a call, leave it as a call.
5628c24ff90SDimitry Andric       auto *FuncletPad = cast<Instruction>(FuncletBundle->Inputs[0]);
5638c24ff90SDimitry Andric       Value *UnwindDestToken =
5648c24ff90SDimitry Andric           getUnwindDestToken(FuncletPad, *FuncletUnwindMap);
5658c24ff90SDimitry Andric       if (UnwindDestToken && !isa<ConstantTokenNone>(UnwindDestToken))
5668c24ff90SDimitry Andric         continue;
5678c24ff90SDimitry Andric #ifndef NDEBUG
5688c24ff90SDimitry Andric       Instruction *MemoKey;
5698c24ff90SDimitry Andric       if (auto *CatchPad = dyn_cast<CatchPadInst>(FuncletPad))
5708c24ff90SDimitry Andric         MemoKey = CatchPad->getCatchSwitch();
5718c24ff90SDimitry Andric       else
5728c24ff90SDimitry Andric         MemoKey = FuncletPad;
5738c24ff90SDimitry Andric       assert(FuncletUnwindMap->count(MemoKey) &&
5748c24ff90SDimitry Andric              (*FuncletUnwindMap)[MemoKey] == UnwindDestToken &&
5758c24ff90SDimitry Andric              "must get memoized to avoid confusing later searches");
5768c24ff90SDimitry Andric #endif // NDEBUG
5778c24ff90SDimitry Andric     }
5788c24ff90SDimitry Andric 
579d88c1a5aSDimitry Andric     changeToInvokeAndSplitBasicBlock(CI, UnwindEdge);
5807d523365SDimitry Andric     return BB;
581f22ef01cSRoman Divacky   }
5827d523365SDimitry Andric   return nullptr;
583f22ef01cSRoman Divacky }
584f22ef01cSRoman Divacky 
585ff0cc061SDimitry Andric /// If we inlined an invoke site, we need to convert calls
586dff0c46cSDimitry Andric /// in the body of the inlined function into invokes.
587f22ef01cSRoman Divacky ///
588f22ef01cSRoman Divacky /// II is the invoke instruction being inlined.  FirstNewBlock is the first
589f22ef01cSRoman Divacky /// block of the inlined code (the last block is the end of the function),
590f22ef01cSRoman Divacky /// and InlineCodeInfo is information about the code that got inlined.
HandleInlinedLandingPad(InvokeInst * II,BasicBlock * FirstNewBlock,ClonedCodeInfo & InlinedCodeInfo)5917d523365SDimitry Andric static void HandleInlinedLandingPad(InvokeInst *II, BasicBlock *FirstNewBlock,
592f22ef01cSRoman Divacky                                     ClonedCodeInfo &InlinedCodeInfo) {
593f22ef01cSRoman Divacky   BasicBlock *InvokeDest = II->getUnwindDest();
594f22ef01cSRoman Divacky 
595f22ef01cSRoman Divacky   Function *Caller = FirstNewBlock->getParent();
596f22ef01cSRoman Divacky 
597f22ef01cSRoman Divacky   // The inlined code is currently at the end of the function, scan from the
598f22ef01cSRoman Divacky   // start of the inlined code to its end, checking for stuff we need to
599139f7f9bSDimitry Andric   // rewrite.
6007d523365SDimitry Andric   LandingPadInliningInfo Invoke(II);
601bd5abe19SDimitry Andric 
602139f7f9bSDimitry Andric   // Get all of the inlined landing pad instructions.
603139f7f9bSDimitry Andric   SmallPtrSet<LandingPadInst*, 16> InlinedLPads;
6047d523365SDimitry Andric   for (Function::iterator I = FirstNewBlock->getIterator(), E = Caller->end();
6057d523365SDimitry Andric        I != E; ++I)
606139f7f9bSDimitry Andric     if (InvokeInst *II = dyn_cast<InvokeInst>(I->getTerminator()))
607139f7f9bSDimitry Andric       InlinedLPads.insert(II->getLandingPadInst());
608139f7f9bSDimitry Andric 
60991bc56edSDimitry Andric   // Append the clauses from the outer landing pad instruction into the inlined
61091bc56edSDimitry Andric   // landing pad instructions.
61191bc56edSDimitry Andric   LandingPadInst *OuterLPad = Invoke.getLandingPadInst();
61239d628a0SDimitry Andric   for (LandingPadInst *InlinedLPad : InlinedLPads) {
61391bc56edSDimitry Andric     unsigned OuterNum = OuterLPad->getNumClauses();
61491bc56edSDimitry Andric     InlinedLPad->reserveClauses(OuterNum);
61591bc56edSDimitry Andric     for (unsigned OuterIdx = 0; OuterIdx != OuterNum; ++OuterIdx)
61691bc56edSDimitry Andric       InlinedLPad->addClause(OuterLPad->getClause(OuterIdx));
61791bc56edSDimitry Andric     if (OuterLPad->isCleanup())
61891bc56edSDimitry Andric       InlinedLPad->setCleanup(true);
61991bc56edSDimitry Andric   }
62091bc56edSDimitry Andric 
6217d523365SDimitry Andric   for (Function::iterator BB = FirstNewBlock->getIterator(), E = Caller->end();
6227d523365SDimitry Andric        BB != E; ++BB) {
623f22ef01cSRoman Divacky     if (InlinedCodeInfo.ContainsCalls)
6247d523365SDimitry Andric       if (BasicBlock *NewBB = HandleCallsInBlockInlinedThroughInvoke(
6257d523365SDimitry Andric               &*BB, Invoke.getOuterResumeDest()))
6267d523365SDimitry Andric         // Update any PHI nodes in the exceptional block to indicate that there
6277d523365SDimitry Andric         // is now a new entry in them.
6287d523365SDimitry Andric         Invoke.addIncomingPHIValuesFor(NewBB);
629f22ef01cSRoman Divacky 
630139f7f9bSDimitry Andric     // Forward any resumes that are remaining here.
631dff0c46cSDimitry Andric     if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator()))
632139f7f9bSDimitry Andric       Invoke.forwardResume(RI, InlinedLPads);
6336122f3e6SDimitry Andric   }
634f22ef01cSRoman Divacky 
635f22ef01cSRoman Divacky   // Now that everything is happy, we have one final detail.  The PHI nodes in
636f22ef01cSRoman Divacky   // the exception destination block still have entries due to the original
637f22ef01cSRoman Divacky   // invoke instruction. Eliminate these entries (which might even delete the
638f22ef01cSRoman Divacky   // PHI node) now.
639f22ef01cSRoman Divacky   InvokeDest->removePredecessor(II->getParent());
640f22ef01cSRoman Divacky }
641f22ef01cSRoman Divacky 
6427d523365SDimitry Andric /// If we inlined an invoke site, we need to convert calls
6437d523365SDimitry Andric /// in the body of the inlined function into invokes.
6447d523365SDimitry Andric ///
6457d523365SDimitry Andric /// II is the invoke instruction being inlined.  FirstNewBlock is the first
6467d523365SDimitry Andric /// block of the inlined code (the last block is the end of the function),
6477d523365SDimitry Andric /// and InlineCodeInfo is information about the code that got inlined.
HandleInlinedEHPad(InvokeInst * II,BasicBlock * FirstNewBlock,ClonedCodeInfo & InlinedCodeInfo)6487d523365SDimitry Andric static void HandleInlinedEHPad(InvokeInst *II, BasicBlock *FirstNewBlock,
6497d523365SDimitry Andric                                ClonedCodeInfo &InlinedCodeInfo) {
6507d523365SDimitry Andric   BasicBlock *UnwindDest = II->getUnwindDest();
6517d523365SDimitry Andric   Function *Caller = FirstNewBlock->getParent();
6527d523365SDimitry Andric 
6537d523365SDimitry Andric   assert(UnwindDest->getFirstNonPHI()->isEHPad() && "unexpected BasicBlock!");
6547d523365SDimitry Andric 
6557d523365SDimitry Andric   // If there are PHI nodes in the unwind destination block, we need to keep
6567d523365SDimitry Andric   // track of which values came into them from the invoke before removing the
6577d523365SDimitry Andric   // edge from this block.
6587d523365SDimitry Andric   SmallVector<Value *, 8> UnwindDestPHIValues;
6592cab237bSDimitry Andric   BasicBlock *InvokeBB = II->getParent();
6607d523365SDimitry Andric   for (Instruction &I : *UnwindDest) {
6617d523365SDimitry Andric     // Save the value to use for this edge.
6627d523365SDimitry Andric     PHINode *PHI = dyn_cast<PHINode>(&I);
6637d523365SDimitry Andric     if (!PHI)
6647d523365SDimitry Andric       break;
6657d523365SDimitry Andric     UnwindDestPHIValues.push_back(PHI->getIncomingValueForBlock(InvokeBB));
6667d523365SDimitry Andric   }
6677d523365SDimitry Andric 
6687d523365SDimitry Andric   // Add incoming-PHI values to the unwind destination block for the given basic
6697d523365SDimitry Andric   // block, using the values for the original invoke's source block.
6707d523365SDimitry Andric   auto UpdatePHINodes = [&](BasicBlock *Src) {
6717d523365SDimitry Andric     BasicBlock::iterator I = UnwindDest->begin();
6727d523365SDimitry Andric     for (Value *V : UnwindDestPHIValues) {
6737d523365SDimitry Andric       PHINode *PHI = cast<PHINode>(I);
6747d523365SDimitry Andric       PHI->addIncoming(V, Src);
6757d523365SDimitry Andric       ++I;
6767d523365SDimitry Andric     }
6777d523365SDimitry Andric   };
6787d523365SDimitry Andric 
6797d523365SDimitry Andric   // This connects all the instructions which 'unwind to caller' to the invoke
6807d523365SDimitry Andric   // destination.
6818c24ff90SDimitry Andric   UnwindDestMemoTy FuncletUnwindMap;
6827d523365SDimitry Andric   for (Function::iterator BB = FirstNewBlock->getIterator(), E = Caller->end();
6837d523365SDimitry Andric        BB != E; ++BB) {
6847d523365SDimitry Andric     if (auto *CRI = dyn_cast<CleanupReturnInst>(BB->getTerminator())) {
6857d523365SDimitry Andric       if (CRI->unwindsToCaller()) {
6868c24ff90SDimitry Andric         auto *CleanupPad = CRI->getCleanupPad();
6878c24ff90SDimitry Andric         CleanupReturnInst::Create(CleanupPad, UnwindDest, CRI);
6887d523365SDimitry Andric         CRI->eraseFromParent();
6897d523365SDimitry Andric         UpdatePHINodes(&*BB);
6908c24ff90SDimitry Andric         // Finding a cleanupret with an unwind destination would confuse
6918c24ff90SDimitry Andric         // subsequent calls to getUnwindDestToken, so map the cleanuppad
6928c24ff90SDimitry Andric         // to short-circuit any such calls and recognize this as an "unwind
6938c24ff90SDimitry Andric         // to caller" cleanup.
6948c24ff90SDimitry Andric         assert(!FuncletUnwindMap.count(CleanupPad) ||
6958c24ff90SDimitry Andric                isa<ConstantTokenNone>(FuncletUnwindMap[CleanupPad]));
6968c24ff90SDimitry Andric         FuncletUnwindMap[CleanupPad] =
6978c24ff90SDimitry Andric             ConstantTokenNone::get(Caller->getContext());
6987d523365SDimitry Andric       }
6997d523365SDimitry Andric     }
7007d523365SDimitry Andric 
7017d523365SDimitry Andric     Instruction *I = BB->getFirstNonPHI();
7027d523365SDimitry Andric     if (!I->isEHPad())
7037d523365SDimitry Andric       continue;
7047d523365SDimitry Andric 
7057d523365SDimitry Andric     Instruction *Replacement = nullptr;
7067d523365SDimitry Andric     if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(I)) {
7077d523365SDimitry Andric       if (CatchSwitch->unwindsToCaller()) {
7088c24ff90SDimitry Andric         Value *UnwindDestToken;
7098c24ff90SDimitry Andric         if (auto *ParentPad =
7108c24ff90SDimitry Andric                 dyn_cast<Instruction>(CatchSwitch->getParentPad())) {
7118c24ff90SDimitry Andric           // This catchswitch is nested inside another funclet.  If that
7128c24ff90SDimitry Andric           // funclet has an unwind destination within the inlinee, then
7138c24ff90SDimitry Andric           // unwinding out of this catchswitch would be UB.  Rewriting this
7148c24ff90SDimitry Andric           // catchswitch to unwind to the inlined invoke's unwind dest would
7158c24ff90SDimitry Andric           // give the parent funclet multiple unwind destinations, which is
7168c24ff90SDimitry Andric           // something that subsequent EH table generation can't handle and
7178c24ff90SDimitry Andric           // that the veirifer rejects.  So when we see such a call, leave it
7188c24ff90SDimitry Andric           // as "unwind to caller".
7198c24ff90SDimitry Andric           UnwindDestToken = getUnwindDestToken(ParentPad, FuncletUnwindMap);
7208c24ff90SDimitry Andric           if (UnwindDestToken && !isa<ConstantTokenNone>(UnwindDestToken))
7218c24ff90SDimitry Andric             continue;
7228c24ff90SDimitry Andric         } else {
7238c24ff90SDimitry Andric           // This catchswitch has no parent to inherit constraints from, and
7248c24ff90SDimitry Andric           // none of its descendants can have an unwind edge that exits it and
7258c24ff90SDimitry Andric           // targets another funclet in the inlinee.  It may or may not have a
7268c24ff90SDimitry Andric           // descendant that definitively has an unwind to caller.  In either
7278c24ff90SDimitry Andric           // case, we'll have to assume that any unwinds out of it may need to
7288c24ff90SDimitry Andric           // be routed to the caller, so treat it as though it has a definitive
7298c24ff90SDimitry Andric           // unwind to caller.
7308c24ff90SDimitry Andric           UnwindDestToken = ConstantTokenNone::get(Caller->getContext());
7318c24ff90SDimitry Andric         }
7327d523365SDimitry Andric         auto *NewCatchSwitch = CatchSwitchInst::Create(
7337d523365SDimitry Andric             CatchSwitch->getParentPad(), UnwindDest,
7347d523365SDimitry Andric             CatchSwitch->getNumHandlers(), CatchSwitch->getName(),
7357d523365SDimitry Andric             CatchSwitch);
7367d523365SDimitry Andric         for (BasicBlock *PadBB : CatchSwitch->handlers())
7377d523365SDimitry Andric           NewCatchSwitch->addHandler(PadBB);
7388c24ff90SDimitry Andric         // Propagate info for the old catchswitch over to the new one in
7398c24ff90SDimitry Andric         // the unwind map.  This also serves to short-circuit any subsequent
7408c24ff90SDimitry Andric         // checks for the unwind dest of this catchswitch, which would get
7418c24ff90SDimitry Andric         // confused if they found the outer handler in the callee.
7428c24ff90SDimitry Andric         FuncletUnwindMap[NewCatchSwitch] = UnwindDestToken;
7437d523365SDimitry Andric         Replacement = NewCatchSwitch;
7447d523365SDimitry Andric       }
7457d523365SDimitry Andric     } else if (!isa<FuncletPadInst>(I)) {
7467d523365SDimitry Andric       llvm_unreachable("unexpected EHPad!");
7477d523365SDimitry Andric     }
7487d523365SDimitry Andric 
7497d523365SDimitry Andric     if (Replacement) {
7507d523365SDimitry Andric       Replacement->takeName(I);
7517d523365SDimitry Andric       I->replaceAllUsesWith(Replacement);
7527d523365SDimitry Andric       I->eraseFromParent();
7537d523365SDimitry Andric       UpdatePHINodes(&*BB);
7547d523365SDimitry Andric     }
7557d523365SDimitry Andric   }
7567d523365SDimitry Andric 
7577d523365SDimitry Andric   if (InlinedCodeInfo.ContainsCalls)
7587d523365SDimitry Andric     for (Function::iterator BB = FirstNewBlock->getIterator(),
7597d523365SDimitry Andric                             E = Caller->end();
7607d523365SDimitry Andric          BB != E; ++BB)
7618c24ff90SDimitry Andric       if (BasicBlock *NewBB = HandleCallsInBlockInlinedThroughInvoke(
7628c24ff90SDimitry Andric               &*BB, UnwindDest, &FuncletUnwindMap))
7637d523365SDimitry Andric         // Update any PHI nodes in the exceptional block to indicate that there
7647d523365SDimitry Andric         // is now a new entry in them.
7657d523365SDimitry Andric         UpdatePHINodes(NewBB);
7667d523365SDimitry Andric 
7677d523365SDimitry Andric   // Now that everything is happy, we have one final detail.  The PHI nodes in
7687d523365SDimitry Andric   // the exception destination block still have entries due to the original
7697d523365SDimitry Andric   // invoke instruction. Eliminate these entries (which might even delete the
7707d523365SDimitry Andric   // PHI node) now.
7717d523365SDimitry Andric   UnwindDest->removePredecessor(InvokeBB);
7727d523365SDimitry Andric }
7737d523365SDimitry Andric 
774*b5893f02SDimitry Andric /// When inlining a call site that has !llvm.mem.parallel_loop_access or
775*b5893f02SDimitry Andric /// llvm.access.group metadata, that metadata should be propagated to all
776*b5893f02SDimitry Andric /// memory-accessing cloned instructions.
PropagateParallelLoopAccessMetadata(CallSite CS,ValueToValueMapTy & VMap)7773ca95b02SDimitry Andric static void PropagateParallelLoopAccessMetadata(CallSite CS,
7783ca95b02SDimitry Andric                                                 ValueToValueMapTy &VMap) {
7793ca95b02SDimitry Andric   MDNode *M =
7803ca95b02SDimitry Andric     CS.getInstruction()->getMetadata(LLVMContext::MD_mem_parallel_loop_access);
781*b5893f02SDimitry Andric   MDNode *CallAccessGroup =
782*b5893f02SDimitry Andric       CS.getInstruction()->getMetadata(LLVMContext::MD_access_group);
783*b5893f02SDimitry Andric   if (!M && !CallAccessGroup)
7843ca95b02SDimitry Andric     return;
7853ca95b02SDimitry Andric 
7863ca95b02SDimitry Andric   for (ValueToValueMapTy::iterator VMI = VMap.begin(), VMIE = VMap.end();
7873ca95b02SDimitry Andric        VMI != VMIE; ++VMI) {
7883ca95b02SDimitry Andric     if (!VMI->second)
7893ca95b02SDimitry Andric       continue;
7903ca95b02SDimitry Andric 
7913ca95b02SDimitry Andric     Instruction *NI = dyn_cast<Instruction>(VMI->second);
7923ca95b02SDimitry Andric     if (!NI)
7933ca95b02SDimitry Andric       continue;
7943ca95b02SDimitry Andric 
795*b5893f02SDimitry Andric     if (M) {
796*b5893f02SDimitry Andric       if (MDNode *PM =
797*b5893f02SDimitry Andric               NI->getMetadata(LLVMContext::MD_mem_parallel_loop_access)) {
7983ca95b02SDimitry Andric         M = MDNode::concatenate(PM, M);
7993ca95b02SDimitry Andric       NI->setMetadata(LLVMContext::MD_mem_parallel_loop_access, M);
8003ca95b02SDimitry Andric       } else if (NI->mayReadOrWriteMemory()) {
8013ca95b02SDimitry Andric         NI->setMetadata(LLVMContext::MD_mem_parallel_loop_access, M);
8023ca95b02SDimitry Andric       }
8033ca95b02SDimitry Andric     }
804*b5893f02SDimitry Andric 
805*b5893f02SDimitry Andric     if (NI->mayReadOrWriteMemory()) {
806*b5893f02SDimitry Andric       MDNode *UnitedAccGroups = uniteAccessGroups(
807*b5893f02SDimitry Andric           NI->getMetadata(LLVMContext::MD_access_group), CallAccessGroup);
808*b5893f02SDimitry Andric       NI->setMetadata(LLVMContext::MD_access_group, UnitedAccGroups);
809*b5893f02SDimitry Andric     }
810*b5893f02SDimitry Andric   }
8113ca95b02SDimitry Andric }
8123ca95b02SDimitry Andric 
813ff0cc061SDimitry Andric /// When inlining a function that contains noalias scope metadata,
814ff0cc061SDimitry Andric /// this metadata needs to be cloned so that the inlined blocks
8158e0f8b8cSDimitry Andric /// have different "unique scopes" at every call site. Were this not done, then
81639d628a0SDimitry Andric /// aliasing scopes from a function inlined into a caller multiple times could
81739d628a0SDimitry Andric /// not be differentiated (and this would lead to miscompiles because the
81839d628a0SDimitry Andric /// non-aliasing property communicated by the metadata could have
81939d628a0SDimitry Andric /// call-site-specific control dependencies).
CloneAliasScopeMetadata(CallSite CS,ValueToValueMapTy & VMap)82039d628a0SDimitry Andric static void CloneAliasScopeMetadata(CallSite CS, ValueToValueMapTy &VMap) {
82139d628a0SDimitry Andric   const Function *CalledFunc = CS.getCalledFunction();
82239d628a0SDimitry Andric   SetVector<const MDNode *> MD;
82339d628a0SDimitry Andric 
82439d628a0SDimitry Andric   // Note: We could only clone the metadata if it is already used in the
82539d628a0SDimitry Andric   // caller. I'm omitting that check here because it might confuse
82639d628a0SDimitry Andric   // inter-procedural alias analysis passes. We can revisit this if it becomes
82739d628a0SDimitry Andric   // an efficiency or overhead problem.
82839d628a0SDimitry Andric 
8293ca95b02SDimitry Andric   for (const BasicBlock &I : *CalledFunc)
8303ca95b02SDimitry Andric     for (const Instruction &J : I) {
8313ca95b02SDimitry Andric       if (const MDNode *M = J.getMetadata(LLVMContext::MD_alias_scope))
83239d628a0SDimitry Andric         MD.insert(M);
8333ca95b02SDimitry Andric       if (const MDNode *M = J.getMetadata(LLVMContext::MD_noalias))
83439d628a0SDimitry Andric         MD.insert(M);
83539d628a0SDimitry Andric     }
83639d628a0SDimitry Andric 
83739d628a0SDimitry Andric   if (MD.empty())
83839d628a0SDimitry Andric     return;
83939d628a0SDimitry Andric 
84039d628a0SDimitry Andric   // Walk the existing metadata, adding the complete (perhaps cyclic) chain to
84139d628a0SDimitry Andric   // the set.
84239d628a0SDimitry Andric   SmallVector<const Metadata *, 16> Queue(MD.begin(), MD.end());
84339d628a0SDimitry Andric   while (!Queue.empty()) {
84439d628a0SDimitry Andric     const MDNode *M = cast<MDNode>(Queue.pop_back_val());
84539d628a0SDimitry Andric     for (unsigned i = 0, ie = M->getNumOperands(); i != ie; ++i)
84639d628a0SDimitry Andric       if (const MDNode *M1 = dyn_cast<MDNode>(M->getOperand(i)))
84739d628a0SDimitry Andric         if (MD.insert(M1))
84839d628a0SDimitry Andric           Queue.push_back(M1);
84939d628a0SDimitry Andric   }
85039d628a0SDimitry Andric 
85139d628a0SDimitry Andric   // Now we have a complete set of all metadata in the chains used to specify
85239d628a0SDimitry Andric   // the noalias scopes and the lists of those scopes.
853ff0cc061SDimitry Andric   SmallVector<TempMDTuple, 16> DummyNodes;
85439d628a0SDimitry Andric   DenseMap<const MDNode *, TrackingMDNodeRef> MDMap;
8553ca95b02SDimitry Andric   for (const MDNode *I : MD) {
856ff0cc061SDimitry Andric     DummyNodes.push_back(MDTuple::getTemporary(CalledFunc->getContext(), None));
8573ca95b02SDimitry Andric     MDMap[I].reset(DummyNodes.back().get());
85839d628a0SDimitry Andric   }
85939d628a0SDimitry Andric 
86039d628a0SDimitry Andric   // Create new metadata nodes to replace the dummy nodes, replacing old
86139d628a0SDimitry Andric   // metadata references with either a dummy node or an already-created new
86239d628a0SDimitry Andric   // node.
8633ca95b02SDimitry Andric   for (const MDNode *I : MD) {
86439d628a0SDimitry Andric     SmallVector<Metadata *, 4> NewOps;
8653ca95b02SDimitry Andric     for (unsigned i = 0, ie = I->getNumOperands(); i != ie; ++i) {
8663ca95b02SDimitry Andric       const Metadata *V = I->getOperand(i);
86739d628a0SDimitry Andric       if (const MDNode *M = dyn_cast<MDNode>(V))
86839d628a0SDimitry Andric         NewOps.push_back(MDMap[M]);
86939d628a0SDimitry Andric       else
87039d628a0SDimitry Andric         NewOps.push_back(const_cast<Metadata *>(V));
87139d628a0SDimitry Andric     }
87239d628a0SDimitry Andric 
87339d628a0SDimitry Andric     MDNode *NewM = MDNode::get(CalledFunc->getContext(), NewOps);
8743ca95b02SDimitry Andric     MDTuple *TempM = cast<MDTuple>(MDMap[I]);
875ff0cc061SDimitry Andric     assert(TempM->isTemporary() && "Expected temporary node");
87639d628a0SDimitry Andric 
87739d628a0SDimitry Andric     TempM->replaceAllUsesWith(NewM);
87839d628a0SDimitry Andric   }
87939d628a0SDimitry Andric 
88039d628a0SDimitry Andric   // Now replace the metadata in the new inlined instructions with the
88139d628a0SDimitry Andric   // repacements from the map.
88239d628a0SDimitry Andric   for (ValueToValueMapTy::iterator VMI = VMap.begin(), VMIE = VMap.end();
88339d628a0SDimitry Andric        VMI != VMIE; ++VMI) {
88439d628a0SDimitry Andric     if (!VMI->second)
88539d628a0SDimitry Andric       continue;
88639d628a0SDimitry Andric 
88739d628a0SDimitry Andric     Instruction *NI = dyn_cast<Instruction>(VMI->second);
88839d628a0SDimitry Andric     if (!NI)
88939d628a0SDimitry Andric       continue;
89039d628a0SDimitry Andric 
89139d628a0SDimitry Andric     if (MDNode *M = NI->getMetadata(LLVMContext::MD_alias_scope)) {
89239d628a0SDimitry Andric       MDNode *NewMD = MDMap[M];
89339d628a0SDimitry Andric       // If the call site also had alias scope metadata (a list of scopes to
89439d628a0SDimitry Andric       // which instructions inside it might belong), propagate those scopes to
89539d628a0SDimitry Andric       // the inlined instructions.
89639d628a0SDimitry Andric       if (MDNode *CSM =
89739d628a0SDimitry Andric               CS.getInstruction()->getMetadata(LLVMContext::MD_alias_scope))
89839d628a0SDimitry Andric         NewMD = MDNode::concatenate(NewMD, CSM);
89939d628a0SDimitry Andric       NI->setMetadata(LLVMContext::MD_alias_scope, NewMD);
90039d628a0SDimitry Andric     } else if (NI->mayReadOrWriteMemory()) {
90139d628a0SDimitry Andric       if (MDNode *M =
90239d628a0SDimitry Andric               CS.getInstruction()->getMetadata(LLVMContext::MD_alias_scope))
90339d628a0SDimitry Andric         NI->setMetadata(LLVMContext::MD_alias_scope, M);
90439d628a0SDimitry Andric     }
90539d628a0SDimitry Andric 
90639d628a0SDimitry Andric     if (MDNode *M = NI->getMetadata(LLVMContext::MD_noalias)) {
90739d628a0SDimitry Andric       MDNode *NewMD = MDMap[M];
90839d628a0SDimitry Andric       // If the call site also had noalias metadata (a list of scopes with
90939d628a0SDimitry Andric       // which instructions inside it don't alias), propagate those scopes to
91039d628a0SDimitry Andric       // the inlined instructions.
91139d628a0SDimitry Andric       if (MDNode *CSM =
91239d628a0SDimitry Andric               CS.getInstruction()->getMetadata(LLVMContext::MD_noalias))
91339d628a0SDimitry Andric         NewMD = MDNode::concatenate(NewMD, CSM);
91439d628a0SDimitry Andric       NI->setMetadata(LLVMContext::MD_noalias, NewMD);
91539d628a0SDimitry Andric     } else if (NI->mayReadOrWriteMemory()) {
91639d628a0SDimitry Andric       if (MDNode *M = CS.getInstruction()->getMetadata(LLVMContext::MD_noalias))
91739d628a0SDimitry Andric         NI->setMetadata(LLVMContext::MD_noalias, M);
91839d628a0SDimitry Andric     }
91939d628a0SDimitry Andric   }
92039d628a0SDimitry Andric }
92139d628a0SDimitry Andric 
922ff0cc061SDimitry Andric /// If the inlined function has noalias arguments,
923ff0cc061SDimitry Andric /// then add new alias scopes for each noalias argument, tag the mapped noalias
92439d628a0SDimitry Andric /// parameters with noalias metadata specifying the new scope, and tag all
92539d628a0SDimitry Andric /// non-derived loads, stores and memory intrinsics with the new alias scopes.
AddAliasScopeMetadata(CallSite CS,ValueToValueMapTy & VMap,const DataLayout & DL,AAResults * CalleeAAR)92639d628a0SDimitry Andric static void AddAliasScopeMetadata(CallSite CS, ValueToValueMapTy &VMap,
9277d523365SDimitry Andric                                   const DataLayout &DL, AAResults *CalleeAAR) {
92839d628a0SDimitry Andric   if (!EnableNoAliasConversion)
92939d628a0SDimitry Andric     return;
93039d628a0SDimitry Andric 
93139d628a0SDimitry Andric   const Function *CalledFunc = CS.getCalledFunction();
93239d628a0SDimitry Andric   SmallVector<const Argument *, 4> NoAliasArgs;
93339d628a0SDimitry Andric 
9343ca95b02SDimitry Andric   for (const Argument &Arg : CalledFunc->args())
9353ca95b02SDimitry Andric     if (Arg.hasNoAliasAttr() && !Arg.use_empty())
9363ca95b02SDimitry Andric       NoAliasArgs.push_back(&Arg);
93739d628a0SDimitry Andric 
93839d628a0SDimitry Andric   if (NoAliasArgs.empty())
93939d628a0SDimitry Andric     return;
94039d628a0SDimitry Andric 
94139d628a0SDimitry Andric   // To do a good job, if a noalias variable is captured, we need to know if
94239d628a0SDimitry Andric   // the capture point dominates the particular use we're considering.
94339d628a0SDimitry Andric   DominatorTree DT;
94439d628a0SDimitry Andric   DT.recalculate(const_cast<Function&>(*CalledFunc));
94539d628a0SDimitry Andric 
94639d628a0SDimitry Andric   // noalias indicates that pointer values based on the argument do not alias
94739d628a0SDimitry Andric   // pointer values which are not based on it. So we add a new "scope" for each
94839d628a0SDimitry Andric   // noalias function argument. Accesses using pointers based on that argument
94939d628a0SDimitry Andric   // become part of that alias scope, accesses using pointers not based on that
95039d628a0SDimitry Andric   // argument are tagged as noalias with that scope.
95139d628a0SDimitry Andric 
95239d628a0SDimitry Andric   DenseMap<const Argument *, MDNode *> NewScopes;
95339d628a0SDimitry Andric   MDBuilder MDB(CalledFunc->getContext());
95439d628a0SDimitry Andric 
95539d628a0SDimitry Andric   // Create a new scope domain for this function.
95639d628a0SDimitry Andric   MDNode *NewDomain =
95739d628a0SDimitry Andric     MDB.createAnonymousAliasScopeDomain(CalledFunc->getName());
95839d628a0SDimitry Andric   for (unsigned i = 0, e = NoAliasArgs.size(); i != e; ++i) {
95939d628a0SDimitry Andric     const Argument *A = NoAliasArgs[i];
96039d628a0SDimitry Andric 
96139d628a0SDimitry Andric     std::string Name = CalledFunc->getName();
96239d628a0SDimitry Andric     if (A->hasName()) {
96339d628a0SDimitry Andric       Name += ": %";
96439d628a0SDimitry Andric       Name += A->getName();
96539d628a0SDimitry Andric     } else {
96639d628a0SDimitry Andric       Name += ": argument ";
96739d628a0SDimitry Andric       Name += utostr(i);
96839d628a0SDimitry Andric     }
96939d628a0SDimitry Andric 
97039d628a0SDimitry Andric     // Note: We always create a new anonymous root here. This is true regardless
97139d628a0SDimitry Andric     // of the linkage of the callee because the aliasing "scope" is not just a
97239d628a0SDimitry Andric     // property of the callee, but also all control dependencies in the caller.
97339d628a0SDimitry Andric     MDNode *NewScope = MDB.createAnonymousAliasScope(NewDomain, Name);
97439d628a0SDimitry Andric     NewScopes.insert(std::make_pair(A, NewScope));
97539d628a0SDimitry Andric   }
97639d628a0SDimitry Andric 
97739d628a0SDimitry Andric   // Iterate over all new instructions in the map; for all memory-access
97839d628a0SDimitry Andric   // instructions, add the alias scope metadata.
97939d628a0SDimitry Andric   for (ValueToValueMapTy::iterator VMI = VMap.begin(), VMIE = VMap.end();
98039d628a0SDimitry Andric        VMI != VMIE; ++VMI) {
98139d628a0SDimitry Andric     if (const Instruction *I = dyn_cast<Instruction>(VMI->first)) {
98239d628a0SDimitry Andric       if (!VMI->second)
98339d628a0SDimitry Andric         continue;
98439d628a0SDimitry Andric 
98539d628a0SDimitry Andric       Instruction *NI = dyn_cast<Instruction>(VMI->second);
98639d628a0SDimitry Andric       if (!NI)
98739d628a0SDimitry Andric         continue;
98839d628a0SDimitry Andric 
98939d628a0SDimitry Andric       bool IsArgMemOnlyCall = false, IsFuncCall = false;
99039d628a0SDimitry Andric       SmallVector<const Value *, 2> PtrArgs;
99139d628a0SDimitry Andric 
99239d628a0SDimitry Andric       if (const LoadInst *LI = dyn_cast<LoadInst>(I))
99339d628a0SDimitry Andric         PtrArgs.push_back(LI->getPointerOperand());
99439d628a0SDimitry Andric       else if (const StoreInst *SI = dyn_cast<StoreInst>(I))
99539d628a0SDimitry Andric         PtrArgs.push_back(SI->getPointerOperand());
99639d628a0SDimitry Andric       else if (const VAArgInst *VAAI = dyn_cast<VAArgInst>(I))
99739d628a0SDimitry Andric         PtrArgs.push_back(VAAI->getPointerOperand());
99839d628a0SDimitry Andric       else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I))
99939d628a0SDimitry Andric         PtrArgs.push_back(CXI->getPointerOperand());
100039d628a0SDimitry Andric       else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I))
100139d628a0SDimitry Andric         PtrArgs.push_back(RMWI->getPointerOperand());
1002*b5893f02SDimitry Andric       else if (const auto *Call = dyn_cast<CallBase>(I)) {
100339d628a0SDimitry Andric         // If we know that the call does not access memory, then we'll still
100439d628a0SDimitry Andric         // know that about the inlined clone of this call site, and we don't
100539d628a0SDimitry Andric         // need to add metadata.
1006*b5893f02SDimitry Andric         if (Call->doesNotAccessMemory())
100739d628a0SDimitry Andric           continue;
100839d628a0SDimitry Andric 
100939d628a0SDimitry Andric         IsFuncCall = true;
10107d523365SDimitry Andric         if (CalleeAAR) {
1011*b5893f02SDimitry Andric           FunctionModRefBehavior MRB = CalleeAAR->getModRefBehavior(Call);
10127d523365SDimitry Andric           if (MRB == FMRB_OnlyAccessesArgumentPointees ||
10137d523365SDimitry Andric               MRB == FMRB_OnlyReadsArgumentPointees)
101439d628a0SDimitry Andric             IsArgMemOnlyCall = true;
101539d628a0SDimitry Andric         }
101639d628a0SDimitry Andric 
1017*b5893f02SDimitry Andric         for (Value *Arg : Call->args()) {
101839d628a0SDimitry Andric           // We need to check the underlying objects of all arguments, not just
101939d628a0SDimitry Andric           // the pointer arguments, because we might be passing pointers as
102039d628a0SDimitry Andric           // integers, etc.
102139d628a0SDimitry Andric           // However, if we know that the call only accesses pointer arguments,
102239d628a0SDimitry Andric           // then we only need to check the pointer arguments.
10233ca95b02SDimitry Andric           if (IsArgMemOnlyCall && !Arg->getType()->isPointerTy())
102439d628a0SDimitry Andric             continue;
102539d628a0SDimitry Andric 
10263ca95b02SDimitry Andric           PtrArgs.push_back(Arg);
102739d628a0SDimitry Andric         }
102839d628a0SDimitry Andric       }
102939d628a0SDimitry Andric 
103039d628a0SDimitry Andric       // If we found no pointers, then this instruction is not suitable for
103139d628a0SDimitry Andric       // pairing with an instruction to receive aliasing metadata.
103239d628a0SDimitry Andric       // However, if this is a call, this we might just alias with none of the
103339d628a0SDimitry Andric       // noalias arguments.
103439d628a0SDimitry Andric       if (PtrArgs.empty() && !IsFuncCall)
103539d628a0SDimitry Andric         continue;
103639d628a0SDimitry Andric 
103739d628a0SDimitry Andric       // It is possible that there is only one underlying object, but you
103839d628a0SDimitry Andric       // need to go through several PHIs to see it, and thus could be
103939d628a0SDimitry Andric       // repeated in the Objects list.
104039d628a0SDimitry Andric       SmallPtrSet<const Value *, 4> ObjSet;
104139d628a0SDimitry Andric       SmallVector<Metadata *, 4> Scopes, NoAliases;
104239d628a0SDimitry Andric 
104339d628a0SDimitry Andric       SmallSetVector<const Argument *, 4> NAPtrArgs;
10443ca95b02SDimitry Andric       for (const Value *V : PtrArgs) {
104539d628a0SDimitry Andric         SmallVector<Value *, 4> Objects;
10463ca95b02SDimitry Andric         GetUnderlyingObjects(const_cast<Value*>(V),
10477d523365SDimitry Andric                              Objects, DL, /* LI = */ nullptr);
104839d628a0SDimitry Andric 
104939d628a0SDimitry Andric         for (Value *O : Objects)
105039d628a0SDimitry Andric           ObjSet.insert(O);
105139d628a0SDimitry Andric       }
105239d628a0SDimitry Andric 
105339d628a0SDimitry Andric       // Figure out if we're derived from anything that is not a noalias
105439d628a0SDimitry Andric       // argument.
105539d628a0SDimitry Andric       bool CanDeriveViaCapture = false, UsesAliasingPtr = false;
105639d628a0SDimitry Andric       for (const Value *V : ObjSet) {
105739d628a0SDimitry Andric         // Is this value a constant that cannot be derived from any pointer
105839d628a0SDimitry Andric         // value (we need to exclude constant expressions, for example, that
105939d628a0SDimitry Andric         // are formed from arithmetic on global symbols).
106039d628a0SDimitry Andric         bool IsNonPtrConst = isa<ConstantInt>(V) || isa<ConstantFP>(V) ||
106139d628a0SDimitry Andric                              isa<ConstantPointerNull>(V) ||
106239d628a0SDimitry Andric                              isa<ConstantDataVector>(V) || isa<UndefValue>(V);
106339d628a0SDimitry Andric         if (IsNonPtrConst)
106439d628a0SDimitry Andric           continue;
106539d628a0SDimitry Andric 
106639d628a0SDimitry Andric         // If this is anything other than a noalias argument, then we cannot
106739d628a0SDimitry Andric         // completely describe the aliasing properties using alias.scope
106839d628a0SDimitry Andric         // metadata (and, thus, won't add any).
106939d628a0SDimitry Andric         if (const Argument *A = dyn_cast<Argument>(V)) {
107039d628a0SDimitry Andric           if (!A->hasNoAliasAttr())
107139d628a0SDimitry Andric             UsesAliasingPtr = true;
107239d628a0SDimitry Andric         } else {
107339d628a0SDimitry Andric           UsesAliasingPtr = true;
107439d628a0SDimitry Andric         }
107539d628a0SDimitry Andric 
107639d628a0SDimitry Andric         // If this is not some identified function-local object (which cannot
107739d628a0SDimitry Andric         // directly alias a noalias argument), or some other argument (which,
107839d628a0SDimitry Andric         // by definition, also cannot alias a noalias argument), then we could
107939d628a0SDimitry Andric         // alias a noalias argument that has been captured).
108039d628a0SDimitry Andric         if (!isa<Argument>(V) &&
108139d628a0SDimitry Andric             !isIdentifiedFunctionLocal(const_cast<Value*>(V)))
108239d628a0SDimitry Andric           CanDeriveViaCapture = true;
108339d628a0SDimitry Andric       }
108439d628a0SDimitry Andric 
108539d628a0SDimitry Andric       // A function call can always get captured noalias pointers (via other
108639d628a0SDimitry Andric       // parameters, globals, etc.).
108739d628a0SDimitry Andric       if (IsFuncCall && !IsArgMemOnlyCall)
108839d628a0SDimitry Andric         CanDeriveViaCapture = true;
108939d628a0SDimitry Andric 
109039d628a0SDimitry Andric       // First, we want to figure out all of the sets with which we definitely
109139d628a0SDimitry Andric       // don't alias. Iterate over all noalias set, and add those for which:
109239d628a0SDimitry Andric       //   1. The noalias argument is not in the set of objects from which we
109339d628a0SDimitry Andric       //      definitely derive.
109439d628a0SDimitry Andric       //   2. The noalias argument has not yet been captured.
109539d628a0SDimitry Andric       // An arbitrary function that might load pointers could see captured
109639d628a0SDimitry Andric       // noalias arguments via other noalias arguments or globals, and so we
109739d628a0SDimitry Andric       // must always check for prior capture.
109839d628a0SDimitry Andric       for (const Argument *A : NoAliasArgs) {
109939d628a0SDimitry Andric         if (!ObjSet.count(A) && (!CanDeriveViaCapture ||
110039d628a0SDimitry Andric                                  // It might be tempting to skip the
110139d628a0SDimitry Andric                                  // PointerMayBeCapturedBefore check if
110239d628a0SDimitry Andric                                  // A->hasNoCaptureAttr() is true, but this is
110339d628a0SDimitry Andric                                  // incorrect because nocapture only guarantees
110439d628a0SDimitry Andric                                  // that no copies outlive the function, not
110539d628a0SDimitry Andric                                  // that the value cannot be locally captured.
110639d628a0SDimitry Andric                                  !PointerMayBeCapturedBefore(A,
110739d628a0SDimitry Andric                                    /* ReturnCaptures */ false,
110839d628a0SDimitry Andric                                    /* StoreCaptures */ false, I, &DT)))
110939d628a0SDimitry Andric           NoAliases.push_back(NewScopes[A]);
111039d628a0SDimitry Andric       }
111139d628a0SDimitry Andric 
111239d628a0SDimitry Andric       if (!NoAliases.empty())
111339d628a0SDimitry Andric         NI->setMetadata(LLVMContext::MD_noalias,
111439d628a0SDimitry Andric                         MDNode::concatenate(
111539d628a0SDimitry Andric                             NI->getMetadata(LLVMContext::MD_noalias),
111639d628a0SDimitry Andric                             MDNode::get(CalledFunc->getContext(), NoAliases)));
111739d628a0SDimitry Andric 
111839d628a0SDimitry Andric       // Next, we want to figure out all of the sets to which we might belong.
111939d628a0SDimitry Andric       // We might belong to a set if the noalias argument is in the set of
112039d628a0SDimitry Andric       // underlying objects. If there is some non-noalias argument in our list
112139d628a0SDimitry Andric       // of underlying objects, then we cannot add a scope because the fact
112239d628a0SDimitry Andric       // that some access does not alias with any set of our noalias arguments
112339d628a0SDimitry Andric       // cannot itself guarantee that it does not alias with this access
112439d628a0SDimitry Andric       // (because there is some pointer of unknown origin involved and the
112539d628a0SDimitry Andric       // other access might also depend on this pointer). We also cannot add
112639d628a0SDimitry Andric       // scopes to arbitrary functions unless we know they don't access any
112739d628a0SDimitry Andric       // non-parameter pointer-values.
112839d628a0SDimitry Andric       bool CanAddScopes = !UsesAliasingPtr;
112939d628a0SDimitry Andric       if (CanAddScopes && IsFuncCall)
113039d628a0SDimitry Andric         CanAddScopes = IsArgMemOnlyCall;
113139d628a0SDimitry Andric 
113239d628a0SDimitry Andric       if (CanAddScopes)
113339d628a0SDimitry Andric         for (const Argument *A : NoAliasArgs) {
113439d628a0SDimitry Andric           if (ObjSet.count(A))
113539d628a0SDimitry Andric             Scopes.push_back(NewScopes[A]);
113639d628a0SDimitry Andric         }
113739d628a0SDimitry Andric 
113839d628a0SDimitry Andric       if (!Scopes.empty())
113939d628a0SDimitry Andric         NI->setMetadata(
114039d628a0SDimitry Andric             LLVMContext::MD_alias_scope,
114139d628a0SDimitry Andric             MDNode::concatenate(NI->getMetadata(LLVMContext::MD_alias_scope),
114239d628a0SDimitry Andric                                 MDNode::get(CalledFunc->getContext(), Scopes)));
114339d628a0SDimitry Andric     }
114439d628a0SDimitry Andric   }
114539d628a0SDimitry Andric }
114639d628a0SDimitry Andric 
114739d628a0SDimitry Andric /// If the inlined function has non-byval align arguments, then
114839d628a0SDimitry Andric /// add @llvm.assume-based alignment assumptions to preserve this information.
AddAlignmentAssumptions(CallSite CS,InlineFunctionInfo & IFI)114939d628a0SDimitry Andric static void AddAlignmentAssumptions(CallSite CS, InlineFunctionInfo &IFI) {
1150d88c1a5aSDimitry Andric   if (!PreserveAlignmentAssumptions || !IFI.GetAssumptionCache)
115139d628a0SDimitry Andric     return;
1152d88c1a5aSDimitry Andric 
1153d88c1a5aSDimitry Andric   AssumptionCache *AC = &(*IFI.GetAssumptionCache)(*CS.getCaller());
1154ff0cc061SDimitry Andric   auto &DL = CS.getCaller()->getParent()->getDataLayout();
115539d628a0SDimitry Andric 
115639d628a0SDimitry Andric   // To avoid inserting redundant assumptions, we should check for assumptions
115739d628a0SDimitry Andric   // already in the caller. To do this, we might need a DT of the caller.
115839d628a0SDimitry Andric   DominatorTree DT;
115939d628a0SDimitry Andric   bool DTCalculated = false;
116039d628a0SDimitry Andric 
116139d628a0SDimitry Andric   Function *CalledFunc = CS.getCalledFunction();
11627a7e6055SDimitry Andric   for (Argument &Arg : CalledFunc->args()) {
11637a7e6055SDimitry Andric     unsigned Align = Arg.getType()->isPointerTy() ? Arg.getParamAlignment() : 0;
11647a7e6055SDimitry Andric     if (Align && !Arg.hasByValOrInAllocaAttr() && !Arg.hasNUses(0)) {
116539d628a0SDimitry Andric       if (!DTCalculated) {
11667a7e6055SDimitry Andric         DT.recalculate(*CS.getCaller());
116739d628a0SDimitry Andric         DTCalculated = true;
116839d628a0SDimitry Andric       }
116939d628a0SDimitry Andric 
117039d628a0SDimitry Andric       // If we can already prove the asserted alignment in the context of the
117139d628a0SDimitry Andric       // caller, then don't bother inserting the assumption.
11727a7e6055SDimitry Andric       Value *ArgVal = CS.getArgument(Arg.getArgNo());
11737a7e6055SDimitry Andric       if (getKnownAlignment(ArgVal, DL, CS.getInstruction(), AC, &DT) >= Align)
117439d628a0SDimitry Andric         continue;
117539d628a0SDimitry Andric 
11767a7e6055SDimitry Andric       CallInst *NewAsmp = IRBuilder<>(CS.getInstruction())
11777a7e6055SDimitry Andric                               .CreateAlignmentAssumption(DL, ArgVal, Align);
11787a7e6055SDimitry Andric       AC->registerAssumption(NewAsmp);
117939d628a0SDimitry Andric     }
118039d628a0SDimitry Andric   }
118139d628a0SDimitry Andric }
118239d628a0SDimitry Andric 
1183ff0cc061SDimitry Andric /// Once we have cloned code over from a callee into the caller,
1184ff0cc061SDimitry Andric /// update the specified callgraph to reflect the changes we made.
1185ff0cc061SDimitry Andric /// Note that it's possible that not all code was copied over, so only
1186f22ef01cSRoman Divacky /// some edges of the callgraph may remain.
UpdateCallGraphAfterInlining(CallSite CS,Function::iterator FirstNewBlock,ValueToValueMapTy & VMap,InlineFunctionInfo & IFI)1187f22ef01cSRoman Divacky static void UpdateCallGraphAfterInlining(CallSite CS,
1188f22ef01cSRoman Divacky                                          Function::iterator FirstNewBlock,
11892754fe60SDimitry Andric                                          ValueToValueMapTy &VMap,
1190f22ef01cSRoman Divacky                                          InlineFunctionInfo &IFI) {
1191f22ef01cSRoman Divacky   CallGraph &CG = *IFI.CG;
11927a7e6055SDimitry Andric   const Function *Caller = CS.getCaller();
1193f22ef01cSRoman Divacky   const Function *Callee = CS.getCalledFunction();
1194f22ef01cSRoman Divacky   CallGraphNode *CalleeNode = CG[Callee];
1195f22ef01cSRoman Divacky   CallGraphNode *CallerNode = CG[Caller];
1196f22ef01cSRoman Divacky 
1197f22ef01cSRoman Divacky   // Since we inlined some uninlined call sites in the callee into the caller,
1198f22ef01cSRoman Divacky   // add edges from the caller to all of the callees of the callee.
1199f22ef01cSRoman Divacky   CallGraphNode::iterator I = CalleeNode->begin(), E = CalleeNode->end();
1200f22ef01cSRoman Divacky 
1201f22ef01cSRoman Divacky   // Consider the case where CalleeNode == CallerNode.
1202f22ef01cSRoman Divacky   CallGraphNode::CalledFunctionsVector CallCache;
1203f22ef01cSRoman Divacky   if (CalleeNode == CallerNode) {
1204f22ef01cSRoman Divacky     CallCache.assign(I, E);
1205f22ef01cSRoman Divacky     I = CallCache.begin();
1206f22ef01cSRoman Divacky     E = CallCache.end();
1207f22ef01cSRoman Divacky   }
1208f22ef01cSRoman Divacky 
1209f22ef01cSRoman Divacky   for (; I != E; ++I) {
1210f22ef01cSRoman Divacky     const Value *OrigCall = I->first;
1211f22ef01cSRoman Divacky 
12122754fe60SDimitry Andric     ValueToValueMapTy::iterator VMI = VMap.find(OrigCall);
1213f22ef01cSRoman Divacky     // Only copy the edge if the call was inlined!
121491bc56edSDimitry Andric     if (VMI == VMap.end() || VMI->second == nullptr)
1215f22ef01cSRoman Divacky       continue;
1216f22ef01cSRoman Divacky 
1217f22ef01cSRoman Divacky     // If the call was inlined, but then constant folded, there is no edge to
1218f22ef01cSRoman Divacky     // add.  Check for this case.
1219f22ef01cSRoman Divacky     Instruction *NewCall = dyn_cast<Instruction>(VMI->second);
1220ff0cc061SDimitry Andric     if (!NewCall)
1221ff0cc061SDimitry Andric       continue;
1222ff0cc061SDimitry Andric 
1223ff0cc061SDimitry Andric     // We do not treat intrinsic calls like real function calls because we
1224ff0cc061SDimitry Andric     // expect them to become inline code; do not add an edge for an intrinsic.
1225ff0cc061SDimitry Andric     CallSite CS = CallSite(NewCall);
1226ff0cc061SDimitry Andric     if (CS && CS.getCalledFunction() && CS.getCalledFunction()->isIntrinsic())
1227ff0cc061SDimitry Andric       continue;
1228f22ef01cSRoman Divacky 
1229f22ef01cSRoman Divacky     // Remember that this call site got inlined for the client of
1230f22ef01cSRoman Divacky     // InlineFunction.
1231f22ef01cSRoman Divacky     IFI.InlinedCalls.push_back(NewCall);
1232f22ef01cSRoman Divacky 
1233f22ef01cSRoman Divacky     // It's possible that inlining the callsite will cause it to go from an
1234f22ef01cSRoman Divacky     // indirect to a direct call by resolving a function pointer.  If this
1235f22ef01cSRoman Divacky     // happens, set the callee of the new call site to a more precise
1236f22ef01cSRoman Divacky     // destination.  This can also happen if the call graph node of the caller
1237f22ef01cSRoman Divacky     // was just unnecessarily imprecise.
123891bc56edSDimitry Andric     if (!I->second->getFunction())
1239f22ef01cSRoman Divacky       if (Function *F = CallSite(NewCall).getCalledFunction()) {
1240f22ef01cSRoman Divacky         // Indirect call site resolved to direct call.
1241e580952dSDimitry Andric         CallerNode->addCalledFunction(CallSite(NewCall), CG[F]);
1242f22ef01cSRoman Divacky 
1243f22ef01cSRoman Divacky         continue;
1244f22ef01cSRoman Divacky       }
1245f22ef01cSRoman Divacky 
1246e580952dSDimitry Andric     CallerNode->addCalledFunction(CallSite(NewCall), I->second);
1247f22ef01cSRoman Divacky   }
1248f22ef01cSRoman Divacky 
1249f22ef01cSRoman Divacky   // Update the call graph by deleting the edge from Callee to Caller.  We must
1250f22ef01cSRoman Divacky   // do this after the loop above in case Caller and Callee are the same.
1251f22ef01cSRoman Divacky   CallerNode->removeCallEdgeFor(CS);
1252f22ef01cSRoman Divacky }
1253f22ef01cSRoman Divacky 
HandleByValArgumentInit(Value * Dst,Value * Src,Module * M,BasicBlock * InsertBlock,InlineFunctionInfo & IFI)125491bc56edSDimitry Andric static void HandleByValArgumentInit(Value *Dst, Value *Src, Module *M,
125591bc56edSDimitry Andric                                     BasicBlock *InsertBlock,
125691bc56edSDimitry Andric                                     InlineFunctionInfo &IFI) {
125791bc56edSDimitry Andric   Type *AggTy = cast<PointerType>(Src->getType())->getElementType();
12587d523365SDimitry Andric   IRBuilder<> Builder(InsertBlock, InsertBlock->begin());
125991bc56edSDimitry Andric 
1260ff0cc061SDimitry Andric   Value *Size = Builder.getInt64(M->getDataLayout().getTypeStoreSize(AggTy));
126191bc56edSDimitry Andric 
126291bc56edSDimitry Andric   // Always generate a memcpy of alignment 1 here because we don't know
126391bc56edSDimitry Andric   // the alignment of the src pointer.  Other optimizations can infer
126491bc56edSDimitry Andric   // better alignment.
12654ba319b5SDimitry Andric   Builder.CreateMemCpy(Dst, /*DstAlign*/1, Src, /*SrcAlign*/1, Size);
126691bc56edSDimitry Andric }
126791bc56edSDimitry Andric 
1268ff0cc061SDimitry Andric /// When inlining a call site that has a byval argument,
12692754fe60SDimitry Andric /// we have to make the implicit memcpy explicit by adding it.
HandleByValArgument(Value * Arg,Instruction * TheCall,const Function * CalledFunc,InlineFunctionInfo & IFI,unsigned ByValAlignment)12702754fe60SDimitry Andric static Value *HandleByValArgument(Value *Arg, Instruction *TheCall,
12712754fe60SDimitry Andric                                   const Function *CalledFunc,
12722754fe60SDimitry Andric                                   InlineFunctionInfo &IFI,
12732754fe60SDimitry Andric                                   unsigned ByValAlignment) {
127491bc56edSDimitry Andric   PointerType *ArgTy = cast<PointerType>(Arg->getType());
127591bc56edSDimitry Andric   Type *AggTy = ArgTy->getElementType();
12762754fe60SDimitry Andric 
12777a7e6055SDimitry Andric   Function *Caller = TheCall->getFunction();
12787a7e6055SDimitry Andric   const DataLayout &DL = Caller->getParent()->getDataLayout();
127939d628a0SDimitry Andric 
12802754fe60SDimitry Andric   // If the called function is readonly, then it could not mutate the caller's
12812754fe60SDimitry Andric   // copy of the byval'd memory.  In this case, it is safe to elide the copy and
12822754fe60SDimitry Andric   // temporary.
12832754fe60SDimitry Andric   if (CalledFunc->onlyReadsMemory()) {
12842754fe60SDimitry Andric     // If the byval argument has a specified alignment that is greater than the
12852754fe60SDimitry Andric     // passed in pointer, then we either have to round up the input pointer or
12862754fe60SDimitry Andric     // give up on this transformation.
12872754fe60SDimitry Andric     if (ByValAlignment <= 1)  // 0 = unspecified, 1 = no particular alignment.
12882754fe60SDimitry Andric       return Arg;
12892754fe60SDimitry Andric 
1290d88c1a5aSDimitry Andric     AssumptionCache *AC =
1291d88c1a5aSDimitry Andric         IFI.GetAssumptionCache ? &(*IFI.GetAssumptionCache)(*Caller) : nullptr;
1292ff0cc061SDimitry Andric 
12932754fe60SDimitry Andric     // If the pointer is already known to be sufficiently aligned, or if we can
12942754fe60SDimitry Andric     // round it up to a larger alignment, then we don't need a temporary.
1295d88c1a5aSDimitry Andric     if (getOrEnforceKnownAlignment(Arg, ByValAlignment, DL, TheCall, AC) >=
1296ff0cc061SDimitry Andric         ByValAlignment)
12972754fe60SDimitry Andric       return Arg;
12982754fe60SDimitry Andric 
12992754fe60SDimitry Andric     // Otherwise, we have to make a memcpy to get a safe alignment.  This is bad
13002754fe60SDimitry Andric     // for code quality, but rarely happens and is required for correctness.
13012754fe60SDimitry Andric   }
13022754fe60SDimitry Andric 
13033861d79fSDimitry Andric   // Create the alloca.  If we have DataLayout, use nice alignment.
13047a7e6055SDimitry Andric   unsigned Align = DL.getPrefTypeAlignment(AggTy);
13052754fe60SDimitry Andric 
13062754fe60SDimitry Andric   // If the byval had an alignment specified, we *must* use at least that
13072754fe60SDimitry Andric   // alignment, as it is required by the byval argument (and uses of the
13082754fe60SDimitry Andric   // pointer inside the callee).
13092754fe60SDimitry Andric   Align = std::max(Align, ByValAlignment);
13102754fe60SDimitry Andric 
13117a7e6055SDimitry Andric   Value *NewAlloca = new AllocaInst(AggTy, DL.getAllocaAddrSpace(),
13127a7e6055SDimitry Andric                                     nullptr, Align, Arg->getName(),
13132754fe60SDimitry Andric                                     &*Caller->begin()->begin());
131491bc56edSDimitry Andric   IFI.StaticAllocas.push_back(cast<AllocaInst>(NewAlloca));
13152754fe60SDimitry Andric 
13162754fe60SDimitry Andric   // Uses of the argument in the function should use our new alloca
13172754fe60SDimitry Andric   // instead.
13182754fe60SDimitry Andric   return NewAlloca;
13192754fe60SDimitry Andric }
13202754fe60SDimitry Andric 
1321ff0cc061SDimitry Andric // Check whether this Value is used by a lifetime intrinsic.
isUsedByLifetimeMarker(Value * V)1322bd5abe19SDimitry Andric static bool isUsedByLifetimeMarker(Value *V) {
1323*b5893f02SDimitry Andric   for (User *U : V->users())
1324*b5893f02SDimitry Andric     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U))
1325*b5893f02SDimitry Andric       if (II->isLifetimeStartOrEnd())
1326bd5abe19SDimitry Andric         return true;
1327bd5abe19SDimitry Andric   return false;
1328bd5abe19SDimitry Andric }
1329bd5abe19SDimitry Andric 
1330ff0cc061SDimitry Andric // Check whether the given alloca already has
1331bd5abe19SDimitry Andric // lifetime.start or lifetime.end intrinsics.
hasLifetimeMarkers(AllocaInst * AI)1332bd5abe19SDimitry Andric static bool hasLifetimeMarkers(AllocaInst *AI) {
133391bc56edSDimitry Andric   Type *Ty = AI->getType();
133491bc56edSDimitry Andric   Type *Int8PtrTy = Type::getInt8PtrTy(Ty->getContext(),
133591bc56edSDimitry Andric                                        Ty->getPointerAddressSpace());
133691bc56edSDimitry Andric   if (Ty == Int8PtrTy)
1337bd5abe19SDimitry Andric     return isUsedByLifetimeMarker(AI);
1338bd5abe19SDimitry Andric 
133917a519f9SDimitry Andric   // Do a scan to find all the casts to i8*.
134091bc56edSDimitry Andric   for (User *U : AI->users()) {
134191bc56edSDimitry Andric     if (U->getType() != Int8PtrTy) continue;
134291bc56edSDimitry Andric     if (U->stripPointerCasts() != AI) continue;
134391bc56edSDimitry Andric     if (isUsedByLifetimeMarker(U))
1344bd5abe19SDimitry Andric       return true;
1345bd5abe19SDimitry Andric   }
1346bd5abe19SDimitry Andric   return false;
1347bd5abe19SDimitry Andric }
1348bd5abe19SDimitry Andric 
13496c4bc1bdSDimitry Andric /// Return the result of AI->isStaticAlloca() if AI were moved to the entry
13506c4bc1bdSDimitry Andric /// block. Allocas used in inalloca calls and allocas of dynamic array size
13516c4bc1bdSDimitry Andric /// cannot be static.
allocaWouldBeStaticInEntry(const AllocaInst * AI)13526c4bc1bdSDimitry Andric static bool allocaWouldBeStaticInEntry(const AllocaInst *AI ) {
13536c4bc1bdSDimitry Andric   return isa<Constant>(AI->getArraySize()) && !AI->isUsedWithInAlloca();
13546c4bc1bdSDimitry Andric }
13556c4bc1bdSDimitry Andric 
1356ff0cc061SDimitry Andric /// Update inlined instructions' line numbers to
135717a519f9SDimitry Andric /// to encode location where these instructions are inlined.
fixupLineNumbers(Function * Fn,Function::iterator FI,Instruction * TheCall,bool CalleeHasDebugInfo)135817a519f9SDimitry Andric static void fixupLineNumbers(Function *Fn, Function::iterator FI,
1359d88c1a5aSDimitry Andric                              Instruction *TheCall, bool CalleeHasDebugInfo) {
13603ca95b02SDimitry Andric   const DebugLoc &TheCallDL = TheCall->getDebugLoc();
1361ff0cc061SDimitry Andric   if (!TheCallDL)
136217a519f9SDimitry Andric     return;
136317a519f9SDimitry Andric 
1364ff0cc061SDimitry Andric   auto &Ctx = Fn->getContext();
1365ff0cc061SDimitry Andric   DILocation *InlinedAtNode = TheCallDL;
1366ff0cc061SDimitry Andric 
1367ff0cc061SDimitry Andric   // Create a unique call site, not to be confused with any other call from the
1368ff0cc061SDimitry Andric   // same location.
1369ff0cc061SDimitry Andric   InlinedAtNode = DILocation::getDistinct(
1370ff0cc061SDimitry Andric       Ctx, InlinedAtNode->getLine(), InlinedAtNode->getColumn(),
1371ff0cc061SDimitry Andric       InlinedAtNode->getScope(), InlinedAtNode->getInlinedAt());
1372ff0cc061SDimitry Andric 
1373ff0cc061SDimitry Andric   // Cache the inlined-at nodes as they're built so they are reused, without
1374ff0cc061SDimitry Andric   // this every instruction's inlined-at chain would become distinct from each
1375ff0cc061SDimitry Andric   // other.
13765517e702SDimitry Andric   DenseMap<const MDNode *, MDNode *> IANodes;
1377ff0cc061SDimitry Andric 
137817a519f9SDimitry Andric   for (; FI != Fn->end(); ++FI) {
137917a519f9SDimitry Andric     for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
138017a519f9SDimitry Andric          BI != BE; ++BI) {
1381d88c1a5aSDimitry Andric       if (DebugLoc DL = BI->getDebugLoc()) {
13825517e702SDimitry Andric         auto IA = DebugLoc::appendInlinedAt(DL, InlinedAtNode, BI->getContext(),
13835517e702SDimitry Andric                                             IANodes);
13845517e702SDimitry Andric         auto IDL = DebugLoc::get(DL.getLine(), DL.getCol(), DL.getScope(), IA);
13855517e702SDimitry Andric         BI->setDebugLoc(IDL);
1386d88c1a5aSDimitry Andric         continue;
1387d88c1a5aSDimitry Andric       }
1388d88c1a5aSDimitry Andric 
1389d88c1a5aSDimitry Andric       if (CalleeHasDebugInfo)
1390d88c1a5aSDimitry Andric         continue;
1391d88c1a5aSDimitry Andric 
139291bc56edSDimitry Andric       // If the inlined instruction has no line number, make it look as if it
139391bc56edSDimitry Andric       // originates from the call location. This is important for
139491bc56edSDimitry Andric       // ((__always_inline__, __nodebug__)) functions which must use caller
139591bc56edSDimitry Andric       // location for all instructions in their function body.
139639d628a0SDimitry Andric 
139739d628a0SDimitry Andric       // Don't update static allocas, as they may get moved later.
139839d628a0SDimitry Andric       if (auto *AI = dyn_cast<AllocaInst>(BI))
13996c4bc1bdSDimitry Andric         if (allocaWouldBeStaticInEntry(AI))
140039d628a0SDimitry Andric           continue;
140139d628a0SDimitry Andric 
140291bc56edSDimitry Andric       BI->setDebugLoc(TheCallDL);
140317a519f9SDimitry Andric     }
140417a519f9SDimitry Andric   }
140517a519f9SDimitry Andric }
14062cab237bSDimitry Andric 
14077a7e6055SDimitry Andric /// Update the block frequencies of the caller after a callee has been inlined.
14087a7e6055SDimitry Andric ///
14097a7e6055SDimitry Andric /// Each block cloned into the caller has its block frequency scaled by the
14107a7e6055SDimitry Andric /// ratio of CallSiteFreq/CalleeEntryFreq. This ensures that the cloned copy of
14117a7e6055SDimitry Andric /// callee's entry block gets the same frequency as the callsite block and the
14127a7e6055SDimitry Andric /// relative frequencies of all cloned blocks remain the same after cloning.
updateCallerBFI(BasicBlock * CallSiteBlock,const ValueToValueMapTy & VMap,BlockFrequencyInfo * CallerBFI,BlockFrequencyInfo * CalleeBFI,const BasicBlock & CalleeEntryBlock)14137a7e6055SDimitry Andric static void updateCallerBFI(BasicBlock *CallSiteBlock,
14147a7e6055SDimitry Andric                             const ValueToValueMapTy &VMap,
14157a7e6055SDimitry Andric                             BlockFrequencyInfo *CallerBFI,
14167a7e6055SDimitry Andric                             BlockFrequencyInfo *CalleeBFI,
14177a7e6055SDimitry Andric                             const BasicBlock &CalleeEntryBlock) {
14187a7e6055SDimitry Andric   SmallPtrSet<BasicBlock *, 16> ClonedBBs;
14197a7e6055SDimitry Andric   for (auto const &Entry : VMap) {
14207a7e6055SDimitry Andric     if (!isa<BasicBlock>(Entry.first) || !Entry.second)
14217a7e6055SDimitry Andric       continue;
14227a7e6055SDimitry Andric     auto *OrigBB = cast<BasicBlock>(Entry.first);
14237a7e6055SDimitry Andric     auto *ClonedBB = cast<BasicBlock>(Entry.second);
14247a7e6055SDimitry Andric     uint64_t Freq = CalleeBFI->getBlockFreq(OrigBB).getFrequency();
14257a7e6055SDimitry Andric     if (!ClonedBBs.insert(ClonedBB).second) {
14267a7e6055SDimitry Andric       // Multiple blocks in the callee might get mapped to one cloned block in
14277a7e6055SDimitry Andric       // the caller since we prune the callee as we clone it. When that happens,
14287a7e6055SDimitry Andric       // we want to use the maximum among the original blocks' frequencies.
14297a7e6055SDimitry Andric       uint64_t NewFreq = CallerBFI->getBlockFreq(ClonedBB).getFrequency();
14307a7e6055SDimitry Andric       if (NewFreq > Freq)
14317a7e6055SDimitry Andric         Freq = NewFreq;
14327a7e6055SDimitry Andric     }
14337a7e6055SDimitry Andric     CallerBFI->setBlockFreq(ClonedBB, Freq);
14347a7e6055SDimitry Andric   }
14357a7e6055SDimitry Andric   BasicBlock *EntryClone = cast<BasicBlock>(VMap.lookup(&CalleeEntryBlock));
14367a7e6055SDimitry Andric   CallerBFI->setBlockFreqAndScale(
14377a7e6055SDimitry Andric       EntryClone, CallerBFI->getBlockFreq(CallSiteBlock).getFrequency(),
14387a7e6055SDimitry Andric       ClonedBBs);
14397a7e6055SDimitry Andric }
14407a7e6055SDimitry Andric 
14417a7e6055SDimitry Andric /// Update the branch metadata for cloned call instructions.
updateCallProfile(Function * Callee,const ValueToValueMapTy & VMap,const ProfileCount & CalleeEntryCount,const Instruction * TheCall,ProfileSummaryInfo * PSI,BlockFrequencyInfo * CallerBFI)14427a7e6055SDimitry Andric static void updateCallProfile(Function *Callee, const ValueToValueMapTy &VMap,
14434ba319b5SDimitry Andric                               const ProfileCount &CalleeEntryCount,
14445517e702SDimitry Andric                               const Instruction *TheCall,
1445302affcbSDimitry Andric                               ProfileSummaryInfo *PSI,
1446302affcbSDimitry Andric                               BlockFrequencyInfo *CallerBFI) {
14474ba319b5SDimitry Andric   if (!CalleeEntryCount.hasValue() || CalleeEntryCount.isSynthetic() ||
14484ba319b5SDimitry Andric       CalleeEntryCount.getCount() < 1)
14497a7e6055SDimitry Andric     return;
14504ba319b5SDimitry Andric   auto CallSiteCount = PSI ? PSI->getProfileCount(TheCall, CallerBFI) : None;
14517a7e6055SDimitry Andric   uint64_t CallCount =
14527a7e6055SDimitry Andric       std::min(CallSiteCount.hasValue() ? CallSiteCount.getValue() : 0,
14534ba319b5SDimitry Andric                CalleeEntryCount.getCount());
14547a7e6055SDimitry Andric 
14557a7e6055SDimitry Andric   for (auto const &Entry : VMap)
14567a7e6055SDimitry Andric     if (isa<CallInst>(Entry.first))
14577a7e6055SDimitry Andric       if (auto *CI = dyn_cast_or_null<CallInst>(Entry.second))
14584ba319b5SDimitry Andric         CI->updateProfWeight(CallCount, CalleeEntryCount.getCount());
14597a7e6055SDimitry Andric   for (BasicBlock &BB : *Callee)
14607a7e6055SDimitry Andric     // No need to update the callsite if it is pruned during inlining.
14617a7e6055SDimitry Andric     if (VMap.count(&BB))
14627a7e6055SDimitry Andric       for (Instruction &I : BB)
14637a7e6055SDimitry Andric         if (CallInst *CI = dyn_cast<CallInst>(&I))
14644ba319b5SDimitry Andric           CI->updateProfWeight(CalleeEntryCount.getCount() - CallCount,
14654ba319b5SDimitry Andric                                CalleeEntryCount.getCount());
14667a7e6055SDimitry Andric }
14677a7e6055SDimitry Andric 
14687a7e6055SDimitry Andric /// Update the entry count of callee after inlining.
14697a7e6055SDimitry Andric ///
14707a7e6055SDimitry Andric /// The callsite's block count is subtracted from the callee's function entry
14717a7e6055SDimitry Andric /// count.
updateCalleeCount(BlockFrequencyInfo * CallerBFI,BasicBlock * CallBB,Instruction * CallInst,Function * Callee,ProfileSummaryInfo * PSI)14727a7e6055SDimitry Andric static void updateCalleeCount(BlockFrequencyInfo *CallerBFI, BasicBlock *CallBB,
14735517e702SDimitry Andric                               Instruction *CallInst, Function *Callee,
14745517e702SDimitry Andric                               ProfileSummaryInfo *PSI) {
14757a7e6055SDimitry Andric   // If the callee has a original count of N, and the estimated count of
14767a7e6055SDimitry Andric   // callsite is M, the new callee count is set to N - M. M is estimated from
14777a7e6055SDimitry Andric   // the caller's entry count, its entry block frequency and the block frequency
14787a7e6055SDimitry Andric   // of the callsite.
14794ba319b5SDimitry Andric   auto CalleeCount = Callee->getEntryCount();
14805517e702SDimitry Andric   if (!CalleeCount.hasValue() || !PSI)
14817a7e6055SDimitry Andric     return;
14824ba319b5SDimitry Andric   auto CallCount = PSI->getProfileCount(CallInst, CallerBFI);
14837a7e6055SDimitry Andric   if (!CallCount.hasValue())
14847a7e6055SDimitry Andric     return;
14857a7e6055SDimitry Andric   // Since CallSiteCount is an estimate, it could exceed the original callee
14867a7e6055SDimitry Andric   // count and has to be set to 0.
14874ba319b5SDimitry Andric   if (CallCount.getValue() > CalleeCount.getCount())
14884ba319b5SDimitry Andric     CalleeCount.setCount(0);
14897a7e6055SDimitry Andric   else
14904ba319b5SDimitry Andric     CalleeCount.setCount(CalleeCount.getCount() - CallCount.getValue());
14914ba319b5SDimitry Andric   Callee->setEntryCount(CalleeCount);
14927a7e6055SDimitry Andric }
149317a519f9SDimitry Andric 
1494ff0cc061SDimitry Andric /// This function inlines the called function into the basic block of the
1495ff0cc061SDimitry Andric /// caller. This returns false if it is not possible to inline this call.
1496ff0cc061SDimitry Andric /// The program is still in a well defined state if this occurs though.
1497dff0c46cSDimitry Andric ///
1498dff0c46cSDimitry Andric /// Note that this only does one level of inlining.  For example, if the
1499dff0c46cSDimitry Andric /// instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
1500dff0c46cSDimitry Andric /// exists in the instruction stream.  Similarly this will inline a recursive
1501dff0c46cSDimitry Andric /// function by one level.
InlineFunction(CallSite CS,InlineFunctionInfo & IFI,AAResults * CalleeAAR,bool InsertLifetime,Function * ForwardVarArgsTo)1502*b5893f02SDimitry Andric llvm::InlineResult llvm::InlineFunction(CallSite CS, InlineFunctionInfo &IFI,
1503*b5893f02SDimitry Andric                                         AAResults *CalleeAAR,
1504*b5893f02SDimitry Andric                                         bool InsertLifetime,
15052cab237bSDimitry Andric                                         Function *ForwardVarArgsTo) {
1506f22ef01cSRoman Divacky   Instruction *TheCall = CS.getInstruction();
15077a7e6055SDimitry Andric   assert(TheCall->getParent() && TheCall->getFunction()
15087a7e6055SDimitry Andric          && "Instruction not in function!");
1509f22ef01cSRoman Divacky 
1510f22ef01cSRoman Divacky   // If IFI has any state in it, zap it before we fill it in.
1511f22ef01cSRoman Divacky   IFI.reset();
1512f22ef01cSRoman Divacky 
15137a7e6055SDimitry Andric   Function *CalledFunc = CS.getCalledFunction();
151491bc56edSDimitry Andric   if (!CalledFunc ||               // Can't inline external function or indirect
15154ba319b5SDimitry Andric       CalledFunc->isDeclaration()) // call!
1516*b5893f02SDimitry Andric     return "external or indirect";
1517f22ef01cSRoman Divacky 
15187d523365SDimitry Andric   // The inliner does not know how to inline through calls with operand bundles
15197d523365SDimitry Andric   // in general ...
15207d523365SDimitry Andric   if (CS.hasOperandBundles()) {
15217d523365SDimitry Andric     for (int i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
15227d523365SDimitry Andric       uint32_t Tag = CS.getOperandBundleAt(i).getTagID();
15237d523365SDimitry Andric       // ... but it knows how to inline through "deopt" operand bundles ...
15247d523365SDimitry Andric       if (Tag == LLVMContext::OB_deopt)
15257d523365SDimitry Andric         continue;
15267d523365SDimitry Andric       // ... and "funclet" operand bundles.
15277d523365SDimitry Andric       if (Tag == LLVMContext::OB_funclet)
15287d523365SDimitry Andric         continue;
15297d523365SDimitry Andric 
1530*b5893f02SDimitry Andric       return "unsupported operand bundle";
15317d523365SDimitry Andric     }
15327d523365SDimitry Andric   }
15337d523365SDimitry Andric 
1534f22ef01cSRoman Divacky   // If the call to the callee cannot throw, set the 'nounwind' flag on any
1535f22ef01cSRoman Divacky   // calls that we inline.
1536f22ef01cSRoman Divacky   bool MarkNoUnwind = CS.doesNotThrow();
1537f22ef01cSRoman Divacky 
1538f22ef01cSRoman Divacky   BasicBlock *OrigBB = TheCall->getParent();
1539f22ef01cSRoman Divacky   Function *Caller = OrigBB->getParent();
1540f22ef01cSRoman Divacky 
1541f22ef01cSRoman Divacky   // GC poses two hazards to inlining, which only occur when the callee has GC:
1542f22ef01cSRoman Divacky   //  1. If the caller has no GC, then the callee's GC must be propagated to the
1543f22ef01cSRoman Divacky   //     caller.
1544f22ef01cSRoman Divacky   //  2. If the caller has a differing GC, it is invalid to inline.
1545f22ef01cSRoman Divacky   if (CalledFunc->hasGC()) {
1546f22ef01cSRoman Divacky     if (!Caller->hasGC())
1547f22ef01cSRoman Divacky       Caller->setGC(CalledFunc->getGC());
1548f22ef01cSRoman Divacky     else if (CalledFunc->getGC() != Caller->getGC())
1549*b5893f02SDimitry Andric       return "incompatible GC";
1550f22ef01cSRoman Divacky   }
1551f22ef01cSRoman Divacky 
1552dff0c46cSDimitry Andric   // Get the personality function from the callee if it contains a landing pad.
15538f0fd8f6SDimitry Andric   Constant *CalledPersonality =
15547d523365SDimitry Andric       CalledFunc->hasPersonalityFn()
15557d523365SDimitry Andric           ? CalledFunc->getPersonalityFn()->stripPointerCasts()
15567d523365SDimitry Andric           : nullptr;
1557dff0c46cSDimitry Andric 
15586122f3e6SDimitry Andric   // Find the personality function used by the landing pads of the caller. If it
15596122f3e6SDimitry Andric   // exists, then check to see that it matches the personality function used in
15606122f3e6SDimitry Andric   // the callee.
15618f0fd8f6SDimitry Andric   Constant *CallerPersonality =
15627d523365SDimitry Andric       Caller->hasPersonalityFn()
15637d523365SDimitry Andric           ? Caller->getPersonalityFn()->stripPointerCasts()
15647d523365SDimitry Andric           : nullptr;
15658f0fd8f6SDimitry Andric   if (CalledPersonality) {
15668f0fd8f6SDimitry Andric     if (!CallerPersonality)
15678f0fd8f6SDimitry Andric       Caller->setPersonalityFn(CalledPersonality);
15686122f3e6SDimitry Andric     // If the personality functions match, then we can perform the
15696122f3e6SDimitry Andric     // inlining. Otherwise, we can't inline.
15706122f3e6SDimitry Andric     // TODO: This isn't 100% true. Some personality functions are proper
15716122f3e6SDimitry Andric     //       supersets of others and can be used in place of the other.
15728f0fd8f6SDimitry Andric     else if (CalledPersonality != CallerPersonality)
1573*b5893f02SDimitry Andric       return "incompatible personality";
1574dff0c46cSDimitry Andric   }
15756122f3e6SDimitry Andric 
15767d523365SDimitry Andric   // We need to figure out which funclet the callsite was in so that we may
15777d523365SDimitry Andric   // properly nest the callee.
15787d523365SDimitry Andric   Instruction *CallSiteEHPad = nullptr;
15797d523365SDimitry Andric   if (CallerPersonality) {
15807d523365SDimitry Andric     EHPersonality Personality = classifyEHPersonality(CallerPersonality);
15814ba319b5SDimitry Andric     if (isScopedEHPersonality(Personality)) {
15827d523365SDimitry Andric       Optional<OperandBundleUse> ParentFunclet =
15837d523365SDimitry Andric           CS.getOperandBundle(LLVMContext::OB_funclet);
15847d523365SDimitry Andric       if (ParentFunclet)
15857d523365SDimitry Andric         CallSiteEHPad = cast<FuncletPadInst>(ParentFunclet->Inputs.front());
15867d523365SDimitry Andric 
15877d523365SDimitry Andric       // OK, the inlining site is legal.  What about the target function?
15887d523365SDimitry Andric 
15897d523365SDimitry Andric       if (CallSiteEHPad) {
15907d523365SDimitry Andric         if (Personality == EHPersonality::MSVC_CXX) {
15917d523365SDimitry Andric           // The MSVC personality cannot tolerate catches getting inlined into
15927d523365SDimitry Andric           // cleanup funclets.
15937d523365SDimitry Andric           if (isa<CleanupPadInst>(CallSiteEHPad)) {
15947d523365SDimitry Andric             // Ok, the call site is within a cleanuppad.  Let's check the callee
15957d523365SDimitry Andric             // for catchpads.
15967d523365SDimitry Andric             for (const BasicBlock &CalledBB : *CalledFunc) {
15977d523365SDimitry Andric               if (isa<CatchSwitchInst>(CalledBB.getFirstNonPHI()))
1598*b5893f02SDimitry Andric                 return "catch in cleanup funclet";
15997d523365SDimitry Andric             }
16007d523365SDimitry Andric           }
16017d523365SDimitry Andric         } else if (isAsynchronousEHPersonality(Personality)) {
16027d523365SDimitry Andric           // SEH is even less tolerant, there may not be any sort of exceptional
16037d523365SDimitry Andric           // funclet in the callee.
16047d523365SDimitry Andric           for (const BasicBlock &CalledBB : *CalledFunc) {
16057d523365SDimitry Andric             if (CalledBB.isEHPad())
1606*b5893f02SDimitry Andric               return "SEH in cleanup funclet";
16077d523365SDimitry Andric           }
16087d523365SDimitry Andric         }
16097d523365SDimitry Andric       }
16107d523365SDimitry Andric     }
16117d523365SDimitry Andric   }
16127d523365SDimitry Andric 
16133ca95b02SDimitry Andric   // Determine if we are dealing with a call in an EHPad which does not unwind
16143ca95b02SDimitry Andric   // to caller.
16153ca95b02SDimitry Andric   bool EHPadForCallUnwindsLocally = false;
16163ca95b02SDimitry Andric   if (CallSiteEHPad && CS.isCall()) {
16173ca95b02SDimitry Andric     UnwindDestMemoTy FuncletUnwindMap;
16183ca95b02SDimitry Andric     Value *CallSiteUnwindDestToken =
16193ca95b02SDimitry Andric         getUnwindDestToken(CallSiteEHPad, FuncletUnwindMap);
16203ca95b02SDimitry Andric 
16213ca95b02SDimitry Andric     EHPadForCallUnwindsLocally =
16223ca95b02SDimitry Andric         CallSiteUnwindDestToken &&
16233ca95b02SDimitry Andric         !isa<ConstantTokenNone>(CallSiteUnwindDestToken);
16243ca95b02SDimitry Andric   }
16253ca95b02SDimitry Andric 
1626f22ef01cSRoman Divacky   // Get an iterator to the last basic block in the function, which will have
1627f22ef01cSRoman Divacky   // the new function inlined after it.
16287d523365SDimitry Andric   Function::iterator LastBlock = --Caller->end();
1629f22ef01cSRoman Divacky 
1630f22ef01cSRoman Divacky   // Make sure to capture all of the return instructions from the cloned
1631f22ef01cSRoman Divacky   // function.
1632f22ef01cSRoman Divacky   SmallVector<ReturnInst*, 8> Returns;
1633f22ef01cSRoman Divacky   ClonedCodeInfo InlinedFunctionInfo;
1634f22ef01cSRoman Divacky   Function::iterator FirstNewBlock;
1635f22ef01cSRoman Divacky 
1636ffd1746dSEd Schouten   { // Scope to destroy VMap after cloning.
16372754fe60SDimitry Andric     ValueToValueMapTy VMap;
163891bc56edSDimitry Andric     // Keep a list of pair (dst, src) to emit byval initializations.
163991bc56edSDimitry Andric     SmallVector<std::pair<Value*, Value*>, 4> ByValInit;
1640f22ef01cSRoman Divacky 
1641ff0cc061SDimitry Andric     auto &DL = Caller->getParent()->getDataLayout();
1642ff0cc061SDimitry Andric 
1643f22ef01cSRoman Divacky     // Calculate the vector of arguments to pass into the function cloner, which
1644f22ef01cSRoman Divacky     // matches up the formal to the actual argument values.
1645f22ef01cSRoman Divacky     CallSite::arg_iterator AI = CS.arg_begin();
1646f22ef01cSRoman Divacky     unsigned ArgNo = 0;
16477a7e6055SDimitry Andric     for (Function::arg_iterator I = CalledFunc->arg_begin(),
1648f22ef01cSRoman Divacky          E = CalledFunc->arg_end(); I != E; ++I, ++AI, ++ArgNo) {
1649f22ef01cSRoman Divacky       Value *ActualArg = *AI;
1650f22ef01cSRoman Divacky 
1651f22ef01cSRoman Divacky       // When byval arguments actually inlined, we need to make the copy implied
1652f22ef01cSRoman Divacky       // by them explicit.  However, we don't do this if the callee is readonly
1653f22ef01cSRoman Divacky       // or readnone, because the copy would be unneeded: the callee doesn't
1654f22ef01cSRoman Divacky       // modify the struct.
1655dff0c46cSDimitry Andric       if (CS.isByValArgument(ArgNo)) {
16562754fe60SDimitry Andric         ActualArg = HandleByValArgument(ActualArg, TheCall, CalledFunc, IFI,
1657f37b6182SDimitry Andric                                         CalledFunc->getParamAlignment(ArgNo));
165891bc56edSDimitry Andric         if (ActualArg != *AI)
165991bc56edSDimitry Andric           ByValInit.push_back(std::make_pair(ActualArg, (Value*) *AI));
1660f22ef01cSRoman Divacky       }
1661f22ef01cSRoman Divacky 
16627d523365SDimitry Andric       VMap[&*I] = ActualArg;
1663f22ef01cSRoman Divacky     }
1664f22ef01cSRoman Divacky 
166539d628a0SDimitry Andric     // Add alignment assumptions if necessary. We do this before the inlined
166639d628a0SDimitry Andric     // instructions are actually cloned into the caller so that we can easily
166739d628a0SDimitry Andric     // check what will be known at the start of the inlined code.
166839d628a0SDimitry Andric     AddAlignmentAssumptions(CS, IFI);
166939d628a0SDimitry Andric 
1670f22ef01cSRoman Divacky     // We want the inliner to prune the code as it copies.  We would LOVE to
1671f22ef01cSRoman Divacky     // have no dead or constant instructions leftover after inlining occurs
1672f22ef01cSRoman Divacky     // (which can happen, e.g., because an argument was constant), but we'll be
1673f22ef01cSRoman Divacky     // happy with whatever the cloner can do.
1674e580952dSDimitry Andric     CloneAndPruneFunctionInto(Caller, CalledFunc, VMap,
1675e580952dSDimitry Andric                               /*ModuleLevelChanges=*/false, Returns, ".i",
1676ff0cc061SDimitry Andric                               &InlinedFunctionInfo, TheCall);
1677f22ef01cSRoman Divacky     // Remember the first block that is newly cloned over.
1678f22ef01cSRoman Divacky     FirstNewBlock = LastBlock; ++FirstNewBlock;
1679f22ef01cSRoman Divacky 
16807a7e6055SDimitry Andric     if (IFI.CallerBFI != nullptr && IFI.CalleeBFI != nullptr)
16817a7e6055SDimitry Andric       // Update the BFI of blocks cloned into the caller.
16827a7e6055SDimitry Andric       updateCallerBFI(OrigBB, VMap, IFI.CallerBFI, IFI.CalleeBFI,
16837a7e6055SDimitry Andric                       CalledFunc->front());
16847a7e6055SDimitry Andric 
16855517e702SDimitry Andric     updateCallProfile(CalledFunc, VMap, CalledFunc->getEntryCount(), TheCall,
1686302affcbSDimitry Andric                       IFI.PSI, IFI.CallerBFI);
16877a7e6055SDimitry Andric     // Update the profile count of callee.
16885517e702SDimitry Andric     updateCalleeCount(IFI.CallerBFI, OrigBB, TheCall, CalledFunc, IFI.PSI);
16897a7e6055SDimitry Andric 
169091bc56edSDimitry Andric     // Inject byval arguments initialization.
169191bc56edSDimitry Andric     for (std::pair<Value*, Value*> &Init : ByValInit)
169291bc56edSDimitry Andric       HandleByValArgumentInit(Init.first, Init.second, Caller->getParent(),
16937d523365SDimitry Andric                               &*FirstNewBlock, IFI);
16947d523365SDimitry Andric 
16957d523365SDimitry Andric     Optional<OperandBundleUse> ParentDeopt =
16967d523365SDimitry Andric         CS.getOperandBundle(LLVMContext::OB_deopt);
16977d523365SDimitry Andric     if (ParentDeopt) {
16987d523365SDimitry Andric       SmallVector<OperandBundleDef, 2> OpDefs;
16997d523365SDimitry Andric 
17007d523365SDimitry Andric       for (auto &VH : InlinedFunctionInfo.OperandBundleCallSites) {
17017d523365SDimitry Andric         Instruction *I = dyn_cast_or_null<Instruction>(VH);
17027d523365SDimitry Andric         if (!I) continue;  // instruction was DCE'd or RAUW'ed to undef
17037d523365SDimitry Andric 
17047d523365SDimitry Andric         OpDefs.clear();
17057d523365SDimitry Andric 
17067d523365SDimitry Andric         CallSite ICS(I);
17077d523365SDimitry Andric         OpDefs.reserve(ICS.getNumOperandBundles());
17087d523365SDimitry Andric 
17097d523365SDimitry Andric         for (unsigned i = 0, e = ICS.getNumOperandBundles(); i < e; ++i) {
17107d523365SDimitry Andric           auto ChildOB = ICS.getOperandBundleAt(i);
17117d523365SDimitry Andric           if (ChildOB.getTagID() != LLVMContext::OB_deopt) {
17127d523365SDimitry Andric             // If the inlined call has other operand bundles, let them be
17137d523365SDimitry Andric             OpDefs.emplace_back(ChildOB);
17147d523365SDimitry Andric             continue;
17157d523365SDimitry Andric           }
17167d523365SDimitry Andric 
17177d523365SDimitry Andric           // It may be useful to separate this logic (of handling operand
17187d523365SDimitry Andric           // bundles) out to a separate "policy" component if this gets crowded.
17197d523365SDimitry Andric           // Prepend the parent's deoptimization continuation to the newly
17207d523365SDimitry Andric           // inlined call's deoptimization continuation.
17217d523365SDimitry Andric           std::vector<Value *> MergedDeoptArgs;
17227d523365SDimitry Andric           MergedDeoptArgs.reserve(ParentDeopt->Inputs.size() +
17237d523365SDimitry Andric                                   ChildOB.Inputs.size());
17247d523365SDimitry Andric 
17257d523365SDimitry Andric           MergedDeoptArgs.insert(MergedDeoptArgs.end(),
17267d523365SDimitry Andric                                  ParentDeopt->Inputs.begin(),
17277d523365SDimitry Andric                                  ParentDeopt->Inputs.end());
17287d523365SDimitry Andric           MergedDeoptArgs.insert(MergedDeoptArgs.end(), ChildOB.Inputs.begin(),
17297d523365SDimitry Andric                                  ChildOB.Inputs.end());
17307d523365SDimitry Andric 
17317d523365SDimitry Andric           OpDefs.emplace_back("deopt", std::move(MergedDeoptArgs));
17327d523365SDimitry Andric         }
17337d523365SDimitry Andric 
17347d523365SDimitry Andric         Instruction *NewI = nullptr;
17357d523365SDimitry Andric         if (isa<CallInst>(I))
17367d523365SDimitry Andric           NewI = CallInst::Create(cast<CallInst>(I), OpDefs, I);
17377d523365SDimitry Andric         else
17387d523365SDimitry Andric           NewI = InvokeInst::Create(cast<InvokeInst>(I), OpDefs, I);
17397d523365SDimitry Andric 
17407d523365SDimitry Andric         // Note: the RAUW does the appropriate fixup in VMap, so we need to do
17417d523365SDimitry Andric         // this even if the call returns void.
17427d523365SDimitry Andric         I->replaceAllUsesWith(NewI);
17437d523365SDimitry Andric 
17447d523365SDimitry Andric         VH = nullptr;
17457d523365SDimitry Andric         I->eraseFromParent();
17467d523365SDimitry Andric       }
17477d523365SDimitry Andric     }
174891bc56edSDimitry Andric 
1749f22ef01cSRoman Divacky     // Update the callgraph if requested.
1750f22ef01cSRoman Divacky     if (IFI.CG)
1751ffd1746dSEd Schouten       UpdateCallGraphAfterInlining(CS, FirstNewBlock, VMap, IFI);
175217a519f9SDimitry Andric 
1753d88c1a5aSDimitry Andric     // For 'nodebug' functions, the associated DISubprogram is always null.
1754d88c1a5aSDimitry Andric     // Conservatively avoid propagating the callsite debug location to
1755d88c1a5aSDimitry Andric     // instructions inlined from a function whose DISubprogram is not null.
1756d88c1a5aSDimitry Andric     fixupLineNumbers(Caller, FirstNewBlock, TheCall,
1757d88c1a5aSDimitry Andric                      CalledFunc->getSubprogram() != nullptr);
175839d628a0SDimitry Andric 
175939d628a0SDimitry Andric     // Clone existing noalias metadata if necessary.
176039d628a0SDimitry Andric     CloneAliasScopeMetadata(CS, VMap);
176139d628a0SDimitry Andric 
176239d628a0SDimitry Andric     // Add noalias metadata if necessary.
17637d523365SDimitry Andric     AddAliasScopeMetadata(CS, VMap, DL, CalleeAAR);
176439d628a0SDimitry Andric 
17653ca95b02SDimitry Andric     // Propagate llvm.mem.parallel_loop_access if necessary.
17663ca95b02SDimitry Andric     PropagateParallelLoopAccessMetadata(CS, VMap);
17673ca95b02SDimitry Andric 
1768d88c1a5aSDimitry Andric     // Register any cloned assumptions.
1769d88c1a5aSDimitry Andric     if (IFI.GetAssumptionCache)
1770d88c1a5aSDimitry Andric       for (BasicBlock &NewBlock :
1771d88c1a5aSDimitry Andric            make_range(FirstNewBlock->getIterator(), Caller->end()))
1772d88c1a5aSDimitry Andric         for (Instruction &I : NewBlock) {
1773d88c1a5aSDimitry Andric           if (auto *II = dyn_cast<IntrinsicInst>(&I))
1774d88c1a5aSDimitry Andric             if (II->getIntrinsicID() == Intrinsic::assume)
1775d88c1a5aSDimitry Andric               (*IFI.GetAssumptionCache)(*Caller).registerAssumption(II);
1776d88c1a5aSDimitry Andric         }
1777f22ef01cSRoman Divacky   }
1778f22ef01cSRoman Divacky 
1779f22ef01cSRoman Divacky   // If there are any alloca instructions in the block that used to be the entry
1780f22ef01cSRoman Divacky   // block for the callee, move them to the entry block of the caller.  First
1781f22ef01cSRoman Divacky   // calculate which instruction they should be inserted before.  We insert the
1782f22ef01cSRoman Divacky   // instructions at the end of the current alloca list.
1783f22ef01cSRoman Divacky   {
1784f22ef01cSRoman Divacky     BasicBlock::iterator InsertPoint = Caller->begin()->begin();
1785f22ef01cSRoman Divacky     for (BasicBlock::iterator I = FirstNewBlock->begin(),
1786f22ef01cSRoman Divacky          E = FirstNewBlock->end(); I != E; ) {
1787f22ef01cSRoman Divacky       AllocaInst *AI = dyn_cast<AllocaInst>(I++);
178891bc56edSDimitry Andric       if (!AI) continue;
1789f22ef01cSRoman Divacky 
1790f22ef01cSRoman Divacky       // If the alloca is now dead, remove it.  This often occurs due to code
1791f22ef01cSRoman Divacky       // specialization.
1792f22ef01cSRoman Divacky       if (AI->use_empty()) {
1793f22ef01cSRoman Divacky         AI->eraseFromParent();
1794f22ef01cSRoman Divacky         continue;
1795f22ef01cSRoman Divacky       }
1796f22ef01cSRoman Divacky 
17976c4bc1bdSDimitry Andric       if (!allocaWouldBeStaticInEntry(AI))
1798f22ef01cSRoman Divacky         continue;
1799f22ef01cSRoman Divacky 
18002754fe60SDimitry Andric       // Keep track of the static allocas that we inline into the caller.
1801f22ef01cSRoman Divacky       IFI.StaticAllocas.push_back(AI);
1802f22ef01cSRoman Divacky 
1803f22ef01cSRoman Divacky       // Scan for the block of allocas that we can move over, and move them
1804f22ef01cSRoman Divacky       // all at once.
1805f22ef01cSRoman Divacky       while (isa<AllocaInst>(I) &&
18066c4bc1bdSDimitry Andric              allocaWouldBeStaticInEntry(cast<AllocaInst>(I))) {
1807f22ef01cSRoman Divacky         IFI.StaticAllocas.push_back(cast<AllocaInst>(I));
1808f22ef01cSRoman Divacky         ++I;
1809f22ef01cSRoman Divacky       }
1810f22ef01cSRoman Divacky 
1811f22ef01cSRoman Divacky       // Transfer all of the allocas over in a block.  Using splice means
1812f22ef01cSRoman Divacky       // that the instructions aren't removed from the symbol table, then
1813f22ef01cSRoman Divacky       // reinserted.
18147d523365SDimitry Andric       Caller->getEntryBlock().getInstList().splice(
18157d523365SDimitry Andric           InsertPoint, FirstNewBlock->getInstList(), AI->getIterator(), I);
1816f22ef01cSRoman Divacky     }
1817ff0cc061SDimitry Andric     // Move any dbg.declares describing the allocas into the entry basic block.
1818ff0cc061SDimitry Andric     DIBuilder DIB(*Caller->getParent());
1819ff0cc061SDimitry Andric     for (auto &AI : IFI.StaticAllocas)
18202cab237bSDimitry Andric       replaceDbgDeclareForAlloca(AI, AI, DIB, DIExpression::NoDeref, 0,
18212cab237bSDimitry Andric                                  DIExpression::NoDeref);
1822f22ef01cSRoman Divacky   }
1823f22ef01cSRoman Divacky 
18242cab237bSDimitry Andric   SmallVector<Value*,4> VarArgsToForward;
18254ba319b5SDimitry Andric   SmallVector<AttributeSet, 4> VarArgsAttrs;
18262cab237bSDimitry Andric   for (unsigned i = CalledFunc->getFunctionType()->getNumParams();
18274ba319b5SDimitry Andric        i < CS.getNumArgOperands(); i++) {
18282cab237bSDimitry Andric     VarArgsToForward.push_back(CS.getArgOperand(i));
18294ba319b5SDimitry Andric     VarArgsAttrs.push_back(CS.getAttributes().getParamAttributes(i));
18304ba319b5SDimitry Andric   }
18312cab237bSDimitry Andric 
18323ca95b02SDimitry Andric   bool InlinedMustTailCalls = false, InlinedDeoptimizeCalls = false;
183391bc56edSDimitry Andric   if (InlinedFunctionInfo.ContainsCalls) {
183491bc56edSDimitry Andric     CallInst::TailCallKind CallSiteTailKind = CallInst::TCK_None;
183591bc56edSDimitry Andric     if (CallInst *CI = dyn_cast<CallInst>(TheCall))
183691bc56edSDimitry Andric       CallSiteTailKind = CI->getTailCallKind();
183791bc56edSDimitry Andric 
18384ba319b5SDimitry Andric     // For inlining purposes, the "notail" marker is the same as no marker.
18394ba319b5SDimitry Andric     if (CallSiteTailKind == CallInst::TCK_NoTail)
18404ba319b5SDimitry Andric       CallSiteTailKind = CallInst::TCK_None;
18414ba319b5SDimitry Andric 
184291bc56edSDimitry Andric     for (Function::iterator BB = FirstNewBlock, E = Caller->end(); BB != E;
184391bc56edSDimitry Andric          ++BB) {
18442cab237bSDimitry Andric       for (auto II = BB->begin(); II != BB->end();) {
18452cab237bSDimitry Andric         Instruction &I = *II++;
184691bc56edSDimitry Andric         CallInst *CI = dyn_cast<CallInst>(&I);
184791bc56edSDimitry Andric         if (!CI)
184891bc56edSDimitry Andric           continue;
184991bc56edSDimitry Andric 
18504ba319b5SDimitry Andric         // Forward varargs from inlined call site to calls to the
18514ba319b5SDimitry Andric         // ForwardVarArgsTo function, if requested, and to musttail calls.
18524ba319b5SDimitry Andric         if (!VarArgsToForward.empty() &&
18534ba319b5SDimitry Andric             ((ForwardVarArgsTo &&
18544ba319b5SDimitry Andric               CI->getCalledFunction() == ForwardVarArgsTo) ||
18554ba319b5SDimitry Andric              CI->isMustTailCall())) {
18564ba319b5SDimitry Andric           // Collect attributes for non-vararg parameters.
18574ba319b5SDimitry Andric           AttributeList Attrs = CI->getAttributes();
18584ba319b5SDimitry Andric           SmallVector<AttributeSet, 8> ArgAttrs;
18594ba319b5SDimitry Andric           if (!Attrs.isEmpty() || !VarArgsAttrs.empty()) {
18604ba319b5SDimitry Andric             for (unsigned ArgNo = 0;
18614ba319b5SDimitry Andric                  ArgNo < CI->getFunctionType()->getNumParams(); ++ArgNo)
18624ba319b5SDimitry Andric               ArgAttrs.push_back(Attrs.getParamAttributes(ArgNo));
18634ba319b5SDimitry Andric           }
18644ba319b5SDimitry Andric 
18654ba319b5SDimitry Andric           // Add VarArg attributes.
18664ba319b5SDimitry Andric           ArgAttrs.append(VarArgsAttrs.begin(), VarArgsAttrs.end());
18674ba319b5SDimitry Andric           Attrs = AttributeList::get(CI->getContext(), Attrs.getFnAttributes(),
18684ba319b5SDimitry Andric                                      Attrs.getRetAttributes(), ArgAttrs);
18694ba319b5SDimitry Andric           // Add VarArgs to existing parameters.
18704ba319b5SDimitry Andric           SmallVector<Value *, 6> Params(CI->arg_operands());
18714ba319b5SDimitry Andric           Params.append(VarArgsToForward.begin(), VarArgsToForward.end());
18724ba319b5SDimitry Andric           CallInst *NewCI =
18734ba319b5SDimitry Andric               CallInst::Create(CI->getCalledFunction() ? CI->getCalledFunction()
18744ba319b5SDimitry Andric                                                        : CI->getCalledValue(),
18754ba319b5SDimitry Andric                                Params, "", CI);
18764ba319b5SDimitry Andric           NewCI->setDebugLoc(CI->getDebugLoc());
18774ba319b5SDimitry Andric           NewCI->setAttributes(Attrs);
18784ba319b5SDimitry Andric           NewCI->setCallingConv(CI->getCallingConv());
18794ba319b5SDimitry Andric           CI->replaceAllUsesWith(NewCI);
18804ba319b5SDimitry Andric           CI->eraseFromParent();
18814ba319b5SDimitry Andric           CI = NewCI;
18824ba319b5SDimitry Andric         }
18834ba319b5SDimitry Andric 
18843ca95b02SDimitry Andric         if (Function *F = CI->getCalledFunction())
18853ca95b02SDimitry Andric           InlinedDeoptimizeCalls |=
18863ca95b02SDimitry Andric               F->getIntrinsicID() == Intrinsic::experimental_deoptimize;
18873ca95b02SDimitry Andric 
188891bc56edSDimitry Andric         // We need to reduce the strength of any inlined tail calls.  For
188991bc56edSDimitry Andric         // musttail, we have to avoid introducing potential unbounded stack
189091bc56edSDimitry Andric         // growth.  For example, if functions 'f' and 'g' are mutually recursive
189191bc56edSDimitry Andric         // with musttail, we can inline 'g' into 'f' so long as we preserve
189291bc56edSDimitry Andric         // musttail on the cloned call to 'f'.  If either the inlined call site
189391bc56edSDimitry Andric         // or the cloned call site is *not* musttail, the program already has
189491bc56edSDimitry Andric         // one frame of stack growth, so it's safe to remove musttail.  Here is
189591bc56edSDimitry Andric         // a table of example transformations:
189691bc56edSDimitry Andric         //
189791bc56edSDimitry Andric         //    f -> musttail g -> musttail f  ==>  f -> musttail f
189891bc56edSDimitry Andric         //    f -> musttail g ->     tail f  ==>  f ->     tail f
189991bc56edSDimitry Andric         //    f ->          g -> musttail f  ==>  f ->          f
190091bc56edSDimitry Andric         //    f ->          g ->     tail f  ==>  f ->          f
19014ba319b5SDimitry Andric         //
19024ba319b5SDimitry Andric         // Inlined notail calls should remain notail calls.
190391bc56edSDimitry Andric         CallInst::TailCallKind ChildTCK = CI->getTailCallKind();
19042cab237bSDimitry Andric         if (ChildTCK != CallInst::TCK_NoTail)
190591bc56edSDimitry Andric           ChildTCK = std::min(CallSiteTailKind, ChildTCK);
190691bc56edSDimitry Andric         CI->setTailCallKind(ChildTCK);
190791bc56edSDimitry Andric         InlinedMustTailCalls |= CI->isMustTailCall();
190891bc56edSDimitry Andric 
190991bc56edSDimitry Andric         // Calls inlined through a 'nounwind' call site should be marked
191091bc56edSDimitry Andric         // 'nounwind'.
191191bc56edSDimitry Andric         if (MarkNoUnwind)
191291bc56edSDimitry Andric           CI->setDoesNotThrow();
191391bc56edSDimitry Andric       }
191491bc56edSDimitry Andric     }
191591bc56edSDimitry Andric   }
191691bc56edSDimitry Andric 
1917bd5abe19SDimitry Andric   // Leave lifetime markers for the static alloca's, scoping them to the
1918bd5abe19SDimitry Andric   // function we just inlined.
1919dff0c46cSDimitry Andric   if (InsertLifetime && !IFI.StaticAllocas.empty()) {
19207d523365SDimitry Andric     IRBuilder<> builder(&FirstNewBlock->front());
1921bd5abe19SDimitry Andric     for (unsigned ai = 0, ae = IFI.StaticAllocas.size(); ai != ae; ++ai) {
1922bd5abe19SDimitry Andric       AllocaInst *AI = IFI.StaticAllocas[ai];
1923d88c1a5aSDimitry Andric       // Don't mark swifterror allocas. They can't have bitcast uses.
1924d88c1a5aSDimitry Andric       if (AI->isSwiftError())
1925d88c1a5aSDimitry Andric         continue;
1926bd5abe19SDimitry Andric 
1927bd5abe19SDimitry Andric       // If the alloca is already scoped to something smaller than the whole
1928bd5abe19SDimitry Andric       // function then there's no need to add redundant, less accurate markers.
1929bd5abe19SDimitry Andric       if (hasLifetimeMarkers(AI))
1930bd5abe19SDimitry Andric         continue;
1931bd5abe19SDimitry Andric 
1932139f7f9bSDimitry Andric       // Try to determine the size of the allocation.
193391bc56edSDimitry Andric       ConstantInt *AllocaSize = nullptr;
1934139f7f9bSDimitry Andric       if (ConstantInt *AIArraySize =
1935139f7f9bSDimitry Andric           dyn_cast<ConstantInt>(AI->getArraySize())) {
1936ff0cc061SDimitry Andric         auto &DL = Caller->getParent()->getDataLayout();
1937139f7f9bSDimitry Andric         Type *AllocaType = AI->getAllocatedType();
1938ff0cc061SDimitry Andric         uint64_t AllocaTypeSize = DL.getTypeAllocSize(AllocaType);
1939139f7f9bSDimitry Andric         uint64_t AllocaArraySize = AIArraySize->getLimitedValue();
1940ff0cc061SDimitry Andric 
1941ff0cc061SDimitry Andric         // Don't add markers for zero-sized allocas.
1942ff0cc061SDimitry Andric         if (AllocaArraySize == 0)
1943ff0cc061SDimitry Andric           continue;
1944ff0cc061SDimitry Andric 
1945139f7f9bSDimitry Andric         // Check that array size doesn't saturate uint64_t and doesn't
1946139f7f9bSDimitry Andric         // overflow when it's multiplied by type size.
19472cab237bSDimitry Andric         if (AllocaArraySize != std::numeric_limits<uint64_t>::max() &&
19482cab237bSDimitry Andric             std::numeric_limits<uint64_t>::max() / AllocaArraySize >=
19492cab237bSDimitry Andric                 AllocaTypeSize) {
1950139f7f9bSDimitry Andric           AllocaSize = ConstantInt::get(Type::getInt64Ty(AI->getContext()),
1951139f7f9bSDimitry Andric                                         AllocaArraySize * AllocaTypeSize);
1952139f7f9bSDimitry Andric         }
1953139f7f9bSDimitry Andric       }
1954139f7f9bSDimitry Andric 
1955139f7f9bSDimitry Andric       builder.CreateLifetimeStart(AI, AllocaSize);
195691bc56edSDimitry Andric       for (ReturnInst *RI : Returns) {
19573ca95b02SDimitry Andric         // Don't insert llvm.lifetime.end calls between a musttail or deoptimize
19583ca95b02SDimitry Andric         // call and a return.  The return kills all local allocas.
195939d628a0SDimitry Andric         if (InlinedMustTailCalls &&
196039d628a0SDimitry Andric             RI->getParent()->getTerminatingMustTailCall())
196191bc56edSDimitry Andric           continue;
19623ca95b02SDimitry Andric         if (InlinedDeoptimizeCalls &&
19633ca95b02SDimitry Andric             RI->getParent()->getTerminatingDeoptimizeCall())
19643ca95b02SDimitry Andric           continue;
196591bc56edSDimitry Andric         IRBuilder<>(RI).CreateLifetimeEnd(AI, AllocaSize);
1966bd5abe19SDimitry Andric       }
1967bd5abe19SDimitry Andric     }
1968bd5abe19SDimitry Andric   }
1969bd5abe19SDimitry Andric 
1970f22ef01cSRoman Divacky   // If the inlined code contained dynamic alloca instructions, wrap the inlined
1971f22ef01cSRoman Divacky   // code with llvm.stacksave/llvm.stackrestore intrinsics.
1972f22ef01cSRoman Divacky   if (InlinedFunctionInfo.ContainsDynamicAllocas) {
1973f22ef01cSRoman Divacky     Module *M = Caller->getParent();
1974f22ef01cSRoman Divacky     // Get the two intrinsics we care about.
1975f22ef01cSRoman Divacky     Function *StackSave = Intrinsic::getDeclaration(M, Intrinsic::stacksave);
1976f22ef01cSRoman Divacky     Function *StackRestore=Intrinsic::getDeclaration(M,Intrinsic::stackrestore);
1977f22ef01cSRoman Divacky 
1978f22ef01cSRoman Divacky     // Insert the llvm.stacksave.
19797d523365SDimitry Andric     CallInst *SavedPtr = IRBuilder<>(&*FirstNewBlock, FirstNewBlock->begin())
1980ff0cc061SDimitry Andric                              .CreateCall(StackSave, {}, "savedstack");
1981f22ef01cSRoman Divacky 
1982f22ef01cSRoman Divacky     // Insert a call to llvm.stackrestore before any return instructions in the
1983f22ef01cSRoman Divacky     // inlined function.
198491bc56edSDimitry Andric     for (ReturnInst *RI : Returns) {
19853ca95b02SDimitry Andric       // Don't insert llvm.stackrestore calls between a musttail or deoptimize
19863ca95b02SDimitry Andric       // call and a return.  The return will restore the stack pointer.
198739d628a0SDimitry Andric       if (InlinedMustTailCalls && RI->getParent()->getTerminatingMustTailCall())
198891bc56edSDimitry Andric         continue;
19893ca95b02SDimitry Andric       if (InlinedDeoptimizeCalls && RI->getParent()->getTerminatingDeoptimizeCall())
19903ca95b02SDimitry Andric         continue;
199191bc56edSDimitry Andric       IRBuilder<>(RI).CreateCall(StackRestore, SavedPtr);
1992f22ef01cSRoman Divacky     }
1993f22ef01cSRoman Divacky   }
1994f22ef01cSRoman Divacky 
19958c24ff90SDimitry Andric   // If we are inlining for an invoke instruction, we must make sure to rewrite
19968c24ff90SDimitry Andric   // any call instructions into invoke instructions.  This is sensitive to which
19978c24ff90SDimitry Andric   // funclet pads were top-level in the inlinee, so must be done before
19988c24ff90SDimitry Andric   // rewriting the "parent pad" links.
19998c24ff90SDimitry Andric   if (auto *II = dyn_cast<InvokeInst>(TheCall)) {
20008c24ff90SDimitry Andric     BasicBlock *UnwindDest = II->getUnwindDest();
20018c24ff90SDimitry Andric     Instruction *FirstNonPHI = UnwindDest->getFirstNonPHI();
20028c24ff90SDimitry Andric     if (isa<LandingPadInst>(FirstNonPHI)) {
20038c24ff90SDimitry Andric       HandleInlinedLandingPad(II, &*FirstNewBlock, InlinedFunctionInfo);
20048c24ff90SDimitry Andric     } else {
20058c24ff90SDimitry Andric       HandleInlinedEHPad(II, &*FirstNewBlock, InlinedFunctionInfo);
20068c24ff90SDimitry Andric     }
20078c24ff90SDimitry Andric   }
20088c24ff90SDimitry Andric 
20097d523365SDimitry Andric   // Update the lexical scopes of the new funclets and callsites.
20107d523365SDimitry Andric   // Anything that had 'none' as its parent is now nested inside the callsite's
20117d523365SDimitry Andric   // EHPad.
20127d523365SDimitry Andric 
20137d523365SDimitry Andric   if (CallSiteEHPad) {
20147d523365SDimitry Andric     for (Function::iterator BB = FirstNewBlock->getIterator(),
20157d523365SDimitry Andric                             E = Caller->end();
20167d523365SDimitry Andric          BB != E; ++BB) {
20177d523365SDimitry Andric       // Add bundle operands to any top-level call sites.
20187d523365SDimitry Andric       SmallVector<OperandBundleDef, 1> OpBundles;
20197d523365SDimitry Andric       for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E;) {
20207d523365SDimitry Andric         Instruction *I = &*BBI++;
20217d523365SDimitry Andric         CallSite CS(I);
20227d523365SDimitry Andric         if (!CS)
20237d523365SDimitry Andric           continue;
20247d523365SDimitry Andric 
20257d523365SDimitry Andric         // Skip call sites which are nounwind intrinsics.
20267d523365SDimitry Andric         auto *CalledFn =
20277d523365SDimitry Andric             dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts());
20287d523365SDimitry Andric         if (CalledFn && CalledFn->isIntrinsic() && CS.doesNotThrow())
20297d523365SDimitry Andric           continue;
20307d523365SDimitry Andric 
20317d523365SDimitry Andric         // Skip call sites which already have a "funclet" bundle.
20327d523365SDimitry Andric         if (CS.getOperandBundle(LLVMContext::OB_funclet))
20337d523365SDimitry Andric           continue;
20347d523365SDimitry Andric 
20357d523365SDimitry Andric         CS.getOperandBundlesAsDefs(OpBundles);
20367d523365SDimitry Andric         OpBundles.emplace_back("funclet", CallSiteEHPad);
20377d523365SDimitry Andric 
20387d523365SDimitry Andric         Instruction *NewInst;
20397d523365SDimitry Andric         if (CS.isCall())
20407d523365SDimitry Andric           NewInst = CallInst::Create(cast<CallInst>(I), OpBundles, I);
20417d523365SDimitry Andric         else
20427d523365SDimitry Andric           NewInst = InvokeInst::Create(cast<InvokeInst>(I), OpBundles, I);
20437d523365SDimitry Andric         NewInst->takeName(I);
20447d523365SDimitry Andric         I->replaceAllUsesWith(NewInst);
20457d523365SDimitry Andric         I->eraseFromParent();
20467d523365SDimitry Andric 
20477d523365SDimitry Andric         OpBundles.clear();
20487d523365SDimitry Andric       }
20497d523365SDimitry Andric 
20503ca95b02SDimitry Andric       // It is problematic if the inlinee has a cleanupret which unwinds to
20513ca95b02SDimitry Andric       // caller and we inline it into a call site which doesn't unwind but into
20523ca95b02SDimitry Andric       // an EH pad that does.  Such an edge must be dynamically unreachable.
20533ca95b02SDimitry Andric       // As such, we replace the cleanupret with unreachable.
20543ca95b02SDimitry Andric       if (auto *CleanupRet = dyn_cast<CleanupReturnInst>(BB->getTerminator()))
20553ca95b02SDimitry Andric         if (CleanupRet->unwindsToCaller() && EHPadForCallUnwindsLocally)
20563ca95b02SDimitry Andric           changeToUnreachable(CleanupRet, /*UseLLVMTrap=*/false);
20573ca95b02SDimitry Andric 
20587d523365SDimitry Andric       Instruction *I = BB->getFirstNonPHI();
20597d523365SDimitry Andric       if (!I->isEHPad())
20607d523365SDimitry Andric         continue;
20617d523365SDimitry Andric 
20627d523365SDimitry Andric       if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(I)) {
20637d523365SDimitry Andric         if (isa<ConstantTokenNone>(CatchSwitch->getParentPad()))
20647d523365SDimitry Andric           CatchSwitch->setParentPad(CallSiteEHPad);
20657d523365SDimitry Andric       } else {
20667d523365SDimitry Andric         auto *FPI = cast<FuncletPadInst>(I);
20677d523365SDimitry Andric         if (isa<ConstantTokenNone>(FPI->getParentPad()))
20687d523365SDimitry Andric           FPI->setParentPad(CallSiteEHPad);
20697d523365SDimitry Andric       }
20707d523365SDimitry Andric     }
20717d523365SDimitry Andric   }
20727d523365SDimitry Andric 
20733ca95b02SDimitry Andric   if (InlinedDeoptimizeCalls) {
20743ca95b02SDimitry Andric     // We need to at least remove the deoptimizing returns from the Return set,
20753ca95b02SDimitry Andric     // so that the control flow from those returns does not get merged into the
20763ca95b02SDimitry Andric     // caller (but terminate it instead).  If the caller's return type does not
20773ca95b02SDimitry Andric     // match the callee's return type, we also need to change the return type of
20783ca95b02SDimitry Andric     // the intrinsic.
20793ca95b02SDimitry Andric     if (Caller->getReturnType() == TheCall->getType()) {
20802cab237bSDimitry Andric       auto NewEnd = llvm::remove_if(Returns, [](ReturnInst *RI) {
20813ca95b02SDimitry Andric         return RI->getParent()->getTerminatingDeoptimizeCall() != nullptr;
20823ca95b02SDimitry Andric       });
20833ca95b02SDimitry Andric       Returns.erase(NewEnd, Returns.end());
20843ca95b02SDimitry Andric     } else {
20853ca95b02SDimitry Andric       SmallVector<ReturnInst *, 8> NormalReturns;
20863ca95b02SDimitry Andric       Function *NewDeoptIntrinsic = Intrinsic::getDeclaration(
20873ca95b02SDimitry Andric           Caller->getParent(), Intrinsic::experimental_deoptimize,
20883ca95b02SDimitry Andric           {Caller->getReturnType()});
20893ca95b02SDimitry Andric 
20903ca95b02SDimitry Andric       for (ReturnInst *RI : Returns) {
20913ca95b02SDimitry Andric         CallInst *DeoptCall = RI->getParent()->getTerminatingDeoptimizeCall();
20923ca95b02SDimitry Andric         if (!DeoptCall) {
20933ca95b02SDimitry Andric           NormalReturns.push_back(RI);
20943ca95b02SDimitry Andric           continue;
20953ca95b02SDimitry Andric         }
20963ca95b02SDimitry Andric 
20973ca95b02SDimitry Andric         // The calling convention on the deoptimize call itself may be bogus,
20983ca95b02SDimitry Andric         // since the code we're inlining may have undefined behavior (and may
20993ca95b02SDimitry Andric         // never actually execute at runtime); but all
21003ca95b02SDimitry Andric         // @llvm.experimental.deoptimize declarations have to have the same
21013ca95b02SDimitry Andric         // calling convention in a well-formed module.
21023ca95b02SDimitry Andric         auto CallingConv = DeoptCall->getCalledFunction()->getCallingConv();
21033ca95b02SDimitry Andric         NewDeoptIntrinsic->setCallingConv(CallingConv);
21043ca95b02SDimitry Andric         auto *CurBB = RI->getParent();
21053ca95b02SDimitry Andric         RI->eraseFromParent();
21063ca95b02SDimitry Andric 
21073ca95b02SDimitry Andric         SmallVector<Value *, 4> CallArgs(DeoptCall->arg_begin(),
21083ca95b02SDimitry Andric                                          DeoptCall->arg_end());
21093ca95b02SDimitry Andric 
21103ca95b02SDimitry Andric         SmallVector<OperandBundleDef, 1> OpBundles;
21113ca95b02SDimitry Andric         DeoptCall->getOperandBundlesAsDefs(OpBundles);
21123ca95b02SDimitry Andric         DeoptCall->eraseFromParent();
21133ca95b02SDimitry Andric         assert(!OpBundles.empty() &&
21143ca95b02SDimitry Andric                "Expected at least the deopt operand bundle");
21153ca95b02SDimitry Andric 
21163ca95b02SDimitry Andric         IRBuilder<> Builder(CurBB);
21173ca95b02SDimitry Andric         CallInst *NewDeoptCall =
21183ca95b02SDimitry Andric             Builder.CreateCall(NewDeoptIntrinsic, CallArgs, OpBundles);
21193ca95b02SDimitry Andric         NewDeoptCall->setCallingConv(CallingConv);
21203ca95b02SDimitry Andric         if (NewDeoptCall->getType()->isVoidTy())
21213ca95b02SDimitry Andric           Builder.CreateRetVoid();
21223ca95b02SDimitry Andric         else
21233ca95b02SDimitry Andric           Builder.CreateRet(NewDeoptCall);
21243ca95b02SDimitry Andric       }
21253ca95b02SDimitry Andric 
21263ca95b02SDimitry Andric       // Leave behind the normal returns so we can merge control flow.
21273ca95b02SDimitry Andric       std::swap(Returns, NormalReturns);
21283ca95b02SDimitry Andric     }
21293ca95b02SDimitry Andric   }
21303ca95b02SDimitry Andric 
213191bc56edSDimitry Andric   // Handle any inlined musttail call sites.  In order for a new call site to be
213291bc56edSDimitry Andric   // musttail, the source of the clone and the inlined call site must have been
213391bc56edSDimitry Andric   // musttail.  Therefore it's safe to return without merging control into the
213491bc56edSDimitry Andric   // phi below.
213591bc56edSDimitry Andric   if (InlinedMustTailCalls) {
213691bc56edSDimitry Andric     // Check if we need to bitcast the result of any musttail calls.
213791bc56edSDimitry Andric     Type *NewRetTy = Caller->getReturnType();
213891bc56edSDimitry Andric     bool NeedBitCast = !TheCall->use_empty() && TheCall->getType() != NewRetTy;
213991bc56edSDimitry Andric 
214091bc56edSDimitry Andric     // Handle the returns preceded by musttail calls separately.
214191bc56edSDimitry Andric     SmallVector<ReturnInst *, 8> NormalReturns;
214291bc56edSDimitry Andric     for (ReturnInst *RI : Returns) {
214339d628a0SDimitry Andric       CallInst *ReturnedMustTail =
214439d628a0SDimitry Andric           RI->getParent()->getTerminatingMustTailCall();
214591bc56edSDimitry Andric       if (!ReturnedMustTail) {
214691bc56edSDimitry Andric         NormalReturns.push_back(RI);
214791bc56edSDimitry Andric         continue;
214891bc56edSDimitry Andric       }
214991bc56edSDimitry Andric       if (!NeedBitCast)
215091bc56edSDimitry Andric         continue;
215191bc56edSDimitry Andric 
215291bc56edSDimitry Andric       // Delete the old return and any preceding bitcast.
215391bc56edSDimitry Andric       BasicBlock *CurBB = RI->getParent();
215491bc56edSDimitry Andric       auto *OldCast = dyn_cast_or_null<BitCastInst>(RI->getReturnValue());
215591bc56edSDimitry Andric       RI->eraseFromParent();
215691bc56edSDimitry Andric       if (OldCast)
215791bc56edSDimitry Andric         OldCast->eraseFromParent();
215891bc56edSDimitry Andric 
215991bc56edSDimitry Andric       // Insert a new bitcast and return with the right type.
216091bc56edSDimitry Andric       IRBuilder<> Builder(CurBB);
216191bc56edSDimitry Andric       Builder.CreateRet(Builder.CreateBitCast(ReturnedMustTail, NewRetTy));
216291bc56edSDimitry Andric     }
216391bc56edSDimitry Andric 
216491bc56edSDimitry Andric     // Leave behind the normal returns so we can merge control flow.
216591bc56edSDimitry Andric     std::swap(Returns, NormalReturns);
216691bc56edSDimitry Andric   }
216791bc56edSDimitry Andric 
2168d88c1a5aSDimitry Andric   // Now that all of the transforms on the inlined code have taken place but
2169d88c1a5aSDimitry Andric   // before we splice the inlined code into the CFG and lose track of which
2170d88c1a5aSDimitry Andric   // blocks were actually inlined, collect the call sites. We only do this if
2171d88c1a5aSDimitry Andric   // call graph updates weren't requested, as those provide value handle based
2172d88c1a5aSDimitry Andric   // tracking of inlined call sites instead.
2173d88c1a5aSDimitry Andric   if (InlinedFunctionInfo.ContainsCalls && !IFI.CG) {
2174d88c1a5aSDimitry Andric     // Otherwise just collect the raw call sites that were inlined.
2175d88c1a5aSDimitry Andric     for (BasicBlock &NewBB :
2176d88c1a5aSDimitry Andric          make_range(FirstNewBlock->getIterator(), Caller->end()))
2177d88c1a5aSDimitry Andric       for (Instruction &I : NewBB)
2178d88c1a5aSDimitry Andric         if (auto CS = CallSite(&I))
2179d88c1a5aSDimitry Andric           IFI.InlinedCallSites.push_back(CS);
2180d88c1a5aSDimitry Andric   }
2181d88c1a5aSDimitry Andric 
2182f22ef01cSRoman Divacky   // If we cloned in _exactly one_ basic block, and if that block ends in a
2183f22ef01cSRoman Divacky   // return instruction, we splice the body of the inlined callee directly into
2184f22ef01cSRoman Divacky   // the calling basic block.
2185f22ef01cSRoman Divacky   if (Returns.size() == 1 && std::distance(FirstNewBlock, Caller->end()) == 1) {
2186f22ef01cSRoman Divacky     // Move all of the instructions right before the call.
21877d523365SDimitry Andric     OrigBB->getInstList().splice(TheCall->getIterator(),
21887d523365SDimitry Andric                                  FirstNewBlock->getInstList(),
2189f22ef01cSRoman Divacky                                  FirstNewBlock->begin(), FirstNewBlock->end());
2190f22ef01cSRoman Divacky     // Remove the cloned basic block.
2191f22ef01cSRoman Divacky     Caller->getBasicBlockList().pop_back();
2192f22ef01cSRoman Divacky 
2193f22ef01cSRoman Divacky     // If the call site was an invoke instruction, add a branch to the normal
2194f22ef01cSRoman Divacky     // destination.
2195284c1978SDimitry Andric     if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
2196284c1978SDimitry Andric       BranchInst *NewBr = BranchInst::Create(II->getNormalDest(), TheCall);
2197284c1978SDimitry Andric       NewBr->setDebugLoc(Returns[0]->getDebugLoc());
2198284c1978SDimitry Andric     }
2199f22ef01cSRoman Divacky 
2200f22ef01cSRoman Divacky     // If the return instruction returned a value, replace uses of the call with
2201f22ef01cSRoman Divacky     // uses of the returned value.
2202f22ef01cSRoman Divacky     if (!TheCall->use_empty()) {
2203f22ef01cSRoman Divacky       ReturnInst *R = Returns[0];
2204f22ef01cSRoman Divacky       if (TheCall == R->getReturnValue())
2205f22ef01cSRoman Divacky         TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
2206f22ef01cSRoman Divacky       else
2207f22ef01cSRoman Divacky         TheCall->replaceAllUsesWith(R->getReturnValue());
2208f22ef01cSRoman Divacky     }
2209f22ef01cSRoman Divacky     // Since we are now done with the Call/Invoke, we can delete it.
2210f22ef01cSRoman Divacky     TheCall->eraseFromParent();
2211f22ef01cSRoman Divacky 
2212f22ef01cSRoman Divacky     // Since we are now done with the return instruction, delete it also.
2213f22ef01cSRoman Divacky     Returns[0]->eraseFromParent();
2214f22ef01cSRoman Divacky 
2215f22ef01cSRoman Divacky     // We are now done with the inlining.
2216f22ef01cSRoman Divacky     return true;
2217f22ef01cSRoman Divacky   }
2218f22ef01cSRoman Divacky 
2219f22ef01cSRoman Divacky   // Otherwise, we have the normal case, of more than one block to inline or
2220f22ef01cSRoman Divacky   // multiple return sites.
2221f22ef01cSRoman Divacky 
2222f22ef01cSRoman Divacky   // We want to clone the entire callee function into the hole between the
2223f22ef01cSRoman Divacky   // "starter" and "ender" blocks.  How we accomplish this depends on whether
2224f22ef01cSRoman Divacky   // this is an invoke instruction or a call instruction.
2225f22ef01cSRoman Divacky   BasicBlock *AfterCallBB;
222691bc56edSDimitry Andric   BranchInst *CreatedBranchToNormalDest = nullptr;
2227f22ef01cSRoman Divacky   if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
2228f22ef01cSRoman Divacky 
2229f22ef01cSRoman Divacky     // Add an unconditional branch to make this look like the CallInst case...
2230284c1978SDimitry Andric     CreatedBranchToNormalDest = BranchInst::Create(II->getNormalDest(), TheCall);
2231f22ef01cSRoman Divacky 
2232f22ef01cSRoman Divacky     // Split the basic block.  This guarantees that no PHI nodes will have to be
2233f22ef01cSRoman Divacky     // updated due to new incoming edges, and make the invoke case more
2234f22ef01cSRoman Divacky     // symmetric to the call case.
22357d523365SDimitry Andric     AfterCallBB =
22367d523365SDimitry Andric         OrigBB->splitBasicBlock(CreatedBranchToNormalDest->getIterator(),
2237f22ef01cSRoman Divacky                                 CalledFunc->getName() + ".exit");
2238f22ef01cSRoman Divacky 
2239f22ef01cSRoman Divacky   } else {  // It's a call
2240f22ef01cSRoman Divacky     // If this is a call instruction, we need to split the basic block that
2241f22ef01cSRoman Divacky     // the call lives in.
2242f22ef01cSRoman Divacky     //
22437d523365SDimitry Andric     AfterCallBB = OrigBB->splitBasicBlock(TheCall->getIterator(),
2244f22ef01cSRoman Divacky                                           CalledFunc->getName() + ".exit");
2245f22ef01cSRoman Divacky   }
2246f22ef01cSRoman Divacky 
22477a7e6055SDimitry Andric   if (IFI.CallerBFI) {
22487a7e6055SDimitry Andric     // Copy original BB's block frequency to AfterCallBB
22497a7e6055SDimitry Andric     IFI.CallerBFI->setBlockFreq(
22507a7e6055SDimitry Andric         AfterCallBB, IFI.CallerBFI->getBlockFreq(OrigBB).getFrequency());
22517a7e6055SDimitry Andric   }
22527a7e6055SDimitry Andric 
2253f22ef01cSRoman Divacky   // Change the branch that used to go to AfterCallBB to branch to the first
2254f22ef01cSRoman Divacky   // basic block of the inlined function.
2255f22ef01cSRoman Divacky   //
2256*b5893f02SDimitry Andric   Instruction *Br = OrigBB->getTerminator();
2257f22ef01cSRoman Divacky   assert(Br && Br->getOpcode() == Instruction::Br &&
2258f22ef01cSRoman Divacky          "splitBasicBlock broken!");
22597d523365SDimitry Andric   Br->setOperand(0, &*FirstNewBlock);
2260f22ef01cSRoman Divacky 
2261f22ef01cSRoman Divacky   // Now that the function is correct, make it a little bit nicer.  In
2262f22ef01cSRoman Divacky   // particular, move the basic blocks inserted from the end of the function
2263f22ef01cSRoman Divacky   // into the space made by splitting the source basic block.
22647d523365SDimitry Andric   Caller->getBasicBlockList().splice(AfterCallBB->getIterator(),
22657d523365SDimitry Andric                                      Caller->getBasicBlockList(), FirstNewBlock,
22667d523365SDimitry Andric                                      Caller->end());
2267f22ef01cSRoman Divacky 
2268f22ef01cSRoman Divacky   // Handle all of the return instructions that we just cloned in, and eliminate
2269f22ef01cSRoman Divacky   // any users of the original call/invoke instruction.
22706122f3e6SDimitry Andric   Type *RTy = CalledFunc->getReturnType();
2271f22ef01cSRoman Divacky 
227291bc56edSDimitry Andric   PHINode *PHI = nullptr;
2273f22ef01cSRoman Divacky   if (Returns.size() > 1) {
2274f22ef01cSRoman Divacky     // The PHI node should go at the front of the new basic block to merge all
2275f22ef01cSRoman Divacky     // possible incoming values.
2276f22ef01cSRoman Divacky     if (!TheCall->use_empty()) {
22773b0f4066SDimitry Andric       PHI = PHINode::Create(RTy, Returns.size(), TheCall->getName(),
22787d523365SDimitry Andric                             &AfterCallBB->front());
2279f22ef01cSRoman Divacky       // Anything that used the result of the function call should now use the
2280f22ef01cSRoman Divacky       // PHI node as their operand.
2281f22ef01cSRoman Divacky       TheCall->replaceAllUsesWith(PHI);
2282f22ef01cSRoman Divacky     }
2283f22ef01cSRoman Divacky 
2284f22ef01cSRoman Divacky     // Loop over all of the return instructions adding entries to the PHI node
2285f22ef01cSRoman Divacky     // as appropriate.
2286f22ef01cSRoman Divacky     if (PHI) {
2287f22ef01cSRoman Divacky       for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
2288f22ef01cSRoman Divacky         ReturnInst *RI = Returns[i];
2289f22ef01cSRoman Divacky         assert(RI->getReturnValue()->getType() == PHI->getType() &&
2290f22ef01cSRoman Divacky                "Ret value not consistent in function!");
2291f22ef01cSRoman Divacky         PHI->addIncoming(RI->getReturnValue(), RI->getParent());
2292f22ef01cSRoman Divacky       }
2293f22ef01cSRoman Divacky     }
2294f22ef01cSRoman Divacky 
2295f22ef01cSRoman Divacky     // Add a branch to the merge points and remove return instructions.
2296284c1978SDimitry Andric     DebugLoc Loc;
2297f22ef01cSRoman Divacky     for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
2298f22ef01cSRoman Divacky       ReturnInst *RI = Returns[i];
2299284c1978SDimitry Andric       BranchInst* BI = BranchInst::Create(AfterCallBB, RI);
2300284c1978SDimitry Andric       Loc = RI->getDebugLoc();
2301284c1978SDimitry Andric       BI->setDebugLoc(Loc);
2302f22ef01cSRoman Divacky       RI->eraseFromParent();
2303f22ef01cSRoman Divacky     }
2304284c1978SDimitry Andric     // We need to set the debug location to *somewhere* inside the
2305284c1978SDimitry Andric     // inlined function. The line number may be nonsensical, but the
2306284c1978SDimitry Andric     // instruction will at least be associated with the right
2307284c1978SDimitry Andric     // function.
2308284c1978SDimitry Andric     if (CreatedBranchToNormalDest)
2309284c1978SDimitry Andric       CreatedBranchToNormalDest->setDebugLoc(Loc);
2310f22ef01cSRoman Divacky   } else if (!Returns.empty()) {
2311f22ef01cSRoman Divacky     // Otherwise, if there is exactly one return value, just replace anything
2312f22ef01cSRoman Divacky     // using the return value of the call with the computed value.
2313f22ef01cSRoman Divacky     if (!TheCall->use_empty()) {
2314f22ef01cSRoman Divacky       if (TheCall == Returns[0]->getReturnValue())
2315f22ef01cSRoman Divacky         TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
2316f22ef01cSRoman Divacky       else
2317f22ef01cSRoman Divacky         TheCall->replaceAllUsesWith(Returns[0]->getReturnValue());
2318f22ef01cSRoman Divacky     }
2319f22ef01cSRoman Divacky 
232017a519f9SDimitry Andric     // Update PHI nodes that use the ReturnBB to use the AfterCallBB.
232117a519f9SDimitry Andric     BasicBlock *ReturnBB = Returns[0]->getParent();
232217a519f9SDimitry Andric     ReturnBB->replaceAllUsesWith(AfterCallBB);
232317a519f9SDimitry Andric 
2324f22ef01cSRoman Divacky     // Splice the code from the return block into the block that it will return
2325f22ef01cSRoman Divacky     // to, which contains the code that was after the call.
2326f22ef01cSRoman Divacky     AfterCallBB->getInstList().splice(AfterCallBB->begin(),
2327f22ef01cSRoman Divacky                                       ReturnBB->getInstList());
2328f22ef01cSRoman Divacky 
2329284c1978SDimitry Andric     if (CreatedBranchToNormalDest)
2330284c1978SDimitry Andric       CreatedBranchToNormalDest->setDebugLoc(Returns[0]->getDebugLoc());
2331284c1978SDimitry Andric 
2332f22ef01cSRoman Divacky     // Delete the return instruction now and empty ReturnBB now.
2333f22ef01cSRoman Divacky     Returns[0]->eraseFromParent();
2334f22ef01cSRoman Divacky     ReturnBB->eraseFromParent();
2335f22ef01cSRoman Divacky   } else if (!TheCall->use_empty()) {
2336f22ef01cSRoman Divacky     // No returns, but something is using the return value of the call.  Just
2337f22ef01cSRoman Divacky     // nuke the result.
2338f22ef01cSRoman Divacky     TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
2339f22ef01cSRoman Divacky   }
2340f22ef01cSRoman Divacky 
2341f22ef01cSRoman Divacky   // Since we are now done with the Call/Invoke, we can delete it.
2342f22ef01cSRoman Divacky   TheCall->eraseFromParent();
2343f22ef01cSRoman Divacky 
234491bc56edSDimitry Andric   // If we inlined any musttail calls and the original return is now
234591bc56edSDimitry Andric   // unreachable, delete it.  It can only contain a bitcast and ret.
234691bc56edSDimitry Andric   if (InlinedMustTailCalls && pred_begin(AfterCallBB) == pred_end(AfterCallBB))
234791bc56edSDimitry Andric     AfterCallBB->eraseFromParent();
234891bc56edSDimitry Andric 
2349f22ef01cSRoman Divacky   // We should always be able to fold the entry block of the function into the
2350f22ef01cSRoman Divacky   // single predecessor of the block...
2351f22ef01cSRoman Divacky   assert(cast<BranchInst>(Br)->isUnconditional() && "splitBasicBlock broken!");
2352f22ef01cSRoman Divacky   BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0);
2353f22ef01cSRoman Divacky 
2354f22ef01cSRoman Divacky   // Splice the code entry block into calling block, right before the
2355f22ef01cSRoman Divacky   // unconditional branch.
2356f22ef01cSRoman Divacky   CalleeEntry->replaceAllUsesWith(OrigBB);  // Update PHI nodes
23577d523365SDimitry Andric   OrigBB->getInstList().splice(Br->getIterator(), CalleeEntry->getInstList());
2358f22ef01cSRoman Divacky 
2359f22ef01cSRoman Divacky   // Remove the unconditional branch.
2360f22ef01cSRoman Divacky   OrigBB->getInstList().erase(Br);
2361f22ef01cSRoman Divacky 
2362f22ef01cSRoman Divacky   // Now we can remove the CalleeEntry block, which is now empty.
2363f22ef01cSRoman Divacky   Caller->getBasicBlockList().erase(CalleeEntry);
2364f22ef01cSRoman Divacky 
23652754fe60SDimitry Andric   // If we inserted a phi node, check to see if it has a single value (e.g. all
23662754fe60SDimitry Andric   // the entries are the same or undef).  If so, remove the PHI so it doesn't
23672754fe60SDimitry Andric   // block other optimizations.
2368dff0c46cSDimitry Andric   if (PHI) {
2369d88c1a5aSDimitry Andric     AssumptionCache *AC =
2370d88c1a5aSDimitry Andric         IFI.GetAssumptionCache ? &(*IFI.GetAssumptionCache)(*Caller) : nullptr;
2371ff0cc061SDimitry Andric     auto &DL = Caller->getParent()->getDataLayout();
2372f37b6182SDimitry Andric     if (Value *V = SimplifyInstruction(PHI, {DL, nullptr, nullptr, AC})) {
23732754fe60SDimitry Andric       PHI->replaceAllUsesWith(V);
23742754fe60SDimitry Andric       PHI->eraseFromParent();
23752754fe60SDimitry Andric     }
2376dff0c46cSDimitry Andric   }
23772754fe60SDimitry Andric 
2378f22ef01cSRoman Divacky   return true;
2379f22ef01cSRoman Divacky }
2380