xref: /freebsd-src/contrib/llvm-project/llvm/lib/Transforms/Utils/InlineFunction.cpp (revision e8d8bef961a50d4dc22501cde4fb9fb0be1b2532)
10b57cec5SDimitry Andric //===- InlineFunction.cpp - Code to perform function inlining -------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file implements inlining of a function into a call site, resolving
100b57cec5SDimitry Andric // parameters and the return value as appropriate.
110b57cec5SDimitry Andric //
120b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
130b57cec5SDimitry Andric 
140b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
150b57cec5SDimitry Andric #include "llvm/ADT/None.h"
160b57cec5SDimitry Andric #include "llvm/ADT/Optional.h"
170b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
180b57cec5SDimitry Andric #include "llvm/ADT/SetVector.h"
190b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
200b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
210b57cec5SDimitry Andric #include "llvm/ADT/StringExtras.h"
220b57cec5SDimitry Andric #include "llvm/ADT/iterator_range.h"
230b57cec5SDimitry Andric #include "llvm/Analysis/AliasAnalysis.h"
240b57cec5SDimitry Andric #include "llvm/Analysis/AssumptionCache.h"
250b57cec5SDimitry Andric #include "llvm/Analysis/BlockFrequencyInfo.h"
260b57cec5SDimitry Andric #include "llvm/Analysis/CallGraph.h"
270b57cec5SDimitry Andric #include "llvm/Analysis/CaptureTracking.h"
280b57cec5SDimitry Andric #include "llvm/Analysis/EHPersonalities.h"
290b57cec5SDimitry Andric #include "llvm/Analysis/InstructionSimplify.h"
300b57cec5SDimitry Andric #include "llvm/Analysis/ProfileSummaryInfo.h"
310b57cec5SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
320b57cec5SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
330b57cec5SDimitry Andric #include "llvm/Analysis/VectorUtils.h"
340b57cec5SDimitry Andric #include "llvm/IR/Argument.h"
350b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h"
360b57cec5SDimitry Andric #include "llvm/IR/CFG.h"
370b57cec5SDimitry Andric #include "llvm/IR/Constant.h"
380b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
390b57cec5SDimitry Andric #include "llvm/IR/DIBuilder.h"
400b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
410b57cec5SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
420b57cec5SDimitry Andric #include "llvm/IR/DebugLoc.h"
430b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h"
440b57cec5SDimitry Andric #include "llvm/IR/Dominators.h"
450b57cec5SDimitry Andric #include "llvm/IR/Function.h"
460b57cec5SDimitry Andric #include "llvm/IR/IRBuilder.h"
470b57cec5SDimitry Andric #include "llvm/IR/InstrTypes.h"
480b57cec5SDimitry Andric #include "llvm/IR/Instruction.h"
490b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
500b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
510b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h"
520b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h"
530b57cec5SDimitry Andric #include "llvm/IR/MDBuilder.h"
540b57cec5SDimitry Andric #include "llvm/IR/Metadata.h"
550b57cec5SDimitry Andric #include "llvm/IR/Module.h"
560b57cec5SDimitry Andric #include "llvm/IR/Type.h"
570b57cec5SDimitry Andric #include "llvm/IR/User.h"
580b57cec5SDimitry Andric #include "llvm/IR/Value.h"
590b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
600b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
610b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
625ffd83dbSDimitry Andric #include "llvm/Transforms/Utils/AssumeBundleBuilder.h"
630b57cec5SDimitry Andric #include "llvm/Transforms/Utils/Cloning.h"
640b57cec5SDimitry Andric #include "llvm/Transforms/Utils/ValueMapper.h"
650b57cec5SDimitry Andric #include <algorithm>
660b57cec5SDimitry Andric #include <cassert>
670b57cec5SDimitry Andric #include <cstdint>
680b57cec5SDimitry Andric #include <iterator>
690b57cec5SDimitry Andric #include <limits>
700b57cec5SDimitry Andric #include <string>
710b57cec5SDimitry Andric #include <utility>
720b57cec5SDimitry Andric #include <vector>
730b57cec5SDimitry Andric 
740b57cec5SDimitry Andric using namespace llvm;
750b57cec5SDimitry Andric using ProfileCount = Function::ProfileCount;
760b57cec5SDimitry Andric 
770b57cec5SDimitry Andric static cl::opt<bool>
780b57cec5SDimitry Andric EnableNoAliasConversion("enable-noalias-to-md-conversion", cl::init(true),
790b57cec5SDimitry Andric   cl::Hidden,
800b57cec5SDimitry Andric   cl::desc("Convert noalias attributes to metadata during inlining."));
810b57cec5SDimitry Andric 
82*e8d8bef9SDimitry Andric static cl::opt<bool>
83*e8d8bef9SDimitry Andric     UseNoAliasIntrinsic("use-noalias-intrinsic-during-inlining", cl::Hidden,
84*e8d8bef9SDimitry Andric                         cl::ZeroOrMore, cl::init(true),
85*e8d8bef9SDimitry Andric                         cl::desc("Use the llvm.experimental.noalias.scope.decl "
86*e8d8bef9SDimitry Andric                                  "intrinsic during inlining."));
87*e8d8bef9SDimitry Andric 
885ffd83dbSDimitry Andric // Disabled by default, because the added alignment assumptions may increase
895ffd83dbSDimitry Andric // compile-time and block optimizations. This option is not suitable for use
905ffd83dbSDimitry Andric // with frontends that emit comprehensive parameter alignment annotations.
910b57cec5SDimitry Andric static cl::opt<bool>
920b57cec5SDimitry Andric PreserveAlignmentAssumptions("preserve-alignment-assumptions-during-inlining",
935ffd83dbSDimitry Andric   cl::init(false), cl::Hidden,
940b57cec5SDimitry Andric   cl::desc("Convert align attributes to assumptions during inlining."));
950b57cec5SDimitry Andric 
965ffd83dbSDimitry Andric static cl::opt<bool> UpdateReturnAttributes(
975ffd83dbSDimitry Andric         "update-return-attrs", cl::init(true), cl::Hidden,
985ffd83dbSDimitry Andric             cl::desc("Update return attributes on calls within inlined body"));
995ffd83dbSDimitry Andric 
1005ffd83dbSDimitry Andric static cl::opt<unsigned> InlinerAttributeWindow(
1015ffd83dbSDimitry Andric     "max-inst-checked-for-throw-during-inlining", cl::Hidden,
1025ffd83dbSDimitry Andric     cl::desc("the maximum number of instructions analyzed for may throw during "
1035ffd83dbSDimitry Andric              "attribute inference in inlined body"),
1045ffd83dbSDimitry Andric     cl::init(4));
1050b57cec5SDimitry Andric 
1060b57cec5SDimitry Andric namespace {
1070b57cec5SDimitry Andric 
1080b57cec5SDimitry Andric   /// A class for recording information about inlining a landing pad.
1090b57cec5SDimitry Andric   class LandingPadInliningInfo {
1100b57cec5SDimitry Andric     /// Destination of the invoke's unwind.
1110b57cec5SDimitry Andric     BasicBlock *OuterResumeDest;
1120b57cec5SDimitry Andric 
1130b57cec5SDimitry Andric     /// Destination for the callee's resume.
1140b57cec5SDimitry Andric     BasicBlock *InnerResumeDest = nullptr;
1150b57cec5SDimitry Andric 
1160b57cec5SDimitry Andric     /// LandingPadInst associated with the invoke.
1170b57cec5SDimitry Andric     LandingPadInst *CallerLPad = nullptr;
1180b57cec5SDimitry Andric 
1190b57cec5SDimitry Andric     /// PHI for EH values from landingpad insts.
1200b57cec5SDimitry Andric     PHINode *InnerEHValuesPHI = nullptr;
1210b57cec5SDimitry Andric 
1220b57cec5SDimitry Andric     SmallVector<Value*, 8> UnwindDestPHIValues;
1230b57cec5SDimitry Andric 
1240b57cec5SDimitry Andric   public:
1250b57cec5SDimitry Andric     LandingPadInliningInfo(InvokeInst *II)
1260b57cec5SDimitry Andric         : OuterResumeDest(II->getUnwindDest()) {
1270b57cec5SDimitry Andric       // If there are PHI nodes in the unwind destination block, we need to keep
1280b57cec5SDimitry Andric       // track of which values came into them from the invoke before removing
1290b57cec5SDimitry Andric       // the edge from this block.
1300b57cec5SDimitry Andric       BasicBlock *InvokeBB = II->getParent();
1310b57cec5SDimitry Andric       BasicBlock::iterator I = OuterResumeDest->begin();
1320b57cec5SDimitry Andric       for (; isa<PHINode>(I); ++I) {
1330b57cec5SDimitry Andric         // Save the value to use for this edge.
1340b57cec5SDimitry Andric         PHINode *PHI = cast<PHINode>(I);
1350b57cec5SDimitry Andric         UnwindDestPHIValues.push_back(PHI->getIncomingValueForBlock(InvokeBB));
1360b57cec5SDimitry Andric       }
1370b57cec5SDimitry Andric 
1380b57cec5SDimitry Andric       CallerLPad = cast<LandingPadInst>(I);
1390b57cec5SDimitry Andric     }
1400b57cec5SDimitry Andric 
1410b57cec5SDimitry Andric     /// The outer unwind destination is the target of
1420b57cec5SDimitry Andric     /// unwind edges introduced for calls within the inlined function.
1430b57cec5SDimitry Andric     BasicBlock *getOuterResumeDest() const {
1440b57cec5SDimitry Andric       return OuterResumeDest;
1450b57cec5SDimitry Andric     }
1460b57cec5SDimitry Andric 
1470b57cec5SDimitry Andric     BasicBlock *getInnerResumeDest();
1480b57cec5SDimitry Andric 
1490b57cec5SDimitry Andric     LandingPadInst *getLandingPadInst() const { return CallerLPad; }
1500b57cec5SDimitry Andric 
1510b57cec5SDimitry Andric     /// Forward the 'resume' instruction to the caller's landing pad block.
1520b57cec5SDimitry Andric     /// When the landing pad block has only one predecessor, this is
1530b57cec5SDimitry Andric     /// a simple branch. When there is more than one predecessor, we need to
1540b57cec5SDimitry Andric     /// split the landing pad block after the landingpad instruction and jump
1550b57cec5SDimitry Andric     /// to there.
1560b57cec5SDimitry Andric     void forwardResume(ResumeInst *RI,
1570b57cec5SDimitry Andric                        SmallPtrSetImpl<LandingPadInst*> &InlinedLPads);
1580b57cec5SDimitry Andric 
1590b57cec5SDimitry Andric     /// Add incoming-PHI values to the unwind destination block for the given
1600b57cec5SDimitry Andric     /// basic block, using the values for the original invoke's source block.
1610b57cec5SDimitry Andric     void addIncomingPHIValuesFor(BasicBlock *BB) const {
1620b57cec5SDimitry Andric       addIncomingPHIValuesForInto(BB, OuterResumeDest);
1630b57cec5SDimitry Andric     }
1640b57cec5SDimitry Andric 
1650b57cec5SDimitry Andric     void addIncomingPHIValuesForInto(BasicBlock *src, BasicBlock *dest) const {
1660b57cec5SDimitry Andric       BasicBlock::iterator I = dest->begin();
1670b57cec5SDimitry Andric       for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
1680b57cec5SDimitry Andric         PHINode *phi = cast<PHINode>(I);
1690b57cec5SDimitry Andric         phi->addIncoming(UnwindDestPHIValues[i], src);
1700b57cec5SDimitry Andric       }
1710b57cec5SDimitry Andric     }
1720b57cec5SDimitry Andric   };
1730b57cec5SDimitry Andric 
1740b57cec5SDimitry Andric } // end anonymous namespace
1750b57cec5SDimitry Andric 
1760b57cec5SDimitry Andric /// Get or create a target for the branch from ResumeInsts.
1770b57cec5SDimitry Andric BasicBlock *LandingPadInliningInfo::getInnerResumeDest() {
1780b57cec5SDimitry Andric   if (InnerResumeDest) return InnerResumeDest;
1790b57cec5SDimitry Andric 
1800b57cec5SDimitry Andric   // Split the landing pad.
1810b57cec5SDimitry Andric   BasicBlock::iterator SplitPoint = ++CallerLPad->getIterator();
1820b57cec5SDimitry Andric   InnerResumeDest =
1830b57cec5SDimitry Andric     OuterResumeDest->splitBasicBlock(SplitPoint,
1840b57cec5SDimitry Andric                                      OuterResumeDest->getName() + ".body");
1850b57cec5SDimitry Andric 
1860b57cec5SDimitry Andric   // The number of incoming edges we expect to the inner landing pad.
1870b57cec5SDimitry Andric   const unsigned PHICapacity = 2;
1880b57cec5SDimitry Andric 
1890b57cec5SDimitry Andric   // Create corresponding new PHIs for all the PHIs in the outer landing pad.
1900b57cec5SDimitry Andric   Instruction *InsertPoint = &InnerResumeDest->front();
1910b57cec5SDimitry Andric   BasicBlock::iterator I = OuterResumeDest->begin();
1920b57cec5SDimitry Andric   for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
1930b57cec5SDimitry Andric     PHINode *OuterPHI = cast<PHINode>(I);
1940b57cec5SDimitry Andric     PHINode *InnerPHI = PHINode::Create(OuterPHI->getType(), PHICapacity,
1950b57cec5SDimitry Andric                                         OuterPHI->getName() + ".lpad-body",
1960b57cec5SDimitry Andric                                         InsertPoint);
1970b57cec5SDimitry Andric     OuterPHI->replaceAllUsesWith(InnerPHI);
1980b57cec5SDimitry Andric     InnerPHI->addIncoming(OuterPHI, OuterResumeDest);
1990b57cec5SDimitry Andric   }
2000b57cec5SDimitry Andric 
2010b57cec5SDimitry Andric   // Create a PHI for the exception values.
2020b57cec5SDimitry Andric   InnerEHValuesPHI = PHINode::Create(CallerLPad->getType(), PHICapacity,
2030b57cec5SDimitry Andric                                      "eh.lpad-body", InsertPoint);
2040b57cec5SDimitry Andric   CallerLPad->replaceAllUsesWith(InnerEHValuesPHI);
2050b57cec5SDimitry Andric   InnerEHValuesPHI->addIncoming(CallerLPad, OuterResumeDest);
2060b57cec5SDimitry Andric 
2070b57cec5SDimitry Andric   // All done.
2080b57cec5SDimitry Andric   return InnerResumeDest;
2090b57cec5SDimitry Andric }
2100b57cec5SDimitry Andric 
2110b57cec5SDimitry Andric /// Forward the 'resume' instruction to the caller's landing pad block.
2120b57cec5SDimitry Andric /// When the landing pad block has only one predecessor, this is a simple
2130b57cec5SDimitry Andric /// branch. When there is more than one predecessor, we need to split the
2140b57cec5SDimitry Andric /// landing pad block after the landingpad instruction and jump to there.
2150b57cec5SDimitry Andric void LandingPadInliningInfo::forwardResume(
2160b57cec5SDimitry Andric     ResumeInst *RI, SmallPtrSetImpl<LandingPadInst *> &InlinedLPads) {
2170b57cec5SDimitry Andric   BasicBlock *Dest = getInnerResumeDest();
2180b57cec5SDimitry Andric   BasicBlock *Src = RI->getParent();
2190b57cec5SDimitry Andric 
2200b57cec5SDimitry Andric   BranchInst::Create(Dest, Src);
2210b57cec5SDimitry Andric 
2220b57cec5SDimitry Andric   // Update the PHIs in the destination. They were inserted in an order which
2230b57cec5SDimitry Andric   // makes this work.
2240b57cec5SDimitry Andric   addIncomingPHIValuesForInto(Src, Dest);
2250b57cec5SDimitry Andric 
2260b57cec5SDimitry Andric   InnerEHValuesPHI->addIncoming(RI->getOperand(0), Src);
2270b57cec5SDimitry Andric   RI->eraseFromParent();
2280b57cec5SDimitry Andric }
2290b57cec5SDimitry Andric 
2300b57cec5SDimitry Andric /// Helper for getUnwindDestToken/getUnwindDestTokenHelper.
2310b57cec5SDimitry Andric static Value *getParentPad(Value *EHPad) {
2320b57cec5SDimitry Andric   if (auto *FPI = dyn_cast<FuncletPadInst>(EHPad))
2330b57cec5SDimitry Andric     return FPI->getParentPad();
2340b57cec5SDimitry Andric   return cast<CatchSwitchInst>(EHPad)->getParentPad();
2350b57cec5SDimitry Andric }
2360b57cec5SDimitry Andric 
2370b57cec5SDimitry Andric using UnwindDestMemoTy = DenseMap<Instruction *, Value *>;
2380b57cec5SDimitry Andric 
2390b57cec5SDimitry Andric /// Helper for getUnwindDestToken that does the descendant-ward part of
2400b57cec5SDimitry Andric /// the search.
2410b57cec5SDimitry Andric static Value *getUnwindDestTokenHelper(Instruction *EHPad,
2420b57cec5SDimitry Andric                                        UnwindDestMemoTy &MemoMap) {
2430b57cec5SDimitry Andric   SmallVector<Instruction *, 8> Worklist(1, EHPad);
2440b57cec5SDimitry Andric 
2450b57cec5SDimitry Andric   while (!Worklist.empty()) {
2460b57cec5SDimitry Andric     Instruction *CurrentPad = Worklist.pop_back_val();
2470b57cec5SDimitry Andric     // We only put pads on the worklist that aren't in the MemoMap.  When
2480b57cec5SDimitry Andric     // we find an unwind dest for a pad we may update its ancestors, but
2490b57cec5SDimitry Andric     // the queue only ever contains uncles/great-uncles/etc. of CurrentPad,
2500b57cec5SDimitry Andric     // so they should never get updated while queued on the worklist.
2510b57cec5SDimitry Andric     assert(!MemoMap.count(CurrentPad));
2520b57cec5SDimitry Andric     Value *UnwindDestToken = nullptr;
2530b57cec5SDimitry Andric     if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(CurrentPad)) {
2540b57cec5SDimitry Andric       if (CatchSwitch->hasUnwindDest()) {
2550b57cec5SDimitry Andric         UnwindDestToken = CatchSwitch->getUnwindDest()->getFirstNonPHI();
2560b57cec5SDimitry Andric       } else {
2570b57cec5SDimitry Andric         // Catchswitch doesn't have a 'nounwind' variant, and one might be
2580b57cec5SDimitry Andric         // annotated as "unwinds to caller" when really it's nounwind (see
2590b57cec5SDimitry Andric         // e.g. SimplifyCFGOpt::SimplifyUnreachable), so we can't infer the
2600b57cec5SDimitry Andric         // parent's unwind dest from this.  We can check its catchpads'
2610b57cec5SDimitry Andric         // descendants, since they might include a cleanuppad with an
2620b57cec5SDimitry Andric         // "unwinds to caller" cleanupret, which can be trusted.
2630b57cec5SDimitry Andric         for (auto HI = CatchSwitch->handler_begin(),
2640b57cec5SDimitry Andric                   HE = CatchSwitch->handler_end();
2650b57cec5SDimitry Andric              HI != HE && !UnwindDestToken; ++HI) {
2660b57cec5SDimitry Andric           BasicBlock *HandlerBlock = *HI;
2670b57cec5SDimitry Andric           auto *CatchPad = cast<CatchPadInst>(HandlerBlock->getFirstNonPHI());
2680b57cec5SDimitry Andric           for (User *Child : CatchPad->users()) {
2690b57cec5SDimitry Andric             // Intentionally ignore invokes here -- since the catchswitch is
2700b57cec5SDimitry Andric             // marked "unwind to caller", it would be a verifier error if it
2710b57cec5SDimitry Andric             // contained an invoke which unwinds out of it, so any invoke we'd
2720b57cec5SDimitry Andric             // encounter must unwind to some child of the catch.
2730b57cec5SDimitry Andric             if (!isa<CleanupPadInst>(Child) && !isa<CatchSwitchInst>(Child))
2740b57cec5SDimitry Andric               continue;
2750b57cec5SDimitry Andric 
2760b57cec5SDimitry Andric             Instruction *ChildPad = cast<Instruction>(Child);
2770b57cec5SDimitry Andric             auto Memo = MemoMap.find(ChildPad);
2780b57cec5SDimitry Andric             if (Memo == MemoMap.end()) {
2790b57cec5SDimitry Andric               // Haven't figured out this child pad yet; queue it.
2800b57cec5SDimitry Andric               Worklist.push_back(ChildPad);
2810b57cec5SDimitry Andric               continue;
2820b57cec5SDimitry Andric             }
2830b57cec5SDimitry Andric             // We've already checked this child, but might have found that
2840b57cec5SDimitry Andric             // it offers no proof either way.
2850b57cec5SDimitry Andric             Value *ChildUnwindDestToken = Memo->second;
2860b57cec5SDimitry Andric             if (!ChildUnwindDestToken)
2870b57cec5SDimitry Andric               continue;
2880b57cec5SDimitry Andric             // We already know the child's unwind dest, which can either
2890b57cec5SDimitry Andric             // be ConstantTokenNone to indicate unwind to caller, or can
2900b57cec5SDimitry Andric             // be another child of the catchpad.  Only the former indicates
2910b57cec5SDimitry Andric             // the unwind dest of the catchswitch.
2920b57cec5SDimitry Andric             if (isa<ConstantTokenNone>(ChildUnwindDestToken)) {
2930b57cec5SDimitry Andric               UnwindDestToken = ChildUnwindDestToken;
2940b57cec5SDimitry Andric               break;
2950b57cec5SDimitry Andric             }
2960b57cec5SDimitry Andric             assert(getParentPad(ChildUnwindDestToken) == CatchPad);
2970b57cec5SDimitry Andric           }
2980b57cec5SDimitry Andric         }
2990b57cec5SDimitry Andric       }
3000b57cec5SDimitry Andric     } else {
3010b57cec5SDimitry Andric       auto *CleanupPad = cast<CleanupPadInst>(CurrentPad);
3020b57cec5SDimitry Andric       for (User *U : CleanupPad->users()) {
3030b57cec5SDimitry Andric         if (auto *CleanupRet = dyn_cast<CleanupReturnInst>(U)) {
3040b57cec5SDimitry Andric           if (BasicBlock *RetUnwindDest = CleanupRet->getUnwindDest())
3050b57cec5SDimitry Andric             UnwindDestToken = RetUnwindDest->getFirstNonPHI();
3060b57cec5SDimitry Andric           else
3070b57cec5SDimitry Andric             UnwindDestToken = ConstantTokenNone::get(CleanupPad->getContext());
3080b57cec5SDimitry Andric           break;
3090b57cec5SDimitry Andric         }
3100b57cec5SDimitry Andric         Value *ChildUnwindDestToken;
3110b57cec5SDimitry Andric         if (auto *Invoke = dyn_cast<InvokeInst>(U)) {
3120b57cec5SDimitry Andric           ChildUnwindDestToken = Invoke->getUnwindDest()->getFirstNonPHI();
3130b57cec5SDimitry Andric         } else if (isa<CleanupPadInst>(U) || isa<CatchSwitchInst>(U)) {
3140b57cec5SDimitry Andric           Instruction *ChildPad = cast<Instruction>(U);
3150b57cec5SDimitry Andric           auto Memo = MemoMap.find(ChildPad);
3160b57cec5SDimitry Andric           if (Memo == MemoMap.end()) {
3170b57cec5SDimitry Andric             // Haven't resolved this child yet; queue it and keep searching.
3180b57cec5SDimitry Andric             Worklist.push_back(ChildPad);
3190b57cec5SDimitry Andric             continue;
3200b57cec5SDimitry Andric           }
3210b57cec5SDimitry Andric           // We've checked this child, but still need to ignore it if it
3220b57cec5SDimitry Andric           // had no proof either way.
3230b57cec5SDimitry Andric           ChildUnwindDestToken = Memo->second;
3240b57cec5SDimitry Andric           if (!ChildUnwindDestToken)
3250b57cec5SDimitry Andric             continue;
3260b57cec5SDimitry Andric         } else {
3270b57cec5SDimitry Andric           // Not a relevant user of the cleanuppad
3280b57cec5SDimitry Andric           continue;
3290b57cec5SDimitry Andric         }
3300b57cec5SDimitry Andric         // In a well-formed program, the child/invoke must either unwind to
3310b57cec5SDimitry Andric         // an(other) child of the cleanup, or exit the cleanup.  In the
3320b57cec5SDimitry Andric         // first case, continue searching.
3330b57cec5SDimitry Andric         if (isa<Instruction>(ChildUnwindDestToken) &&
3340b57cec5SDimitry Andric             getParentPad(ChildUnwindDestToken) == CleanupPad)
3350b57cec5SDimitry Andric           continue;
3360b57cec5SDimitry Andric         UnwindDestToken = ChildUnwindDestToken;
3370b57cec5SDimitry Andric         break;
3380b57cec5SDimitry Andric       }
3390b57cec5SDimitry Andric     }
3400b57cec5SDimitry Andric     // If we haven't found an unwind dest for CurrentPad, we may have queued its
3410b57cec5SDimitry Andric     // children, so move on to the next in the worklist.
3420b57cec5SDimitry Andric     if (!UnwindDestToken)
3430b57cec5SDimitry Andric       continue;
3440b57cec5SDimitry Andric 
3450b57cec5SDimitry Andric     // Now we know that CurrentPad unwinds to UnwindDestToken.  It also exits
3460b57cec5SDimitry Andric     // any ancestors of CurrentPad up to but not including UnwindDestToken's
3470b57cec5SDimitry Andric     // parent pad.  Record this in the memo map, and check to see if the
3480b57cec5SDimitry Andric     // original EHPad being queried is one of the ones exited.
3490b57cec5SDimitry Andric     Value *UnwindParent;
3500b57cec5SDimitry Andric     if (auto *UnwindPad = dyn_cast<Instruction>(UnwindDestToken))
3510b57cec5SDimitry Andric       UnwindParent = getParentPad(UnwindPad);
3520b57cec5SDimitry Andric     else
3530b57cec5SDimitry Andric       UnwindParent = nullptr;
3540b57cec5SDimitry Andric     bool ExitedOriginalPad = false;
3550b57cec5SDimitry Andric     for (Instruction *ExitedPad = CurrentPad;
3560b57cec5SDimitry Andric          ExitedPad && ExitedPad != UnwindParent;
3570b57cec5SDimitry Andric          ExitedPad = dyn_cast<Instruction>(getParentPad(ExitedPad))) {
3580b57cec5SDimitry Andric       // Skip over catchpads since they just follow their catchswitches.
3590b57cec5SDimitry Andric       if (isa<CatchPadInst>(ExitedPad))
3600b57cec5SDimitry Andric         continue;
3610b57cec5SDimitry Andric       MemoMap[ExitedPad] = UnwindDestToken;
3620b57cec5SDimitry Andric       ExitedOriginalPad |= (ExitedPad == EHPad);
3630b57cec5SDimitry Andric     }
3640b57cec5SDimitry Andric 
3650b57cec5SDimitry Andric     if (ExitedOriginalPad)
3660b57cec5SDimitry Andric       return UnwindDestToken;
3670b57cec5SDimitry Andric 
3680b57cec5SDimitry Andric     // Continue the search.
3690b57cec5SDimitry Andric   }
3700b57cec5SDimitry Andric 
3710b57cec5SDimitry Andric   // No definitive information is contained within this funclet.
3720b57cec5SDimitry Andric   return nullptr;
3730b57cec5SDimitry Andric }
3740b57cec5SDimitry Andric 
3750b57cec5SDimitry Andric /// Given an EH pad, find where it unwinds.  If it unwinds to an EH pad,
3760b57cec5SDimitry Andric /// return that pad instruction.  If it unwinds to caller, return
3770b57cec5SDimitry Andric /// ConstantTokenNone.  If it does not have a definitive unwind destination,
3780b57cec5SDimitry Andric /// return nullptr.
3790b57cec5SDimitry Andric ///
3800b57cec5SDimitry Andric /// This routine gets invoked for calls in funclets in inlinees when inlining
3810b57cec5SDimitry Andric /// an invoke.  Since many funclets don't have calls inside them, it's queried
3820b57cec5SDimitry Andric /// on-demand rather than building a map of pads to unwind dests up front.
3830b57cec5SDimitry Andric /// Determining a funclet's unwind dest may require recursively searching its
3840b57cec5SDimitry Andric /// descendants, and also ancestors and cousins if the descendants don't provide
3850b57cec5SDimitry Andric /// an answer.  Since most funclets will have their unwind dest immediately
3860b57cec5SDimitry Andric /// available as the unwind dest of a catchswitch or cleanupret, this routine
3870b57cec5SDimitry Andric /// searches top-down from the given pad and then up. To avoid worst-case
3880b57cec5SDimitry Andric /// quadratic run-time given that approach, it uses a memo map to avoid
3890b57cec5SDimitry Andric /// re-processing funclet trees.  The callers that rewrite the IR as they go
3900b57cec5SDimitry Andric /// take advantage of this, for correctness, by checking/forcing rewritten
3910b57cec5SDimitry Andric /// pads' entries to match the original callee view.
3920b57cec5SDimitry Andric static Value *getUnwindDestToken(Instruction *EHPad,
3930b57cec5SDimitry Andric                                  UnwindDestMemoTy &MemoMap) {
3940b57cec5SDimitry Andric   // Catchpads unwind to the same place as their catchswitch;
3950b57cec5SDimitry Andric   // redirct any queries on catchpads so the code below can
3960b57cec5SDimitry Andric   // deal with just catchswitches and cleanuppads.
3970b57cec5SDimitry Andric   if (auto *CPI = dyn_cast<CatchPadInst>(EHPad))
3980b57cec5SDimitry Andric     EHPad = CPI->getCatchSwitch();
3990b57cec5SDimitry Andric 
4000b57cec5SDimitry Andric   // Check if we've already determined the unwind dest for this pad.
4010b57cec5SDimitry Andric   auto Memo = MemoMap.find(EHPad);
4020b57cec5SDimitry Andric   if (Memo != MemoMap.end())
4030b57cec5SDimitry Andric     return Memo->second;
4040b57cec5SDimitry Andric 
4050b57cec5SDimitry Andric   // Search EHPad and, if necessary, its descendants.
4060b57cec5SDimitry Andric   Value *UnwindDestToken = getUnwindDestTokenHelper(EHPad, MemoMap);
4070b57cec5SDimitry Andric   assert((UnwindDestToken == nullptr) != (MemoMap.count(EHPad) != 0));
4080b57cec5SDimitry Andric   if (UnwindDestToken)
4090b57cec5SDimitry Andric     return UnwindDestToken;
4100b57cec5SDimitry Andric 
4110b57cec5SDimitry Andric   // No information is available for this EHPad from itself or any of its
4120b57cec5SDimitry Andric   // descendants.  An unwind all the way out to a pad in the caller would
4130b57cec5SDimitry Andric   // need also to agree with the unwind dest of the parent funclet, so
4140b57cec5SDimitry Andric   // search up the chain to try to find a funclet with information.  Put
4150b57cec5SDimitry Andric   // null entries in the memo map to avoid re-processing as we go up.
4160b57cec5SDimitry Andric   MemoMap[EHPad] = nullptr;
4170b57cec5SDimitry Andric #ifndef NDEBUG
4180b57cec5SDimitry Andric   SmallPtrSet<Instruction *, 4> TempMemos;
4190b57cec5SDimitry Andric   TempMemos.insert(EHPad);
4200b57cec5SDimitry Andric #endif
4210b57cec5SDimitry Andric   Instruction *LastUselessPad = EHPad;
4220b57cec5SDimitry Andric   Value *AncestorToken;
4230b57cec5SDimitry Andric   for (AncestorToken = getParentPad(EHPad);
4240b57cec5SDimitry Andric        auto *AncestorPad = dyn_cast<Instruction>(AncestorToken);
4250b57cec5SDimitry Andric        AncestorToken = getParentPad(AncestorToken)) {
4260b57cec5SDimitry Andric     // Skip over catchpads since they just follow their catchswitches.
4270b57cec5SDimitry Andric     if (isa<CatchPadInst>(AncestorPad))
4280b57cec5SDimitry Andric       continue;
4290b57cec5SDimitry Andric     // If the MemoMap had an entry mapping AncestorPad to nullptr, since we
4300b57cec5SDimitry Andric     // haven't yet called getUnwindDestTokenHelper for AncestorPad in this
4310b57cec5SDimitry Andric     // call to getUnwindDestToken, that would mean that AncestorPad had no
4320b57cec5SDimitry Andric     // information in itself, its descendants, or its ancestors.  If that
4330b57cec5SDimitry Andric     // were the case, then we should also have recorded the lack of information
4340b57cec5SDimitry Andric     // for the descendant that we're coming from.  So assert that we don't
4350b57cec5SDimitry Andric     // find a null entry in the MemoMap for AncestorPad.
4360b57cec5SDimitry Andric     assert(!MemoMap.count(AncestorPad) || MemoMap[AncestorPad]);
4370b57cec5SDimitry Andric     auto AncestorMemo = MemoMap.find(AncestorPad);
4380b57cec5SDimitry Andric     if (AncestorMemo == MemoMap.end()) {
4390b57cec5SDimitry Andric       UnwindDestToken = getUnwindDestTokenHelper(AncestorPad, MemoMap);
4400b57cec5SDimitry Andric     } else {
4410b57cec5SDimitry Andric       UnwindDestToken = AncestorMemo->second;
4420b57cec5SDimitry Andric     }
4430b57cec5SDimitry Andric     if (UnwindDestToken)
4440b57cec5SDimitry Andric       break;
4450b57cec5SDimitry Andric     LastUselessPad = AncestorPad;
4460b57cec5SDimitry Andric     MemoMap[LastUselessPad] = nullptr;
4470b57cec5SDimitry Andric #ifndef NDEBUG
4480b57cec5SDimitry Andric     TempMemos.insert(LastUselessPad);
4490b57cec5SDimitry Andric #endif
4500b57cec5SDimitry Andric   }
4510b57cec5SDimitry Andric 
4520b57cec5SDimitry Andric   // We know that getUnwindDestTokenHelper was called on LastUselessPad and
4530b57cec5SDimitry Andric   // returned nullptr (and likewise for EHPad and any of its ancestors up to
4540b57cec5SDimitry Andric   // LastUselessPad), so LastUselessPad has no information from below.  Since
4550b57cec5SDimitry Andric   // getUnwindDestTokenHelper must investigate all downward paths through
4560b57cec5SDimitry Andric   // no-information nodes to prove that a node has no information like this,
4570b57cec5SDimitry Andric   // and since any time it finds information it records it in the MemoMap for
4580b57cec5SDimitry Andric   // not just the immediately-containing funclet but also any ancestors also
4590b57cec5SDimitry Andric   // exited, it must be the case that, walking downward from LastUselessPad,
4600b57cec5SDimitry Andric   // visiting just those nodes which have not been mapped to an unwind dest
4610b57cec5SDimitry Andric   // by getUnwindDestTokenHelper (the nullptr TempMemos notwithstanding, since
4620b57cec5SDimitry Andric   // they are just used to keep getUnwindDestTokenHelper from repeating work),
4630b57cec5SDimitry Andric   // any node visited must have been exhaustively searched with no information
4640b57cec5SDimitry Andric   // for it found.
4650b57cec5SDimitry Andric   SmallVector<Instruction *, 8> Worklist(1, LastUselessPad);
4660b57cec5SDimitry Andric   while (!Worklist.empty()) {
4670b57cec5SDimitry Andric     Instruction *UselessPad = Worklist.pop_back_val();
4680b57cec5SDimitry Andric     auto Memo = MemoMap.find(UselessPad);
4690b57cec5SDimitry Andric     if (Memo != MemoMap.end() && Memo->second) {
4700b57cec5SDimitry Andric       // Here the name 'UselessPad' is a bit of a misnomer, because we've found
4710b57cec5SDimitry Andric       // that it is a funclet that does have information about unwinding to
4720b57cec5SDimitry Andric       // a particular destination; its parent was a useless pad.
4730b57cec5SDimitry Andric       // Since its parent has no information, the unwind edge must not escape
4740b57cec5SDimitry Andric       // the parent, and must target a sibling of this pad.  This local unwind
4750b57cec5SDimitry Andric       // gives us no information about EHPad.  Leave it and the subtree rooted
4760b57cec5SDimitry Andric       // at it alone.
4770b57cec5SDimitry Andric       assert(getParentPad(Memo->second) == getParentPad(UselessPad));
4780b57cec5SDimitry Andric       continue;
4790b57cec5SDimitry Andric     }
4800b57cec5SDimitry Andric     // We know we don't have information for UselesPad.  If it has an entry in
4810b57cec5SDimitry Andric     // the MemoMap (mapping it to nullptr), it must be one of the TempMemos
4820b57cec5SDimitry Andric     // added on this invocation of getUnwindDestToken; if a previous invocation
4830b57cec5SDimitry Andric     // recorded nullptr, it would have had to prove that the ancestors of
4840b57cec5SDimitry Andric     // UselessPad, which include LastUselessPad, had no information, and that
4850b57cec5SDimitry Andric     // in turn would have required proving that the descendants of
4860b57cec5SDimitry Andric     // LastUselesPad, which include EHPad, have no information about
4870b57cec5SDimitry Andric     // LastUselessPad, which would imply that EHPad was mapped to nullptr in
4880b57cec5SDimitry Andric     // the MemoMap on that invocation, which isn't the case if we got here.
4890b57cec5SDimitry Andric     assert(!MemoMap.count(UselessPad) || TempMemos.count(UselessPad));
4900b57cec5SDimitry Andric     // Assert as we enumerate users that 'UselessPad' doesn't have any unwind
4910b57cec5SDimitry Andric     // information that we'd be contradicting by making a map entry for it
4920b57cec5SDimitry Andric     // (which is something that getUnwindDestTokenHelper must have proved for
4930b57cec5SDimitry Andric     // us to get here).  Just assert on is direct users here; the checks in
4940b57cec5SDimitry Andric     // this downward walk at its descendants will verify that they don't have
4950b57cec5SDimitry Andric     // any unwind edges that exit 'UselessPad' either (i.e. they either have no
4960b57cec5SDimitry Andric     // unwind edges or unwind to a sibling).
4970b57cec5SDimitry Andric     MemoMap[UselessPad] = UnwindDestToken;
4980b57cec5SDimitry Andric     if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(UselessPad)) {
4990b57cec5SDimitry Andric       assert(CatchSwitch->getUnwindDest() == nullptr && "Expected useless pad");
5000b57cec5SDimitry Andric       for (BasicBlock *HandlerBlock : CatchSwitch->handlers()) {
5010b57cec5SDimitry Andric         auto *CatchPad = HandlerBlock->getFirstNonPHI();
5020b57cec5SDimitry Andric         for (User *U : CatchPad->users()) {
5030b57cec5SDimitry Andric           assert(
5040b57cec5SDimitry Andric               (!isa<InvokeInst>(U) ||
5050b57cec5SDimitry Andric                (getParentPad(
5060b57cec5SDimitry Andric                     cast<InvokeInst>(U)->getUnwindDest()->getFirstNonPHI()) ==
5070b57cec5SDimitry Andric                 CatchPad)) &&
5080b57cec5SDimitry Andric               "Expected useless pad");
5090b57cec5SDimitry Andric           if (isa<CatchSwitchInst>(U) || isa<CleanupPadInst>(U))
5100b57cec5SDimitry Andric             Worklist.push_back(cast<Instruction>(U));
5110b57cec5SDimitry Andric         }
5120b57cec5SDimitry Andric       }
5130b57cec5SDimitry Andric     } else {
5140b57cec5SDimitry Andric       assert(isa<CleanupPadInst>(UselessPad));
5150b57cec5SDimitry Andric       for (User *U : UselessPad->users()) {
5160b57cec5SDimitry Andric         assert(!isa<CleanupReturnInst>(U) && "Expected useless pad");
5170b57cec5SDimitry Andric         assert((!isa<InvokeInst>(U) ||
5180b57cec5SDimitry Andric                 (getParentPad(
5190b57cec5SDimitry Andric                      cast<InvokeInst>(U)->getUnwindDest()->getFirstNonPHI()) ==
5200b57cec5SDimitry Andric                  UselessPad)) &&
5210b57cec5SDimitry Andric                "Expected useless pad");
5220b57cec5SDimitry Andric         if (isa<CatchSwitchInst>(U) || isa<CleanupPadInst>(U))
5230b57cec5SDimitry Andric           Worklist.push_back(cast<Instruction>(U));
5240b57cec5SDimitry Andric       }
5250b57cec5SDimitry Andric     }
5260b57cec5SDimitry Andric   }
5270b57cec5SDimitry Andric 
5280b57cec5SDimitry Andric   return UnwindDestToken;
5290b57cec5SDimitry Andric }
5300b57cec5SDimitry Andric 
5310b57cec5SDimitry Andric /// When we inline a basic block into an invoke,
5320b57cec5SDimitry Andric /// we have to turn all of the calls that can throw into invokes.
5330b57cec5SDimitry Andric /// This function analyze BB to see if there are any calls, and if so,
5340b57cec5SDimitry Andric /// it rewrites them to be invokes that jump to InvokeDest and fills in the PHI
5350b57cec5SDimitry Andric /// nodes in that block with the values specified in InvokeDestPHIValues.
5360b57cec5SDimitry Andric static BasicBlock *HandleCallsInBlockInlinedThroughInvoke(
5370b57cec5SDimitry Andric     BasicBlock *BB, BasicBlock *UnwindEdge,
5380b57cec5SDimitry Andric     UnwindDestMemoTy *FuncletUnwindMap = nullptr) {
5390b57cec5SDimitry Andric   for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
5400b57cec5SDimitry Andric     Instruction *I = &*BBI++;
5410b57cec5SDimitry Andric 
5420b57cec5SDimitry Andric     // We only need to check for function calls: inlined invoke
5430b57cec5SDimitry Andric     // instructions require no special handling.
5440b57cec5SDimitry Andric     CallInst *CI = dyn_cast<CallInst>(I);
5450b57cec5SDimitry Andric 
5465ffd83dbSDimitry Andric     if (!CI || CI->doesNotThrow() || CI->isInlineAsm())
5470b57cec5SDimitry Andric       continue;
5480b57cec5SDimitry Andric 
5490b57cec5SDimitry Andric     // We do not need to (and in fact, cannot) convert possibly throwing calls
5500b57cec5SDimitry Andric     // to @llvm.experimental_deoptimize (resp. @llvm.experimental.guard) into
5510b57cec5SDimitry Andric     // invokes.  The caller's "segment" of the deoptimization continuation
5520b57cec5SDimitry Andric     // attached to the newly inlined @llvm.experimental_deoptimize
5530b57cec5SDimitry Andric     // (resp. @llvm.experimental.guard) call should contain the exception
5540b57cec5SDimitry Andric     // handling logic, if any.
5550b57cec5SDimitry Andric     if (auto *F = CI->getCalledFunction())
5560b57cec5SDimitry Andric       if (F->getIntrinsicID() == Intrinsic::experimental_deoptimize ||
5570b57cec5SDimitry Andric           F->getIntrinsicID() == Intrinsic::experimental_guard)
5580b57cec5SDimitry Andric         continue;
5590b57cec5SDimitry Andric 
5600b57cec5SDimitry Andric     if (auto FuncletBundle = CI->getOperandBundle(LLVMContext::OB_funclet)) {
5610b57cec5SDimitry Andric       // This call is nested inside a funclet.  If that funclet has an unwind
5620b57cec5SDimitry Andric       // destination within the inlinee, then unwinding out of this call would
5630b57cec5SDimitry Andric       // be UB.  Rewriting this call to an invoke which targets the inlined
5640b57cec5SDimitry Andric       // invoke's unwind dest would give the call's parent funclet multiple
5650b57cec5SDimitry Andric       // unwind destinations, which is something that subsequent EH table
5660b57cec5SDimitry Andric       // generation can't handle and that the veirifer rejects.  So when we
5670b57cec5SDimitry Andric       // see such a call, leave it as a call.
5680b57cec5SDimitry Andric       auto *FuncletPad = cast<Instruction>(FuncletBundle->Inputs[0]);
5690b57cec5SDimitry Andric       Value *UnwindDestToken =
5700b57cec5SDimitry Andric           getUnwindDestToken(FuncletPad, *FuncletUnwindMap);
5710b57cec5SDimitry Andric       if (UnwindDestToken && !isa<ConstantTokenNone>(UnwindDestToken))
5720b57cec5SDimitry Andric         continue;
5730b57cec5SDimitry Andric #ifndef NDEBUG
5740b57cec5SDimitry Andric       Instruction *MemoKey;
5750b57cec5SDimitry Andric       if (auto *CatchPad = dyn_cast<CatchPadInst>(FuncletPad))
5760b57cec5SDimitry Andric         MemoKey = CatchPad->getCatchSwitch();
5770b57cec5SDimitry Andric       else
5780b57cec5SDimitry Andric         MemoKey = FuncletPad;
5790b57cec5SDimitry Andric       assert(FuncletUnwindMap->count(MemoKey) &&
5800b57cec5SDimitry Andric              (*FuncletUnwindMap)[MemoKey] == UnwindDestToken &&
5810b57cec5SDimitry Andric              "must get memoized to avoid confusing later searches");
5820b57cec5SDimitry Andric #endif // NDEBUG
5830b57cec5SDimitry Andric     }
5840b57cec5SDimitry Andric 
5850b57cec5SDimitry Andric     changeToInvokeAndSplitBasicBlock(CI, UnwindEdge);
5860b57cec5SDimitry Andric     return BB;
5870b57cec5SDimitry Andric   }
5880b57cec5SDimitry Andric   return nullptr;
5890b57cec5SDimitry Andric }
5900b57cec5SDimitry Andric 
5910b57cec5SDimitry Andric /// If we inlined an invoke site, we need to convert calls
5920b57cec5SDimitry Andric /// in the body of the inlined function into invokes.
5930b57cec5SDimitry Andric ///
5940b57cec5SDimitry Andric /// II is the invoke instruction being inlined.  FirstNewBlock is the first
5950b57cec5SDimitry Andric /// block of the inlined code (the last block is the end of the function),
5960b57cec5SDimitry Andric /// and InlineCodeInfo is information about the code that got inlined.
5970b57cec5SDimitry Andric static void HandleInlinedLandingPad(InvokeInst *II, BasicBlock *FirstNewBlock,
5980b57cec5SDimitry Andric                                     ClonedCodeInfo &InlinedCodeInfo) {
5990b57cec5SDimitry Andric   BasicBlock *InvokeDest = II->getUnwindDest();
6000b57cec5SDimitry Andric 
6010b57cec5SDimitry Andric   Function *Caller = FirstNewBlock->getParent();
6020b57cec5SDimitry Andric 
6030b57cec5SDimitry Andric   // The inlined code is currently at the end of the function, scan from the
6040b57cec5SDimitry Andric   // start of the inlined code to its end, checking for stuff we need to
6050b57cec5SDimitry Andric   // rewrite.
6060b57cec5SDimitry Andric   LandingPadInliningInfo Invoke(II);
6070b57cec5SDimitry Andric 
6080b57cec5SDimitry Andric   // Get all of the inlined landing pad instructions.
6090b57cec5SDimitry Andric   SmallPtrSet<LandingPadInst*, 16> InlinedLPads;
6100b57cec5SDimitry Andric   for (Function::iterator I = FirstNewBlock->getIterator(), E = Caller->end();
6110b57cec5SDimitry Andric        I != E; ++I)
6120b57cec5SDimitry Andric     if (InvokeInst *II = dyn_cast<InvokeInst>(I->getTerminator()))
6130b57cec5SDimitry Andric       InlinedLPads.insert(II->getLandingPadInst());
6140b57cec5SDimitry Andric 
6150b57cec5SDimitry Andric   // Append the clauses from the outer landing pad instruction into the inlined
6160b57cec5SDimitry Andric   // landing pad instructions.
6170b57cec5SDimitry Andric   LandingPadInst *OuterLPad = Invoke.getLandingPadInst();
6180b57cec5SDimitry Andric   for (LandingPadInst *InlinedLPad : InlinedLPads) {
6190b57cec5SDimitry Andric     unsigned OuterNum = OuterLPad->getNumClauses();
6200b57cec5SDimitry Andric     InlinedLPad->reserveClauses(OuterNum);
6210b57cec5SDimitry Andric     for (unsigned OuterIdx = 0; OuterIdx != OuterNum; ++OuterIdx)
6220b57cec5SDimitry Andric       InlinedLPad->addClause(OuterLPad->getClause(OuterIdx));
6230b57cec5SDimitry Andric     if (OuterLPad->isCleanup())
6240b57cec5SDimitry Andric       InlinedLPad->setCleanup(true);
6250b57cec5SDimitry Andric   }
6260b57cec5SDimitry Andric 
6270b57cec5SDimitry Andric   for (Function::iterator BB = FirstNewBlock->getIterator(), E = Caller->end();
6280b57cec5SDimitry Andric        BB != E; ++BB) {
6290b57cec5SDimitry Andric     if (InlinedCodeInfo.ContainsCalls)
6300b57cec5SDimitry Andric       if (BasicBlock *NewBB = HandleCallsInBlockInlinedThroughInvoke(
6310b57cec5SDimitry Andric               &*BB, Invoke.getOuterResumeDest()))
6320b57cec5SDimitry Andric         // Update any PHI nodes in the exceptional block to indicate that there
6330b57cec5SDimitry Andric         // is now a new entry in them.
6340b57cec5SDimitry Andric         Invoke.addIncomingPHIValuesFor(NewBB);
6350b57cec5SDimitry Andric 
6360b57cec5SDimitry Andric     // Forward any resumes that are remaining here.
6370b57cec5SDimitry Andric     if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator()))
6380b57cec5SDimitry Andric       Invoke.forwardResume(RI, InlinedLPads);
6390b57cec5SDimitry Andric   }
6400b57cec5SDimitry Andric 
6410b57cec5SDimitry Andric   // Now that everything is happy, we have one final detail.  The PHI nodes in
6420b57cec5SDimitry Andric   // the exception destination block still have entries due to the original
6430b57cec5SDimitry Andric   // invoke instruction. Eliminate these entries (which might even delete the
6440b57cec5SDimitry Andric   // PHI node) now.
6450b57cec5SDimitry Andric   InvokeDest->removePredecessor(II->getParent());
6460b57cec5SDimitry Andric }
6470b57cec5SDimitry Andric 
6480b57cec5SDimitry Andric /// If we inlined an invoke site, we need to convert calls
6490b57cec5SDimitry Andric /// in the body of the inlined function into invokes.
6500b57cec5SDimitry Andric ///
6510b57cec5SDimitry Andric /// II is the invoke instruction being inlined.  FirstNewBlock is the first
6520b57cec5SDimitry Andric /// block of the inlined code (the last block is the end of the function),
6530b57cec5SDimitry Andric /// and InlineCodeInfo is information about the code that got inlined.
6540b57cec5SDimitry Andric static void HandleInlinedEHPad(InvokeInst *II, BasicBlock *FirstNewBlock,
6550b57cec5SDimitry Andric                                ClonedCodeInfo &InlinedCodeInfo) {
6560b57cec5SDimitry Andric   BasicBlock *UnwindDest = II->getUnwindDest();
6570b57cec5SDimitry Andric   Function *Caller = FirstNewBlock->getParent();
6580b57cec5SDimitry Andric 
6590b57cec5SDimitry Andric   assert(UnwindDest->getFirstNonPHI()->isEHPad() && "unexpected BasicBlock!");
6600b57cec5SDimitry Andric 
6610b57cec5SDimitry Andric   // If there are PHI nodes in the unwind destination block, we need to keep
6620b57cec5SDimitry Andric   // track of which values came into them from the invoke before removing the
6630b57cec5SDimitry Andric   // edge from this block.
6640b57cec5SDimitry Andric   SmallVector<Value *, 8> UnwindDestPHIValues;
6650b57cec5SDimitry Andric   BasicBlock *InvokeBB = II->getParent();
6660b57cec5SDimitry Andric   for (Instruction &I : *UnwindDest) {
6670b57cec5SDimitry Andric     // Save the value to use for this edge.
6680b57cec5SDimitry Andric     PHINode *PHI = dyn_cast<PHINode>(&I);
6690b57cec5SDimitry Andric     if (!PHI)
6700b57cec5SDimitry Andric       break;
6710b57cec5SDimitry Andric     UnwindDestPHIValues.push_back(PHI->getIncomingValueForBlock(InvokeBB));
6720b57cec5SDimitry Andric   }
6730b57cec5SDimitry Andric 
6740b57cec5SDimitry Andric   // Add incoming-PHI values to the unwind destination block for the given basic
6750b57cec5SDimitry Andric   // block, using the values for the original invoke's source block.
6760b57cec5SDimitry Andric   auto UpdatePHINodes = [&](BasicBlock *Src) {
6770b57cec5SDimitry Andric     BasicBlock::iterator I = UnwindDest->begin();
6780b57cec5SDimitry Andric     for (Value *V : UnwindDestPHIValues) {
6790b57cec5SDimitry Andric       PHINode *PHI = cast<PHINode>(I);
6800b57cec5SDimitry Andric       PHI->addIncoming(V, Src);
6810b57cec5SDimitry Andric       ++I;
6820b57cec5SDimitry Andric     }
6830b57cec5SDimitry Andric   };
6840b57cec5SDimitry Andric 
6850b57cec5SDimitry Andric   // This connects all the instructions which 'unwind to caller' to the invoke
6860b57cec5SDimitry Andric   // destination.
6870b57cec5SDimitry Andric   UnwindDestMemoTy FuncletUnwindMap;
6880b57cec5SDimitry Andric   for (Function::iterator BB = FirstNewBlock->getIterator(), E = Caller->end();
6890b57cec5SDimitry Andric        BB != E; ++BB) {
6900b57cec5SDimitry Andric     if (auto *CRI = dyn_cast<CleanupReturnInst>(BB->getTerminator())) {
6910b57cec5SDimitry Andric       if (CRI->unwindsToCaller()) {
6920b57cec5SDimitry Andric         auto *CleanupPad = CRI->getCleanupPad();
6930b57cec5SDimitry Andric         CleanupReturnInst::Create(CleanupPad, UnwindDest, CRI);
6940b57cec5SDimitry Andric         CRI->eraseFromParent();
6950b57cec5SDimitry Andric         UpdatePHINodes(&*BB);
6960b57cec5SDimitry Andric         // Finding a cleanupret with an unwind destination would confuse
6970b57cec5SDimitry Andric         // subsequent calls to getUnwindDestToken, so map the cleanuppad
6980b57cec5SDimitry Andric         // to short-circuit any such calls and recognize this as an "unwind
6990b57cec5SDimitry Andric         // to caller" cleanup.
7000b57cec5SDimitry Andric         assert(!FuncletUnwindMap.count(CleanupPad) ||
7010b57cec5SDimitry Andric                isa<ConstantTokenNone>(FuncletUnwindMap[CleanupPad]));
7020b57cec5SDimitry Andric         FuncletUnwindMap[CleanupPad] =
7030b57cec5SDimitry Andric             ConstantTokenNone::get(Caller->getContext());
7040b57cec5SDimitry Andric       }
7050b57cec5SDimitry Andric     }
7060b57cec5SDimitry Andric 
7070b57cec5SDimitry Andric     Instruction *I = BB->getFirstNonPHI();
7080b57cec5SDimitry Andric     if (!I->isEHPad())
7090b57cec5SDimitry Andric       continue;
7100b57cec5SDimitry Andric 
7110b57cec5SDimitry Andric     Instruction *Replacement = nullptr;
7120b57cec5SDimitry Andric     if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(I)) {
7130b57cec5SDimitry Andric       if (CatchSwitch->unwindsToCaller()) {
7140b57cec5SDimitry Andric         Value *UnwindDestToken;
7150b57cec5SDimitry Andric         if (auto *ParentPad =
7160b57cec5SDimitry Andric                 dyn_cast<Instruction>(CatchSwitch->getParentPad())) {
7170b57cec5SDimitry Andric           // This catchswitch is nested inside another funclet.  If that
7180b57cec5SDimitry Andric           // funclet has an unwind destination within the inlinee, then
7190b57cec5SDimitry Andric           // unwinding out of this catchswitch would be UB.  Rewriting this
7200b57cec5SDimitry Andric           // catchswitch to unwind to the inlined invoke's unwind dest would
7210b57cec5SDimitry Andric           // give the parent funclet multiple unwind destinations, which is
7220b57cec5SDimitry Andric           // something that subsequent EH table generation can't handle and
7230b57cec5SDimitry Andric           // that the veirifer rejects.  So when we see such a call, leave it
7240b57cec5SDimitry Andric           // as "unwind to caller".
7250b57cec5SDimitry Andric           UnwindDestToken = getUnwindDestToken(ParentPad, FuncletUnwindMap);
7260b57cec5SDimitry Andric           if (UnwindDestToken && !isa<ConstantTokenNone>(UnwindDestToken))
7270b57cec5SDimitry Andric             continue;
7280b57cec5SDimitry Andric         } else {
7290b57cec5SDimitry Andric           // This catchswitch has no parent to inherit constraints from, and
7300b57cec5SDimitry Andric           // none of its descendants can have an unwind edge that exits it and
7310b57cec5SDimitry Andric           // targets another funclet in the inlinee.  It may or may not have a
7320b57cec5SDimitry Andric           // descendant that definitively has an unwind to caller.  In either
7330b57cec5SDimitry Andric           // case, we'll have to assume that any unwinds out of it may need to
7340b57cec5SDimitry Andric           // be routed to the caller, so treat it as though it has a definitive
7350b57cec5SDimitry Andric           // unwind to caller.
7360b57cec5SDimitry Andric           UnwindDestToken = ConstantTokenNone::get(Caller->getContext());
7370b57cec5SDimitry Andric         }
7380b57cec5SDimitry Andric         auto *NewCatchSwitch = CatchSwitchInst::Create(
7390b57cec5SDimitry Andric             CatchSwitch->getParentPad(), UnwindDest,
7400b57cec5SDimitry Andric             CatchSwitch->getNumHandlers(), CatchSwitch->getName(),
7410b57cec5SDimitry Andric             CatchSwitch);
7420b57cec5SDimitry Andric         for (BasicBlock *PadBB : CatchSwitch->handlers())
7430b57cec5SDimitry Andric           NewCatchSwitch->addHandler(PadBB);
7440b57cec5SDimitry Andric         // Propagate info for the old catchswitch over to the new one in
7450b57cec5SDimitry Andric         // the unwind map.  This also serves to short-circuit any subsequent
7460b57cec5SDimitry Andric         // checks for the unwind dest of this catchswitch, which would get
7470b57cec5SDimitry Andric         // confused if they found the outer handler in the callee.
7480b57cec5SDimitry Andric         FuncletUnwindMap[NewCatchSwitch] = UnwindDestToken;
7490b57cec5SDimitry Andric         Replacement = NewCatchSwitch;
7500b57cec5SDimitry Andric       }
7510b57cec5SDimitry Andric     } else if (!isa<FuncletPadInst>(I)) {
7520b57cec5SDimitry Andric       llvm_unreachable("unexpected EHPad!");
7530b57cec5SDimitry Andric     }
7540b57cec5SDimitry Andric 
7550b57cec5SDimitry Andric     if (Replacement) {
7560b57cec5SDimitry Andric       Replacement->takeName(I);
7570b57cec5SDimitry Andric       I->replaceAllUsesWith(Replacement);
7580b57cec5SDimitry Andric       I->eraseFromParent();
7590b57cec5SDimitry Andric       UpdatePHINodes(&*BB);
7600b57cec5SDimitry Andric     }
7610b57cec5SDimitry Andric   }
7620b57cec5SDimitry Andric 
7630b57cec5SDimitry Andric   if (InlinedCodeInfo.ContainsCalls)
7640b57cec5SDimitry Andric     for (Function::iterator BB = FirstNewBlock->getIterator(),
7650b57cec5SDimitry Andric                             E = Caller->end();
7660b57cec5SDimitry Andric          BB != E; ++BB)
7670b57cec5SDimitry Andric       if (BasicBlock *NewBB = HandleCallsInBlockInlinedThroughInvoke(
7680b57cec5SDimitry Andric               &*BB, UnwindDest, &FuncletUnwindMap))
7690b57cec5SDimitry Andric         // Update any PHI nodes in the exceptional block to indicate that there
7700b57cec5SDimitry Andric         // is now a new entry in them.
7710b57cec5SDimitry Andric         UpdatePHINodes(NewBB);
7720b57cec5SDimitry Andric 
7730b57cec5SDimitry Andric   // Now that everything is happy, we have one final detail.  The PHI nodes in
7740b57cec5SDimitry Andric   // the exception destination block still have entries due to the original
7750b57cec5SDimitry Andric   // invoke instruction. Eliminate these entries (which might even delete the
7760b57cec5SDimitry Andric   // PHI node) now.
7770b57cec5SDimitry Andric   UnwindDest->removePredecessor(InvokeBB);
7780b57cec5SDimitry Andric }
7790b57cec5SDimitry Andric 
780*e8d8bef9SDimitry Andric /// When inlining a call site that has !llvm.mem.parallel_loop_access,
781*e8d8bef9SDimitry Andric /// !llvm.access.group, !alias.scope or !noalias metadata, that metadata should
782*e8d8bef9SDimitry Andric /// be propagated to all memory-accessing cloned instructions.
783*e8d8bef9SDimitry Andric static void PropagateCallSiteMetadata(CallBase &CB, ValueToValueMapTy &VMap) {
784*e8d8bef9SDimitry Andric   MDNode *MemParallelLoopAccess =
785*e8d8bef9SDimitry Andric       CB.getMetadata(LLVMContext::MD_mem_parallel_loop_access);
786*e8d8bef9SDimitry Andric   MDNode *AccessGroup = CB.getMetadata(LLVMContext::MD_access_group);
787*e8d8bef9SDimitry Andric   MDNode *AliasScope = CB.getMetadata(LLVMContext::MD_alias_scope);
788*e8d8bef9SDimitry Andric   MDNode *NoAlias = CB.getMetadata(LLVMContext::MD_noalias);
789*e8d8bef9SDimitry Andric   if (!MemParallelLoopAccess && !AccessGroup && !AliasScope && !NoAlias)
7900b57cec5SDimitry Andric     return;
7910b57cec5SDimitry Andric 
7920b57cec5SDimitry Andric   for (ValueToValueMapTy::iterator VMI = VMap.begin(), VMIE = VMap.end();
7930b57cec5SDimitry Andric        VMI != VMIE; ++VMI) {
794*e8d8bef9SDimitry Andric     // Check that key is an instruction, to skip the Argument mapping, which
795*e8d8bef9SDimitry Andric     // points to an instruction in the original function, not the inlined one.
796*e8d8bef9SDimitry Andric     if (!VMI->second || !isa<Instruction>(VMI->first))
7970b57cec5SDimitry Andric       continue;
7980b57cec5SDimitry Andric 
7990b57cec5SDimitry Andric     Instruction *NI = dyn_cast<Instruction>(VMI->second);
8000b57cec5SDimitry Andric     if (!NI)
8010b57cec5SDimitry Andric       continue;
8020b57cec5SDimitry Andric 
803*e8d8bef9SDimitry Andric     // This metadata is only relevant for instructions that access memory.
804*e8d8bef9SDimitry Andric     if (!NI->mayReadOrWriteMemory())
805*e8d8bef9SDimitry Andric       continue;
806*e8d8bef9SDimitry Andric 
807*e8d8bef9SDimitry Andric     if (MemParallelLoopAccess) {
808*e8d8bef9SDimitry Andric       // TODO: This probably should not overwrite MemParalleLoopAccess.
809*e8d8bef9SDimitry Andric       MemParallelLoopAccess = MDNode::concatenate(
810*e8d8bef9SDimitry Andric           NI->getMetadata(LLVMContext::MD_mem_parallel_loop_access),
811*e8d8bef9SDimitry Andric           MemParallelLoopAccess);
812*e8d8bef9SDimitry Andric       NI->setMetadata(LLVMContext::MD_mem_parallel_loop_access,
813*e8d8bef9SDimitry Andric                       MemParallelLoopAccess);
814*e8d8bef9SDimitry Andric     }
815*e8d8bef9SDimitry Andric 
816*e8d8bef9SDimitry Andric     if (AccessGroup)
817*e8d8bef9SDimitry Andric       NI->setMetadata(LLVMContext::MD_access_group, uniteAccessGroups(
818*e8d8bef9SDimitry Andric           NI->getMetadata(LLVMContext::MD_access_group), AccessGroup));
819*e8d8bef9SDimitry Andric 
820*e8d8bef9SDimitry Andric     if (AliasScope)
821*e8d8bef9SDimitry Andric       NI->setMetadata(LLVMContext::MD_alias_scope, MDNode::concatenate(
822*e8d8bef9SDimitry Andric           NI->getMetadata(LLVMContext::MD_alias_scope), AliasScope));
823*e8d8bef9SDimitry Andric 
824*e8d8bef9SDimitry Andric     if (NoAlias)
825*e8d8bef9SDimitry Andric       NI->setMetadata(LLVMContext::MD_noalias, MDNode::concatenate(
826*e8d8bef9SDimitry Andric           NI->getMetadata(LLVMContext::MD_noalias), NoAlias));
8270b57cec5SDimitry Andric   }
8280b57cec5SDimitry Andric }
8290b57cec5SDimitry Andric 
830*e8d8bef9SDimitry Andric /// Utility for cloning !noalias and !alias.scope metadata. When a code region
831*e8d8bef9SDimitry Andric /// using scoped alias metadata is inlined, the aliasing relationships may not
832*e8d8bef9SDimitry Andric /// hold between the two version. It is necessary to create a deep clone of the
833*e8d8bef9SDimitry Andric /// metadata, putting the two versions in separate scope domains.
834*e8d8bef9SDimitry Andric class ScopedAliasMetadataDeepCloner {
835*e8d8bef9SDimitry Andric   using MetadataMap = DenseMap<const MDNode *, TrackingMDNodeRef>;
8360b57cec5SDimitry Andric   SetVector<const MDNode *> MD;
837*e8d8bef9SDimitry Andric   MetadataMap MDMap;
838*e8d8bef9SDimitry Andric   void addRecursiveMetadataUses();
8390b57cec5SDimitry Andric 
840*e8d8bef9SDimitry Andric public:
841*e8d8bef9SDimitry Andric   ScopedAliasMetadataDeepCloner(const Function *F);
8420b57cec5SDimitry Andric 
843*e8d8bef9SDimitry Andric   /// Create a new clone of the scoped alias metadata, which will be used by
844*e8d8bef9SDimitry Andric   /// subsequent remap() calls.
845*e8d8bef9SDimitry Andric   void clone();
846*e8d8bef9SDimitry Andric 
847*e8d8bef9SDimitry Andric   /// Remap instructions in the given VMap from the original to the cloned
848*e8d8bef9SDimitry Andric   /// metadata.
849*e8d8bef9SDimitry Andric   void remap(ValueToValueMapTy &VMap);
850*e8d8bef9SDimitry Andric };
851*e8d8bef9SDimitry Andric 
852*e8d8bef9SDimitry Andric ScopedAliasMetadataDeepCloner::ScopedAliasMetadataDeepCloner(
853*e8d8bef9SDimitry Andric     const Function *F) {
854*e8d8bef9SDimitry Andric   for (const BasicBlock &BB : *F) {
855*e8d8bef9SDimitry Andric     for (const Instruction &I : BB) {
856*e8d8bef9SDimitry Andric       if (const MDNode *M = I.getMetadata(LLVMContext::MD_alias_scope))
8570b57cec5SDimitry Andric         MD.insert(M);
858*e8d8bef9SDimitry Andric       if (const MDNode *M = I.getMetadata(LLVMContext::MD_noalias))
8590b57cec5SDimitry Andric         MD.insert(M);
860*e8d8bef9SDimitry Andric 
861*e8d8bef9SDimitry Andric       // We also need to clone the metadata in noalias intrinsics.
862*e8d8bef9SDimitry Andric       if (const auto *Decl = dyn_cast<NoAliasScopeDeclInst>(&I))
863*e8d8bef9SDimitry Andric         MD.insert(Decl->getScopeList());
864*e8d8bef9SDimitry Andric     }
865*e8d8bef9SDimitry Andric   }
866*e8d8bef9SDimitry Andric   addRecursiveMetadataUses();
8670b57cec5SDimitry Andric }
8680b57cec5SDimitry Andric 
869*e8d8bef9SDimitry Andric void ScopedAliasMetadataDeepCloner::addRecursiveMetadataUses() {
8700b57cec5SDimitry Andric   SmallVector<const Metadata *, 16> Queue(MD.begin(), MD.end());
8710b57cec5SDimitry Andric   while (!Queue.empty()) {
8720b57cec5SDimitry Andric     const MDNode *M = cast<MDNode>(Queue.pop_back_val());
873*e8d8bef9SDimitry Andric     for (const Metadata *Op : M->operands())
874*e8d8bef9SDimitry Andric       if (const MDNode *OpMD = dyn_cast<MDNode>(Op))
875*e8d8bef9SDimitry Andric         if (MD.insert(OpMD))
876*e8d8bef9SDimitry Andric           Queue.push_back(OpMD);
877*e8d8bef9SDimitry Andric   }
8780b57cec5SDimitry Andric }
8790b57cec5SDimitry Andric 
880*e8d8bef9SDimitry Andric void ScopedAliasMetadataDeepCloner::clone() {
881*e8d8bef9SDimitry Andric   assert(MDMap.empty() && "clone() already called ?");
882*e8d8bef9SDimitry Andric 
8830b57cec5SDimitry Andric   SmallVector<TempMDTuple, 16> DummyNodes;
8840b57cec5SDimitry Andric   for (const MDNode *I : MD) {
885*e8d8bef9SDimitry Andric     DummyNodes.push_back(MDTuple::getTemporary(I->getContext(), None));
8860b57cec5SDimitry Andric     MDMap[I].reset(DummyNodes.back().get());
8870b57cec5SDimitry Andric   }
8880b57cec5SDimitry Andric 
8890b57cec5SDimitry Andric   // Create new metadata nodes to replace the dummy nodes, replacing old
8900b57cec5SDimitry Andric   // metadata references with either a dummy node or an already-created new
8910b57cec5SDimitry Andric   // node.
8920b57cec5SDimitry Andric   SmallVector<Metadata *, 4> NewOps;
893*e8d8bef9SDimitry Andric   for (const MDNode *I : MD) {
894*e8d8bef9SDimitry Andric     for (const Metadata *Op : I->operands()) {
895*e8d8bef9SDimitry Andric       if (const MDNode *M = dyn_cast<MDNode>(Op))
8960b57cec5SDimitry Andric         NewOps.push_back(MDMap[M]);
8970b57cec5SDimitry Andric       else
898*e8d8bef9SDimitry Andric         NewOps.push_back(const_cast<Metadata *>(Op));
8990b57cec5SDimitry Andric     }
9000b57cec5SDimitry Andric 
901*e8d8bef9SDimitry Andric     MDNode *NewM = MDNode::get(I->getContext(), NewOps);
9020b57cec5SDimitry Andric     MDTuple *TempM = cast<MDTuple>(MDMap[I]);
9030b57cec5SDimitry Andric     assert(TempM->isTemporary() && "Expected temporary node");
9040b57cec5SDimitry Andric 
9050b57cec5SDimitry Andric     TempM->replaceAllUsesWith(NewM);
906*e8d8bef9SDimitry Andric     NewOps.clear();
907*e8d8bef9SDimitry Andric   }
9080b57cec5SDimitry Andric }
9090b57cec5SDimitry Andric 
910*e8d8bef9SDimitry Andric void ScopedAliasMetadataDeepCloner::remap(ValueToValueMapTy &VMap) {
911*e8d8bef9SDimitry Andric   if (MDMap.empty())
912*e8d8bef9SDimitry Andric     return; // Nothing to do.
913*e8d8bef9SDimitry Andric 
914*e8d8bef9SDimitry Andric   for (auto Entry : VMap) {
915*e8d8bef9SDimitry Andric     // Check that key is an instruction, to skip the Argument mapping, which
916*e8d8bef9SDimitry Andric     // points to an instruction in the original function, not the inlined one.
917*e8d8bef9SDimitry Andric     if (!Entry->second || !isa<Instruction>(Entry->first))
9180b57cec5SDimitry Andric       continue;
9190b57cec5SDimitry Andric 
920*e8d8bef9SDimitry Andric     Instruction *I = dyn_cast<Instruction>(Entry->second);
921*e8d8bef9SDimitry Andric     if (!I)
9220b57cec5SDimitry Andric       continue;
9230b57cec5SDimitry Andric 
924*e8d8bef9SDimitry Andric     if (MDNode *M = I->getMetadata(LLVMContext::MD_alias_scope))
925*e8d8bef9SDimitry Andric       I->setMetadata(LLVMContext::MD_alias_scope, MDMap[M]);
9260b57cec5SDimitry Andric 
927*e8d8bef9SDimitry Andric     if (MDNode *M = I->getMetadata(LLVMContext::MD_noalias))
928*e8d8bef9SDimitry Andric       I->setMetadata(LLVMContext::MD_noalias, MDMap[M]);
929*e8d8bef9SDimitry Andric 
930*e8d8bef9SDimitry Andric     if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(I))
931*e8d8bef9SDimitry Andric       Decl->setScopeList(MDMap[Decl->getScopeList()]);
9320b57cec5SDimitry Andric   }
9330b57cec5SDimitry Andric }
9340b57cec5SDimitry Andric 
9350b57cec5SDimitry Andric /// If the inlined function has noalias arguments,
9360b57cec5SDimitry Andric /// then add new alias scopes for each noalias argument, tag the mapped noalias
9370b57cec5SDimitry Andric /// parameters with noalias metadata specifying the new scope, and tag all
9380b57cec5SDimitry Andric /// non-derived loads, stores and memory intrinsics with the new alias scopes.
9395ffd83dbSDimitry Andric static void AddAliasScopeMetadata(CallBase &CB, ValueToValueMapTy &VMap,
9400b57cec5SDimitry Andric                                   const DataLayout &DL, AAResults *CalleeAAR) {
9410b57cec5SDimitry Andric   if (!EnableNoAliasConversion)
9420b57cec5SDimitry Andric     return;
9430b57cec5SDimitry Andric 
9445ffd83dbSDimitry Andric   const Function *CalledFunc = CB.getCalledFunction();
9450b57cec5SDimitry Andric   SmallVector<const Argument *, 4> NoAliasArgs;
9460b57cec5SDimitry Andric 
9470b57cec5SDimitry Andric   for (const Argument &Arg : CalledFunc->args())
9485ffd83dbSDimitry Andric     if (CB.paramHasAttr(Arg.getArgNo(), Attribute::NoAlias) && !Arg.use_empty())
9490b57cec5SDimitry Andric       NoAliasArgs.push_back(&Arg);
9500b57cec5SDimitry Andric 
9510b57cec5SDimitry Andric   if (NoAliasArgs.empty())
9520b57cec5SDimitry Andric     return;
9530b57cec5SDimitry Andric 
9540b57cec5SDimitry Andric   // To do a good job, if a noalias variable is captured, we need to know if
9550b57cec5SDimitry Andric   // the capture point dominates the particular use we're considering.
9560b57cec5SDimitry Andric   DominatorTree DT;
9570b57cec5SDimitry Andric   DT.recalculate(const_cast<Function&>(*CalledFunc));
9580b57cec5SDimitry Andric 
9590b57cec5SDimitry Andric   // noalias indicates that pointer values based on the argument do not alias
9600b57cec5SDimitry Andric   // pointer values which are not based on it. So we add a new "scope" for each
9610b57cec5SDimitry Andric   // noalias function argument. Accesses using pointers based on that argument
9620b57cec5SDimitry Andric   // become part of that alias scope, accesses using pointers not based on that
9630b57cec5SDimitry Andric   // argument are tagged as noalias with that scope.
9640b57cec5SDimitry Andric 
9650b57cec5SDimitry Andric   DenseMap<const Argument *, MDNode *> NewScopes;
9660b57cec5SDimitry Andric   MDBuilder MDB(CalledFunc->getContext());
9670b57cec5SDimitry Andric 
9680b57cec5SDimitry Andric   // Create a new scope domain for this function.
9690b57cec5SDimitry Andric   MDNode *NewDomain =
9700b57cec5SDimitry Andric     MDB.createAnonymousAliasScopeDomain(CalledFunc->getName());
9710b57cec5SDimitry Andric   for (unsigned i = 0, e = NoAliasArgs.size(); i != e; ++i) {
9720b57cec5SDimitry Andric     const Argument *A = NoAliasArgs[i];
9730b57cec5SDimitry Andric 
9745ffd83dbSDimitry Andric     std::string Name = std::string(CalledFunc->getName());
9750b57cec5SDimitry Andric     if (A->hasName()) {
9760b57cec5SDimitry Andric       Name += ": %";
9770b57cec5SDimitry Andric       Name += A->getName();
9780b57cec5SDimitry Andric     } else {
9790b57cec5SDimitry Andric       Name += ": argument ";
9800b57cec5SDimitry Andric       Name += utostr(i);
9810b57cec5SDimitry Andric     }
9820b57cec5SDimitry Andric 
9830b57cec5SDimitry Andric     // Note: We always create a new anonymous root here. This is true regardless
9840b57cec5SDimitry Andric     // of the linkage of the callee because the aliasing "scope" is not just a
9850b57cec5SDimitry Andric     // property of the callee, but also all control dependencies in the caller.
9860b57cec5SDimitry Andric     MDNode *NewScope = MDB.createAnonymousAliasScope(NewDomain, Name);
9870b57cec5SDimitry Andric     NewScopes.insert(std::make_pair(A, NewScope));
988*e8d8bef9SDimitry Andric 
989*e8d8bef9SDimitry Andric     if (UseNoAliasIntrinsic) {
990*e8d8bef9SDimitry Andric       // Introduce a llvm.experimental.noalias.scope.decl for the noalias
991*e8d8bef9SDimitry Andric       // argument.
992*e8d8bef9SDimitry Andric       MDNode *AScopeList = MDNode::get(CalledFunc->getContext(), NewScope);
993*e8d8bef9SDimitry Andric       auto *NoAliasDecl =
994*e8d8bef9SDimitry Andric           IRBuilder<>(&CB).CreateNoAliasScopeDeclaration(AScopeList);
995*e8d8bef9SDimitry Andric       // Ignore the result for now. The result will be used when the
996*e8d8bef9SDimitry Andric       // llvm.noalias intrinsic is introduced.
997*e8d8bef9SDimitry Andric       (void)NoAliasDecl;
998*e8d8bef9SDimitry Andric     }
9990b57cec5SDimitry Andric   }
10000b57cec5SDimitry Andric 
10010b57cec5SDimitry Andric   // Iterate over all new instructions in the map; for all memory-access
10020b57cec5SDimitry Andric   // instructions, add the alias scope metadata.
10030b57cec5SDimitry Andric   for (ValueToValueMapTy::iterator VMI = VMap.begin(), VMIE = VMap.end();
10040b57cec5SDimitry Andric        VMI != VMIE; ++VMI) {
10050b57cec5SDimitry Andric     if (const Instruction *I = dyn_cast<Instruction>(VMI->first)) {
10060b57cec5SDimitry Andric       if (!VMI->second)
10070b57cec5SDimitry Andric         continue;
10080b57cec5SDimitry Andric 
10090b57cec5SDimitry Andric       Instruction *NI = dyn_cast<Instruction>(VMI->second);
10100b57cec5SDimitry Andric       if (!NI)
10110b57cec5SDimitry Andric         continue;
10120b57cec5SDimitry Andric 
10130b57cec5SDimitry Andric       bool IsArgMemOnlyCall = false, IsFuncCall = false;
10140b57cec5SDimitry Andric       SmallVector<const Value *, 2> PtrArgs;
10150b57cec5SDimitry Andric 
10160b57cec5SDimitry Andric       if (const LoadInst *LI = dyn_cast<LoadInst>(I))
10170b57cec5SDimitry Andric         PtrArgs.push_back(LI->getPointerOperand());
10180b57cec5SDimitry Andric       else if (const StoreInst *SI = dyn_cast<StoreInst>(I))
10190b57cec5SDimitry Andric         PtrArgs.push_back(SI->getPointerOperand());
10200b57cec5SDimitry Andric       else if (const VAArgInst *VAAI = dyn_cast<VAArgInst>(I))
10210b57cec5SDimitry Andric         PtrArgs.push_back(VAAI->getPointerOperand());
10220b57cec5SDimitry Andric       else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I))
10230b57cec5SDimitry Andric         PtrArgs.push_back(CXI->getPointerOperand());
10240b57cec5SDimitry Andric       else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I))
10250b57cec5SDimitry Andric         PtrArgs.push_back(RMWI->getPointerOperand());
10260b57cec5SDimitry Andric       else if (const auto *Call = dyn_cast<CallBase>(I)) {
10270b57cec5SDimitry Andric         // If we know that the call does not access memory, then we'll still
10280b57cec5SDimitry Andric         // know that about the inlined clone of this call site, and we don't
10290b57cec5SDimitry Andric         // need to add metadata.
10300b57cec5SDimitry Andric         if (Call->doesNotAccessMemory())
10310b57cec5SDimitry Andric           continue;
10320b57cec5SDimitry Andric 
10330b57cec5SDimitry Andric         IsFuncCall = true;
10340b57cec5SDimitry Andric         if (CalleeAAR) {
10350b57cec5SDimitry Andric           FunctionModRefBehavior MRB = CalleeAAR->getModRefBehavior(Call);
10365ffd83dbSDimitry Andric           if (AAResults::onlyAccessesArgPointees(MRB))
10370b57cec5SDimitry Andric             IsArgMemOnlyCall = true;
10380b57cec5SDimitry Andric         }
10390b57cec5SDimitry Andric 
10400b57cec5SDimitry Andric         for (Value *Arg : Call->args()) {
10410b57cec5SDimitry Andric           // We need to check the underlying objects of all arguments, not just
10420b57cec5SDimitry Andric           // the pointer arguments, because we might be passing pointers as
10430b57cec5SDimitry Andric           // integers, etc.
10440b57cec5SDimitry Andric           // However, if we know that the call only accesses pointer arguments,
10450b57cec5SDimitry Andric           // then we only need to check the pointer arguments.
10460b57cec5SDimitry Andric           if (IsArgMemOnlyCall && !Arg->getType()->isPointerTy())
10470b57cec5SDimitry Andric             continue;
10480b57cec5SDimitry Andric 
10490b57cec5SDimitry Andric           PtrArgs.push_back(Arg);
10500b57cec5SDimitry Andric         }
10510b57cec5SDimitry Andric       }
10520b57cec5SDimitry Andric 
10530b57cec5SDimitry Andric       // If we found no pointers, then this instruction is not suitable for
10540b57cec5SDimitry Andric       // pairing with an instruction to receive aliasing metadata.
10550b57cec5SDimitry Andric       // However, if this is a call, this we might just alias with none of the
10560b57cec5SDimitry Andric       // noalias arguments.
10570b57cec5SDimitry Andric       if (PtrArgs.empty() && !IsFuncCall)
10580b57cec5SDimitry Andric         continue;
10590b57cec5SDimitry Andric 
10600b57cec5SDimitry Andric       // It is possible that there is only one underlying object, but you
10610b57cec5SDimitry Andric       // need to go through several PHIs to see it, and thus could be
10620b57cec5SDimitry Andric       // repeated in the Objects list.
10630b57cec5SDimitry Andric       SmallPtrSet<const Value *, 4> ObjSet;
10640b57cec5SDimitry Andric       SmallVector<Metadata *, 4> Scopes, NoAliases;
10650b57cec5SDimitry Andric 
10660b57cec5SDimitry Andric       SmallSetVector<const Argument *, 4> NAPtrArgs;
10670b57cec5SDimitry Andric       for (const Value *V : PtrArgs) {
10680b57cec5SDimitry Andric         SmallVector<const Value *, 4> Objects;
1069*e8d8bef9SDimitry Andric         getUnderlyingObjects(V, Objects, /* LI = */ nullptr);
10700b57cec5SDimitry Andric 
10710b57cec5SDimitry Andric         for (const Value *O : Objects)
10720b57cec5SDimitry Andric           ObjSet.insert(O);
10730b57cec5SDimitry Andric       }
10740b57cec5SDimitry Andric 
10750b57cec5SDimitry Andric       // Figure out if we're derived from anything that is not a noalias
10760b57cec5SDimitry Andric       // argument.
10770b57cec5SDimitry Andric       bool CanDeriveViaCapture = false, UsesAliasingPtr = false;
10780b57cec5SDimitry Andric       for (const Value *V : ObjSet) {
10790b57cec5SDimitry Andric         // Is this value a constant that cannot be derived from any pointer
10800b57cec5SDimitry Andric         // value (we need to exclude constant expressions, for example, that
10810b57cec5SDimitry Andric         // are formed from arithmetic on global symbols).
10820b57cec5SDimitry Andric         bool IsNonPtrConst = isa<ConstantInt>(V) || isa<ConstantFP>(V) ||
10830b57cec5SDimitry Andric                              isa<ConstantPointerNull>(V) ||
10840b57cec5SDimitry Andric                              isa<ConstantDataVector>(V) || isa<UndefValue>(V);
10850b57cec5SDimitry Andric         if (IsNonPtrConst)
10860b57cec5SDimitry Andric           continue;
10870b57cec5SDimitry Andric 
10880b57cec5SDimitry Andric         // If this is anything other than a noalias argument, then we cannot
10890b57cec5SDimitry Andric         // completely describe the aliasing properties using alias.scope
10900b57cec5SDimitry Andric         // metadata (and, thus, won't add any).
10910b57cec5SDimitry Andric         if (const Argument *A = dyn_cast<Argument>(V)) {
10925ffd83dbSDimitry Andric           if (!CB.paramHasAttr(A->getArgNo(), Attribute::NoAlias))
10930b57cec5SDimitry Andric             UsesAliasingPtr = true;
10940b57cec5SDimitry Andric         } else {
10950b57cec5SDimitry Andric           UsesAliasingPtr = true;
10960b57cec5SDimitry Andric         }
10970b57cec5SDimitry Andric 
10980b57cec5SDimitry Andric         // If this is not some identified function-local object (which cannot
10990b57cec5SDimitry Andric         // directly alias a noalias argument), or some other argument (which,
11000b57cec5SDimitry Andric         // by definition, also cannot alias a noalias argument), then we could
11010b57cec5SDimitry Andric         // alias a noalias argument that has been captured).
11020b57cec5SDimitry Andric         if (!isa<Argument>(V) &&
11030b57cec5SDimitry Andric             !isIdentifiedFunctionLocal(const_cast<Value*>(V)))
11040b57cec5SDimitry Andric           CanDeriveViaCapture = true;
11050b57cec5SDimitry Andric       }
11060b57cec5SDimitry Andric 
11070b57cec5SDimitry Andric       // A function call can always get captured noalias pointers (via other
11080b57cec5SDimitry Andric       // parameters, globals, etc.).
11090b57cec5SDimitry Andric       if (IsFuncCall && !IsArgMemOnlyCall)
11100b57cec5SDimitry Andric         CanDeriveViaCapture = true;
11110b57cec5SDimitry Andric 
11120b57cec5SDimitry Andric       // First, we want to figure out all of the sets with which we definitely
11130b57cec5SDimitry Andric       // don't alias. Iterate over all noalias set, and add those for which:
11140b57cec5SDimitry Andric       //   1. The noalias argument is not in the set of objects from which we
11150b57cec5SDimitry Andric       //      definitely derive.
11160b57cec5SDimitry Andric       //   2. The noalias argument has not yet been captured.
11170b57cec5SDimitry Andric       // An arbitrary function that might load pointers could see captured
11180b57cec5SDimitry Andric       // noalias arguments via other noalias arguments or globals, and so we
11190b57cec5SDimitry Andric       // must always check for prior capture.
11200b57cec5SDimitry Andric       for (const Argument *A : NoAliasArgs) {
11210b57cec5SDimitry Andric         if (!ObjSet.count(A) && (!CanDeriveViaCapture ||
11220b57cec5SDimitry Andric                                  // It might be tempting to skip the
11230b57cec5SDimitry Andric                                  // PointerMayBeCapturedBefore check if
11240b57cec5SDimitry Andric                                  // A->hasNoCaptureAttr() is true, but this is
11250b57cec5SDimitry Andric                                  // incorrect because nocapture only guarantees
11260b57cec5SDimitry Andric                                  // that no copies outlive the function, not
11270b57cec5SDimitry Andric                                  // that the value cannot be locally captured.
11280b57cec5SDimitry Andric                                  !PointerMayBeCapturedBefore(A,
11290b57cec5SDimitry Andric                                    /* ReturnCaptures */ false,
11300b57cec5SDimitry Andric                                    /* StoreCaptures */ false, I, &DT)))
11310b57cec5SDimitry Andric           NoAliases.push_back(NewScopes[A]);
11320b57cec5SDimitry Andric       }
11330b57cec5SDimitry Andric 
11340b57cec5SDimitry Andric       if (!NoAliases.empty())
11350b57cec5SDimitry Andric         NI->setMetadata(LLVMContext::MD_noalias,
11360b57cec5SDimitry Andric                         MDNode::concatenate(
11370b57cec5SDimitry Andric                             NI->getMetadata(LLVMContext::MD_noalias),
11380b57cec5SDimitry Andric                             MDNode::get(CalledFunc->getContext(), NoAliases)));
11390b57cec5SDimitry Andric 
11400b57cec5SDimitry Andric       // Next, we want to figure out all of the sets to which we might belong.
11410b57cec5SDimitry Andric       // We might belong to a set if the noalias argument is in the set of
11420b57cec5SDimitry Andric       // underlying objects. If there is some non-noalias argument in our list
11430b57cec5SDimitry Andric       // of underlying objects, then we cannot add a scope because the fact
11440b57cec5SDimitry Andric       // that some access does not alias with any set of our noalias arguments
11450b57cec5SDimitry Andric       // cannot itself guarantee that it does not alias with this access
11460b57cec5SDimitry Andric       // (because there is some pointer of unknown origin involved and the
11470b57cec5SDimitry Andric       // other access might also depend on this pointer). We also cannot add
11480b57cec5SDimitry Andric       // scopes to arbitrary functions unless we know they don't access any
11490b57cec5SDimitry Andric       // non-parameter pointer-values.
11500b57cec5SDimitry Andric       bool CanAddScopes = !UsesAliasingPtr;
11510b57cec5SDimitry Andric       if (CanAddScopes && IsFuncCall)
11520b57cec5SDimitry Andric         CanAddScopes = IsArgMemOnlyCall;
11530b57cec5SDimitry Andric 
11540b57cec5SDimitry Andric       if (CanAddScopes)
11550b57cec5SDimitry Andric         for (const Argument *A : NoAliasArgs) {
11560b57cec5SDimitry Andric           if (ObjSet.count(A))
11570b57cec5SDimitry Andric             Scopes.push_back(NewScopes[A]);
11580b57cec5SDimitry Andric         }
11590b57cec5SDimitry Andric 
11600b57cec5SDimitry Andric       if (!Scopes.empty())
11610b57cec5SDimitry Andric         NI->setMetadata(
11620b57cec5SDimitry Andric             LLVMContext::MD_alias_scope,
11630b57cec5SDimitry Andric             MDNode::concatenate(NI->getMetadata(LLVMContext::MD_alias_scope),
11640b57cec5SDimitry Andric                                 MDNode::get(CalledFunc->getContext(), Scopes)));
11650b57cec5SDimitry Andric     }
11660b57cec5SDimitry Andric   }
11670b57cec5SDimitry Andric }
11680b57cec5SDimitry Andric 
11695ffd83dbSDimitry Andric static bool MayContainThrowingOrExitingCall(Instruction *Begin,
11705ffd83dbSDimitry Andric                                             Instruction *End) {
11715ffd83dbSDimitry Andric 
11725ffd83dbSDimitry Andric   assert(Begin->getParent() == End->getParent() &&
11735ffd83dbSDimitry Andric          "Expected to be in same basic block!");
11745ffd83dbSDimitry Andric   unsigned NumInstChecked = 0;
11755ffd83dbSDimitry Andric   // Check that all instructions in the range [Begin, End) are guaranteed to
11765ffd83dbSDimitry Andric   // transfer execution to successor.
11775ffd83dbSDimitry Andric   for (auto &I : make_range(Begin->getIterator(), End->getIterator()))
11785ffd83dbSDimitry Andric     if (NumInstChecked++ > InlinerAttributeWindow ||
11795ffd83dbSDimitry Andric         !isGuaranteedToTransferExecutionToSuccessor(&I))
11805ffd83dbSDimitry Andric       return true;
11815ffd83dbSDimitry Andric   return false;
11825ffd83dbSDimitry Andric }
11835ffd83dbSDimitry Andric 
11845ffd83dbSDimitry Andric static AttrBuilder IdentifyValidAttributes(CallBase &CB) {
11855ffd83dbSDimitry Andric 
11865ffd83dbSDimitry Andric   AttrBuilder AB(CB.getAttributes(), AttributeList::ReturnIndex);
11875ffd83dbSDimitry Andric   if (AB.empty())
11885ffd83dbSDimitry Andric     return AB;
11895ffd83dbSDimitry Andric   AttrBuilder Valid;
11905ffd83dbSDimitry Andric   // Only allow these white listed attributes to be propagated back to the
11915ffd83dbSDimitry Andric   // callee. This is because other attributes may only be valid on the call
11925ffd83dbSDimitry Andric   // itself, i.e. attributes such as signext and zeroext.
11935ffd83dbSDimitry Andric   if (auto DerefBytes = AB.getDereferenceableBytes())
11945ffd83dbSDimitry Andric     Valid.addDereferenceableAttr(DerefBytes);
11955ffd83dbSDimitry Andric   if (auto DerefOrNullBytes = AB.getDereferenceableOrNullBytes())
11965ffd83dbSDimitry Andric     Valid.addDereferenceableOrNullAttr(DerefOrNullBytes);
11975ffd83dbSDimitry Andric   if (AB.contains(Attribute::NoAlias))
11985ffd83dbSDimitry Andric     Valid.addAttribute(Attribute::NoAlias);
11995ffd83dbSDimitry Andric   if (AB.contains(Attribute::NonNull))
12005ffd83dbSDimitry Andric     Valid.addAttribute(Attribute::NonNull);
12015ffd83dbSDimitry Andric   return Valid;
12025ffd83dbSDimitry Andric }
12035ffd83dbSDimitry Andric 
12045ffd83dbSDimitry Andric static void AddReturnAttributes(CallBase &CB, ValueToValueMapTy &VMap) {
12055ffd83dbSDimitry Andric   if (!UpdateReturnAttributes)
12065ffd83dbSDimitry Andric     return;
12075ffd83dbSDimitry Andric 
12085ffd83dbSDimitry Andric   AttrBuilder Valid = IdentifyValidAttributes(CB);
12095ffd83dbSDimitry Andric   if (Valid.empty())
12105ffd83dbSDimitry Andric     return;
12115ffd83dbSDimitry Andric   auto *CalledFunction = CB.getCalledFunction();
12125ffd83dbSDimitry Andric   auto &Context = CalledFunction->getContext();
12135ffd83dbSDimitry Andric 
12145ffd83dbSDimitry Andric   for (auto &BB : *CalledFunction) {
12155ffd83dbSDimitry Andric     auto *RI = dyn_cast<ReturnInst>(BB.getTerminator());
12165ffd83dbSDimitry Andric     if (!RI || !isa<CallBase>(RI->getOperand(0)))
12175ffd83dbSDimitry Andric       continue;
12185ffd83dbSDimitry Andric     auto *RetVal = cast<CallBase>(RI->getOperand(0));
12195ffd83dbSDimitry Andric     // Sanity check that the cloned RetVal exists and is a call, otherwise we
12205ffd83dbSDimitry Andric     // cannot add the attributes on the cloned RetVal.
12215ffd83dbSDimitry Andric     // Simplification during inlining could have transformed the cloned
12225ffd83dbSDimitry Andric     // instruction.
12235ffd83dbSDimitry Andric     auto *NewRetVal = dyn_cast_or_null<CallBase>(VMap.lookup(RetVal));
12245ffd83dbSDimitry Andric     if (!NewRetVal)
12255ffd83dbSDimitry Andric       continue;
12265ffd83dbSDimitry Andric     // Backward propagation of attributes to the returned value may be incorrect
12275ffd83dbSDimitry Andric     // if it is control flow dependent.
12285ffd83dbSDimitry Andric     // Consider:
12295ffd83dbSDimitry Andric     // @callee {
12305ffd83dbSDimitry Andric     //  %rv = call @foo()
12315ffd83dbSDimitry Andric     //  %rv2 = call @bar()
12325ffd83dbSDimitry Andric     //  if (%rv2 != null)
12335ffd83dbSDimitry Andric     //    return %rv2
12345ffd83dbSDimitry Andric     //  if (%rv == null)
12355ffd83dbSDimitry Andric     //    exit()
12365ffd83dbSDimitry Andric     //  return %rv
12375ffd83dbSDimitry Andric     // }
12385ffd83dbSDimitry Andric     // caller() {
12395ffd83dbSDimitry Andric     //   %val = call nonnull @callee()
12405ffd83dbSDimitry Andric     // }
12415ffd83dbSDimitry Andric     // Here we cannot add the nonnull attribute on either foo or bar. So, we
12425ffd83dbSDimitry Andric     // limit the check to both RetVal and RI are in the same basic block and
12435ffd83dbSDimitry Andric     // there are no throwing/exiting instructions between these instructions.
12445ffd83dbSDimitry Andric     if (RI->getParent() != RetVal->getParent() ||
12455ffd83dbSDimitry Andric         MayContainThrowingOrExitingCall(RetVal, RI))
12465ffd83dbSDimitry Andric       continue;
12475ffd83dbSDimitry Andric     // Add to the existing attributes of NewRetVal, i.e. the cloned call
12485ffd83dbSDimitry Andric     // instruction.
12495ffd83dbSDimitry Andric     // NB! When we have the same attribute already existing on NewRetVal, but
12505ffd83dbSDimitry Andric     // with a differing value, the AttributeList's merge API honours the already
12515ffd83dbSDimitry Andric     // existing attribute value (i.e. attributes such as dereferenceable,
12525ffd83dbSDimitry Andric     // dereferenceable_or_null etc). See AttrBuilder::merge for more details.
12535ffd83dbSDimitry Andric     AttributeList AL = NewRetVal->getAttributes();
12545ffd83dbSDimitry Andric     AttributeList NewAL =
12555ffd83dbSDimitry Andric         AL.addAttributes(Context, AttributeList::ReturnIndex, Valid);
12565ffd83dbSDimitry Andric     NewRetVal->setAttributes(NewAL);
12575ffd83dbSDimitry Andric   }
12585ffd83dbSDimitry Andric }
12595ffd83dbSDimitry Andric 
12600b57cec5SDimitry Andric /// If the inlined function has non-byval align arguments, then
12610b57cec5SDimitry Andric /// add @llvm.assume-based alignment assumptions to preserve this information.
12625ffd83dbSDimitry Andric static void AddAlignmentAssumptions(CallBase &CB, InlineFunctionInfo &IFI) {
12630b57cec5SDimitry Andric   if (!PreserveAlignmentAssumptions || !IFI.GetAssumptionCache)
12640b57cec5SDimitry Andric     return;
12650b57cec5SDimitry Andric 
12665ffd83dbSDimitry Andric   AssumptionCache *AC = &IFI.GetAssumptionCache(*CB.getCaller());
12675ffd83dbSDimitry Andric   auto &DL = CB.getCaller()->getParent()->getDataLayout();
12680b57cec5SDimitry Andric 
12690b57cec5SDimitry Andric   // To avoid inserting redundant assumptions, we should check for assumptions
12700b57cec5SDimitry Andric   // already in the caller. To do this, we might need a DT of the caller.
12710b57cec5SDimitry Andric   DominatorTree DT;
12720b57cec5SDimitry Andric   bool DTCalculated = false;
12730b57cec5SDimitry Andric 
12745ffd83dbSDimitry Andric   Function *CalledFunc = CB.getCalledFunction();
12750b57cec5SDimitry Andric   for (Argument &Arg : CalledFunc->args()) {
12760b57cec5SDimitry Andric     unsigned Align = Arg.getType()->isPointerTy() ? Arg.getParamAlignment() : 0;
1277*e8d8bef9SDimitry Andric     if (Align && !Arg.hasPassPointeeByValueCopyAttr() && !Arg.hasNUses(0)) {
12780b57cec5SDimitry Andric       if (!DTCalculated) {
12795ffd83dbSDimitry Andric         DT.recalculate(*CB.getCaller());
12800b57cec5SDimitry Andric         DTCalculated = true;
12810b57cec5SDimitry Andric       }
12820b57cec5SDimitry Andric 
12830b57cec5SDimitry Andric       // If we can already prove the asserted alignment in the context of the
12840b57cec5SDimitry Andric       // caller, then don't bother inserting the assumption.
12855ffd83dbSDimitry Andric       Value *ArgVal = CB.getArgOperand(Arg.getArgNo());
12865ffd83dbSDimitry Andric       if (getKnownAlignment(ArgVal, DL, &CB, AC, &DT) >= Align)
12870b57cec5SDimitry Andric         continue;
12880b57cec5SDimitry Andric 
12895ffd83dbSDimitry Andric       CallInst *NewAsmp =
12905ffd83dbSDimitry Andric           IRBuilder<>(&CB).CreateAlignmentAssumption(DL, ArgVal, Align);
12910b57cec5SDimitry Andric       AC->registerAssumption(NewAsmp);
12920b57cec5SDimitry Andric     }
12930b57cec5SDimitry Andric   }
12940b57cec5SDimitry Andric }
12950b57cec5SDimitry Andric 
12960b57cec5SDimitry Andric /// Once we have cloned code over from a callee into the caller,
12970b57cec5SDimitry Andric /// update the specified callgraph to reflect the changes we made.
12980b57cec5SDimitry Andric /// Note that it's possible that not all code was copied over, so only
12990b57cec5SDimitry Andric /// some edges of the callgraph may remain.
13005ffd83dbSDimitry Andric static void UpdateCallGraphAfterInlining(CallBase &CB,
13010b57cec5SDimitry Andric                                          Function::iterator FirstNewBlock,
13020b57cec5SDimitry Andric                                          ValueToValueMapTy &VMap,
13030b57cec5SDimitry Andric                                          InlineFunctionInfo &IFI) {
13040b57cec5SDimitry Andric   CallGraph &CG = *IFI.CG;
13055ffd83dbSDimitry Andric   const Function *Caller = CB.getCaller();
13065ffd83dbSDimitry Andric   const Function *Callee = CB.getCalledFunction();
13070b57cec5SDimitry Andric   CallGraphNode *CalleeNode = CG[Callee];
13080b57cec5SDimitry Andric   CallGraphNode *CallerNode = CG[Caller];
13090b57cec5SDimitry Andric 
13100b57cec5SDimitry Andric   // Since we inlined some uninlined call sites in the callee into the caller,
13110b57cec5SDimitry Andric   // add edges from the caller to all of the callees of the callee.
13120b57cec5SDimitry Andric   CallGraphNode::iterator I = CalleeNode->begin(), E = CalleeNode->end();
13130b57cec5SDimitry Andric 
13140b57cec5SDimitry Andric   // Consider the case where CalleeNode == CallerNode.
13150b57cec5SDimitry Andric   CallGraphNode::CalledFunctionsVector CallCache;
13160b57cec5SDimitry Andric   if (CalleeNode == CallerNode) {
13170b57cec5SDimitry Andric     CallCache.assign(I, E);
13180b57cec5SDimitry Andric     I = CallCache.begin();
13190b57cec5SDimitry Andric     E = CallCache.end();
13200b57cec5SDimitry Andric   }
13210b57cec5SDimitry Andric 
13220b57cec5SDimitry Andric   for (; I != E; ++I) {
13235ffd83dbSDimitry Andric     // Skip 'refererence' call records.
13245ffd83dbSDimitry Andric     if (!I->first)
13255ffd83dbSDimitry Andric       continue;
13265ffd83dbSDimitry Andric 
13275ffd83dbSDimitry Andric     const Value *OrigCall = *I->first;
13280b57cec5SDimitry Andric 
13290b57cec5SDimitry Andric     ValueToValueMapTy::iterator VMI = VMap.find(OrigCall);
13300b57cec5SDimitry Andric     // Only copy the edge if the call was inlined!
13310b57cec5SDimitry Andric     if (VMI == VMap.end() || VMI->second == nullptr)
13320b57cec5SDimitry Andric       continue;
13330b57cec5SDimitry Andric 
13340b57cec5SDimitry Andric     // If the call was inlined, but then constant folded, there is no edge to
13350b57cec5SDimitry Andric     // add.  Check for this case.
13360b57cec5SDimitry Andric     auto *NewCall = dyn_cast<CallBase>(VMI->second);
13370b57cec5SDimitry Andric     if (!NewCall)
13380b57cec5SDimitry Andric       continue;
13390b57cec5SDimitry Andric 
13400b57cec5SDimitry Andric     // We do not treat intrinsic calls like real function calls because we
13410b57cec5SDimitry Andric     // expect them to become inline code; do not add an edge for an intrinsic.
13420b57cec5SDimitry Andric     if (NewCall->getCalledFunction() &&
13430b57cec5SDimitry Andric         NewCall->getCalledFunction()->isIntrinsic())
13440b57cec5SDimitry Andric       continue;
13450b57cec5SDimitry Andric 
13460b57cec5SDimitry Andric     // Remember that this call site got inlined for the client of
13470b57cec5SDimitry Andric     // InlineFunction.
13480b57cec5SDimitry Andric     IFI.InlinedCalls.push_back(NewCall);
13490b57cec5SDimitry Andric 
13500b57cec5SDimitry Andric     // It's possible that inlining the callsite will cause it to go from an
13510b57cec5SDimitry Andric     // indirect to a direct call by resolving a function pointer.  If this
13520b57cec5SDimitry Andric     // happens, set the callee of the new call site to a more precise
13530b57cec5SDimitry Andric     // destination.  This can also happen if the call graph node of the caller
13540b57cec5SDimitry Andric     // was just unnecessarily imprecise.
13550b57cec5SDimitry Andric     if (!I->second->getFunction())
13560b57cec5SDimitry Andric       if (Function *F = NewCall->getCalledFunction()) {
13570b57cec5SDimitry Andric         // Indirect call site resolved to direct call.
13580b57cec5SDimitry Andric         CallerNode->addCalledFunction(NewCall, CG[F]);
13590b57cec5SDimitry Andric 
13600b57cec5SDimitry Andric         continue;
13610b57cec5SDimitry Andric       }
13620b57cec5SDimitry Andric 
13630b57cec5SDimitry Andric     CallerNode->addCalledFunction(NewCall, I->second);
13640b57cec5SDimitry Andric   }
13650b57cec5SDimitry Andric 
13660b57cec5SDimitry Andric   // Update the call graph by deleting the edge from Callee to Caller.  We must
13670b57cec5SDimitry Andric   // do this after the loop above in case Caller and Callee are the same.
13685ffd83dbSDimitry Andric   CallerNode->removeCallEdgeFor(*cast<CallBase>(&CB));
13690b57cec5SDimitry Andric }
13700b57cec5SDimitry Andric 
13710b57cec5SDimitry Andric static void HandleByValArgumentInit(Value *Dst, Value *Src, Module *M,
13720b57cec5SDimitry Andric                                     BasicBlock *InsertBlock,
13730b57cec5SDimitry Andric                                     InlineFunctionInfo &IFI) {
13740b57cec5SDimitry Andric   Type *AggTy = cast<PointerType>(Src->getType())->getElementType();
13750b57cec5SDimitry Andric   IRBuilder<> Builder(InsertBlock, InsertBlock->begin());
13760b57cec5SDimitry Andric 
13770b57cec5SDimitry Andric   Value *Size = Builder.getInt64(M->getDataLayout().getTypeStoreSize(AggTy));
13780b57cec5SDimitry Andric 
13790b57cec5SDimitry Andric   // Always generate a memcpy of alignment 1 here because we don't know
13800b57cec5SDimitry Andric   // the alignment of the src pointer.  Other optimizations can infer
13810b57cec5SDimitry Andric   // better alignment.
13825ffd83dbSDimitry Andric   Builder.CreateMemCpy(Dst, /*DstAlign*/ Align(1), Src,
13835ffd83dbSDimitry Andric                        /*SrcAlign*/ Align(1), Size);
13840b57cec5SDimitry Andric }
13850b57cec5SDimitry Andric 
13860b57cec5SDimitry Andric /// When inlining a call site that has a byval argument,
13870b57cec5SDimitry Andric /// we have to make the implicit memcpy explicit by adding it.
13880b57cec5SDimitry Andric static Value *HandleByValArgument(Value *Arg, Instruction *TheCall,
13890b57cec5SDimitry Andric                                   const Function *CalledFunc,
13900b57cec5SDimitry Andric                                   InlineFunctionInfo &IFI,
13910b57cec5SDimitry Andric                                   unsigned ByValAlignment) {
13920b57cec5SDimitry Andric   PointerType *ArgTy = cast<PointerType>(Arg->getType());
13930b57cec5SDimitry Andric   Type *AggTy = ArgTy->getElementType();
13940b57cec5SDimitry Andric 
13950b57cec5SDimitry Andric   Function *Caller = TheCall->getFunction();
13960b57cec5SDimitry Andric   const DataLayout &DL = Caller->getParent()->getDataLayout();
13970b57cec5SDimitry Andric 
13980b57cec5SDimitry Andric   // If the called function is readonly, then it could not mutate the caller's
13990b57cec5SDimitry Andric   // copy of the byval'd memory.  In this case, it is safe to elide the copy and
14000b57cec5SDimitry Andric   // temporary.
14010b57cec5SDimitry Andric   if (CalledFunc->onlyReadsMemory()) {
14020b57cec5SDimitry Andric     // If the byval argument has a specified alignment that is greater than the
14030b57cec5SDimitry Andric     // passed in pointer, then we either have to round up the input pointer or
14040b57cec5SDimitry Andric     // give up on this transformation.
14050b57cec5SDimitry Andric     if (ByValAlignment <= 1)  // 0 = unspecified, 1 = no particular alignment.
14060b57cec5SDimitry Andric       return Arg;
14070b57cec5SDimitry Andric 
14080b57cec5SDimitry Andric     AssumptionCache *AC =
14095ffd83dbSDimitry Andric         IFI.GetAssumptionCache ? &IFI.GetAssumptionCache(*Caller) : nullptr;
14100b57cec5SDimitry Andric 
14110b57cec5SDimitry Andric     // If the pointer is already known to be sufficiently aligned, or if we can
14120b57cec5SDimitry Andric     // round it up to a larger alignment, then we don't need a temporary.
14135ffd83dbSDimitry Andric     if (getOrEnforceKnownAlignment(Arg, Align(ByValAlignment), DL, TheCall,
14145ffd83dbSDimitry Andric                                    AC) >= ByValAlignment)
14150b57cec5SDimitry Andric       return Arg;
14160b57cec5SDimitry Andric 
14170b57cec5SDimitry Andric     // Otherwise, we have to make a memcpy to get a safe alignment.  This is bad
14180b57cec5SDimitry Andric     // for code quality, but rarely happens and is required for correctness.
14190b57cec5SDimitry Andric   }
14200b57cec5SDimitry Andric 
14210b57cec5SDimitry Andric   // Create the alloca.  If we have DataLayout, use nice alignment.
1422480093f4SDimitry Andric   Align Alignment(DL.getPrefTypeAlignment(AggTy));
14230b57cec5SDimitry Andric 
14240b57cec5SDimitry Andric   // If the byval had an alignment specified, we *must* use at least that
14250b57cec5SDimitry Andric   // alignment, as it is required by the byval argument (and uses of the
14260b57cec5SDimitry Andric   // pointer inside the callee).
1427480093f4SDimitry Andric   Alignment = max(Alignment, MaybeAlign(ByValAlignment));
14280b57cec5SDimitry Andric 
1429480093f4SDimitry Andric   Value *NewAlloca =
1430480093f4SDimitry Andric       new AllocaInst(AggTy, DL.getAllocaAddrSpace(), nullptr, Alignment,
1431480093f4SDimitry Andric                      Arg->getName(), &*Caller->begin()->begin());
14320b57cec5SDimitry Andric   IFI.StaticAllocas.push_back(cast<AllocaInst>(NewAlloca));
14330b57cec5SDimitry Andric 
14340b57cec5SDimitry Andric   // Uses of the argument in the function should use our new alloca
14350b57cec5SDimitry Andric   // instead.
14360b57cec5SDimitry Andric   return NewAlloca;
14370b57cec5SDimitry Andric }
14380b57cec5SDimitry Andric 
14390b57cec5SDimitry Andric // Check whether this Value is used by a lifetime intrinsic.
14400b57cec5SDimitry Andric static bool isUsedByLifetimeMarker(Value *V) {
14410b57cec5SDimitry Andric   for (User *U : V->users())
14420b57cec5SDimitry Andric     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U))
14430b57cec5SDimitry Andric       if (II->isLifetimeStartOrEnd())
14440b57cec5SDimitry Andric         return true;
14450b57cec5SDimitry Andric   return false;
14460b57cec5SDimitry Andric }
14470b57cec5SDimitry Andric 
14480b57cec5SDimitry Andric // Check whether the given alloca already has
14490b57cec5SDimitry Andric // lifetime.start or lifetime.end intrinsics.
14500b57cec5SDimitry Andric static bool hasLifetimeMarkers(AllocaInst *AI) {
14510b57cec5SDimitry Andric   Type *Ty = AI->getType();
14520b57cec5SDimitry Andric   Type *Int8PtrTy = Type::getInt8PtrTy(Ty->getContext(),
14530b57cec5SDimitry Andric                                        Ty->getPointerAddressSpace());
14540b57cec5SDimitry Andric   if (Ty == Int8PtrTy)
14550b57cec5SDimitry Andric     return isUsedByLifetimeMarker(AI);
14560b57cec5SDimitry Andric 
14570b57cec5SDimitry Andric   // Do a scan to find all the casts to i8*.
14580b57cec5SDimitry Andric   for (User *U : AI->users()) {
14590b57cec5SDimitry Andric     if (U->getType() != Int8PtrTy) continue;
14600b57cec5SDimitry Andric     if (U->stripPointerCasts() != AI) continue;
14610b57cec5SDimitry Andric     if (isUsedByLifetimeMarker(U))
14620b57cec5SDimitry Andric       return true;
14630b57cec5SDimitry Andric   }
14640b57cec5SDimitry Andric   return false;
14650b57cec5SDimitry Andric }
14660b57cec5SDimitry Andric 
14670b57cec5SDimitry Andric /// Return the result of AI->isStaticAlloca() if AI were moved to the entry
14680b57cec5SDimitry Andric /// block. Allocas used in inalloca calls and allocas of dynamic array size
14690b57cec5SDimitry Andric /// cannot be static.
14700b57cec5SDimitry Andric static bool allocaWouldBeStaticInEntry(const AllocaInst *AI ) {
14710b57cec5SDimitry Andric   return isa<Constant>(AI->getArraySize()) && !AI->isUsedWithInAlloca();
14720b57cec5SDimitry Andric }
14730b57cec5SDimitry Andric 
14740b57cec5SDimitry Andric /// Returns a DebugLoc for a new DILocation which is a clone of \p OrigDL
14750b57cec5SDimitry Andric /// inlined at \p InlinedAt. \p IANodes is an inlined-at cache.
14760b57cec5SDimitry Andric static DebugLoc inlineDebugLoc(DebugLoc OrigDL, DILocation *InlinedAt,
14770b57cec5SDimitry Andric                                LLVMContext &Ctx,
14780b57cec5SDimitry Andric                                DenseMap<const MDNode *, MDNode *> &IANodes) {
14790b57cec5SDimitry Andric   auto IA = DebugLoc::appendInlinedAt(OrigDL, InlinedAt, Ctx, IANodes);
1480*e8d8bef9SDimitry Andric   return DILocation::get(Ctx, OrigDL.getLine(), OrigDL.getCol(),
1481*e8d8bef9SDimitry Andric                          OrigDL.getScope(), IA);
14820b57cec5SDimitry Andric }
14830b57cec5SDimitry Andric 
14840b57cec5SDimitry Andric /// Update inlined instructions' line numbers to
14850b57cec5SDimitry Andric /// to encode location where these instructions are inlined.
14860b57cec5SDimitry Andric static void fixupLineNumbers(Function *Fn, Function::iterator FI,
14870b57cec5SDimitry Andric                              Instruction *TheCall, bool CalleeHasDebugInfo) {
14880b57cec5SDimitry Andric   const DebugLoc &TheCallDL = TheCall->getDebugLoc();
14890b57cec5SDimitry Andric   if (!TheCallDL)
14900b57cec5SDimitry Andric     return;
14910b57cec5SDimitry Andric 
14920b57cec5SDimitry Andric   auto &Ctx = Fn->getContext();
14930b57cec5SDimitry Andric   DILocation *InlinedAtNode = TheCallDL;
14940b57cec5SDimitry Andric 
14950b57cec5SDimitry Andric   // Create a unique call site, not to be confused with any other call from the
14960b57cec5SDimitry Andric   // same location.
14970b57cec5SDimitry Andric   InlinedAtNode = DILocation::getDistinct(
14980b57cec5SDimitry Andric       Ctx, InlinedAtNode->getLine(), InlinedAtNode->getColumn(),
14990b57cec5SDimitry Andric       InlinedAtNode->getScope(), InlinedAtNode->getInlinedAt());
15000b57cec5SDimitry Andric 
15010b57cec5SDimitry Andric   // Cache the inlined-at nodes as they're built so they are reused, without
15020b57cec5SDimitry Andric   // this every instruction's inlined-at chain would become distinct from each
15030b57cec5SDimitry Andric   // other.
15040b57cec5SDimitry Andric   DenseMap<const MDNode *, MDNode *> IANodes;
15050b57cec5SDimitry Andric 
1506480093f4SDimitry Andric   // Check if we are not generating inline line tables and want to use
1507480093f4SDimitry Andric   // the call site location instead.
1508480093f4SDimitry Andric   bool NoInlineLineTables = Fn->hasFnAttribute("no-inline-line-tables");
1509480093f4SDimitry Andric 
15100b57cec5SDimitry Andric   for (; FI != Fn->end(); ++FI) {
15110b57cec5SDimitry Andric     for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
15120b57cec5SDimitry Andric          BI != BE; ++BI) {
15130b57cec5SDimitry Andric       // Loop metadata needs to be updated so that the start and end locs
15140b57cec5SDimitry Andric       // reference inlined-at locations.
15155ffd83dbSDimitry Andric       auto updateLoopInfoLoc = [&Ctx, &InlinedAtNode, &IANodes](
15165ffd83dbSDimitry Andric                                    const DILocation &Loc) -> DILocation * {
15175ffd83dbSDimitry Andric         return inlineDebugLoc(&Loc, InlinedAtNode, Ctx, IANodes).get();
15185ffd83dbSDimitry Andric       };
15195ffd83dbSDimitry Andric       updateLoopMetadataDebugLocations(*BI, updateLoopInfoLoc);
15200b57cec5SDimitry Andric 
1521480093f4SDimitry Andric       if (!NoInlineLineTables)
15220b57cec5SDimitry Andric         if (DebugLoc DL = BI->getDebugLoc()) {
15230b57cec5SDimitry Andric           DebugLoc IDL =
15240b57cec5SDimitry Andric               inlineDebugLoc(DL, InlinedAtNode, BI->getContext(), IANodes);
15250b57cec5SDimitry Andric           BI->setDebugLoc(IDL);
15260b57cec5SDimitry Andric           continue;
15270b57cec5SDimitry Andric         }
15280b57cec5SDimitry Andric 
1529480093f4SDimitry Andric       if (CalleeHasDebugInfo && !NoInlineLineTables)
15300b57cec5SDimitry Andric         continue;
15310b57cec5SDimitry Andric 
1532480093f4SDimitry Andric       // If the inlined instruction has no line number, or if inline info
1533480093f4SDimitry Andric       // is not being generated, make it look as if it originates from the call
1534480093f4SDimitry Andric       // location. This is important for ((__always_inline, __nodebug__))
1535480093f4SDimitry Andric       // functions which must use caller location for all instructions in their
1536480093f4SDimitry Andric       // function body.
15370b57cec5SDimitry Andric 
15380b57cec5SDimitry Andric       // Don't update static allocas, as they may get moved later.
15390b57cec5SDimitry Andric       if (auto *AI = dyn_cast<AllocaInst>(BI))
15400b57cec5SDimitry Andric         if (allocaWouldBeStaticInEntry(AI))
15410b57cec5SDimitry Andric           continue;
15420b57cec5SDimitry Andric 
15430b57cec5SDimitry Andric       BI->setDebugLoc(TheCallDL);
15440b57cec5SDimitry Andric     }
1545480093f4SDimitry Andric 
1546480093f4SDimitry Andric     // Remove debug info intrinsics if we're not keeping inline info.
1547480093f4SDimitry Andric     if (NoInlineLineTables) {
1548480093f4SDimitry Andric       BasicBlock::iterator BI = FI->begin();
1549480093f4SDimitry Andric       while (BI != FI->end()) {
1550480093f4SDimitry Andric         if (isa<DbgInfoIntrinsic>(BI)) {
1551480093f4SDimitry Andric           BI = BI->eraseFromParent();
1552480093f4SDimitry Andric           continue;
1553480093f4SDimitry Andric         }
1554480093f4SDimitry Andric         ++BI;
1555480093f4SDimitry Andric       }
1556480093f4SDimitry Andric     }
1557480093f4SDimitry Andric 
15580b57cec5SDimitry Andric   }
15590b57cec5SDimitry Andric }
15600b57cec5SDimitry Andric 
15610b57cec5SDimitry Andric /// Update the block frequencies of the caller after a callee has been inlined.
15620b57cec5SDimitry Andric ///
15630b57cec5SDimitry Andric /// Each block cloned into the caller has its block frequency scaled by the
15640b57cec5SDimitry Andric /// ratio of CallSiteFreq/CalleeEntryFreq. This ensures that the cloned copy of
15650b57cec5SDimitry Andric /// callee's entry block gets the same frequency as the callsite block and the
15660b57cec5SDimitry Andric /// relative frequencies of all cloned blocks remain the same after cloning.
15670b57cec5SDimitry Andric static void updateCallerBFI(BasicBlock *CallSiteBlock,
15680b57cec5SDimitry Andric                             const ValueToValueMapTy &VMap,
15690b57cec5SDimitry Andric                             BlockFrequencyInfo *CallerBFI,
15700b57cec5SDimitry Andric                             BlockFrequencyInfo *CalleeBFI,
15710b57cec5SDimitry Andric                             const BasicBlock &CalleeEntryBlock) {
15720b57cec5SDimitry Andric   SmallPtrSet<BasicBlock *, 16> ClonedBBs;
1573480093f4SDimitry Andric   for (auto Entry : VMap) {
15740b57cec5SDimitry Andric     if (!isa<BasicBlock>(Entry.first) || !Entry.second)
15750b57cec5SDimitry Andric       continue;
15760b57cec5SDimitry Andric     auto *OrigBB = cast<BasicBlock>(Entry.first);
15770b57cec5SDimitry Andric     auto *ClonedBB = cast<BasicBlock>(Entry.second);
15780b57cec5SDimitry Andric     uint64_t Freq = CalleeBFI->getBlockFreq(OrigBB).getFrequency();
15790b57cec5SDimitry Andric     if (!ClonedBBs.insert(ClonedBB).second) {
15800b57cec5SDimitry Andric       // Multiple blocks in the callee might get mapped to one cloned block in
15810b57cec5SDimitry Andric       // the caller since we prune the callee as we clone it. When that happens,
15820b57cec5SDimitry Andric       // we want to use the maximum among the original blocks' frequencies.
15830b57cec5SDimitry Andric       uint64_t NewFreq = CallerBFI->getBlockFreq(ClonedBB).getFrequency();
15840b57cec5SDimitry Andric       if (NewFreq > Freq)
15850b57cec5SDimitry Andric         Freq = NewFreq;
15860b57cec5SDimitry Andric     }
15870b57cec5SDimitry Andric     CallerBFI->setBlockFreq(ClonedBB, Freq);
15880b57cec5SDimitry Andric   }
15890b57cec5SDimitry Andric   BasicBlock *EntryClone = cast<BasicBlock>(VMap.lookup(&CalleeEntryBlock));
15900b57cec5SDimitry Andric   CallerBFI->setBlockFreqAndScale(
15910b57cec5SDimitry Andric       EntryClone, CallerBFI->getBlockFreq(CallSiteBlock).getFrequency(),
15920b57cec5SDimitry Andric       ClonedBBs);
15930b57cec5SDimitry Andric }
15940b57cec5SDimitry Andric 
15950b57cec5SDimitry Andric /// Update the branch metadata for cloned call instructions.
15960b57cec5SDimitry Andric static void updateCallProfile(Function *Callee, const ValueToValueMapTy &VMap,
15970b57cec5SDimitry Andric                               const ProfileCount &CalleeEntryCount,
15985ffd83dbSDimitry Andric                               const CallBase &TheCall, ProfileSummaryInfo *PSI,
15990b57cec5SDimitry Andric                               BlockFrequencyInfo *CallerBFI) {
16000b57cec5SDimitry Andric   if (!CalleeEntryCount.hasValue() || CalleeEntryCount.isSynthetic() ||
16010b57cec5SDimitry Andric       CalleeEntryCount.getCount() < 1)
16020b57cec5SDimitry Andric     return;
16030b57cec5SDimitry Andric   auto CallSiteCount = PSI ? PSI->getProfileCount(TheCall, CallerBFI) : None;
16040b57cec5SDimitry Andric   int64_t CallCount =
1605*e8d8bef9SDimitry Andric       std::min(CallSiteCount.getValueOr(0), CalleeEntryCount.getCount());
16060b57cec5SDimitry Andric   updateProfileCallee(Callee, -CallCount, &VMap);
16070b57cec5SDimitry Andric }
16080b57cec5SDimitry Andric 
16090b57cec5SDimitry Andric void llvm::updateProfileCallee(
16100b57cec5SDimitry Andric     Function *Callee, int64_t entryDelta,
16110b57cec5SDimitry Andric     const ValueMap<const Value *, WeakTrackingVH> *VMap) {
16120b57cec5SDimitry Andric   auto CalleeCount = Callee->getEntryCount();
16130b57cec5SDimitry Andric   if (!CalleeCount.hasValue())
16140b57cec5SDimitry Andric     return;
16150b57cec5SDimitry Andric 
16160b57cec5SDimitry Andric   uint64_t priorEntryCount = CalleeCount.getCount();
16170b57cec5SDimitry Andric   uint64_t newEntryCount;
16180b57cec5SDimitry Andric 
16190b57cec5SDimitry Andric   // Since CallSiteCount is an estimate, it could exceed the original callee
16200b57cec5SDimitry Andric   // count and has to be set to 0 so guard against underflow.
16210b57cec5SDimitry Andric   if (entryDelta < 0 && static_cast<uint64_t>(-entryDelta) > priorEntryCount)
16220b57cec5SDimitry Andric     newEntryCount = 0;
16230b57cec5SDimitry Andric   else
16240b57cec5SDimitry Andric     newEntryCount = priorEntryCount + entryDelta;
16250b57cec5SDimitry Andric 
16260b57cec5SDimitry Andric   // During inlining ?
16270b57cec5SDimitry Andric   if (VMap) {
16280b57cec5SDimitry Andric     uint64_t cloneEntryCount = priorEntryCount - newEntryCount;
1629480093f4SDimitry Andric     for (auto Entry : *VMap)
16300b57cec5SDimitry Andric       if (isa<CallInst>(Entry.first))
16310b57cec5SDimitry Andric         if (auto *CI = dyn_cast_or_null<CallInst>(Entry.second))
16320b57cec5SDimitry Andric           CI->updateProfWeight(cloneEntryCount, priorEntryCount);
16330b57cec5SDimitry Andric   }
1634480093f4SDimitry Andric 
1635480093f4SDimitry Andric   if (entryDelta) {
1636480093f4SDimitry Andric     Callee->setEntryCount(newEntryCount);
1637480093f4SDimitry Andric 
16380b57cec5SDimitry Andric     for (BasicBlock &BB : *Callee)
16390b57cec5SDimitry Andric       // No need to update the callsite if it is pruned during inlining.
16400b57cec5SDimitry Andric       if (!VMap || VMap->count(&BB))
16410b57cec5SDimitry Andric         for (Instruction &I : BB)
16420b57cec5SDimitry Andric           if (CallInst *CI = dyn_cast<CallInst>(&I))
16430b57cec5SDimitry Andric             CI->updateProfWeight(newEntryCount, priorEntryCount);
16440b57cec5SDimitry Andric   }
1645480093f4SDimitry Andric }
16460b57cec5SDimitry Andric 
16470b57cec5SDimitry Andric /// This function inlines the called function into the basic block of the
16480b57cec5SDimitry Andric /// caller. This returns false if it is not possible to inline this call.
16490b57cec5SDimitry Andric /// The program is still in a well defined state if this occurs though.
16500b57cec5SDimitry Andric ///
16510b57cec5SDimitry Andric /// Note that this only does one level of inlining.  For example, if the
16520b57cec5SDimitry Andric /// instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
16530b57cec5SDimitry Andric /// exists in the instruction stream.  Similarly this will inline a recursive
16540b57cec5SDimitry Andric /// function by one level.
16555ffd83dbSDimitry Andric llvm::InlineResult llvm::InlineFunction(CallBase &CB, InlineFunctionInfo &IFI,
16560b57cec5SDimitry Andric                                         AAResults *CalleeAAR,
16570b57cec5SDimitry Andric                                         bool InsertLifetime,
16580b57cec5SDimitry Andric                                         Function *ForwardVarArgsTo) {
16595ffd83dbSDimitry Andric   assert(CB.getParent() && CB.getFunction() && "Instruction not in function!");
16600b57cec5SDimitry Andric 
16610b57cec5SDimitry Andric   // FIXME: we don't inline callbr yet.
16625ffd83dbSDimitry Andric   if (isa<CallBrInst>(CB))
16635ffd83dbSDimitry Andric     return InlineResult::failure("We don't inline callbr yet.");
16640b57cec5SDimitry Andric 
16650b57cec5SDimitry Andric   // If IFI has any state in it, zap it before we fill it in.
16660b57cec5SDimitry Andric   IFI.reset();
16670b57cec5SDimitry Andric 
16685ffd83dbSDimitry Andric   Function *CalledFunc = CB.getCalledFunction();
16690b57cec5SDimitry Andric   if (!CalledFunc ||               // Can't inline external function or indirect
16700b57cec5SDimitry Andric       CalledFunc->isDeclaration()) // call!
16715ffd83dbSDimitry Andric     return InlineResult::failure("external or indirect");
16720b57cec5SDimitry Andric 
16730b57cec5SDimitry Andric   // The inliner does not know how to inline through calls with operand bundles
16740b57cec5SDimitry Andric   // in general ...
16755ffd83dbSDimitry Andric   if (CB.hasOperandBundles()) {
16765ffd83dbSDimitry Andric     for (int i = 0, e = CB.getNumOperandBundles(); i != e; ++i) {
16775ffd83dbSDimitry Andric       uint32_t Tag = CB.getOperandBundleAt(i).getTagID();
16780b57cec5SDimitry Andric       // ... but it knows how to inline through "deopt" operand bundles ...
16790b57cec5SDimitry Andric       if (Tag == LLVMContext::OB_deopt)
16800b57cec5SDimitry Andric         continue;
16810b57cec5SDimitry Andric       // ... and "funclet" operand bundles.
16820b57cec5SDimitry Andric       if (Tag == LLVMContext::OB_funclet)
16830b57cec5SDimitry Andric         continue;
16840b57cec5SDimitry Andric 
16855ffd83dbSDimitry Andric       return InlineResult::failure("unsupported operand bundle");
16860b57cec5SDimitry Andric     }
16870b57cec5SDimitry Andric   }
16880b57cec5SDimitry Andric 
16890b57cec5SDimitry Andric   // If the call to the callee cannot throw, set the 'nounwind' flag on any
16900b57cec5SDimitry Andric   // calls that we inline.
16915ffd83dbSDimitry Andric   bool MarkNoUnwind = CB.doesNotThrow();
16920b57cec5SDimitry Andric 
16935ffd83dbSDimitry Andric   BasicBlock *OrigBB = CB.getParent();
16940b57cec5SDimitry Andric   Function *Caller = OrigBB->getParent();
16950b57cec5SDimitry Andric 
16960b57cec5SDimitry Andric   // GC poses two hazards to inlining, which only occur when the callee has GC:
16970b57cec5SDimitry Andric   //  1. If the caller has no GC, then the callee's GC must be propagated to the
16980b57cec5SDimitry Andric   //     caller.
16990b57cec5SDimitry Andric   //  2. If the caller has a differing GC, it is invalid to inline.
17000b57cec5SDimitry Andric   if (CalledFunc->hasGC()) {
17010b57cec5SDimitry Andric     if (!Caller->hasGC())
17020b57cec5SDimitry Andric       Caller->setGC(CalledFunc->getGC());
17030b57cec5SDimitry Andric     else if (CalledFunc->getGC() != Caller->getGC())
17045ffd83dbSDimitry Andric       return InlineResult::failure("incompatible GC");
17050b57cec5SDimitry Andric   }
17060b57cec5SDimitry Andric 
17070b57cec5SDimitry Andric   // Get the personality function from the callee if it contains a landing pad.
17080b57cec5SDimitry Andric   Constant *CalledPersonality =
17090b57cec5SDimitry Andric       CalledFunc->hasPersonalityFn()
17100b57cec5SDimitry Andric           ? CalledFunc->getPersonalityFn()->stripPointerCasts()
17110b57cec5SDimitry Andric           : nullptr;
17120b57cec5SDimitry Andric 
17130b57cec5SDimitry Andric   // Find the personality function used by the landing pads of the caller. If it
17140b57cec5SDimitry Andric   // exists, then check to see that it matches the personality function used in
17150b57cec5SDimitry Andric   // the callee.
17160b57cec5SDimitry Andric   Constant *CallerPersonality =
17170b57cec5SDimitry Andric       Caller->hasPersonalityFn()
17180b57cec5SDimitry Andric           ? Caller->getPersonalityFn()->stripPointerCasts()
17190b57cec5SDimitry Andric           : nullptr;
17200b57cec5SDimitry Andric   if (CalledPersonality) {
17210b57cec5SDimitry Andric     if (!CallerPersonality)
17220b57cec5SDimitry Andric       Caller->setPersonalityFn(CalledPersonality);
17230b57cec5SDimitry Andric     // If the personality functions match, then we can perform the
17240b57cec5SDimitry Andric     // inlining. Otherwise, we can't inline.
17250b57cec5SDimitry Andric     // TODO: This isn't 100% true. Some personality functions are proper
17260b57cec5SDimitry Andric     //       supersets of others and can be used in place of the other.
17270b57cec5SDimitry Andric     else if (CalledPersonality != CallerPersonality)
17285ffd83dbSDimitry Andric       return InlineResult::failure("incompatible personality");
17290b57cec5SDimitry Andric   }
17300b57cec5SDimitry Andric 
17310b57cec5SDimitry Andric   // We need to figure out which funclet the callsite was in so that we may
17320b57cec5SDimitry Andric   // properly nest the callee.
17330b57cec5SDimitry Andric   Instruction *CallSiteEHPad = nullptr;
17340b57cec5SDimitry Andric   if (CallerPersonality) {
17350b57cec5SDimitry Andric     EHPersonality Personality = classifyEHPersonality(CallerPersonality);
17360b57cec5SDimitry Andric     if (isScopedEHPersonality(Personality)) {
17370b57cec5SDimitry Andric       Optional<OperandBundleUse> ParentFunclet =
17385ffd83dbSDimitry Andric           CB.getOperandBundle(LLVMContext::OB_funclet);
17390b57cec5SDimitry Andric       if (ParentFunclet)
17400b57cec5SDimitry Andric         CallSiteEHPad = cast<FuncletPadInst>(ParentFunclet->Inputs.front());
17410b57cec5SDimitry Andric 
17420b57cec5SDimitry Andric       // OK, the inlining site is legal.  What about the target function?
17430b57cec5SDimitry Andric 
17440b57cec5SDimitry Andric       if (CallSiteEHPad) {
17450b57cec5SDimitry Andric         if (Personality == EHPersonality::MSVC_CXX) {
17460b57cec5SDimitry Andric           // The MSVC personality cannot tolerate catches getting inlined into
17470b57cec5SDimitry Andric           // cleanup funclets.
17480b57cec5SDimitry Andric           if (isa<CleanupPadInst>(CallSiteEHPad)) {
17490b57cec5SDimitry Andric             // Ok, the call site is within a cleanuppad.  Let's check the callee
17500b57cec5SDimitry Andric             // for catchpads.
17510b57cec5SDimitry Andric             for (const BasicBlock &CalledBB : *CalledFunc) {
17520b57cec5SDimitry Andric               if (isa<CatchSwitchInst>(CalledBB.getFirstNonPHI()))
17535ffd83dbSDimitry Andric                 return InlineResult::failure("catch in cleanup funclet");
17540b57cec5SDimitry Andric             }
17550b57cec5SDimitry Andric           }
17560b57cec5SDimitry Andric         } else if (isAsynchronousEHPersonality(Personality)) {
17570b57cec5SDimitry Andric           // SEH is even less tolerant, there may not be any sort of exceptional
17580b57cec5SDimitry Andric           // funclet in the callee.
17590b57cec5SDimitry Andric           for (const BasicBlock &CalledBB : *CalledFunc) {
17600b57cec5SDimitry Andric             if (CalledBB.isEHPad())
17615ffd83dbSDimitry Andric               return InlineResult::failure("SEH in cleanup funclet");
17620b57cec5SDimitry Andric           }
17630b57cec5SDimitry Andric         }
17640b57cec5SDimitry Andric       }
17650b57cec5SDimitry Andric     }
17660b57cec5SDimitry Andric   }
17670b57cec5SDimitry Andric 
17680b57cec5SDimitry Andric   // Determine if we are dealing with a call in an EHPad which does not unwind
17690b57cec5SDimitry Andric   // to caller.
17700b57cec5SDimitry Andric   bool EHPadForCallUnwindsLocally = false;
17715ffd83dbSDimitry Andric   if (CallSiteEHPad && isa<CallInst>(CB)) {
17720b57cec5SDimitry Andric     UnwindDestMemoTy FuncletUnwindMap;
17730b57cec5SDimitry Andric     Value *CallSiteUnwindDestToken =
17740b57cec5SDimitry Andric         getUnwindDestToken(CallSiteEHPad, FuncletUnwindMap);
17750b57cec5SDimitry Andric 
17760b57cec5SDimitry Andric     EHPadForCallUnwindsLocally =
17770b57cec5SDimitry Andric         CallSiteUnwindDestToken &&
17780b57cec5SDimitry Andric         !isa<ConstantTokenNone>(CallSiteUnwindDestToken);
17790b57cec5SDimitry Andric   }
17800b57cec5SDimitry Andric 
17810b57cec5SDimitry Andric   // Get an iterator to the last basic block in the function, which will have
17820b57cec5SDimitry Andric   // the new function inlined after it.
17830b57cec5SDimitry Andric   Function::iterator LastBlock = --Caller->end();
17840b57cec5SDimitry Andric 
17850b57cec5SDimitry Andric   // Make sure to capture all of the return instructions from the cloned
17860b57cec5SDimitry Andric   // function.
17870b57cec5SDimitry Andric   SmallVector<ReturnInst*, 8> Returns;
17880b57cec5SDimitry Andric   ClonedCodeInfo InlinedFunctionInfo;
17890b57cec5SDimitry Andric   Function::iterator FirstNewBlock;
17900b57cec5SDimitry Andric 
17910b57cec5SDimitry Andric   { // Scope to destroy VMap after cloning.
17920b57cec5SDimitry Andric     ValueToValueMapTy VMap;
17930b57cec5SDimitry Andric     // Keep a list of pair (dst, src) to emit byval initializations.
17940b57cec5SDimitry Andric     SmallVector<std::pair<Value*, Value*>, 4> ByValInit;
17950b57cec5SDimitry Andric 
1796*e8d8bef9SDimitry Andric     // When inlining a function that contains noalias scope metadata,
1797*e8d8bef9SDimitry Andric     // this metadata needs to be cloned so that the inlined blocks
1798*e8d8bef9SDimitry Andric     // have different "unique scopes" at every call site.
1799*e8d8bef9SDimitry Andric     // Track the metadata that must be cloned. Do this before other changes to
1800*e8d8bef9SDimitry Andric     // the function, so that we do not get in trouble when inlining caller ==
1801*e8d8bef9SDimitry Andric     // callee.
1802*e8d8bef9SDimitry Andric     ScopedAliasMetadataDeepCloner SAMetadataCloner(CB.getCalledFunction());
1803*e8d8bef9SDimitry Andric 
18040b57cec5SDimitry Andric     auto &DL = Caller->getParent()->getDataLayout();
18050b57cec5SDimitry Andric 
18060b57cec5SDimitry Andric     // Calculate the vector of arguments to pass into the function cloner, which
18070b57cec5SDimitry Andric     // matches up the formal to the actual argument values.
18085ffd83dbSDimitry Andric     auto AI = CB.arg_begin();
18090b57cec5SDimitry Andric     unsigned ArgNo = 0;
18100b57cec5SDimitry Andric     for (Function::arg_iterator I = CalledFunc->arg_begin(),
18110b57cec5SDimitry Andric          E = CalledFunc->arg_end(); I != E; ++I, ++AI, ++ArgNo) {
18120b57cec5SDimitry Andric       Value *ActualArg = *AI;
18130b57cec5SDimitry Andric 
18140b57cec5SDimitry Andric       // When byval arguments actually inlined, we need to make the copy implied
18150b57cec5SDimitry Andric       // by them explicit.  However, we don't do this if the callee is readonly
18160b57cec5SDimitry Andric       // or readnone, because the copy would be unneeded: the callee doesn't
18170b57cec5SDimitry Andric       // modify the struct.
18185ffd83dbSDimitry Andric       if (CB.isByValArgument(ArgNo)) {
18195ffd83dbSDimitry Andric         ActualArg = HandleByValArgument(ActualArg, &CB, CalledFunc, IFI,
18200b57cec5SDimitry Andric                                         CalledFunc->getParamAlignment(ArgNo));
18210b57cec5SDimitry Andric         if (ActualArg != *AI)
18220b57cec5SDimitry Andric           ByValInit.push_back(std::make_pair(ActualArg, (Value*) *AI));
18230b57cec5SDimitry Andric       }
18240b57cec5SDimitry Andric 
18250b57cec5SDimitry Andric       VMap[&*I] = ActualArg;
18260b57cec5SDimitry Andric     }
18270b57cec5SDimitry Andric 
18285ffd83dbSDimitry Andric     // TODO: Remove this when users have been updated to the assume bundles.
18290b57cec5SDimitry Andric     // Add alignment assumptions if necessary. We do this before the inlined
18300b57cec5SDimitry Andric     // instructions are actually cloned into the caller so that we can easily
18310b57cec5SDimitry Andric     // check what will be known at the start of the inlined code.
18325ffd83dbSDimitry Andric     AddAlignmentAssumptions(CB, IFI);
18335ffd83dbSDimitry Andric 
18345ffd83dbSDimitry Andric     AssumptionCache *AC =
18355ffd83dbSDimitry Andric         IFI.GetAssumptionCache ? &IFI.GetAssumptionCache(*Caller) : nullptr;
18365ffd83dbSDimitry Andric 
18375ffd83dbSDimitry Andric     /// Preserve all attributes on of the call and its parameters.
18385ffd83dbSDimitry Andric     salvageKnowledge(&CB, AC);
18390b57cec5SDimitry Andric 
18400b57cec5SDimitry Andric     // We want the inliner to prune the code as it copies.  We would LOVE to
18410b57cec5SDimitry Andric     // have no dead or constant instructions leftover after inlining occurs
18420b57cec5SDimitry Andric     // (which can happen, e.g., because an argument was constant), but we'll be
18430b57cec5SDimitry Andric     // happy with whatever the cloner can do.
18440b57cec5SDimitry Andric     CloneAndPruneFunctionInto(Caller, CalledFunc, VMap,
18450b57cec5SDimitry Andric                               /*ModuleLevelChanges=*/false, Returns, ".i",
18465ffd83dbSDimitry Andric                               &InlinedFunctionInfo, &CB);
18470b57cec5SDimitry Andric     // Remember the first block that is newly cloned over.
18480b57cec5SDimitry Andric     FirstNewBlock = LastBlock; ++FirstNewBlock;
18490b57cec5SDimitry Andric 
18500b57cec5SDimitry Andric     if (IFI.CallerBFI != nullptr && IFI.CalleeBFI != nullptr)
18510b57cec5SDimitry Andric       // Update the BFI of blocks cloned into the caller.
18520b57cec5SDimitry Andric       updateCallerBFI(OrigBB, VMap, IFI.CallerBFI, IFI.CalleeBFI,
18530b57cec5SDimitry Andric                       CalledFunc->front());
18540b57cec5SDimitry Andric 
18555ffd83dbSDimitry Andric     updateCallProfile(CalledFunc, VMap, CalledFunc->getEntryCount(), CB,
18560b57cec5SDimitry Andric                       IFI.PSI, IFI.CallerBFI);
18570b57cec5SDimitry Andric 
18580b57cec5SDimitry Andric     // Inject byval arguments initialization.
18590b57cec5SDimitry Andric     for (std::pair<Value*, Value*> &Init : ByValInit)
18600b57cec5SDimitry Andric       HandleByValArgumentInit(Init.first, Init.second, Caller->getParent(),
18610b57cec5SDimitry Andric                               &*FirstNewBlock, IFI);
18620b57cec5SDimitry Andric 
18630b57cec5SDimitry Andric     Optional<OperandBundleUse> ParentDeopt =
18645ffd83dbSDimitry Andric         CB.getOperandBundle(LLVMContext::OB_deopt);
18650b57cec5SDimitry Andric     if (ParentDeopt) {
18660b57cec5SDimitry Andric       SmallVector<OperandBundleDef, 2> OpDefs;
18670b57cec5SDimitry Andric 
18680b57cec5SDimitry Andric       for (auto &VH : InlinedFunctionInfo.OperandBundleCallSites) {
18695ffd83dbSDimitry Andric         CallBase *ICS = dyn_cast_or_null<CallBase>(VH);
18705ffd83dbSDimitry Andric         if (!ICS)
18715ffd83dbSDimitry Andric           continue; // instruction was DCE'd or RAUW'ed to undef
18720b57cec5SDimitry Andric 
18730b57cec5SDimitry Andric         OpDefs.clear();
18740b57cec5SDimitry Andric 
18755ffd83dbSDimitry Andric         OpDefs.reserve(ICS->getNumOperandBundles());
18760b57cec5SDimitry Andric 
18775ffd83dbSDimitry Andric         for (unsigned COBi = 0, COBe = ICS->getNumOperandBundles(); COBi < COBe;
18785ffd83dbSDimitry Andric              ++COBi) {
18795ffd83dbSDimitry Andric           auto ChildOB = ICS->getOperandBundleAt(COBi);
18800b57cec5SDimitry Andric           if (ChildOB.getTagID() != LLVMContext::OB_deopt) {
18810b57cec5SDimitry Andric             // If the inlined call has other operand bundles, let them be
18820b57cec5SDimitry Andric             OpDefs.emplace_back(ChildOB);
18830b57cec5SDimitry Andric             continue;
18840b57cec5SDimitry Andric           }
18850b57cec5SDimitry Andric 
18860b57cec5SDimitry Andric           // It may be useful to separate this logic (of handling operand
18870b57cec5SDimitry Andric           // bundles) out to a separate "policy" component if this gets crowded.
18880b57cec5SDimitry Andric           // Prepend the parent's deoptimization continuation to the newly
18890b57cec5SDimitry Andric           // inlined call's deoptimization continuation.
18900b57cec5SDimitry Andric           std::vector<Value *> MergedDeoptArgs;
18910b57cec5SDimitry Andric           MergedDeoptArgs.reserve(ParentDeopt->Inputs.size() +
18920b57cec5SDimitry Andric                                   ChildOB.Inputs.size());
18930b57cec5SDimitry Andric 
1894*e8d8bef9SDimitry Andric           llvm::append_range(MergedDeoptArgs, ParentDeopt->Inputs);
1895*e8d8bef9SDimitry Andric           llvm::append_range(MergedDeoptArgs, ChildOB.Inputs);
18960b57cec5SDimitry Andric 
18970b57cec5SDimitry Andric           OpDefs.emplace_back("deopt", std::move(MergedDeoptArgs));
18980b57cec5SDimitry Andric         }
18990b57cec5SDimitry Andric 
19005ffd83dbSDimitry Andric         Instruction *NewI = CallBase::Create(ICS, OpDefs, ICS);
19010b57cec5SDimitry Andric 
19020b57cec5SDimitry Andric         // Note: the RAUW does the appropriate fixup in VMap, so we need to do
19030b57cec5SDimitry Andric         // this even if the call returns void.
19045ffd83dbSDimitry Andric         ICS->replaceAllUsesWith(NewI);
19050b57cec5SDimitry Andric 
19060b57cec5SDimitry Andric         VH = nullptr;
19075ffd83dbSDimitry Andric         ICS->eraseFromParent();
19080b57cec5SDimitry Andric       }
19090b57cec5SDimitry Andric     }
19100b57cec5SDimitry Andric 
19110b57cec5SDimitry Andric     // Update the callgraph if requested.
19120b57cec5SDimitry Andric     if (IFI.CG)
19135ffd83dbSDimitry Andric       UpdateCallGraphAfterInlining(CB, FirstNewBlock, VMap, IFI);
19140b57cec5SDimitry Andric 
19150b57cec5SDimitry Andric     // For 'nodebug' functions, the associated DISubprogram is always null.
19160b57cec5SDimitry Andric     // Conservatively avoid propagating the callsite debug location to
19170b57cec5SDimitry Andric     // instructions inlined from a function whose DISubprogram is not null.
19185ffd83dbSDimitry Andric     fixupLineNumbers(Caller, FirstNewBlock, &CB,
19190b57cec5SDimitry Andric                      CalledFunc->getSubprogram() != nullptr);
19200b57cec5SDimitry Andric 
1921*e8d8bef9SDimitry Andric     // Now clone the inlined noalias scope metadata.
1922*e8d8bef9SDimitry Andric     SAMetadataCloner.clone();
1923*e8d8bef9SDimitry Andric     SAMetadataCloner.remap(VMap);
19240b57cec5SDimitry Andric 
19250b57cec5SDimitry Andric     // Add noalias metadata if necessary.
19265ffd83dbSDimitry Andric     AddAliasScopeMetadata(CB, VMap, DL, CalleeAAR);
19275ffd83dbSDimitry Andric 
19285ffd83dbSDimitry Andric     // Clone return attributes on the callsite into the calls within the inlined
19295ffd83dbSDimitry Andric     // function which feed into its return value.
19305ffd83dbSDimitry Andric     AddReturnAttributes(CB, VMap);
19310b57cec5SDimitry Andric 
1932*e8d8bef9SDimitry Andric     // Propagate metadata on the callsite if necessary.
1933*e8d8bef9SDimitry Andric     PropagateCallSiteMetadata(CB, VMap);
19340b57cec5SDimitry Andric 
19350b57cec5SDimitry Andric     // Register any cloned assumptions.
19360b57cec5SDimitry Andric     if (IFI.GetAssumptionCache)
19370b57cec5SDimitry Andric       for (BasicBlock &NewBlock :
19380b57cec5SDimitry Andric            make_range(FirstNewBlock->getIterator(), Caller->end()))
19395ffd83dbSDimitry Andric         for (Instruction &I : NewBlock)
19400b57cec5SDimitry Andric           if (auto *II = dyn_cast<IntrinsicInst>(&I))
19410b57cec5SDimitry Andric             if (II->getIntrinsicID() == Intrinsic::assume)
19425ffd83dbSDimitry Andric               IFI.GetAssumptionCache(*Caller).registerAssumption(II);
19430b57cec5SDimitry Andric   }
19440b57cec5SDimitry Andric 
19450b57cec5SDimitry Andric   // If there are any alloca instructions in the block that used to be the entry
19460b57cec5SDimitry Andric   // block for the callee, move them to the entry block of the caller.  First
19470b57cec5SDimitry Andric   // calculate which instruction they should be inserted before.  We insert the
19480b57cec5SDimitry Andric   // instructions at the end of the current alloca list.
19490b57cec5SDimitry Andric   {
19500b57cec5SDimitry Andric     BasicBlock::iterator InsertPoint = Caller->begin()->begin();
19510b57cec5SDimitry Andric     for (BasicBlock::iterator I = FirstNewBlock->begin(),
19520b57cec5SDimitry Andric          E = FirstNewBlock->end(); I != E; ) {
19530b57cec5SDimitry Andric       AllocaInst *AI = dyn_cast<AllocaInst>(I++);
19540b57cec5SDimitry Andric       if (!AI) continue;
19550b57cec5SDimitry Andric 
19560b57cec5SDimitry Andric       // If the alloca is now dead, remove it.  This often occurs due to code
19570b57cec5SDimitry Andric       // specialization.
19580b57cec5SDimitry Andric       if (AI->use_empty()) {
19590b57cec5SDimitry Andric         AI->eraseFromParent();
19600b57cec5SDimitry Andric         continue;
19610b57cec5SDimitry Andric       }
19620b57cec5SDimitry Andric 
19630b57cec5SDimitry Andric       if (!allocaWouldBeStaticInEntry(AI))
19640b57cec5SDimitry Andric         continue;
19650b57cec5SDimitry Andric 
19660b57cec5SDimitry Andric       // Keep track of the static allocas that we inline into the caller.
19670b57cec5SDimitry Andric       IFI.StaticAllocas.push_back(AI);
19680b57cec5SDimitry Andric 
19690b57cec5SDimitry Andric       // Scan for the block of allocas that we can move over, and move them
19700b57cec5SDimitry Andric       // all at once.
19710b57cec5SDimitry Andric       while (isa<AllocaInst>(I) &&
1972480093f4SDimitry Andric              !cast<AllocaInst>(I)->use_empty() &&
19730b57cec5SDimitry Andric              allocaWouldBeStaticInEntry(cast<AllocaInst>(I))) {
19740b57cec5SDimitry Andric         IFI.StaticAllocas.push_back(cast<AllocaInst>(I));
19750b57cec5SDimitry Andric         ++I;
19760b57cec5SDimitry Andric       }
19770b57cec5SDimitry Andric 
19780b57cec5SDimitry Andric       // Transfer all of the allocas over in a block.  Using splice means
19790b57cec5SDimitry Andric       // that the instructions aren't removed from the symbol table, then
19800b57cec5SDimitry Andric       // reinserted.
19810b57cec5SDimitry Andric       Caller->getEntryBlock().getInstList().splice(
19820b57cec5SDimitry Andric           InsertPoint, FirstNewBlock->getInstList(), AI->getIterator(), I);
19830b57cec5SDimitry Andric     }
19840b57cec5SDimitry Andric   }
19850b57cec5SDimitry Andric 
19860b57cec5SDimitry Andric   SmallVector<Value*,4> VarArgsToForward;
19870b57cec5SDimitry Andric   SmallVector<AttributeSet, 4> VarArgsAttrs;
19880b57cec5SDimitry Andric   for (unsigned i = CalledFunc->getFunctionType()->getNumParams();
19895ffd83dbSDimitry Andric        i < CB.getNumArgOperands(); i++) {
19905ffd83dbSDimitry Andric     VarArgsToForward.push_back(CB.getArgOperand(i));
19915ffd83dbSDimitry Andric     VarArgsAttrs.push_back(CB.getAttributes().getParamAttributes(i));
19920b57cec5SDimitry Andric   }
19930b57cec5SDimitry Andric 
19940b57cec5SDimitry Andric   bool InlinedMustTailCalls = false, InlinedDeoptimizeCalls = false;
19950b57cec5SDimitry Andric   if (InlinedFunctionInfo.ContainsCalls) {
19960b57cec5SDimitry Andric     CallInst::TailCallKind CallSiteTailKind = CallInst::TCK_None;
19975ffd83dbSDimitry Andric     if (CallInst *CI = dyn_cast<CallInst>(&CB))
19980b57cec5SDimitry Andric       CallSiteTailKind = CI->getTailCallKind();
19990b57cec5SDimitry Andric 
20000b57cec5SDimitry Andric     // For inlining purposes, the "notail" marker is the same as no marker.
20010b57cec5SDimitry Andric     if (CallSiteTailKind == CallInst::TCK_NoTail)
20020b57cec5SDimitry Andric       CallSiteTailKind = CallInst::TCK_None;
20030b57cec5SDimitry Andric 
20040b57cec5SDimitry Andric     for (Function::iterator BB = FirstNewBlock, E = Caller->end(); BB != E;
20050b57cec5SDimitry Andric          ++BB) {
20060b57cec5SDimitry Andric       for (auto II = BB->begin(); II != BB->end();) {
20070b57cec5SDimitry Andric         Instruction &I = *II++;
20080b57cec5SDimitry Andric         CallInst *CI = dyn_cast<CallInst>(&I);
20090b57cec5SDimitry Andric         if (!CI)
20100b57cec5SDimitry Andric           continue;
20110b57cec5SDimitry Andric 
20120b57cec5SDimitry Andric         // Forward varargs from inlined call site to calls to the
20130b57cec5SDimitry Andric         // ForwardVarArgsTo function, if requested, and to musttail calls.
20140b57cec5SDimitry Andric         if (!VarArgsToForward.empty() &&
20150b57cec5SDimitry Andric             ((ForwardVarArgsTo &&
20160b57cec5SDimitry Andric               CI->getCalledFunction() == ForwardVarArgsTo) ||
20170b57cec5SDimitry Andric              CI->isMustTailCall())) {
20180b57cec5SDimitry Andric           // Collect attributes for non-vararg parameters.
20190b57cec5SDimitry Andric           AttributeList Attrs = CI->getAttributes();
20200b57cec5SDimitry Andric           SmallVector<AttributeSet, 8> ArgAttrs;
20210b57cec5SDimitry Andric           if (!Attrs.isEmpty() || !VarArgsAttrs.empty()) {
20220b57cec5SDimitry Andric             for (unsigned ArgNo = 0;
20230b57cec5SDimitry Andric                  ArgNo < CI->getFunctionType()->getNumParams(); ++ArgNo)
20240b57cec5SDimitry Andric               ArgAttrs.push_back(Attrs.getParamAttributes(ArgNo));
20250b57cec5SDimitry Andric           }
20260b57cec5SDimitry Andric 
20270b57cec5SDimitry Andric           // Add VarArg attributes.
20280b57cec5SDimitry Andric           ArgAttrs.append(VarArgsAttrs.begin(), VarArgsAttrs.end());
20290b57cec5SDimitry Andric           Attrs = AttributeList::get(CI->getContext(), Attrs.getFnAttributes(),
20300b57cec5SDimitry Andric                                      Attrs.getRetAttributes(), ArgAttrs);
20310b57cec5SDimitry Andric           // Add VarArgs to existing parameters.
20320b57cec5SDimitry Andric           SmallVector<Value *, 6> Params(CI->arg_operands());
20330b57cec5SDimitry Andric           Params.append(VarArgsToForward.begin(), VarArgsToForward.end());
20340b57cec5SDimitry Andric           CallInst *NewCI = CallInst::Create(
20350b57cec5SDimitry Andric               CI->getFunctionType(), CI->getCalledOperand(), Params, "", CI);
20360b57cec5SDimitry Andric           NewCI->setDebugLoc(CI->getDebugLoc());
20370b57cec5SDimitry Andric           NewCI->setAttributes(Attrs);
20380b57cec5SDimitry Andric           NewCI->setCallingConv(CI->getCallingConv());
20390b57cec5SDimitry Andric           CI->replaceAllUsesWith(NewCI);
20400b57cec5SDimitry Andric           CI->eraseFromParent();
20410b57cec5SDimitry Andric           CI = NewCI;
20420b57cec5SDimitry Andric         }
20430b57cec5SDimitry Andric 
20440b57cec5SDimitry Andric         if (Function *F = CI->getCalledFunction())
20450b57cec5SDimitry Andric           InlinedDeoptimizeCalls |=
20460b57cec5SDimitry Andric               F->getIntrinsicID() == Intrinsic::experimental_deoptimize;
20470b57cec5SDimitry Andric 
20480b57cec5SDimitry Andric         // We need to reduce the strength of any inlined tail calls.  For
20490b57cec5SDimitry Andric         // musttail, we have to avoid introducing potential unbounded stack
20500b57cec5SDimitry Andric         // growth.  For example, if functions 'f' and 'g' are mutually recursive
20510b57cec5SDimitry Andric         // with musttail, we can inline 'g' into 'f' so long as we preserve
20520b57cec5SDimitry Andric         // musttail on the cloned call to 'f'.  If either the inlined call site
20530b57cec5SDimitry Andric         // or the cloned call site is *not* musttail, the program already has
20540b57cec5SDimitry Andric         // one frame of stack growth, so it's safe to remove musttail.  Here is
20550b57cec5SDimitry Andric         // a table of example transformations:
20560b57cec5SDimitry Andric         //
20570b57cec5SDimitry Andric         //    f -> musttail g -> musttail f  ==>  f -> musttail f
20580b57cec5SDimitry Andric         //    f -> musttail g ->     tail f  ==>  f ->     tail f
20590b57cec5SDimitry Andric         //    f ->          g -> musttail f  ==>  f ->          f
20600b57cec5SDimitry Andric         //    f ->          g ->     tail f  ==>  f ->          f
20610b57cec5SDimitry Andric         //
20620b57cec5SDimitry Andric         // Inlined notail calls should remain notail calls.
20630b57cec5SDimitry Andric         CallInst::TailCallKind ChildTCK = CI->getTailCallKind();
20640b57cec5SDimitry Andric         if (ChildTCK != CallInst::TCK_NoTail)
20650b57cec5SDimitry Andric           ChildTCK = std::min(CallSiteTailKind, ChildTCK);
20660b57cec5SDimitry Andric         CI->setTailCallKind(ChildTCK);
20670b57cec5SDimitry Andric         InlinedMustTailCalls |= CI->isMustTailCall();
20680b57cec5SDimitry Andric 
20690b57cec5SDimitry Andric         // Calls inlined through a 'nounwind' call site should be marked
20700b57cec5SDimitry Andric         // 'nounwind'.
20710b57cec5SDimitry Andric         if (MarkNoUnwind)
20720b57cec5SDimitry Andric           CI->setDoesNotThrow();
20730b57cec5SDimitry Andric       }
20740b57cec5SDimitry Andric     }
20750b57cec5SDimitry Andric   }
20760b57cec5SDimitry Andric 
20770b57cec5SDimitry Andric   // Leave lifetime markers for the static alloca's, scoping them to the
20780b57cec5SDimitry Andric   // function we just inlined.
20790b57cec5SDimitry Andric   if (InsertLifetime && !IFI.StaticAllocas.empty()) {
20800b57cec5SDimitry Andric     IRBuilder<> builder(&FirstNewBlock->front());
20810b57cec5SDimitry Andric     for (unsigned ai = 0, ae = IFI.StaticAllocas.size(); ai != ae; ++ai) {
20820b57cec5SDimitry Andric       AllocaInst *AI = IFI.StaticAllocas[ai];
20830b57cec5SDimitry Andric       // Don't mark swifterror allocas. They can't have bitcast uses.
20840b57cec5SDimitry Andric       if (AI->isSwiftError())
20850b57cec5SDimitry Andric         continue;
20860b57cec5SDimitry Andric 
20870b57cec5SDimitry Andric       // If the alloca is already scoped to something smaller than the whole
20880b57cec5SDimitry Andric       // function then there's no need to add redundant, less accurate markers.
20890b57cec5SDimitry Andric       if (hasLifetimeMarkers(AI))
20900b57cec5SDimitry Andric         continue;
20910b57cec5SDimitry Andric 
20920b57cec5SDimitry Andric       // Try to determine the size of the allocation.
20930b57cec5SDimitry Andric       ConstantInt *AllocaSize = nullptr;
20940b57cec5SDimitry Andric       if (ConstantInt *AIArraySize =
20950b57cec5SDimitry Andric           dyn_cast<ConstantInt>(AI->getArraySize())) {
20960b57cec5SDimitry Andric         auto &DL = Caller->getParent()->getDataLayout();
20970b57cec5SDimitry Andric         Type *AllocaType = AI->getAllocatedType();
2098*e8d8bef9SDimitry Andric         TypeSize AllocaTypeSize = DL.getTypeAllocSize(AllocaType);
20990b57cec5SDimitry Andric         uint64_t AllocaArraySize = AIArraySize->getLimitedValue();
21000b57cec5SDimitry Andric 
21010b57cec5SDimitry Andric         // Don't add markers for zero-sized allocas.
21020b57cec5SDimitry Andric         if (AllocaArraySize == 0)
21030b57cec5SDimitry Andric           continue;
21040b57cec5SDimitry Andric 
21050b57cec5SDimitry Andric         // Check that array size doesn't saturate uint64_t and doesn't
21060b57cec5SDimitry Andric         // overflow when it's multiplied by type size.
2107*e8d8bef9SDimitry Andric         if (!AllocaTypeSize.isScalable() &&
2108*e8d8bef9SDimitry Andric             AllocaArraySize != std::numeric_limits<uint64_t>::max() &&
21090b57cec5SDimitry Andric             std::numeric_limits<uint64_t>::max() / AllocaArraySize >=
2110*e8d8bef9SDimitry Andric                 AllocaTypeSize.getFixedSize()) {
21110b57cec5SDimitry Andric           AllocaSize = ConstantInt::get(Type::getInt64Ty(AI->getContext()),
21120b57cec5SDimitry Andric                                         AllocaArraySize * AllocaTypeSize);
21130b57cec5SDimitry Andric         }
21140b57cec5SDimitry Andric       }
21150b57cec5SDimitry Andric 
21160b57cec5SDimitry Andric       builder.CreateLifetimeStart(AI, AllocaSize);
21170b57cec5SDimitry Andric       for (ReturnInst *RI : Returns) {
21180b57cec5SDimitry Andric         // Don't insert llvm.lifetime.end calls between a musttail or deoptimize
21190b57cec5SDimitry Andric         // call and a return.  The return kills all local allocas.
21200b57cec5SDimitry Andric         if (InlinedMustTailCalls &&
21210b57cec5SDimitry Andric             RI->getParent()->getTerminatingMustTailCall())
21220b57cec5SDimitry Andric           continue;
21230b57cec5SDimitry Andric         if (InlinedDeoptimizeCalls &&
21240b57cec5SDimitry Andric             RI->getParent()->getTerminatingDeoptimizeCall())
21250b57cec5SDimitry Andric           continue;
21260b57cec5SDimitry Andric         IRBuilder<>(RI).CreateLifetimeEnd(AI, AllocaSize);
21270b57cec5SDimitry Andric       }
21280b57cec5SDimitry Andric     }
21290b57cec5SDimitry Andric   }
21300b57cec5SDimitry Andric 
21310b57cec5SDimitry Andric   // If the inlined code contained dynamic alloca instructions, wrap the inlined
21320b57cec5SDimitry Andric   // code with llvm.stacksave/llvm.stackrestore intrinsics.
21330b57cec5SDimitry Andric   if (InlinedFunctionInfo.ContainsDynamicAllocas) {
21340b57cec5SDimitry Andric     Module *M = Caller->getParent();
21350b57cec5SDimitry Andric     // Get the two intrinsics we care about.
21360b57cec5SDimitry Andric     Function *StackSave = Intrinsic::getDeclaration(M, Intrinsic::stacksave);
21370b57cec5SDimitry Andric     Function *StackRestore=Intrinsic::getDeclaration(M,Intrinsic::stackrestore);
21380b57cec5SDimitry Andric 
21390b57cec5SDimitry Andric     // Insert the llvm.stacksave.
21400b57cec5SDimitry Andric     CallInst *SavedPtr = IRBuilder<>(&*FirstNewBlock, FirstNewBlock->begin())
21410b57cec5SDimitry Andric                              .CreateCall(StackSave, {}, "savedstack");
21420b57cec5SDimitry Andric 
21430b57cec5SDimitry Andric     // Insert a call to llvm.stackrestore before any return instructions in the
21440b57cec5SDimitry Andric     // inlined function.
21450b57cec5SDimitry Andric     for (ReturnInst *RI : Returns) {
21460b57cec5SDimitry Andric       // Don't insert llvm.stackrestore calls between a musttail or deoptimize
21470b57cec5SDimitry Andric       // call and a return.  The return will restore the stack pointer.
21480b57cec5SDimitry Andric       if (InlinedMustTailCalls && RI->getParent()->getTerminatingMustTailCall())
21490b57cec5SDimitry Andric         continue;
21500b57cec5SDimitry Andric       if (InlinedDeoptimizeCalls && RI->getParent()->getTerminatingDeoptimizeCall())
21510b57cec5SDimitry Andric         continue;
21520b57cec5SDimitry Andric       IRBuilder<>(RI).CreateCall(StackRestore, SavedPtr);
21530b57cec5SDimitry Andric     }
21540b57cec5SDimitry Andric   }
21550b57cec5SDimitry Andric 
21560b57cec5SDimitry Andric   // If we are inlining for an invoke instruction, we must make sure to rewrite
21570b57cec5SDimitry Andric   // any call instructions into invoke instructions.  This is sensitive to which
21580b57cec5SDimitry Andric   // funclet pads were top-level in the inlinee, so must be done before
21590b57cec5SDimitry Andric   // rewriting the "parent pad" links.
21605ffd83dbSDimitry Andric   if (auto *II = dyn_cast<InvokeInst>(&CB)) {
21610b57cec5SDimitry Andric     BasicBlock *UnwindDest = II->getUnwindDest();
21620b57cec5SDimitry Andric     Instruction *FirstNonPHI = UnwindDest->getFirstNonPHI();
21630b57cec5SDimitry Andric     if (isa<LandingPadInst>(FirstNonPHI)) {
21640b57cec5SDimitry Andric       HandleInlinedLandingPad(II, &*FirstNewBlock, InlinedFunctionInfo);
21650b57cec5SDimitry Andric     } else {
21660b57cec5SDimitry Andric       HandleInlinedEHPad(II, &*FirstNewBlock, InlinedFunctionInfo);
21670b57cec5SDimitry Andric     }
21680b57cec5SDimitry Andric   }
21690b57cec5SDimitry Andric 
21700b57cec5SDimitry Andric   // Update the lexical scopes of the new funclets and callsites.
21710b57cec5SDimitry Andric   // Anything that had 'none' as its parent is now nested inside the callsite's
21720b57cec5SDimitry Andric   // EHPad.
21730b57cec5SDimitry Andric 
21740b57cec5SDimitry Andric   if (CallSiteEHPad) {
21750b57cec5SDimitry Andric     for (Function::iterator BB = FirstNewBlock->getIterator(),
21760b57cec5SDimitry Andric                             E = Caller->end();
21770b57cec5SDimitry Andric          BB != E; ++BB) {
21780b57cec5SDimitry Andric       // Add bundle operands to any top-level call sites.
21790b57cec5SDimitry Andric       SmallVector<OperandBundleDef, 1> OpBundles;
21800b57cec5SDimitry Andric       for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E;) {
21815ffd83dbSDimitry Andric         CallBase *I = dyn_cast<CallBase>(&*BBI++);
21825ffd83dbSDimitry Andric         if (!I)
21830b57cec5SDimitry Andric           continue;
21840b57cec5SDimitry Andric 
21850b57cec5SDimitry Andric         // Skip call sites which are nounwind intrinsics.
21860b57cec5SDimitry Andric         auto *CalledFn =
21875ffd83dbSDimitry Andric             dyn_cast<Function>(I->getCalledOperand()->stripPointerCasts());
21885ffd83dbSDimitry Andric         if (CalledFn && CalledFn->isIntrinsic() && I->doesNotThrow())
21890b57cec5SDimitry Andric           continue;
21900b57cec5SDimitry Andric 
21910b57cec5SDimitry Andric         // Skip call sites which already have a "funclet" bundle.
21925ffd83dbSDimitry Andric         if (I->getOperandBundle(LLVMContext::OB_funclet))
21930b57cec5SDimitry Andric           continue;
21940b57cec5SDimitry Andric 
21955ffd83dbSDimitry Andric         I->getOperandBundlesAsDefs(OpBundles);
21960b57cec5SDimitry Andric         OpBundles.emplace_back("funclet", CallSiteEHPad);
21970b57cec5SDimitry Andric 
21985ffd83dbSDimitry Andric         Instruction *NewInst = CallBase::Create(I, OpBundles, I);
21990b57cec5SDimitry Andric         NewInst->takeName(I);
22000b57cec5SDimitry Andric         I->replaceAllUsesWith(NewInst);
22010b57cec5SDimitry Andric         I->eraseFromParent();
22020b57cec5SDimitry Andric 
22030b57cec5SDimitry Andric         OpBundles.clear();
22040b57cec5SDimitry Andric       }
22050b57cec5SDimitry Andric 
22060b57cec5SDimitry Andric       // It is problematic if the inlinee has a cleanupret which unwinds to
22070b57cec5SDimitry Andric       // caller and we inline it into a call site which doesn't unwind but into
22080b57cec5SDimitry Andric       // an EH pad that does.  Such an edge must be dynamically unreachable.
22090b57cec5SDimitry Andric       // As such, we replace the cleanupret with unreachable.
22100b57cec5SDimitry Andric       if (auto *CleanupRet = dyn_cast<CleanupReturnInst>(BB->getTerminator()))
22110b57cec5SDimitry Andric         if (CleanupRet->unwindsToCaller() && EHPadForCallUnwindsLocally)
22120b57cec5SDimitry Andric           changeToUnreachable(CleanupRet, /*UseLLVMTrap=*/false);
22130b57cec5SDimitry Andric 
22140b57cec5SDimitry Andric       Instruction *I = BB->getFirstNonPHI();
22150b57cec5SDimitry Andric       if (!I->isEHPad())
22160b57cec5SDimitry Andric         continue;
22170b57cec5SDimitry Andric 
22180b57cec5SDimitry Andric       if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(I)) {
22190b57cec5SDimitry Andric         if (isa<ConstantTokenNone>(CatchSwitch->getParentPad()))
22200b57cec5SDimitry Andric           CatchSwitch->setParentPad(CallSiteEHPad);
22210b57cec5SDimitry Andric       } else {
22220b57cec5SDimitry Andric         auto *FPI = cast<FuncletPadInst>(I);
22230b57cec5SDimitry Andric         if (isa<ConstantTokenNone>(FPI->getParentPad()))
22240b57cec5SDimitry Andric           FPI->setParentPad(CallSiteEHPad);
22250b57cec5SDimitry Andric       }
22260b57cec5SDimitry Andric     }
22270b57cec5SDimitry Andric   }
22280b57cec5SDimitry Andric 
22290b57cec5SDimitry Andric   if (InlinedDeoptimizeCalls) {
22300b57cec5SDimitry Andric     // We need to at least remove the deoptimizing returns from the Return set,
22310b57cec5SDimitry Andric     // so that the control flow from those returns does not get merged into the
22320b57cec5SDimitry Andric     // caller (but terminate it instead).  If the caller's return type does not
22330b57cec5SDimitry Andric     // match the callee's return type, we also need to change the return type of
22340b57cec5SDimitry Andric     // the intrinsic.
22355ffd83dbSDimitry Andric     if (Caller->getReturnType() == CB.getType()) {
2236*e8d8bef9SDimitry Andric       llvm::erase_if(Returns, [](ReturnInst *RI) {
22370b57cec5SDimitry Andric         return RI->getParent()->getTerminatingDeoptimizeCall() != nullptr;
22380b57cec5SDimitry Andric       });
22390b57cec5SDimitry Andric     } else {
22400b57cec5SDimitry Andric       SmallVector<ReturnInst *, 8> NormalReturns;
22410b57cec5SDimitry Andric       Function *NewDeoptIntrinsic = Intrinsic::getDeclaration(
22420b57cec5SDimitry Andric           Caller->getParent(), Intrinsic::experimental_deoptimize,
22430b57cec5SDimitry Andric           {Caller->getReturnType()});
22440b57cec5SDimitry Andric 
22450b57cec5SDimitry Andric       for (ReturnInst *RI : Returns) {
22460b57cec5SDimitry Andric         CallInst *DeoptCall = RI->getParent()->getTerminatingDeoptimizeCall();
22470b57cec5SDimitry Andric         if (!DeoptCall) {
22480b57cec5SDimitry Andric           NormalReturns.push_back(RI);
22490b57cec5SDimitry Andric           continue;
22500b57cec5SDimitry Andric         }
22510b57cec5SDimitry Andric 
22520b57cec5SDimitry Andric         // The calling convention on the deoptimize call itself may be bogus,
22530b57cec5SDimitry Andric         // since the code we're inlining may have undefined behavior (and may
22540b57cec5SDimitry Andric         // never actually execute at runtime); but all
22550b57cec5SDimitry Andric         // @llvm.experimental.deoptimize declarations have to have the same
22560b57cec5SDimitry Andric         // calling convention in a well-formed module.
22570b57cec5SDimitry Andric         auto CallingConv = DeoptCall->getCalledFunction()->getCallingConv();
22580b57cec5SDimitry Andric         NewDeoptIntrinsic->setCallingConv(CallingConv);
22590b57cec5SDimitry Andric         auto *CurBB = RI->getParent();
22600b57cec5SDimitry Andric         RI->eraseFromParent();
22610b57cec5SDimitry Andric 
2262*e8d8bef9SDimitry Andric         SmallVector<Value *, 4> CallArgs(DeoptCall->args());
22630b57cec5SDimitry Andric 
22640b57cec5SDimitry Andric         SmallVector<OperandBundleDef, 1> OpBundles;
22650b57cec5SDimitry Andric         DeoptCall->getOperandBundlesAsDefs(OpBundles);
22660b57cec5SDimitry Andric         DeoptCall->eraseFromParent();
22670b57cec5SDimitry Andric         assert(!OpBundles.empty() &&
22680b57cec5SDimitry Andric                "Expected at least the deopt operand bundle");
22690b57cec5SDimitry Andric 
22700b57cec5SDimitry Andric         IRBuilder<> Builder(CurBB);
22710b57cec5SDimitry Andric         CallInst *NewDeoptCall =
22720b57cec5SDimitry Andric             Builder.CreateCall(NewDeoptIntrinsic, CallArgs, OpBundles);
22730b57cec5SDimitry Andric         NewDeoptCall->setCallingConv(CallingConv);
22740b57cec5SDimitry Andric         if (NewDeoptCall->getType()->isVoidTy())
22750b57cec5SDimitry Andric           Builder.CreateRetVoid();
22760b57cec5SDimitry Andric         else
22770b57cec5SDimitry Andric           Builder.CreateRet(NewDeoptCall);
22780b57cec5SDimitry Andric       }
22790b57cec5SDimitry Andric 
22800b57cec5SDimitry Andric       // Leave behind the normal returns so we can merge control flow.
22810b57cec5SDimitry Andric       std::swap(Returns, NormalReturns);
22820b57cec5SDimitry Andric     }
22830b57cec5SDimitry Andric   }
22840b57cec5SDimitry Andric 
22850b57cec5SDimitry Andric   // Handle any inlined musttail call sites.  In order for a new call site to be
22860b57cec5SDimitry Andric   // musttail, the source of the clone and the inlined call site must have been
22870b57cec5SDimitry Andric   // musttail.  Therefore it's safe to return without merging control into the
22880b57cec5SDimitry Andric   // phi below.
22890b57cec5SDimitry Andric   if (InlinedMustTailCalls) {
22900b57cec5SDimitry Andric     // Check if we need to bitcast the result of any musttail calls.
22910b57cec5SDimitry Andric     Type *NewRetTy = Caller->getReturnType();
22925ffd83dbSDimitry Andric     bool NeedBitCast = !CB.use_empty() && CB.getType() != NewRetTy;
22930b57cec5SDimitry Andric 
22940b57cec5SDimitry Andric     // Handle the returns preceded by musttail calls separately.
22950b57cec5SDimitry Andric     SmallVector<ReturnInst *, 8> NormalReturns;
22960b57cec5SDimitry Andric     for (ReturnInst *RI : Returns) {
22970b57cec5SDimitry Andric       CallInst *ReturnedMustTail =
22980b57cec5SDimitry Andric           RI->getParent()->getTerminatingMustTailCall();
22990b57cec5SDimitry Andric       if (!ReturnedMustTail) {
23000b57cec5SDimitry Andric         NormalReturns.push_back(RI);
23010b57cec5SDimitry Andric         continue;
23020b57cec5SDimitry Andric       }
23030b57cec5SDimitry Andric       if (!NeedBitCast)
23040b57cec5SDimitry Andric         continue;
23050b57cec5SDimitry Andric 
23060b57cec5SDimitry Andric       // Delete the old return and any preceding bitcast.
23070b57cec5SDimitry Andric       BasicBlock *CurBB = RI->getParent();
23080b57cec5SDimitry Andric       auto *OldCast = dyn_cast_or_null<BitCastInst>(RI->getReturnValue());
23090b57cec5SDimitry Andric       RI->eraseFromParent();
23100b57cec5SDimitry Andric       if (OldCast)
23110b57cec5SDimitry Andric         OldCast->eraseFromParent();
23120b57cec5SDimitry Andric 
23130b57cec5SDimitry Andric       // Insert a new bitcast and return with the right type.
23140b57cec5SDimitry Andric       IRBuilder<> Builder(CurBB);
23150b57cec5SDimitry Andric       Builder.CreateRet(Builder.CreateBitCast(ReturnedMustTail, NewRetTy));
23160b57cec5SDimitry Andric     }
23170b57cec5SDimitry Andric 
23180b57cec5SDimitry Andric     // Leave behind the normal returns so we can merge control flow.
23190b57cec5SDimitry Andric     std::swap(Returns, NormalReturns);
23200b57cec5SDimitry Andric   }
23210b57cec5SDimitry Andric 
23220b57cec5SDimitry Andric   // Now that all of the transforms on the inlined code have taken place but
23230b57cec5SDimitry Andric   // before we splice the inlined code into the CFG and lose track of which
23240b57cec5SDimitry Andric   // blocks were actually inlined, collect the call sites. We only do this if
23250b57cec5SDimitry Andric   // call graph updates weren't requested, as those provide value handle based
23260b57cec5SDimitry Andric   // tracking of inlined call sites instead.
23270b57cec5SDimitry Andric   if (InlinedFunctionInfo.ContainsCalls && !IFI.CG) {
23280b57cec5SDimitry Andric     // Otherwise just collect the raw call sites that were inlined.
23290b57cec5SDimitry Andric     for (BasicBlock &NewBB :
23300b57cec5SDimitry Andric          make_range(FirstNewBlock->getIterator(), Caller->end()))
23310b57cec5SDimitry Andric       for (Instruction &I : NewBB)
23325ffd83dbSDimitry Andric         if (auto *CB = dyn_cast<CallBase>(&I))
23335ffd83dbSDimitry Andric           IFI.InlinedCallSites.push_back(CB);
23340b57cec5SDimitry Andric   }
23350b57cec5SDimitry Andric 
23360b57cec5SDimitry Andric   // If we cloned in _exactly one_ basic block, and if that block ends in a
23370b57cec5SDimitry Andric   // return instruction, we splice the body of the inlined callee directly into
23380b57cec5SDimitry Andric   // the calling basic block.
23390b57cec5SDimitry Andric   if (Returns.size() == 1 && std::distance(FirstNewBlock, Caller->end()) == 1) {
23400b57cec5SDimitry Andric     // Move all of the instructions right before the call.
23415ffd83dbSDimitry Andric     OrigBB->getInstList().splice(CB.getIterator(), FirstNewBlock->getInstList(),
23420b57cec5SDimitry Andric                                  FirstNewBlock->begin(), FirstNewBlock->end());
23430b57cec5SDimitry Andric     // Remove the cloned basic block.
23440b57cec5SDimitry Andric     Caller->getBasicBlockList().pop_back();
23450b57cec5SDimitry Andric 
23460b57cec5SDimitry Andric     // If the call site was an invoke instruction, add a branch to the normal
23470b57cec5SDimitry Andric     // destination.
23485ffd83dbSDimitry Andric     if (InvokeInst *II = dyn_cast<InvokeInst>(&CB)) {
23495ffd83dbSDimitry Andric       BranchInst *NewBr = BranchInst::Create(II->getNormalDest(), &CB);
23500b57cec5SDimitry Andric       NewBr->setDebugLoc(Returns[0]->getDebugLoc());
23510b57cec5SDimitry Andric     }
23520b57cec5SDimitry Andric 
23530b57cec5SDimitry Andric     // If the return instruction returned a value, replace uses of the call with
23540b57cec5SDimitry Andric     // uses of the returned value.
23555ffd83dbSDimitry Andric     if (!CB.use_empty()) {
23560b57cec5SDimitry Andric       ReturnInst *R = Returns[0];
23575ffd83dbSDimitry Andric       if (&CB == R->getReturnValue())
23585ffd83dbSDimitry Andric         CB.replaceAllUsesWith(UndefValue::get(CB.getType()));
23590b57cec5SDimitry Andric       else
23605ffd83dbSDimitry Andric         CB.replaceAllUsesWith(R->getReturnValue());
23610b57cec5SDimitry Andric     }
23620b57cec5SDimitry Andric     // Since we are now done with the Call/Invoke, we can delete it.
23635ffd83dbSDimitry Andric     CB.eraseFromParent();
23640b57cec5SDimitry Andric 
23650b57cec5SDimitry Andric     // Since we are now done with the return instruction, delete it also.
23660b57cec5SDimitry Andric     Returns[0]->eraseFromParent();
23670b57cec5SDimitry Andric 
23680b57cec5SDimitry Andric     // We are now done with the inlining.
23695ffd83dbSDimitry Andric     return InlineResult::success();
23700b57cec5SDimitry Andric   }
23710b57cec5SDimitry Andric 
23720b57cec5SDimitry Andric   // Otherwise, we have the normal case, of more than one block to inline or
23730b57cec5SDimitry Andric   // multiple return sites.
23740b57cec5SDimitry Andric 
23750b57cec5SDimitry Andric   // We want to clone the entire callee function into the hole between the
23760b57cec5SDimitry Andric   // "starter" and "ender" blocks.  How we accomplish this depends on whether
23770b57cec5SDimitry Andric   // this is an invoke instruction or a call instruction.
23780b57cec5SDimitry Andric   BasicBlock *AfterCallBB;
23790b57cec5SDimitry Andric   BranchInst *CreatedBranchToNormalDest = nullptr;
23805ffd83dbSDimitry Andric   if (InvokeInst *II = dyn_cast<InvokeInst>(&CB)) {
23810b57cec5SDimitry Andric 
23820b57cec5SDimitry Andric     // Add an unconditional branch to make this look like the CallInst case...
23835ffd83dbSDimitry Andric     CreatedBranchToNormalDest = BranchInst::Create(II->getNormalDest(), &CB);
23840b57cec5SDimitry Andric 
23850b57cec5SDimitry Andric     // Split the basic block.  This guarantees that no PHI nodes will have to be
23860b57cec5SDimitry Andric     // updated due to new incoming edges, and make the invoke case more
23870b57cec5SDimitry Andric     // symmetric to the call case.
23880b57cec5SDimitry Andric     AfterCallBB =
23890b57cec5SDimitry Andric         OrigBB->splitBasicBlock(CreatedBranchToNormalDest->getIterator(),
23900b57cec5SDimitry Andric                                 CalledFunc->getName() + ".exit");
23910b57cec5SDimitry Andric 
23920b57cec5SDimitry Andric   } else { // It's a call
23930b57cec5SDimitry Andric     // If this is a call instruction, we need to split the basic block that
23940b57cec5SDimitry Andric     // the call lives in.
23950b57cec5SDimitry Andric     //
23965ffd83dbSDimitry Andric     AfterCallBB = OrigBB->splitBasicBlock(CB.getIterator(),
23970b57cec5SDimitry Andric                                           CalledFunc->getName() + ".exit");
23980b57cec5SDimitry Andric   }
23990b57cec5SDimitry Andric 
24000b57cec5SDimitry Andric   if (IFI.CallerBFI) {
24010b57cec5SDimitry Andric     // Copy original BB's block frequency to AfterCallBB
24020b57cec5SDimitry Andric     IFI.CallerBFI->setBlockFreq(
24030b57cec5SDimitry Andric         AfterCallBB, IFI.CallerBFI->getBlockFreq(OrigBB).getFrequency());
24040b57cec5SDimitry Andric   }
24050b57cec5SDimitry Andric 
24060b57cec5SDimitry Andric   // Change the branch that used to go to AfterCallBB to branch to the first
24070b57cec5SDimitry Andric   // basic block of the inlined function.
24080b57cec5SDimitry Andric   //
24090b57cec5SDimitry Andric   Instruction *Br = OrigBB->getTerminator();
24100b57cec5SDimitry Andric   assert(Br && Br->getOpcode() == Instruction::Br &&
24110b57cec5SDimitry Andric          "splitBasicBlock broken!");
24120b57cec5SDimitry Andric   Br->setOperand(0, &*FirstNewBlock);
24130b57cec5SDimitry Andric 
24140b57cec5SDimitry Andric   // Now that the function is correct, make it a little bit nicer.  In
24150b57cec5SDimitry Andric   // particular, move the basic blocks inserted from the end of the function
24160b57cec5SDimitry Andric   // into the space made by splitting the source basic block.
24170b57cec5SDimitry Andric   Caller->getBasicBlockList().splice(AfterCallBB->getIterator(),
24180b57cec5SDimitry Andric                                      Caller->getBasicBlockList(), FirstNewBlock,
24190b57cec5SDimitry Andric                                      Caller->end());
24200b57cec5SDimitry Andric 
24210b57cec5SDimitry Andric   // Handle all of the return instructions that we just cloned in, and eliminate
24220b57cec5SDimitry Andric   // any users of the original call/invoke instruction.
24230b57cec5SDimitry Andric   Type *RTy = CalledFunc->getReturnType();
24240b57cec5SDimitry Andric 
24250b57cec5SDimitry Andric   PHINode *PHI = nullptr;
24260b57cec5SDimitry Andric   if (Returns.size() > 1) {
24270b57cec5SDimitry Andric     // The PHI node should go at the front of the new basic block to merge all
24280b57cec5SDimitry Andric     // possible incoming values.
24295ffd83dbSDimitry Andric     if (!CB.use_empty()) {
24305ffd83dbSDimitry Andric       PHI = PHINode::Create(RTy, Returns.size(), CB.getName(),
24310b57cec5SDimitry Andric                             &AfterCallBB->front());
24320b57cec5SDimitry Andric       // Anything that used the result of the function call should now use the
24330b57cec5SDimitry Andric       // PHI node as their operand.
24345ffd83dbSDimitry Andric       CB.replaceAllUsesWith(PHI);
24350b57cec5SDimitry Andric     }
24360b57cec5SDimitry Andric 
24370b57cec5SDimitry Andric     // Loop over all of the return instructions adding entries to the PHI node
24380b57cec5SDimitry Andric     // as appropriate.
24390b57cec5SDimitry Andric     if (PHI) {
24400b57cec5SDimitry Andric       for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
24410b57cec5SDimitry Andric         ReturnInst *RI = Returns[i];
24420b57cec5SDimitry Andric         assert(RI->getReturnValue()->getType() == PHI->getType() &&
24430b57cec5SDimitry Andric                "Ret value not consistent in function!");
24440b57cec5SDimitry Andric         PHI->addIncoming(RI->getReturnValue(), RI->getParent());
24450b57cec5SDimitry Andric       }
24460b57cec5SDimitry Andric     }
24470b57cec5SDimitry Andric 
24480b57cec5SDimitry Andric     // Add a branch to the merge points and remove return instructions.
24490b57cec5SDimitry Andric     DebugLoc Loc;
24500b57cec5SDimitry Andric     for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
24510b57cec5SDimitry Andric       ReturnInst *RI = Returns[i];
24520b57cec5SDimitry Andric       BranchInst* BI = BranchInst::Create(AfterCallBB, RI);
24530b57cec5SDimitry Andric       Loc = RI->getDebugLoc();
24540b57cec5SDimitry Andric       BI->setDebugLoc(Loc);
24550b57cec5SDimitry Andric       RI->eraseFromParent();
24560b57cec5SDimitry Andric     }
24570b57cec5SDimitry Andric     // We need to set the debug location to *somewhere* inside the
24580b57cec5SDimitry Andric     // inlined function. The line number may be nonsensical, but the
24590b57cec5SDimitry Andric     // instruction will at least be associated with the right
24600b57cec5SDimitry Andric     // function.
24610b57cec5SDimitry Andric     if (CreatedBranchToNormalDest)
24620b57cec5SDimitry Andric       CreatedBranchToNormalDest->setDebugLoc(Loc);
24630b57cec5SDimitry Andric   } else if (!Returns.empty()) {
24640b57cec5SDimitry Andric     // Otherwise, if there is exactly one return value, just replace anything
24650b57cec5SDimitry Andric     // using the return value of the call with the computed value.
24665ffd83dbSDimitry Andric     if (!CB.use_empty()) {
24675ffd83dbSDimitry Andric       if (&CB == Returns[0]->getReturnValue())
24685ffd83dbSDimitry Andric         CB.replaceAllUsesWith(UndefValue::get(CB.getType()));
24690b57cec5SDimitry Andric       else
24705ffd83dbSDimitry Andric         CB.replaceAllUsesWith(Returns[0]->getReturnValue());
24710b57cec5SDimitry Andric     }
24720b57cec5SDimitry Andric 
24730b57cec5SDimitry Andric     // Update PHI nodes that use the ReturnBB to use the AfterCallBB.
24740b57cec5SDimitry Andric     BasicBlock *ReturnBB = Returns[0]->getParent();
24750b57cec5SDimitry Andric     ReturnBB->replaceAllUsesWith(AfterCallBB);
24760b57cec5SDimitry Andric 
24770b57cec5SDimitry Andric     // Splice the code from the return block into the block that it will return
24780b57cec5SDimitry Andric     // to, which contains the code that was after the call.
24790b57cec5SDimitry Andric     AfterCallBB->getInstList().splice(AfterCallBB->begin(),
24800b57cec5SDimitry Andric                                       ReturnBB->getInstList());
24810b57cec5SDimitry Andric 
24820b57cec5SDimitry Andric     if (CreatedBranchToNormalDest)
24830b57cec5SDimitry Andric       CreatedBranchToNormalDest->setDebugLoc(Returns[0]->getDebugLoc());
24840b57cec5SDimitry Andric 
24850b57cec5SDimitry Andric     // Delete the return instruction now and empty ReturnBB now.
24860b57cec5SDimitry Andric     Returns[0]->eraseFromParent();
24870b57cec5SDimitry Andric     ReturnBB->eraseFromParent();
24885ffd83dbSDimitry Andric   } else if (!CB.use_empty()) {
24890b57cec5SDimitry Andric     // No returns, but something is using the return value of the call.  Just
24900b57cec5SDimitry Andric     // nuke the result.
24915ffd83dbSDimitry Andric     CB.replaceAllUsesWith(UndefValue::get(CB.getType()));
24920b57cec5SDimitry Andric   }
24930b57cec5SDimitry Andric 
24940b57cec5SDimitry Andric   // Since we are now done with the Call/Invoke, we can delete it.
24955ffd83dbSDimitry Andric   CB.eraseFromParent();
24960b57cec5SDimitry Andric 
24970b57cec5SDimitry Andric   // If we inlined any musttail calls and the original return is now
24980b57cec5SDimitry Andric   // unreachable, delete it.  It can only contain a bitcast and ret.
2499*e8d8bef9SDimitry Andric   if (InlinedMustTailCalls && pred_empty(AfterCallBB))
25000b57cec5SDimitry Andric     AfterCallBB->eraseFromParent();
25010b57cec5SDimitry Andric 
25020b57cec5SDimitry Andric   // We should always be able to fold the entry block of the function into the
25030b57cec5SDimitry Andric   // single predecessor of the block...
25040b57cec5SDimitry Andric   assert(cast<BranchInst>(Br)->isUnconditional() && "splitBasicBlock broken!");
25050b57cec5SDimitry Andric   BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0);
25060b57cec5SDimitry Andric 
25070b57cec5SDimitry Andric   // Splice the code entry block into calling block, right before the
25080b57cec5SDimitry Andric   // unconditional branch.
25090b57cec5SDimitry Andric   CalleeEntry->replaceAllUsesWith(OrigBB);  // Update PHI nodes
25100b57cec5SDimitry Andric   OrigBB->getInstList().splice(Br->getIterator(), CalleeEntry->getInstList());
25110b57cec5SDimitry Andric 
25120b57cec5SDimitry Andric   // Remove the unconditional branch.
25130b57cec5SDimitry Andric   OrigBB->getInstList().erase(Br);
25140b57cec5SDimitry Andric 
25150b57cec5SDimitry Andric   // Now we can remove the CalleeEntry block, which is now empty.
25160b57cec5SDimitry Andric   Caller->getBasicBlockList().erase(CalleeEntry);
25170b57cec5SDimitry Andric 
25180b57cec5SDimitry Andric   // If we inserted a phi node, check to see if it has a single value (e.g. all
25190b57cec5SDimitry Andric   // the entries are the same or undef).  If so, remove the PHI so it doesn't
25200b57cec5SDimitry Andric   // block other optimizations.
25210b57cec5SDimitry Andric   if (PHI) {
25220b57cec5SDimitry Andric     AssumptionCache *AC =
25235ffd83dbSDimitry Andric         IFI.GetAssumptionCache ? &IFI.GetAssumptionCache(*Caller) : nullptr;
25240b57cec5SDimitry Andric     auto &DL = Caller->getParent()->getDataLayout();
25250b57cec5SDimitry Andric     if (Value *V = SimplifyInstruction(PHI, {DL, nullptr, nullptr, AC})) {
25260b57cec5SDimitry Andric       PHI->replaceAllUsesWith(V);
25270b57cec5SDimitry Andric       PHI->eraseFromParent();
25280b57cec5SDimitry Andric     }
25290b57cec5SDimitry Andric   }
25300b57cec5SDimitry Andric 
25315ffd83dbSDimitry Andric   return InlineResult::success();
25320b57cec5SDimitry Andric }
2533