1 //===- InlineFunction.cpp - Code to perform function inlining -------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements inlining of a function into a call site, resolving
10 // parameters and the return value as appropriate.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/ADT/DenseMap.h"
15 #include "llvm/ADT/None.h"
16 #include "llvm/ADT/Optional.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SetVector.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/iterator_range.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/Analysis/AssumptionCache.h"
25 #include "llvm/Analysis/BlockFrequencyInfo.h"
26 #include "llvm/Analysis/CallGraph.h"
27 #include "llvm/Analysis/CaptureTracking.h"
28 #include "llvm/Analysis/EHPersonalities.h"
29 #include "llvm/Analysis/InstructionSimplify.h"
30 #include "llvm/Analysis/ProfileSummaryInfo.h"
31 #include "llvm/Transforms/Utils/Local.h"
32 #include "llvm/Analysis/ValueTracking.h"
33 #include "llvm/Analysis/VectorUtils.h"
34 #include "llvm/IR/Argument.h"
35 #include "llvm/IR/BasicBlock.h"
36 #include "llvm/IR/CFG.h"
37 #include "llvm/IR/CallSite.h"
38 #include "llvm/IR/Constant.h"
39 #include "llvm/IR/Constants.h"
40 #include "llvm/IR/DIBuilder.h"
41 #include "llvm/IR/DataLayout.h"
42 #include "llvm/IR/DebugInfoMetadata.h"
43 #include "llvm/IR/DebugLoc.h"
44 #include "llvm/IR/DerivedTypes.h"
45 #include "llvm/IR/Dominators.h"
46 #include "llvm/IR/Function.h"
47 #include "llvm/IR/IRBuilder.h"
48 #include "llvm/IR/InstrTypes.h"
49 #include "llvm/IR/Instruction.h"
50 #include "llvm/IR/Instructions.h"
51 #include "llvm/IR/IntrinsicInst.h"
52 #include "llvm/IR/Intrinsics.h"
53 #include "llvm/IR/LLVMContext.h"
54 #include "llvm/IR/MDBuilder.h"
55 #include "llvm/IR/Metadata.h"
56 #include "llvm/IR/Module.h"
57 #include "llvm/IR/Type.h"
58 #include "llvm/IR/User.h"
59 #include "llvm/IR/Value.h"
60 #include "llvm/Support/Casting.h"
61 #include "llvm/Support/CommandLine.h"
62 #include "llvm/Support/ErrorHandling.h"
63 #include "llvm/Transforms/Utils/Cloning.h"
64 #include "llvm/Transforms/Utils/ValueMapper.h"
65 #include <algorithm>
66 #include <cassert>
67 #include <cstdint>
68 #include <iterator>
69 #include <limits>
70 #include <string>
71 #include <utility>
72 #include <vector>
73 
74 using namespace llvm;
75 using ProfileCount = Function::ProfileCount;
76 
77 static cl::opt<bool>
78 EnableNoAliasConversion("enable-noalias-to-md-conversion", cl::init(true),
79   cl::Hidden,
80   cl::desc("Convert noalias attributes to metadata during inlining."));
81 
82 static cl::opt<bool>
83 PreserveAlignmentAssumptions("preserve-alignment-assumptions-during-inlining",
84   cl::init(true), cl::Hidden,
85   cl::desc("Convert align attributes to assumptions during inlining."));
86 
87 llvm::InlineResult llvm::InlineFunction(CallBase *CB, InlineFunctionInfo &IFI,
88                                         AAResults *CalleeAAR,
89                                         bool InsertLifetime) {
90   return InlineFunction(CallSite(CB), IFI, CalleeAAR, InsertLifetime);
91 }
92 
93 namespace {
94 
95   /// A class for recording information about inlining a landing pad.
96   class LandingPadInliningInfo {
97     /// Destination of the invoke's unwind.
98     BasicBlock *OuterResumeDest;
99 
100     /// Destination for the callee's resume.
101     BasicBlock *InnerResumeDest = nullptr;
102 
103     /// LandingPadInst associated with the invoke.
104     LandingPadInst *CallerLPad = nullptr;
105 
106     /// PHI for EH values from landingpad insts.
107     PHINode *InnerEHValuesPHI = nullptr;
108 
109     SmallVector<Value*, 8> UnwindDestPHIValues;
110 
111   public:
112     LandingPadInliningInfo(InvokeInst *II)
113         : OuterResumeDest(II->getUnwindDest()) {
114       // If there are PHI nodes in the unwind destination block, we need to keep
115       // track of which values came into them from the invoke before removing
116       // the edge from this block.
117       BasicBlock *InvokeBB = II->getParent();
118       BasicBlock::iterator I = OuterResumeDest->begin();
119       for (; isa<PHINode>(I); ++I) {
120         // Save the value to use for this edge.
121         PHINode *PHI = cast<PHINode>(I);
122         UnwindDestPHIValues.push_back(PHI->getIncomingValueForBlock(InvokeBB));
123       }
124 
125       CallerLPad = cast<LandingPadInst>(I);
126     }
127 
128     /// The outer unwind destination is the target of
129     /// unwind edges introduced for calls within the inlined function.
130     BasicBlock *getOuterResumeDest() const {
131       return OuterResumeDest;
132     }
133 
134     BasicBlock *getInnerResumeDest();
135 
136     LandingPadInst *getLandingPadInst() const { return CallerLPad; }
137 
138     /// Forward the 'resume' instruction to the caller's landing pad block.
139     /// When the landing pad block has only one predecessor, this is
140     /// a simple branch. When there is more than one predecessor, we need to
141     /// split the landing pad block after the landingpad instruction and jump
142     /// to there.
143     void forwardResume(ResumeInst *RI,
144                        SmallPtrSetImpl<LandingPadInst*> &InlinedLPads);
145 
146     /// Add incoming-PHI values to the unwind destination block for the given
147     /// basic block, using the values for the original invoke's source block.
148     void addIncomingPHIValuesFor(BasicBlock *BB) const {
149       addIncomingPHIValuesForInto(BB, OuterResumeDest);
150     }
151 
152     void addIncomingPHIValuesForInto(BasicBlock *src, BasicBlock *dest) const {
153       BasicBlock::iterator I = dest->begin();
154       for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
155         PHINode *phi = cast<PHINode>(I);
156         phi->addIncoming(UnwindDestPHIValues[i], src);
157       }
158     }
159   };
160 
161 } // end anonymous namespace
162 
163 /// Get or create a target for the branch from ResumeInsts.
164 BasicBlock *LandingPadInliningInfo::getInnerResumeDest() {
165   if (InnerResumeDest) return InnerResumeDest;
166 
167   // Split the landing pad.
168   BasicBlock::iterator SplitPoint = ++CallerLPad->getIterator();
169   InnerResumeDest =
170     OuterResumeDest->splitBasicBlock(SplitPoint,
171                                      OuterResumeDest->getName() + ".body");
172 
173   // The number of incoming edges we expect to the inner landing pad.
174   const unsigned PHICapacity = 2;
175 
176   // Create corresponding new PHIs for all the PHIs in the outer landing pad.
177   Instruction *InsertPoint = &InnerResumeDest->front();
178   BasicBlock::iterator I = OuterResumeDest->begin();
179   for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
180     PHINode *OuterPHI = cast<PHINode>(I);
181     PHINode *InnerPHI = PHINode::Create(OuterPHI->getType(), PHICapacity,
182                                         OuterPHI->getName() + ".lpad-body",
183                                         InsertPoint);
184     OuterPHI->replaceAllUsesWith(InnerPHI);
185     InnerPHI->addIncoming(OuterPHI, OuterResumeDest);
186   }
187 
188   // Create a PHI for the exception values.
189   InnerEHValuesPHI = PHINode::Create(CallerLPad->getType(), PHICapacity,
190                                      "eh.lpad-body", InsertPoint);
191   CallerLPad->replaceAllUsesWith(InnerEHValuesPHI);
192   InnerEHValuesPHI->addIncoming(CallerLPad, OuterResumeDest);
193 
194   // All done.
195   return InnerResumeDest;
196 }
197 
198 /// Forward the 'resume' instruction to the caller's landing pad block.
199 /// When the landing pad block has only one predecessor, this is a simple
200 /// branch. When there is more than one predecessor, we need to split the
201 /// landing pad block after the landingpad instruction and jump to there.
202 void LandingPadInliningInfo::forwardResume(
203     ResumeInst *RI, SmallPtrSetImpl<LandingPadInst *> &InlinedLPads) {
204   BasicBlock *Dest = getInnerResumeDest();
205   BasicBlock *Src = RI->getParent();
206 
207   BranchInst::Create(Dest, Src);
208 
209   // Update the PHIs in the destination. They were inserted in an order which
210   // makes this work.
211   addIncomingPHIValuesForInto(Src, Dest);
212 
213   InnerEHValuesPHI->addIncoming(RI->getOperand(0), Src);
214   RI->eraseFromParent();
215 }
216 
217 /// Helper for getUnwindDestToken/getUnwindDestTokenHelper.
218 static Value *getParentPad(Value *EHPad) {
219   if (auto *FPI = dyn_cast<FuncletPadInst>(EHPad))
220     return FPI->getParentPad();
221   return cast<CatchSwitchInst>(EHPad)->getParentPad();
222 }
223 
224 using UnwindDestMemoTy = DenseMap<Instruction *, Value *>;
225 
226 /// Helper for getUnwindDestToken that does the descendant-ward part of
227 /// the search.
228 static Value *getUnwindDestTokenHelper(Instruction *EHPad,
229                                        UnwindDestMemoTy &MemoMap) {
230   SmallVector<Instruction *, 8> Worklist(1, EHPad);
231 
232   while (!Worklist.empty()) {
233     Instruction *CurrentPad = Worklist.pop_back_val();
234     // We only put pads on the worklist that aren't in the MemoMap.  When
235     // we find an unwind dest for a pad we may update its ancestors, but
236     // the queue only ever contains uncles/great-uncles/etc. of CurrentPad,
237     // so they should never get updated while queued on the worklist.
238     assert(!MemoMap.count(CurrentPad));
239     Value *UnwindDestToken = nullptr;
240     if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(CurrentPad)) {
241       if (CatchSwitch->hasUnwindDest()) {
242         UnwindDestToken = CatchSwitch->getUnwindDest()->getFirstNonPHI();
243       } else {
244         // Catchswitch doesn't have a 'nounwind' variant, and one might be
245         // annotated as "unwinds to caller" when really it's nounwind (see
246         // e.g. SimplifyCFGOpt::SimplifyUnreachable), so we can't infer the
247         // parent's unwind dest from this.  We can check its catchpads'
248         // descendants, since they might include a cleanuppad with an
249         // "unwinds to caller" cleanupret, which can be trusted.
250         for (auto HI = CatchSwitch->handler_begin(),
251                   HE = CatchSwitch->handler_end();
252              HI != HE && !UnwindDestToken; ++HI) {
253           BasicBlock *HandlerBlock = *HI;
254           auto *CatchPad = cast<CatchPadInst>(HandlerBlock->getFirstNonPHI());
255           for (User *Child : CatchPad->users()) {
256             // Intentionally ignore invokes here -- since the catchswitch is
257             // marked "unwind to caller", it would be a verifier error if it
258             // contained an invoke which unwinds out of it, so any invoke we'd
259             // encounter must unwind to some child of the catch.
260             if (!isa<CleanupPadInst>(Child) && !isa<CatchSwitchInst>(Child))
261               continue;
262 
263             Instruction *ChildPad = cast<Instruction>(Child);
264             auto Memo = MemoMap.find(ChildPad);
265             if (Memo == MemoMap.end()) {
266               // Haven't figured out this child pad yet; queue it.
267               Worklist.push_back(ChildPad);
268               continue;
269             }
270             // We've already checked this child, but might have found that
271             // it offers no proof either way.
272             Value *ChildUnwindDestToken = Memo->second;
273             if (!ChildUnwindDestToken)
274               continue;
275             // We already know the child's unwind dest, which can either
276             // be ConstantTokenNone to indicate unwind to caller, or can
277             // be another child of the catchpad.  Only the former indicates
278             // the unwind dest of the catchswitch.
279             if (isa<ConstantTokenNone>(ChildUnwindDestToken)) {
280               UnwindDestToken = ChildUnwindDestToken;
281               break;
282             }
283             assert(getParentPad(ChildUnwindDestToken) == CatchPad);
284           }
285         }
286       }
287     } else {
288       auto *CleanupPad = cast<CleanupPadInst>(CurrentPad);
289       for (User *U : CleanupPad->users()) {
290         if (auto *CleanupRet = dyn_cast<CleanupReturnInst>(U)) {
291           if (BasicBlock *RetUnwindDest = CleanupRet->getUnwindDest())
292             UnwindDestToken = RetUnwindDest->getFirstNonPHI();
293           else
294             UnwindDestToken = ConstantTokenNone::get(CleanupPad->getContext());
295           break;
296         }
297         Value *ChildUnwindDestToken;
298         if (auto *Invoke = dyn_cast<InvokeInst>(U)) {
299           ChildUnwindDestToken = Invoke->getUnwindDest()->getFirstNonPHI();
300         } else if (isa<CleanupPadInst>(U) || isa<CatchSwitchInst>(U)) {
301           Instruction *ChildPad = cast<Instruction>(U);
302           auto Memo = MemoMap.find(ChildPad);
303           if (Memo == MemoMap.end()) {
304             // Haven't resolved this child yet; queue it and keep searching.
305             Worklist.push_back(ChildPad);
306             continue;
307           }
308           // We've checked this child, but still need to ignore it if it
309           // had no proof either way.
310           ChildUnwindDestToken = Memo->second;
311           if (!ChildUnwindDestToken)
312             continue;
313         } else {
314           // Not a relevant user of the cleanuppad
315           continue;
316         }
317         // In a well-formed program, the child/invoke must either unwind to
318         // an(other) child of the cleanup, or exit the cleanup.  In the
319         // first case, continue searching.
320         if (isa<Instruction>(ChildUnwindDestToken) &&
321             getParentPad(ChildUnwindDestToken) == CleanupPad)
322           continue;
323         UnwindDestToken = ChildUnwindDestToken;
324         break;
325       }
326     }
327     // If we haven't found an unwind dest for CurrentPad, we may have queued its
328     // children, so move on to the next in the worklist.
329     if (!UnwindDestToken)
330       continue;
331 
332     // Now we know that CurrentPad unwinds to UnwindDestToken.  It also exits
333     // any ancestors of CurrentPad up to but not including UnwindDestToken's
334     // parent pad.  Record this in the memo map, and check to see if the
335     // original EHPad being queried is one of the ones exited.
336     Value *UnwindParent;
337     if (auto *UnwindPad = dyn_cast<Instruction>(UnwindDestToken))
338       UnwindParent = getParentPad(UnwindPad);
339     else
340       UnwindParent = nullptr;
341     bool ExitedOriginalPad = false;
342     for (Instruction *ExitedPad = CurrentPad;
343          ExitedPad && ExitedPad != UnwindParent;
344          ExitedPad = dyn_cast<Instruction>(getParentPad(ExitedPad))) {
345       // Skip over catchpads since they just follow their catchswitches.
346       if (isa<CatchPadInst>(ExitedPad))
347         continue;
348       MemoMap[ExitedPad] = UnwindDestToken;
349       ExitedOriginalPad |= (ExitedPad == EHPad);
350     }
351 
352     if (ExitedOriginalPad)
353       return UnwindDestToken;
354 
355     // Continue the search.
356   }
357 
358   // No definitive information is contained within this funclet.
359   return nullptr;
360 }
361 
362 /// Given an EH pad, find where it unwinds.  If it unwinds to an EH pad,
363 /// return that pad instruction.  If it unwinds to caller, return
364 /// ConstantTokenNone.  If it does not have a definitive unwind destination,
365 /// return nullptr.
366 ///
367 /// This routine gets invoked for calls in funclets in inlinees when inlining
368 /// an invoke.  Since many funclets don't have calls inside them, it's queried
369 /// on-demand rather than building a map of pads to unwind dests up front.
370 /// Determining a funclet's unwind dest may require recursively searching its
371 /// descendants, and also ancestors and cousins if the descendants don't provide
372 /// an answer.  Since most funclets will have their unwind dest immediately
373 /// available as the unwind dest of a catchswitch or cleanupret, this routine
374 /// searches top-down from the given pad and then up. To avoid worst-case
375 /// quadratic run-time given that approach, it uses a memo map to avoid
376 /// re-processing funclet trees.  The callers that rewrite the IR as they go
377 /// take advantage of this, for correctness, by checking/forcing rewritten
378 /// pads' entries to match the original callee view.
379 static Value *getUnwindDestToken(Instruction *EHPad,
380                                  UnwindDestMemoTy &MemoMap) {
381   // Catchpads unwind to the same place as their catchswitch;
382   // redirct any queries on catchpads so the code below can
383   // deal with just catchswitches and cleanuppads.
384   if (auto *CPI = dyn_cast<CatchPadInst>(EHPad))
385     EHPad = CPI->getCatchSwitch();
386 
387   // Check if we've already determined the unwind dest for this pad.
388   auto Memo = MemoMap.find(EHPad);
389   if (Memo != MemoMap.end())
390     return Memo->second;
391 
392   // Search EHPad and, if necessary, its descendants.
393   Value *UnwindDestToken = getUnwindDestTokenHelper(EHPad, MemoMap);
394   assert((UnwindDestToken == nullptr) != (MemoMap.count(EHPad) != 0));
395   if (UnwindDestToken)
396     return UnwindDestToken;
397 
398   // No information is available for this EHPad from itself or any of its
399   // descendants.  An unwind all the way out to a pad in the caller would
400   // need also to agree with the unwind dest of the parent funclet, so
401   // search up the chain to try to find a funclet with information.  Put
402   // null entries in the memo map to avoid re-processing as we go up.
403   MemoMap[EHPad] = nullptr;
404 #ifndef NDEBUG
405   SmallPtrSet<Instruction *, 4> TempMemos;
406   TempMemos.insert(EHPad);
407 #endif
408   Instruction *LastUselessPad = EHPad;
409   Value *AncestorToken;
410   for (AncestorToken = getParentPad(EHPad);
411        auto *AncestorPad = dyn_cast<Instruction>(AncestorToken);
412        AncestorToken = getParentPad(AncestorToken)) {
413     // Skip over catchpads since they just follow their catchswitches.
414     if (isa<CatchPadInst>(AncestorPad))
415       continue;
416     // If the MemoMap had an entry mapping AncestorPad to nullptr, since we
417     // haven't yet called getUnwindDestTokenHelper for AncestorPad in this
418     // call to getUnwindDestToken, that would mean that AncestorPad had no
419     // information in itself, its descendants, or its ancestors.  If that
420     // were the case, then we should also have recorded the lack of information
421     // for the descendant that we're coming from.  So assert that we don't
422     // find a null entry in the MemoMap for AncestorPad.
423     assert(!MemoMap.count(AncestorPad) || MemoMap[AncestorPad]);
424     auto AncestorMemo = MemoMap.find(AncestorPad);
425     if (AncestorMemo == MemoMap.end()) {
426       UnwindDestToken = getUnwindDestTokenHelper(AncestorPad, MemoMap);
427     } else {
428       UnwindDestToken = AncestorMemo->second;
429     }
430     if (UnwindDestToken)
431       break;
432     LastUselessPad = AncestorPad;
433     MemoMap[LastUselessPad] = nullptr;
434 #ifndef NDEBUG
435     TempMemos.insert(LastUselessPad);
436 #endif
437   }
438 
439   // We know that getUnwindDestTokenHelper was called on LastUselessPad and
440   // returned nullptr (and likewise for EHPad and any of its ancestors up to
441   // LastUselessPad), so LastUselessPad has no information from below.  Since
442   // getUnwindDestTokenHelper must investigate all downward paths through
443   // no-information nodes to prove that a node has no information like this,
444   // and since any time it finds information it records it in the MemoMap for
445   // not just the immediately-containing funclet but also any ancestors also
446   // exited, it must be the case that, walking downward from LastUselessPad,
447   // visiting just those nodes which have not been mapped to an unwind dest
448   // by getUnwindDestTokenHelper (the nullptr TempMemos notwithstanding, since
449   // they are just used to keep getUnwindDestTokenHelper from repeating work),
450   // any node visited must have been exhaustively searched with no information
451   // for it found.
452   SmallVector<Instruction *, 8> Worklist(1, LastUselessPad);
453   while (!Worklist.empty()) {
454     Instruction *UselessPad = Worklist.pop_back_val();
455     auto Memo = MemoMap.find(UselessPad);
456     if (Memo != MemoMap.end() && Memo->second) {
457       // Here the name 'UselessPad' is a bit of a misnomer, because we've found
458       // that it is a funclet that does have information about unwinding to
459       // a particular destination; its parent was a useless pad.
460       // Since its parent has no information, the unwind edge must not escape
461       // the parent, and must target a sibling of this pad.  This local unwind
462       // gives us no information about EHPad.  Leave it and the subtree rooted
463       // at it alone.
464       assert(getParentPad(Memo->second) == getParentPad(UselessPad));
465       continue;
466     }
467     // We know we don't have information for UselesPad.  If it has an entry in
468     // the MemoMap (mapping it to nullptr), it must be one of the TempMemos
469     // added on this invocation of getUnwindDestToken; if a previous invocation
470     // recorded nullptr, it would have had to prove that the ancestors of
471     // UselessPad, which include LastUselessPad, had no information, and that
472     // in turn would have required proving that the descendants of
473     // LastUselesPad, which include EHPad, have no information about
474     // LastUselessPad, which would imply that EHPad was mapped to nullptr in
475     // the MemoMap on that invocation, which isn't the case if we got here.
476     assert(!MemoMap.count(UselessPad) || TempMemos.count(UselessPad));
477     // Assert as we enumerate users that 'UselessPad' doesn't have any unwind
478     // information that we'd be contradicting by making a map entry for it
479     // (which is something that getUnwindDestTokenHelper must have proved for
480     // us to get here).  Just assert on is direct users here; the checks in
481     // this downward walk at its descendants will verify that they don't have
482     // any unwind edges that exit 'UselessPad' either (i.e. they either have no
483     // unwind edges or unwind to a sibling).
484     MemoMap[UselessPad] = UnwindDestToken;
485     if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(UselessPad)) {
486       assert(CatchSwitch->getUnwindDest() == nullptr && "Expected useless pad");
487       for (BasicBlock *HandlerBlock : CatchSwitch->handlers()) {
488         auto *CatchPad = HandlerBlock->getFirstNonPHI();
489         for (User *U : CatchPad->users()) {
490           assert(
491               (!isa<InvokeInst>(U) ||
492                (getParentPad(
493                     cast<InvokeInst>(U)->getUnwindDest()->getFirstNonPHI()) ==
494                 CatchPad)) &&
495               "Expected useless pad");
496           if (isa<CatchSwitchInst>(U) || isa<CleanupPadInst>(U))
497             Worklist.push_back(cast<Instruction>(U));
498         }
499       }
500     } else {
501       assert(isa<CleanupPadInst>(UselessPad));
502       for (User *U : UselessPad->users()) {
503         assert(!isa<CleanupReturnInst>(U) && "Expected useless pad");
504         assert((!isa<InvokeInst>(U) ||
505                 (getParentPad(
506                      cast<InvokeInst>(U)->getUnwindDest()->getFirstNonPHI()) ==
507                  UselessPad)) &&
508                "Expected useless pad");
509         if (isa<CatchSwitchInst>(U) || isa<CleanupPadInst>(U))
510           Worklist.push_back(cast<Instruction>(U));
511       }
512     }
513   }
514 
515   return UnwindDestToken;
516 }
517 
518 /// When we inline a basic block into an invoke,
519 /// we have to turn all of the calls that can throw into invokes.
520 /// This function analyze BB to see if there are any calls, and if so,
521 /// it rewrites them to be invokes that jump to InvokeDest and fills in the PHI
522 /// nodes in that block with the values specified in InvokeDestPHIValues.
523 static BasicBlock *HandleCallsInBlockInlinedThroughInvoke(
524     BasicBlock *BB, BasicBlock *UnwindEdge,
525     UnwindDestMemoTy *FuncletUnwindMap = nullptr) {
526   for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
527     Instruction *I = &*BBI++;
528 
529     // We only need to check for function calls: inlined invoke
530     // instructions require no special handling.
531     CallInst *CI = dyn_cast<CallInst>(I);
532 
533     if (!CI || CI->doesNotThrow() || isa<InlineAsm>(CI->getCalledValue()))
534       continue;
535 
536     // We do not need to (and in fact, cannot) convert possibly throwing calls
537     // to @llvm.experimental_deoptimize (resp. @llvm.experimental.guard) into
538     // invokes.  The caller's "segment" of the deoptimization continuation
539     // attached to the newly inlined @llvm.experimental_deoptimize
540     // (resp. @llvm.experimental.guard) call should contain the exception
541     // handling logic, if any.
542     if (auto *F = CI->getCalledFunction())
543       if (F->getIntrinsicID() == Intrinsic::experimental_deoptimize ||
544           F->getIntrinsicID() == Intrinsic::experimental_guard)
545         continue;
546 
547     if (auto FuncletBundle = CI->getOperandBundle(LLVMContext::OB_funclet)) {
548       // This call is nested inside a funclet.  If that funclet has an unwind
549       // destination within the inlinee, then unwinding out of this call would
550       // be UB.  Rewriting this call to an invoke which targets the inlined
551       // invoke's unwind dest would give the call's parent funclet multiple
552       // unwind destinations, which is something that subsequent EH table
553       // generation can't handle and that the veirifer rejects.  So when we
554       // see such a call, leave it as a call.
555       auto *FuncletPad = cast<Instruction>(FuncletBundle->Inputs[0]);
556       Value *UnwindDestToken =
557           getUnwindDestToken(FuncletPad, *FuncletUnwindMap);
558       if (UnwindDestToken && !isa<ConstantTokenNone>(UnwindDestToken))
559         continue;
560 #ifndef NDEBUG
561       Instruction *MemoKey;
562       if (auto *CatchPad = dyn_cast<CatchPadInst>(FuncletPad))
563         MemoKey = CatchPad->getCatchSwitch();
564       else
565         MemoKey = FuncletPad;
566       assert(FuncletUnwindMap->count(MemoKey) &&
567              (*FuncletUnwindMap)[MemoKey] == UnwindDestToken &&
568              "must get memoized to avoid confusing later searches");
569 #endif // NDEBUG
570     }
571 
572     changeToInvokeAndSplitBasicBlock(CI, UnwindEdge);
573     return BB;
574   }
575   return nullptr;
576 }
577 
578 /// If we inlined an invoke site, we need to convert calls
579 /// in the body of the inlined function into invokes.
580 ///
581 /// II is the invoke instruction being inlined.  FirstNewBlock is the first
582 /// block of the inlined code (the last block is the end of the function),
583 /// and InlineCodeInfo is information about the code that got inlined.
584 static void HandleInlinedLandingPad(InvokeInst *II, BasicBlock *FirstNewBlock,
585                                     ClonedCodeInfo &InlinedCodeInfo) {
586   BasicBlock *InvokeDest = II->getUnwindDest();
587 
588   Function *Caller = FirstNewBlock->getParent();
589 
590   // The inlined code is currently at the end of the function, scan from the
591   // start of the inlined code to its end, checking for stuff we need to
592   // rewrite.
593   LandingPadInliningInfo Invoke(II);
594 
595   // Get all of the inlined landing pad instructions.
596   SmallPtrSet<LandingPadInst*, 16> InlinedLPads;
597   for (Function::iterator I = FirstNewBlock->getIterator(), E = Caller->end();
598        I != E; ++I)
599     if (InvokeInst *II = dyn_cast<InvokeInst>(I->getTerminator()))
600       InlinedLPads.insert(II->getLandingPadInst());
601 
602   // Append the clauses from the outer landing pad instruction into the inlined
603   // landing pad instructions.
604   LandingPadInst *OuterLPad = Invoke.getLandingPadInst();
605   for (LandingPadInst *InlinedLPad : InlinedLPads) {
606     unsigned OuterNum = OuterLPad->getNumClauses();
607     InlinedLPad->reserveClauses(OuterNum);
608     for (unsigned OuterIdx = 0; OuterIdx != OuterNum; ++OuterIdx)
609       InlinedLPad->addClause(OuterLPad->getClause(OuterIdx));
610     if (OuterLPad->isCleanup())
611       InlinedLPad->setCleanup(true);
612   }
613 
614   for (Function::iterator BB = FirstNewBlock->getIterator(), E = Caller->end();
615        BB != E; ++BB) {
616     if (InlinedCodeInfo.ContainsCalls)
617       if (BasicBlock *NewBB = HandleCallsInBlockInlinedThroughInvoke(
618               &*BB, Invoke.getOuterResumeDest()))
619         // Update any PHI nodes in the exceptional block to indicate that there
620         // is now a new entry in them.
621         Invoke.addIncomingPHIValuesFor(NewBB);
622 
623     // Forward any resumes that are remaining here.
624     if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator()))
625       Invoke.forwardResume(RI, InlinedLPads);
626   }
627 
628   // Now that everything is happy, we have one final detail.  The PHI nodes in
629   // the exception destination block still have entries due to the original
630   // invoke instruction. Eliminate these entries (which might even delete the
631   // PHI node) now.
632   InvokeDest->removePredecessor(II->getParent());
633 }
634 
635 /// If we inlined an invoke site, we need to convert calls
636 /// in the body of the inlined function into invokes.
637 ///
638 /// II is the invoke instruction being inlined.  FirstNewBlock is the first
639 /// block of the inlined code (the last block is the end of the function),
640 /// and InlineCodeInfo is information about the code that got inlined.
641 static void HandleInlinedEHPad(InvokeInst *II, BasicBlock *FirstNewBlock,
642                                ClonedCodeInfo &InlinedCodeInfo) {
643   BasicBlock *UnwindDest = II->getUnwindDest();
644   Function *Caller = FirstNewBlock->getParent();
645 
646   assert(UnwindDest->getFirstNonPHI()->isEHPad() && "unexpected BasicBlock!");
647 
648   // If there are PHI nodes in the unwind destination block, we need to keep
649   // track of which values came into them from the invoke before removing the
650   // edge from this block.
651   SmallVector<Value *, 8> UnwindDestPHIValues;
652   BasicBlock *InvokeBB = II->getParent();
653   for (Instruction &I : *UnwindDest) {
654     // Save the value to use for this edge.
655     PHINode *PHI = dyn_cast<PHINode>(&I);
656     if (!PHI)
657       break;
658     UnwindDestPHIValues.push_back(PHI->getIncomingValueForBlock(InvokeBB));
659   }
660 
661   // Add incoming-PHI values to the unwind destination block for the given basic
662   // block, using the values for the original invoke's source block.
663   auto UpdatePHINodes = [&](BasicBlock *Src) {
664     BasicBlock::iterator I = UnwindDest->begin();
665     for (Value *V : UnwindDestPHIValues) {
666       PHINode *PHI = cast<PHINode>(I);
667       PHI->addIncoming(V, Src);
668       ++I;
669     }
670   };
671 
672   // This connects all the instructions which 'unwind to caller' to the invoke
673   // destination.
674   UnwindDestMemoTy FuncletUnwindMap;
675   for (Function::iterator BB = FirstNewBlock->getIterator(), E = Caller->end();
676        BB != E; ++BB) {
677     if (auto *CRI = dyn_cast<CleanupReturnInst>(BB->getTerminator())) {
678       if (CRI->unwindsToCaller()) {
679         auto *CleanupPad = CRI->getCleanupPad();
680         CleanupReturnInst::Create(CleanupPad, UnwindDest, CRI);
681         CRI->eraseFromParent();
682         UpdatePHINodes(&*BB);
683         // Finding a cleanupret with an unwind destination would confuse
684         // subsequent calls to getUnwindDestToken, so map the cleanuppad
685         // to short-circuit any such calls and recognize this as an "unwind
686         // to caller" cleanup.
687         assert(!FuncletUnwindMap.count(CleanupPad) ||
688                isa<ConstantTokenNone>(FuncletUnwindMap[CleanupPad]));
689         FuncletUnwindMap[CleanupPad] =
690             ConstantTokenNone::get(Caller->getContext());
691       }
692     }
693 
694     Instruction *I = BB->getFirstNonPHI();
695     if (!I->isEHPad())
696       continue;
697 
698     Instruction *Replacement = nullptr;
699     if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(I)) {
700       if (CatchSwitch->unwindsToCaller()) {
701         Value *UnwindDestToken;
702         if (auto *ParentPad =
703                 dyn_cast<Instruction>(CatchSwitch->getParentPad())) {
704           // This catchswitch is nested inside another funclet.  If that
705           // funclet has an unwind destination within the inlinee, then
706           // unwinding out of this catchswitch would be UB.  Rewriting this
707           // catchswitch to unwind to the inlined invoke's unwind dest would
708           // give the parent funclet multiple unwind destinations, which is
709           // something that subsequent EH table generation can't handle and
710           // that the veirifer rejects.  So when we see such a call, leave it
711           // as "unwind to caller".
712           UnwindDestToken = getUnwindDestToken(ParentPad, FuncletUnwindMap);
713           if (UnwindDestToken && !isa<ConstantTokenNone>(UnwindDestToken))
714             continue;
715         } else {
716           // This catchswitch has no parent to inherit constraints from, and
717           // none of its descendants can have an unwind edge that exits it and
718           // targets another funclet in the inlinee.  It may or may not have a
719           // descendant that definitively has an unwind to caller.  In either
720           // case, we'll have to assume that any unwinds out of it may need to
721           // be routed to the caller, so treat it as though it has a definitive
722           // unwind to caller.
723           UnwindDestToken = ConstantTokenNone::get(Caller->getContext());
724         }
725         auto *NewCatchSwitch = CatchSwitchInst::Create(
726             CatchSwitch->getParentPad(), UnwindDest,
727             CatchSwitch->getNumHandlers(), CatchSwitch->getName(),
728             CatchSwitch);
729         for (BasicBlock *PadBB : CatchSwitch->handlers())
730           NewCatchSwitch->addHandler(PadBB);
731         // Propagate info for the old catchswitch over to the new one in
732         // the unwind map.  This also serves to short-circuit any subsequent
733         // checks for the unwind dest of this catchswitch, which would get
734         // confused if they found the outer handler in the callee.
735         FuncletUnwindMap[NewCatchSwitch] = UnwindDestToken;
736         Replacement = NewCatchSwitch;
737       }
738     } else if (!isa<FuncletPadInst>(I)) {
739       llvm_unreachable("unexpected EHPad!");
740     }
741 
742     if (Replacement) {
743       Replacement->takeName(I);
744       I->replaceAllUsesWith(Replacement);
745       I->eraseFromParent();
746       UpdatePHINodes(&*BB);
747     }
748   }
749 
750   if (InlinedCodeInfo.ContainsCalls)
751     for (Function::iterator BB = FirstNewBlock->getIterator(),
752                             E = Caller->end();
753          BB != E; ++BB)
754       if (BasicBlock *NewBB = HandleCallsInBlockInlinedThroughInvoke(
755               &*BB, UnwindDest, &FuncletUnwindMap))
756         // Update any PHI nodes in the exceptional block to indicate that there
757         // is now a new entry in them.
758         UpdatePHINodes(NewBB);
759 
760   // Now that everything is happy, we have one final detail.  The PHI nodes in
761   // the exception destination block still have entries due to the original
762   // invoke instruction. Eliminate these entries (which might even delete the
763   // PHI node) now.
764   UnwindDest->removePredecessor(InvokeBB);
765 }
766 
767 /// When inlining a call site that has !llvm.mem.parallel_loop_access or
768 /// llvm.access.group metadata, that metadata should be propagated to all
769 /// memory-accessing cloned instructions.
770 static void PropagateParallelLoopAccessMetadata(CallSite CS,
771                                                 ValueToValueMapTy &VMap) {
772   MDNode *M =
773     CS.getInstruction()->getMetadata(LLVMContext::MD_mem_parallel_loop_access);
774   MDNode *CallAccessGroup =
775       CS.getInstruction()->getMetadata(LLVMContext::MD_access_group);
776   if (!M && !CallAccessGroup)
777     return;
778 
779   for (ValueToValueMapTy::iterator VMI = VMap.begin(), VMIE = VMap.end();
780        VMI != VMIE; ++VMI) {
781     if (!VMI->second)
782       continue;
783 
784     Instruction *NI = dyn_cast<Instruction>(VMI->second);
785     if (!NI)
786       continue;
787 
788     if (M) {
789       if (MDNode *PM =
790               NI->getMetadata(LLVMContext::MD_mem_parallel_loop_access)) {
791         M = MDNode::concatenate(PM, M);
792       NI->setMetadata(LLVMContext::MD_mem_parallel_loop_access, M);
793       } else if (NI->mayReadOrWriteMemory()) {
794         NI->setMetadata(LLVMContext::MD_mem_parallel_loop_access, M);
795       }
796     }
797 
798     if (NI->mayReadOrWriteMemory()) {
799       MDNode *UnitedAccGroups = uniteAccessGroups(
800           NI->getMetadata(LLVMContext::MD_access_group), CallAccessGroup);
801       NI->setMetadata(LLVMContext::MD_access_group, UnitedAccGroups);
802     }
803   }
804 }
805 
806 /// When inlining a function that contains noalias scope metadata,
807 /// this metadata needs to be cloned so that the inlined blocks
808 /// have different "unique scopes" at every call site. Were this not done, then
809 /// aliasing scopes from a function inlined into a caller multiple times could
810 /// not be differentiated (and this would lead to miscompiles because the
811 /// non-aliasing property communicated by the metadata could have
812 /// call-site-specific control dependencies).
813 static void CloneAliasScopeMetadata(CallSite CS, ValueToValueMapTy &VMap) {
814   const Function *CalledFunc = CS.getCalledFunction();
815   SetVector<const MDNode *> MD;
816 
817   // Note: We could only clone the metadata if it is already used in the
818   // caller. I'm omitting that check here because it might confuse
819   // inter-procedural alias analysis passes. We can revisit this if it becomes
820   // an efficiency or overhead problem.
821 
822   for (const BasicBlock &I : *CalledFunc)
823     for (const Instruction &J : I) {
824       if (const MDNode *M = J.getMetadata(LLVMContext::MD_alias_scope))
825         MD.insert(M);
826       if (const MDNode *M = J.getMetadata(LLVMContext::MD_noalias))
827         MD.insert(M);
828     }
829 
830   if (MD.empty())
831     return;
832 
833   // Walk the existing metadata, adding the complete (perhaps cyclic) chain to
834   // the set.
835   SmallVector<const Metadata *, 16> Queue(MD.begin(), MD.end());
836   while (!Queue.empty()) {
837     const MDNode *M = cast<MDNode>(Queue.pop_back_val());
838     for (unsigned i = 0, ie = M->getNumOperands(); i != ie; ++i)
839       if (const MDNode *M1 = dyn_cast<MDNode>(M->getOperand(i)))
840         if (MD.insert(M1))
841           Queue.push_back(M1);
842   }
843 
844   // Now we have a complete set of all metadata in the chains used to specify
845   // the noalias scopes and the lists of those scopes.
846   SmallVector<TempMDTuple, 16> DummyNodes;
847   DenseMap<const MDNode *, TrackingMDNodeRef> MDMap;
848   for (const MDNode *I : MD) {
849     DummyNodes.push_back(MDTuple::getTemporary(CalledFunc->getContext(), None));
850     MDMap[I].reset(DummyNodes.back().get());
851   }
852 
853   // Create new metadata nodes to replace the dummy nodes, replacing old
854   // metadata references with either a dummy node or an already-created new
855   // node.
856   for (const MDNode *I : MD) {
857     SmallVector<Metadata *, 4> NewOps;
858     for (unsigned i = 0, ie = I->getNumOperands(); i != ie; ++i) {
859       const Metadata *V = I->getOperand(i);
860       if (const MDNode *M = dyn_cast<MDNode>(V))
861         NewOps.push_back(MDMap[M]);
862       else
863         NewOps.push_back(const_cast<Metadata *>(V));
864     }
865 
866     MDNode *NewM = MDNode::get(CalledFunc->getContext(), NewOps);
867     MDTuple *TempM = cast<MDTuple>(MDMap[I]);
868     assert(TempM->isTemporary() && "Expected temporary node");
869 
870     TempM->replaceAllUsesWith(NewM);
871   }
872 
873   // Now replace the metadata in the new inlined instructions with the
874   // repacements from the map.
875   for (ValueToValueMapTy::iterator VMI = VMap.begin(), VMIE = VMap.end();
876        VMI != VMIE; ++VMI) {
877     if (!VMI->second)
878       continue;
879 
880     Instruction *NI = dyn_cast<Instruction>(VMI->second);
881     if (!NI)
882       continue;
883 
884     if (MDNode *M = NI->getMetadata(LLVMContext::MD_alias_scope)) {
885       MDNode *NewMD = MDMap[M];
886       // If the call site also had alias scope metadata (a list of scopes to
887       // which instructions inside it might belong), propagate those scopes to
888       // the inlined instructions.
889       if (MDNode *CSM =
890               CS.getInstruction()->getMetadata(LLVMContext::MD_alias_scope))
891         NewMD = MDNode::concatenate(NewMD, CSM);
892       NI->setMetadata(LLVMContext::MD_alias_scope, NewMD);
893     } else if (NI->mayReadOrWriteMemory()) {
894       if (MDNode *M =
895               CS.getInstruction()->getMetadata(LLVMContext::MD_alias_scope))
896         NI->setMetadata(LLVMContext::MD_alias_scope, M);
897     }
898 
899     if (MDNode *M = NI->getMetadata(LLVMContext::MD_noalias)) {
900       MDNode *NewMD = MDMap[M];
901       // If the call site also had noalias metadata (a list of scopes with
902       // which instructions inside it don't alias), propagate those scopes to
903       // the inlined instructions.
904       if (MDNode *CSM =
905               CS.getInstruction()->getMetadata(LLVMContext::MD_noalias))
906         NewMD = MDNode::concatenate(NewMD, CSM);
907       NI->setMetadata(LLVMContext::MD_noalias, NewMD);
908     } else if (NI->mayReadOrWriteMemory()) {
909       if (MDNode *M = CS.getInstruction()->getMetadata(LLVMContext::MD_noalias))
910         NI->setMetadata(LLVMContext::MD_noalias, M);
911     }
912   }
913 }
914 
915 /// If the inlined function has noalias arguments,
916 /// then add new alias scopes for each noalias argument, tag the mapped noalias
917 /// parameters with noalias metadata specifying the new scope, and tag all
918 /// non-derived loads, stores and memory intrinsics with the new alias scopes.
919 static void AddAliasScopeMetadata(CallSite CS, ValueToValueMapTy &VMap,
920                                   const DataLayout &DL, AAResults *CalleeAAR) {
921   if (!EnableNoAliasConversion)
922     return;
923 
924   const Function *CalledFunc = CS.getCalledFunction();
925   SmallVector<const Argument *, 4> NoAliasArgs;
926 
927   for (const Argument &Arg : CalledFunc->args())
928     if (CS.paramHasAttr(Arg.getArgNo(), Attribute::NoAlias) && !Arg.use_empty())
929       NoAliasArgs.push_back(&Arg);
930 
931   if (NoAliasArgs.empty())
932     return;
933 
934   // To do a good job, if a noalias variable is captured, we need to know if
935   // the capture point dominates the particular use we're considering.
936   DominatorTree DT;
937   DT.recalculate(const_cast<Function&>(*CalledFunc));
938 
939   // noalias indicates that pointer values based on the argument do not alias
940   // pointer values which are not based on it. So we add a new "scope" for each
941   // noalias function argument. Accesses using pointers based on that argument
942   // become part of that alias scope, accesses using pointers not based on that
943   // argument are tagged as noalias with that scope.
944 
945   DenseMap<const Argument *, MDNode *> NewScopes;
946   MDBuilder MDB(CalledFunc->getContext());
947 
948   // Create a new scope domain for this function.
949   MDNode *NewDomain =
950     MDB.createAnonymousAliasScopeDomain(CalledFunc->getName());
951   for (unsigned i = 0, e = NoAliasArgs.size(); i != e; ++i) {
952     const Argument *A = NoAliasArgs[i];
953 
954     std::string Name = std::string(CalledFunc->getName());
955     if (A->hasName()) {
956       Name += ": %";
957       Name += A->getName();
958     } else {
959       Name += ": argument ";
960       Name += utostr(i);
961     }
962 
963     // Note: We always create a new anonymous root here. This is true regardless
964     // of the linkage of the callee because the aliasing "scope" is not just a
965     // property of the callee, but also all control dependencies in the caller.
966     MDNode *NewScope = MDB.createAnonymousAliasScope(NewDomain, Name);
967     NewScopes.insert(std::make_pair(A, NewScope));
968   }
969 
970   // Iterate over all new instructions in the map; for all memory-access
971   // instructions, add the alias scope metadata.
972   for (ValueToValueMapTy::iterator VMI = VMap.begin(), VMIE = VMap.end();
973        VMI != VMIE; ++VMI) {
974     if (const Instruction *I = dyn_cast<Instruction>(VMI->first)) {
975       if (!VMI->second)
976         continue;
977 
978       Instruction *NI = dyn_cast<Instruction>(VMI->second);
979       if (!NI)
980         continue;
981 
982       bool IsArgMemOnlyCall = false, IsFuncCall = false;
983       SmallVector<const Value *, 2> PtrArgs;
984 
985       if (const LoadInst *LI = dyn_cast<LoadInst>(I))
986         PtrArgs.push_back(LI->getPointerOperand());
987       else if (const StoreInst *SI = dyn_cast<StoreInst>(I))
988         PtrArgs.push_back(SI->getPointerOperand());
989       else if (const VAArgInst *VAAI = dyn_cast<VAArgInst>(I))
990         PtrArgs.push_back(VAAI->getPointerOperand());
991       else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I))
992         PtrArgs.push_back(CXI->getPointerOperand());
993       else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I))
994         PtrArgs.push_back(RMWI->getPointerOperand());
995       else if (const auto *Call = dyn_cast<CallBase>(I)) {
996         // If we know that the call does not access memory, then we'll still
997         // know that about the inlined clone of this call site, and we don't
998         // need to add metadata.
999         if (Call->doesNotAccessMemory())
1000           continue;
1001 
1002         IsFuncCall = true;
1003         if (CalleeAAR) {
1004           FunctionModRefBehavior MRB = CalleeAAR->getModRefBehavior(Call);
1005           if (AAResults::onlyAccessesArgPointees(MRB))
1006             IsArgMemOnlyCall = true;
1007         }
1008 
1009         for (Value *Arg : Call->args()) {
1010           // We need to check the underlying objects of all arguments, not just
1011           // the pointer arguments, because we might be passing pointers as
1012           // integers, etc.
1013           // However, if we know that the call only accesses pointer arguments,
1014           // then we only need to check the pointer arguments.
1015           if (IsArgMemOnlyCall && !Arg->getType()->isPointerTy())
1016             continue;
1017 
1018           PtrArgs.push_back(Arg);
1019         }
1020       }
1021 
1022       // If we found no pointers, then this instruction is not suitable for
1023       // pairing with an instruction to receive aliasing metadata.
1024       // However, if this is a call, this we might just alias with none of the
1025       // noalias arguments.
1026       if (PtrArgs.empty() && !IsFuncCall)
1027         continue;
1028 
1029       // It is possible that there is only one underlying object, but you
1030       // need to go through several PHIs to see it, and thus could be
1031       // repeated in the Objects list.
1032       SmallPtrSet<const Value *, 4> ObjSet;
1033       SmallVector<Metadata *, 4> Scopes, NoAliases;
1034 
1035       SmallSetVector<const Argument *, 4> NAPtrArgs;
1036       for (const Value *V : PtrArgs) {
1037         SmallVector<const Value *, 4> Objects;
1038         GetUnderlyingObjects(V, Objects, DL, /* LI = */ nullptr);
1039 
1040         for (const Value *O : Objects)
1041           ObjSet.insert(O);
1042       }
1043 
1044       // Figure out if we're derived from anything that is not a noalias
1045       // argument.
1046       bool CanDeriveViaCapture = false, UsesAliasingPtr = false;
1047       for (const Value *V : ObjSet) {
1048         // Is this value a constant that cannot be derived from any pointer
1049         // value (we need to exclude constant expressions, for example, that
1050         // are formed from arithmetic on global symbols).
1051         bool IsNonPtrConst = isa<ConstantInt>(V) || isa<ConstantFP>(V) ||
1052                              isa<ConstantPointerNull>(V) ||
1053                              isa<ConstantDataVector>(V) || isa<UndefValue>(V);
1054         if (IsNonPtrConst)
1055           continue;
1056 
1057         // If this is anything other than a noalias argument, then we cannot
1058         // completely describe the aliasing properties using alias.scope
1059         // metadata (and, thus, won't add any).
1060         if (const Argument *A = dyn_cast<Argument>(V)) {
1061           if (!CS.paramHasAttr(A->getArgNo(), Attribute::NoAlias))
1062             UsesAliasingPtr = true;
1063         } else {
1064           UsesAliasingPtr = true;
1065         }
1066 
1067         // If this is not some identified function-local object (which cannot
1068         // directly alias a noalias argument), or some other argument (which,
1069         // by definition, also cannot alias a noalias argument), then we could
1070         // alias a noalias argument that has been captured).
1071         if (!isa<Argument>(V) &&
1072             !isIdentifiedFunctionLocal(const_cast<Value*>(V)))
1073           CanDeriveViaCapture = true;
1074       }
1075 
1076       // A function call can always get captured noalias pointers (via other
1077       // parameters, globals, etc.).
1078       if (IsFuncCall && !IsArgMemOnlyCall)
1079         CanDeriveViaCapture = true;
1080 
1081       // First, we want to figure out all of the sets with which we definitely
1082       // don't alias. Iterate over all noalias set, and add those for which:
1083       //   1. The noalias argument is not in the set of objects from which we
1084       //      definitely derive.
1085       //   2. The noalias argument has not yet been captured.
1086       // An arbitrary function that might load pointers could see captured
1087       // noalias arguments via other noalias arguments or globals, and so we
1088       // must always check for prior capture.
1089       for (const Argument *A : NoAliasArgs) {
1090         if (!ObjSet.count(A) && (!CanDeriveViaCapture ||
1091                                  // It might be tempting to skip the
1092                                  // PointerMayBeCapturedBefore check if
1093                                  // A->hasNoCaptureAttr() is true, but this is
1094                                  // incorrect because nocapture only guarantees
1095                                  // that no copies outlive the function, not
1096                                  // that the value cannot be locally captured.
1097                                  !PointerMayBeCapturedBefore(A,
1098                                    /* ReturnCaptures */ false,
1099                                    /* StoreCaptures */ false, I, &DT)))
1100           NoAliases.push_back(NewScopes[A]);
1101       }
1102 
1103       if (!NoAliases.empty())
1104         NI->setMetadata(LLVMContext::MD_noalias,
1105                         MDNode::concatenate(
1106                             NI->getMetadata(LLVMContext::MD_noalias),
1107                             MDNode::get(CalledFunc->getContext(), NoAliases)));
1108 
1109       // Next, we want to figure out all of the sets to which we might belong.
1110       // We might belong to a set if the noalias argument is in the set of
1111       // underlying objects. If there is some non-noalias argument in our list
1112       // of underlying objects, then we cannot add a scope because the fact
1113       // that some access does not alias with any set of our noalias arguments
1114       // cannot itself guarantee that it does not alias with this access
1115       // (because there is some pointer of unknown origin involved and the
1116       // other access might also depend on this pointer). We also cannot add
1117       // scopes to arbitrary functions unless we know they don't access any
1118       // non-parameter pointer-values.
1119       bool CanAddScopes = !UsesAliasingPtr;
1120       if (CanAddScopes && IsFuncCall)
1121         CanAddScopes = IsArgMemOnlyCall;
1122 
1123       if (CanAddScopes)
1124         for (const Argument *A : NoAliasArgs) {
1125           if (ObjSet.count(A))
1126             Scopes.push_back(NewScopes[A]);
1127         }
1128 
1129       if (!Scopes.empty())
1130         NI->setMetadata(
1131             LLVMContext::MD_alias_scope,
1132             MDNode::concatenate(NI->getMetadata(LLVMContext::MD_alias_scope),
1133                                 MDNode::get(CalledFunc->getContext(), Scopes)));
1134     }
1135   }
1136 }
1137 
1138 /// If the inlined function has non-byval align arguments, then
1139 /// add @llvm.assume-based alignment assumptions to preserve this information.
1140 static void AddAlignmentAssumptions(CallSite CS, InlineFunctionInfo &IFI) {
1141   if (!PreserveAlignmentAssumptions || !IFI.GetAssumptionCache)
1142     return;
1143 
1144   AssumptionCache *AC = &(*IFI.GetAssumptionCache)(*CS.getCaller());
1145   auto &DL = CS.getCaller()->getParent()->getDataLayout();
1146 
1147   // To avoid inserting redundant assumptions, we should check for assumptions
1148   // already in the caller. To do this, we might need a DT of the caller.
1149   DominatorTree DT;
1150   bool DTCalculated = false;
1151 
1152   Function *CalledFunc = CS.getCalledFunction();
1153   for (Argument &Arg : CalledFunc->args()) {
1154     unsigned Align = Arg.getType()->isPointerTy() ? Arg.getParamAlignment() : 0;
1155     if (Align && !Arg.hasByValOrInAllocaAttr() && !Arg.hasNUses(0)) {
1156       if (!DTCalculated) {
1157         DT.recalculate(*CS.getCaller());
1158         DTCalculated = true;
1159       }
1160 
1161       // If we can already prove the asserted alignment in the context of the
1162       // caller, then don't bother inserting the assumption.
1163       Value *ArgVal = CS.getArgument(Arg.getArgNo());
1164       if (getKnownAlignment(ArgVal, DL, CS.getInstruction(), AC, &DT) >= Align)
1165         continue;
1166 
1167       CallInst *NewAsmp = IRBuilder<>(CS.getInstruction())
1168                               .CreateAlignmentAssumption(DL, ArgVal, Align);
1169       AC->registerAssumption(NewAsmp);
1170     }
1171   }
1172 }
1173 
1174 /// Once we have cloned code over from a callee into the caller,
1175 /// update the specified callgraph to reflect the changes we made.
1176 /// Note that it's possible that not all code was copied over, so only
1177 /// some edges of the callgraph may remain.
1178 static void UpdateCallGraphAfterInlining(CallSite CS,
1179                                          Function::iterator FirstNewBlock,
1180                                          ValueToValueMapTy &VMap,
1181                                          InlineFunctionInfo &IFI) {
1182   CallGraph &CG = *IFI.CG;
1183   const Function *Caller = CS.getCaller();
1184   const Function *Callee = CS.getCalledFunction();
1185   CallGraphNode *CalleeNode = CG[Callee];
1186   CallGraphNode *CallerNode = CG[Caller];
1187 
1188   // Since we inlined some uninlined call sites in the callee into the caller,
1189   // add edges from the caller to all of the callees of the callee.
1190   CallGraphNode::iterator I = CalleeNode->begin(), E = CalleeNode->end();
1191 
1192   // Consider the case where CalleeNode == CallerNode.
1193   CallGraphNode::CalledFunctionsVector CallCache;
1194   if (CalleeNode == CallerNode) {
1195     CallCache.assign(I, E);
1196     I = CallCache.begin();
1197     E = CallCache.end();
1198   }
1199 
1200   for (; I != E; ++I) {
1201     const Value *OrigCall = I->first;
1202 
1203     ValueToValueMapTy::iterator VMI = VMap.find(OrigCall);
1204     // Only copy the edge if the call was inlined!
1205     if (VMI == VMap.end() || VMI->second == nullptr)
1206       continue;
1207 
1208     // If the call was inlined, but then constant folded, there is no edge to
1209     // add.  Check for this case.
1210     auto *NewCall = dyn_cast<CallBase>(VMI->second);
1211     if (!NewCall)
1212       continue;
1213 
1214     // We do not treat intrinsic calls like real function calls because we
1215     // expect them to become inline code; do not add an edge for an intrinsic.
1216     if (NewCall->getCalledFunction() &&
1217         NewCall->getCalledFunction()->isIntrinsic())
1218       continue;
1219 
1220     // Remember that this call site got inlined for the client of
1221     // InlineFunction.
1222     IFI.InlinedCalls.push_back(NewCall);
1223 
1224     // It's possible that inlining the callsite will cause it to go from an
1225     // indirect to a direct call by resolving a function pointer.  If this
1226     // happens, set the callee of the new call site to a more precise
1227     // destination.  This can also happen if the call graph node of the caller
1228     // was just unnecessarily imprecise.
1229     if (!I->second->getFunction())
1230       if (Function *F = NewCall->getCalledFunction()) {
1231         // Indirect call site resolved to direct call.
1232         CallerNode->addCalledFunction(NewCall, CG[F]);
1233 
1234         continue;
1235       }
1236 
1237     CallerNode->addCalledFunction(NewCall, I->second);
1238   }
1239 
1240   // Update the call graph by deleting the edge from Callee to Caller.  We must
1241   // do this after the loop above in case Caller and Callee are the same.
1242   CallerNode->removeCallEdgeFor(*cast<CallBase>(CS.getInstruction()));
1243 }
1244 
1245 static void HandleByValArgumentInit(Value *Dst, Value *Src, Module *M,
1246                                     BasicBlock *InsertBlock,
1247                                     InlineFunctionInfo &IFI) {
1248   Type *AggTy = cast<PointerType>(Src->getType())->getElementType();
1249   IRBuilder<> Builder(InsertBlock, InsertBlock->begin());
1250 
1251   Value *Size = Builder.getInt64(M->getDataLayout().getTypeStoreSize(AggTy));
1252 
1253   // Always generate a memcpy of alignment 1 here because we don't know
1254   // the alignment of the src pointer.  Other optimizations can infer
1255   // better alignment.
1256   Builder.CreateMemCpy(Dst, /*DstAlign*/ Align(1), Src,
1257                        /*SrcAlign*/ Align(1), Size);
1258 }
1259 
1260 /// When inlining a call site that has a byval argument,
1261 /// we have to make the implicit memcpy explicit by adding it.
1262 static Value *HandleByValArgument(Value *Arg, Instruction *TheCall,
1263                                   const Function *CalledFunc,
1264                                   InlineFunctionInfo &IFI,
1265                                   unsigned ByValAlignment) {
1266   PointerType *ArgTy = cast<PointerType>(Arg->getType());
1267   Type *AggTy = ArgTy->getElementType();
1268 
1269   Function *Caller = TheCall->getFunction();
1270   const DataLayout &DL = Caller->getParent()->getDataLayout();
1271 
1272   // If the called function is readonly, then it could not mutate the caller's
1273   // copy of the byval'd memory.  In this case, it is safe to elide the copy and
1274   // temporary.
1275   if (CalledFunc->onlyReadsMemory()) {
1276     // If the byval argument has a specified alignment that is greater than the
1277     // passed in pointer, then we either have to round up the input pointer or
1278     // give up on this transformation.
1279     if (ByValAlignment <= 1)  // 0 = unspecified, 1 = no particular alignment.
1280       return Arg;
1281 
1282     AssumptionCache *AC =
1283         IFI.GetAssumptionCache ? &(*IFI.GetAssumptionCache)(*Caller) : nullptr;
1284 
1285     // If the pointer is already known to be sufficiently aligned, or if we can
1286     // round it up to a larger alignment, then we don't need a temporary.
1287     if (getOrEnforceKnownAlignment(Arg, ByValAlignment, DL, TheCall, AC) >=
1288         ByValAlignment)
1289       return Arg;
1290 
1291     // Otherwise, we have to make a memcpy to get a safe alignment.  This is bad
1292     // for code quality, but rarely happens and is required for correctness.
1293   }
1294 
1295   // Create the alloca.  If we have DataLayout, use nice alignment.
1296   Align Alignment(DL.getPrefTypeAlignment(AggTy));
1297 
1298   // If the byval had an alignment specified, we *must* use at least that
1299   // alignment, as it is required by the byval argument (and uses of the
1300   // pointer inside the callee).
1301   Alignment = max(Alignment, MaybeAlign(ByValAlignment));
1302 
1303   Value *NewAlloca =
1304       new AllocaInst(AggTy, DL.getAllocaAddrSpace(), nullptr, Alignment,
1305                      Arg->getName(), &*Caller->begin()->begin());
1306   IFI.StaticAllocas.push_back(cast<AllocaInst>(NewAlloca));
1307 
1308   // Uses of the argument in the function should use our new alloca
1309   // instead.
1310   return NewAlloca;
1311 }
1312 
1313 // Check whether this Value is used by a lifetime intrinsic.
1314 static bool isUsedByLifetimeMarker(Value *V) {
1315   for (User *U : V->users())
1316     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U))
1317       if (II->isLifetimeStartOrEnd())
1318         return true;
1319   return false;
1320 }
1321 
1322 // Check whether the given alloca already has
1323 // lifetime.start or lifetime.end intrinsics.
1324 static bool hasLifetimeMarkers(AllocaInst *AI) {
1325   Type *Ty = AI->getType();
1326   Type *Int8PtrTy = Type::getInt8PtrTy(Ty->getContext(),
1327                                        Ty->getPointerAddressSpace());
1328   if (Ty == Int8PtrTy)
1329     return isUsedByLifetimeMarker(AI);
1330 
1331   // Do a scan to find all the casts to i8*.
1332   for (User *U : AI->users()) {
1333     if (U->getType() != Int8PtrTy) continue;
1334     if (U->stripPointerCasts() != AI) continue;
1335     if (isUsedByLifetimeMarker(U))
1336       return true;
1337   }
1338   return false;
1339 }
1340 
1341 /// Return the result of AI->isStaticAlloca() if AI were moved to the entry
1342 /// block. Allocas used in inalloca calls and allocas of dynamic array size
1343 /// cannot be static.
1344 static bool allocaWouldBeStaticInEntry(const AllocaInst *AI ) {
1345   return isa<Constant>(AI->getArraySize()) && !AI->isUsedWithInAlloca();
1346 }
1347 
1348 /// Returns a DebugLoc for a new DILocation which is a clone of \p OrigDL
1349 /// inlined at \p InlinedAt. \p IANodes is an inlined-at cache.
1350 static DebugLoc inlineDebugLoc(DebugLoc OrigDL, DILocation *InlinedAt,
1351                                LLVMContext &Ctx,
1352                                DenseMap<const MDNode *, MDNode *> &IANodes) {
1353   auto IA = DebugLoc::appendInlinedAt(OrigDL, InlinedAt, Ctx, IANodes);
1354   return DebugLoc::get(OrigDL.getLine(), OrigDL.getCol(), OrigDL.getScope(),
1355                        IA);
1356 }
1357 
1358 /// Update inlined instructions' line numbers to
1359 /// to encode location where these instructions are inlined.
1360 static void fixupLineNumbers(Function *Fn, Function::iterator FI,
1361                              Instruction *TheCall, bool CalleeHasDebugInfo) {
1362   const DebugLoc &TheCallDL = TheCall->getDebugLoc();
1363   if (!TheCallDL)
1364     return;
1365 
1366   auto &Ctx = Fn->getContext();
1367   DILocation *InlinedAtNode = TheCallDL;
1368 
1369   // Create a unique call site, not to be confused with any other call from the
1370   // same location.
1371   InlinedAtNode = DILocation::getDistinct(
1372       Ctx, InlinedAtNode->getLine(), InlinedAtNode->getColumn(),
1373       InlinedAtNode->getScope(), InlinedAtNode->getInlinedAt());
1374 
1375   // Cache the inlined-at nodes as they're built so they are reused, without
1376   // this every instruction's inlined-at chain would become distinct from each
1377   // other.
1378   DenseMap<const MDNode *, MDNode *> IANodes;
1379 
1380   // Check if we are not generating inline line tables and want to use
1381   // the call site location instead.
1382   bool NoInlineLineTables = Fn->hasFnAttribute("no-inline-line-tables");
1383 
1384   for (; FI != Fn->end(); ++FI) {
1385     for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
1386          BI != BE; ++BI) {
1387       // Loop metadata needs to be updated so that the start and end locs
1388       // reference inlined-at locations.
1389       auto updateLoopInfoLoc = [&Ctx, &InlinedAtNode, &IANodes](
1390                                    const DILocation &Loc) -> DILocation * {
1391         return inlineDebugLoc(&Loc, InlinedAtNode, Ctx, IANodes).get();
1392       };
1393       updateLoopMetadataDebugLocations(*BI, updateLoopInfoLoc);
1394 
1395       if (!NoInlineLineTables)
1396         if (DebugLoc DL = BI->getDebugLoc()) {
1397           DebugLoc IDL =
1398               inlineDebugLoc(DL, InlinedAtNode, BI->getContext(), IANodes);
1399           BI->setDebugLoc(IDL);
1400           continue;
1401         }
1402 
1403       if (CalleeHasDebugInfo && !NoInlineLineTables)
1404         continue;
1405 
1406       // If the inlined instruction has no line number, or if inline info
1407       // is not being generated, make it look as if it originates from the call
1408       // location. This is important for ((__always_inline, __nodebug__))
1409       // functions which must use caller location for all instructions in their
1410       // function body.
1411 
1412       // Don't update static allocas, as they may get moved later.
1413       if (auto *AI = dyn_cast<AllocaInst>(BI))
1414         if (allocaWouldBeStaticInEntry(AI))
1415           continue;
1416 
1417       BI->setDebugLoc(TheCallDL);
1418     }
1419 
1420     // Remove debug info intrinsics if we're not keeping inline info.
1421     if (NoInlineLineTables) {
1422       BasicBlock::iterator BI = FI->begin();
1423       while (BI != FI->end()) {
1424         if (isa<DbgInfoIntrinsic>(BI)) {
1425           BI = BI->eraseFromParent();
1426           continue;
1427         }
1428         ++BI;
1429       }
1430     }
1431 
1432   }
1433 }
1434 
1435 /// Update the block frequencies of the caller after a callee has been inlined.
1436 ///
1437 /// Each block cloned into the caller has its block frequency scaled by the
1438 /// ratio of CallSiteFreq/CalleeEntryFreq. This ensures that the cloned copy of
1439 /// callee's entry block gets the same frequency as the callsite block and the
1440 /// relative frequencies of all cloned blocks remain the same after cloning.
1441 static void updateCallerBFI(BasicBlock *CallSiteBlock,
1442                             const ValueToValueMapTy &VMap,
1443                             BlockFrequencyInfo *CallerBFI,
1444                             BlockFrequencyInfo *CalleeBFI,
1445                             const BasicBlock &CalleeEntryBlock) {
1446   SmallPtrSet<BasicBlock *, 16> ClonedBBs;
1447   for (auto Entry : VMap) {
1448     if (!isa<BasicBlock>(Entry.first) || !Entry.second)
1449       continue;
1450     auto *OrigBB = cast<BasicBlock>(Entry.first);
1451     auto *ClonedBB = cast<BasicBlock>(Entry.second);
1452     uint64_t Freq = CalleeBFI->getBlockFreq(OrigBB).getFrequency();
1453     if (!ClonedBBs.insert(ClonedBB).second) {
1454       // Multiple blocks in the callee might get mapped to one cloned block in
1455       // the caller since we prune the callee as we clone it. When that happens,
1456       // we want to use the maximum among the original blocks' frequencies.
1457       uint64_t NewFreq = CallerBFI->getBlockFreq(ClonedBB).getFrequency();
1458       if (NewFreq > Freq)
1459         Freq = NewFreq;
1460     }
1461     CallerBFI->setBlockFreq(ClonedBB, Freq);
1462   }
1463   BasicBlock *EntryClone = cast<BasicBlock>(VMap.lookup(&CalleeEntryBlock));
1464   CallerBFI->setBlockFreqAndScale(
1465       EntryClone, CallerBFI->getBlockFreq(CallSiteBlock).getFrequency(),
1466       ClonedBBs);
1467 }
1468 
1469 /// Update the branch metadata for cloned call instructions.
1470 static void updateCallProfile(Function *Callee, const ValueToValueMapTy &VMap,
1471                               const ProfileCount &CalleeEntryCount,
1472                               const Instruction *TheCall,
1473                               ProfileSummaryInfo *PSI,
1474                               BlockFrequencyInfo *CallerBFI) {
1475   if (!CalleeEntryCount.hasValue() || CalleeEntryCount.isSynthetic() ||
1476       CalleeEntryCount.getCount() < 1)
1477     return;
1478   auto CallSiteCount = PSI ? PSI->getProfileCount(TheCall, CallerBFI) : None;
1479   int64_t CallCount =
1480       std::min(CallSiteCount.hasValue() ? CallSiteCount.getValue() : 0,
1481                CalleeEntryCount.getCount());
1482   updateProfileCallee(Callee, -CallCount, &VMap);
1483 }
1484 
1485 void llvm::updateProfileCallee(
1486     Function *Callee, int64_t entryDelta,
1487     const ValueMap<const Value *, WeakTrackingVH> *VMap) {
1488   auto CalleeCount = Callee->getEntryCount();
1489   if (!CalleeCount.hasValue())
1490     return;
1491 
1492   uint64_t priorEntryCount = CalleeCount.getCount();
1493   uint64_t newEntryCount;
1494 
1495   // Since CallSiteCount is an estimate, it could exceed the original callee
1496   // count and has to be set to 0 so guard against underflow.
1497   if (entryDelta < 0 && static_cast<uint64_t>(-entryDelta) > priorEntryCount)
1498     newEntryCount = 0;
1499   else
1500     newEntryCount = priorEntryCount + entryDelta;
1501 
1502   // During inlining ?
1503   if (VMap) {
1504     uint64_t cloneEntryCount = priorEntryCount - newEntryCount;
1505     for (auto Entry : *VMap)
1506       if (isa<CallInst>(Entry.first))
1507         if (auto *CI = dyn_cast_or_null<CallInst>(Entry.second))
1508           CI->updateProfWeight(cloneEntryCount, priorEntryCount);
1509   }
1510 
1511   if (entryDelta) {
1512     Callee->setEntryCount(newEntryCount);
1513 
1514     for (BasicBlock &BB : *Callee)
1515       // No need to update the callsite if it is pruned during inlining.
1516       if (!VMap || VMap->count(&BB))
1517         for (Instruction &I : BB)
1518           if (CallInst *CI = dyn_cast<CallInst>(&I))
1519             CI->updateProfWeight(newEntryCount, priorEntryCount);
1520   }
1521 }
1522 
1523 /// This function inlines the called function into the basic block of the
1524 /// caller. This returns false if it is not possible to inline this call.
1525 /// The program is still in a well defined state if this occurs though.
1526 ///
1527 /// Note that this only does one level of inlining.  For example, if the
1528 /// instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
1529 /// exists in the instruction stream.  Similarly this will inline a recursive
1530 /// function by one level.
1531 llvm::InlineResult llvm::InlineFunction(CallSite CS, InlineFunctionInfo &IFI,
1532                                         AAResults *CalleeAAR,
1533                                         bool InsertLifetime,
1534                                         Function *ForwardVarArgsTo) {
1535   Instruction *TheCall = CS.getInstruction();
1536   assert(TheCall->getParent() && TheCall->getFunction()
1537          && "Instruction not in function!");
1538 
1539   // FIXME: we don't inline callbr yet.
1540   if (isa<CallBrInst>(TheCall))
1541     return InlineResult::failure("We don't inline callbr yet.");
1542 
1543   // If IFI has any state in it, zap it before we fill it in.
1544   IFI.reset();
1545 
1546   Function *CalledFunc = CS.getCalledFunction();
1547   if (!CalledFunc ||               // Can't inline external function or indirect
1548       CalledFunc->isDeclaration()) // call!
1549     return InlineResult::failure("external or indirect");
1550 
1551   // The inliner does not know how to inline through calls with operand bundles
1552   // in general ...
1553   if (CS.hasOperandBundles()) {
1554     for (int i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
1555       uint32_t Tag = CS.getOperandBundleAt(i).getTagID();
1556       // ... but it knows how to inline through "deopt" operand bundles ...
1557       if (Tag == LLVMContext::OB_deopt)
1558         continue;
1559       // ... and "funclet" operand bundles.
1560       if (Tag == LLVMContext::OB_funclet)
1561         continue;
1562 
1563       return InlineResult::failure("unsupported operand bundle");
1564     }
1565   }
1566 
1567   // If the call to the callee cannot throw, set the 'nounwind' flag on any
1568   // calls that we inline.
1569   bool MarkNoUnwind = CS.doesNotThrow();
1570 
1571   BasicBlock *OrigBB = TheCall->getParent();
1572   Function *Caller = OrigBB->getParent();
1573 
1574   // GC poses two hazards to inlining, which only occur when the callee has GC:
1575   //  1. If the caller has no GC, then the callee's GC must be propagated to the
1576   //     caller.
1577   //  2. If the caller has a differing GC, it is invalid to inline.
1578   if (CalledFunc->hasGC()) {
1579     if (!Caller->hasGC())
1580       Caller->setGC(CalledFunc->getGC());
1581     else if (CalledFunc->getGC() != Caller->getGC())
1582       return InlineResult::failure("incompatible GC");
1583   }
1584 
1585   // Get the personality function from the callee if it contains a landing pad.
1586   Constant *CalledPersonality =
1587       CalledFunc->hasPersonalityFn()
1588           ? CalledFunc->getPersonalityFn()->stripPointerCasts()
1589           : nullptr;
1590 
1591   // Find the personality function used by the landing pads of the caller. If it
1592   // exists, then check to see that it matches the personality function used in
1593   // the callee.
1594   Constant *CallerPersonality =
1595       Caller->hasPersonalityFn()
1596           ? Caller->getPersonalityFn()->stripPointerCasts()
1597           : nullptr;
1598   if (CalledPersonality) {
1599     if (!CallerPersonality)
1600       Caller->setPersonalityFn(CalledPersonality);
1601     // If the personality functions match, then we can perform the
1602     // inlining. Otherwise, we can't inline.
1603     // TODO: This isn't 100% true. Some personality functions are proper
1604     //       supersets of others and can be used in place of the other.
1605     else if (CalledPersonality != CallerPersonality)
1606       return InlineResult::failure("incompatible personality");
1607   }
1608 
1609   // We need to figure out which funclet the callsite was in so that we may
1610   // properly nest the callee.
1611   Instruction *CallSiteEHPad = nullptr;
1612   if (CallerPersonality) {
1613     EHPersonality Personality = classifyEHPersonality(CallerPersonality);
1614     if (isScopedEHPersonality(Personality)) {
1615       Optional<OperandBundleUse> ParentFunclet =
1616           CS.getOperandBundle(LLVMContext::OB_funclet);
1617       if (ParentFunclet)
1618         CallSiteEHPad = cast<FuncletPadInst>(ParentFunclet->Inputs.front());
1619 
1620       // OK, the inlining site is legal.  What about the target function?
1621 
1622       if (CallSiteEHPad) {
1623         if (Personality == EHPersonality::MSVC_CXX) {
1624           // The MSVC personality cannot tolerate catches getting inlined into
1625           // cleanup funclets.
1626           if (isa<CleanupPadInst>(CallSiteEHPad)) {
1627             // Ok, the call site is within a cleanuppad.  Let's check the callee
1628             // for catchpads.
1629             for (const BasicBlock &CalledBB : *CalledFunc) {
1630               if (isa<CatchSwitchInst>(CalledBB.getFirstNonPHI()))
1631                 return InlineResult::failure("catch in cleanup funclet");
1632             }
1633           }
1634         } else if (isAsynchronousEHPersonality(Personality)) {
1635           // SEH is even less tolerant, there may not be any sort of exceptional
1636           // funclet in the callee.
1637           for (const BasicBlock &CalledBB : *CalledFunc) {
1638             if (CalledBB.isEHPad())
1639               return InlineResult::failure("SEH in cleanup funclet");
1640           }
1641         }
1642       }
1643     }
1644   }
1645 
1646   // Determine if we are dealing with a call in an EHPad which does not unwind
1647   // to caller.
1648   bool EHPadForCallUnwindsLocally = false;
1649   if (CallSiteEHPad && CS.isCall()) {
1650     UnwindDestMemoTy FuncletUnwindMap;
1651     Value *CallSiteUnwindDestToken =
1652         getUnwindDestToken(CallSiteEHPad, FuncletUnwindMap);
1653 
1654     EHPadForCallUnwindsLocally =
1655         CallSiteUnwindDestToken &&
1656         !isa<ConstantTokenNone>(CallSiteUnwindDestToken);
1657   }
1658 
1659   // Get an iterator to the last basic block in the function, which will have
1660   // the new function inlined after it.
1661   Function::iterator LastBlock = --Caller->end();
1662 
1663   // Make sure to capture all of the return instructions from the cloned
1664   // function.
1665   SmallVector<ReturnInst*, 8> Returns;
1666   ClonedCodeInfo InlinedFunctionInfo;
1667   Function::iterator FirstNewBlock;
1668 
1669   { // Scope to destroy VMap after cloning.
1670     ValueToValueMapTy VMap;
1671     // Keep a list of pair (dst, src) to emit byval initializations.
1672     SmallVector<std::pair<Value*, Value*>, 4> ByValInit;
1673 
1674     auto &DL = Caller->getParent()->getDataLayout();
1675 
1676     // Calculate the vector of arguments to pass into the function cloner, which
1677     // matches up the formal to the actual argument values.
1678     CallSite::arg_iterator AI = CS.arg_begin();
1679     unsigned ArgNo = 0;
1680     for (Function::arg_iterator I = CalledFunc->arg_begin(),
1681          E = CalledFunc->arg_end(); I != E; ++I, ++AI, ++ArgNo) {
1682       Value *ActualArg = *AI;
1683 
1684       // When byval arguments actually inlined, we need to make the copy implied
1685       // by them explicit.  However, we don't do this if the callee is readonly
1686       // or readnone, because the copy would be unneeded: the callee doesn't
1687       // modify the struct.
1688       if (CS.isByValArgument(ArgNo)) {
1689         ActualArg = HandleByValArgument(ActualArg, TheCall, CalledFunc, IFI,
1690                                         CalledFunc->getParamAlignment(ArgNo));
1691         if (ActualArg != *AI)
1692           ByValInit.push_back(std::make_pair(ActualArg, (Value*) *AI));
1693       }
1694 
1695       VMap[&*I] = ActualArg;
1696     }
1697 
1698     // Add alignment assumptions if necessary. We do this before the inlined
1699     // instructions are actually cloned into the caller so that we can easily
1700     // check what will be known at the start of the inlined code.
1701     AddAlignmentAssumptions(CS, IFI);
1702 
1703     // We want the inliner to prune the code as it copies.  We would LOVE to
1704     // have no dead or constant instructions leftover after inlining occurs
1705     // (which can happen, e.g., because an argument was constant), but we'll be
1706     // happy with whatever the cloner can do.
1707     CloneAndPruneFunctionInto(Caller, CalledFunc, VMap,
1708                               /*ModuleLevelChanges=*/false, Returns, ".i",
1709                               &InlinedFunctionInfo, TheCall);
1710     // Remember the first block that is newly cloned over.
1711     FirstNewBlock = LastBlock; ++FirstNewBlock;
1712 
1713     if (IFI.CallerBFI != nullptr && IFI.CalleeBFI != nullptr)
1714       // Update the BFI of blocks cloned into the caller.
1715       updateCallerBFI(OrigBB, VMap, IFI.CallerBFI, IFI.CalleeBFI,
1716                       CalledFunc->front());
1717 
1718     updateCallProfile(CalledFunc, VMap, CalledFunc->getEntryCount(), TheCall,
1719                       IFI.PSI, IFI.CallerBFI);
1720 
1721     // Inject byval arguments initialization.
1722     for (std::pair<Value*, Value*> &Init : ByValInit)
1723       HandleByValArgumentInit(Init.first, Init.second, Caller->getParent(),
1724                               &*FirstNewBlock, IFI);
1725 
1726     Optional<OperandBundleUse> ParentDeopt =
1727         CS.getOperandBundle(LLVMContext::OB_deopt);
1728     if (ParentDeopt) {
1729       SmallVector<OperandBundleDef, 2> OpDefs;
1730 
1731       for (auto &VH : InlinedFunctionInfo.OperandBundleCallSites) {
1732         Instruction *I = dyn_cast_or_null<Instruction>(VH);
1733         if (!I) continue;  // instruction was DCE'd or RAUW'ed to undef
1734 
1735         OpDefs.clear();
1736 
1737         CallSite ICS(I);
1738         OpDefs.reserve(ICS.getNumOperandBundles());
1739 
1740         for (unsigned i = 0, e = ICS.getNumOperandBundles(); i < e; ++i) {
1741           auto ChildOB = ICS.getOperandBundleAt(i);
1742           if (ChildOB.getTagID() != LLVMContext::OB_deopt) {
1743             // If the inlined call has other operand bundles, let them be
1744             OpDefs.emplace_back(ChildOB);
1745             continue;
1746           }
1747 
1748           // It may be useful to separate this logic (of handling operand
1749           // bundles) out to a separate "policy" component if this gets crowded.
1750           // Prepend the parent's deoptimization continuation to the newly
1751           // inlined call's deoptimization continuation.
1752           std::vector<Value *> MergedDeoptArgs;
1753           MergedDeoptArgs.reserve(ParentDeopt->Inputs.size() +
1754                                   ChildOB.Inputs.size());
1755 
1756           MergedDeoptArgs.insert(MergedDeoptArgs.end(),
1757                                  ParentDeopt->Inputs.begin(),
1758                                  ParentDeopt->Inputs.end());
1759           MergedDeoptArgs.insert(MergedDeoptArgs.end(), ChildOB.Inputs.begin(),
1760                                  ChildOB.Inputs.end());
1761 
1762           OpDefs.emplace_back("deopt", std::move(MergedDeoptArgs));
1763         }
1764 
1765         Instruction *NewI = nullptr;
1766         if (isa<CallInst>(I))
1767           NewI = CallInst::Create(cast<CallInst>(I), OpDefs, I);
1768         else if (isa<CallBrInst>(I))
1769           NewI = CallBrInst::Create(cast<CallBrInst>(I), OpDefs, I);
1770         else
1771           NewI = InvokeInst::Create(cast<InvokeInst>(I), OpDefs, I);
1772 
1773         // Note: the RAUW does the appropriate fixup in VMap, so we need to do
1774         // this even if the call returns void.
1775         I->replaceAllUsesWith(NewI);
1776 
1777         VH = nullptr;
1778         I->eraseFromParent();
1779       }
1780     }
1781 
1782     // Update the callgraph if requested.
1783     if (IFI.CG)
1784       UpdateCallGraphAfterInlining(CS, FirstNewBlock, VMap, IFI);
1785 
1786     // For 'nodebug' functions, the associated DISubprogram is always null.
1787     // Conservatively avoid propagating the callsite debug location to
1788     // instructions inlined from a function whose DISubprogram is not null.
1789     fixupLineNumbers(Caller, FirstNewBlock, TheCall,
1790                      CalledFunc->getSubprogram() != nullptr);
1791 
1792     // Clone existing noalias metadata if necessary.
1793     CloneAliasScopeMetadata(CS, VMap);
1794 
1795     // Add noalias metadata if necessary.
1796     AddAliasScopeMetadata(CS, VMap, DL, CalleeAAR);
1797 
1798     // Propagate llvm.mem.parallel_loop_access if necessary.
1799     PropagateParallelLoopAccessMetadata(CS, VMap);
1800 
1801     // Register any cloned assumptions.
1802     if (IFI.GetAssumptionCache)
1803       for (BasicBlock &NewBlock :
1804            make_range(FirstNewBlock->getIterator(), Caller->end()))
1805         for (Instruction &I : NewBlock) {
1806           if (auto *II = dyn_cast<IntrinsicInst>(&I))
1807             if (II->getIntrinsicID() == Intrinsic::assume)
1808               (*IFI.GetAssumptionCache)(*Caller).registerAssumption(II);
1809         }
1810   }
1811 
1812   // If there are any alloca instructions in the block that used to be the entry
1813   // block for the callee, move them to the entry block of the caller.  First
1814   // calculate which instruction they should be inserted before.  We insert the
1815   // instructions at the end of the current alloca list.
1816   {
1817     BasicBlock::iterator InsertPoint = Caller->begin()->begin();
1818     for (BasicBlock::iterator I = FirstNewBlock->begin(),
1819          E = FirstNewBlock->end(); I != E; ) {
1820       AllocaInst *AI = dyn_cast<AllocaInst>(I++);
1821       if (!AI) continue;
1822 
1823       // If the alloca is now dead, remove it.  This often occurs due to code
1824       // specialization.
1825       if (AI->use_empty()) {
1826         AI->eraseFromParent();
1827         continue;
1828       }
1829 
1830       if (!allocaWouldBeStaticInEntry(AI))
1831         continue;
1832 
1833       // Keep track of the static allocas that we inline into the caller.
1834       IFI.StaticAllocas.push_back(AI);
1835 
1836       // Scan for the block of allocas that we can move over, and move them
1837       // all at once.
1838       while (isa<AllocaInst>(I) &&
1839              !cast<AllocaInst>(I)->use_empty() &&
1840              allocaWouldBeStaticInEntry(cast<AllocaInst>(I))) {
1841         IFI.StaticAllocas.push_back(cast<AllocaInst>(I));
1842         ++I;
1843       }
1844 
1845       // Transfer all of the allocas over in a block.  Using splice means
1846       // that the instructions aren't removed from the symbol table, then
1847       // reinserted.
1848       Caller->getEntryBlock().getInstList().splice(
1849           InsertPoint, FirstNewBlock->getInstList(), AI->getIterator(), I);
1850     }
1851   }
1852 
1853   SmallVector<Value*,4> VarArgsToForward;
1854   SmallVector<AttributeSet, 4> VarArgsAttrs;
1855   for (unsigned i = CalledFunc->getFunctionType()->getNumParams();
1856        i < CS.getNumArgOperands(); i++) {
1857     VarArgsToForward.push_back(CS.getArgOperand(i));
1858     VarArgsAttrs.push_back(CS.getAttributes().getParamAttributes(i));
1859   }
1860 
1861   bool InlinedMustTailCalls = false, InlinedDeoptimizeCalls = false;
1862   if (InlinedFunctionInfo.ContainsCalls) {
1863     CallInst::TailCallKind CallSiteTailKind = CallInst::TCK_None;
1864     if (CallInst *CI = dyn_cast<CallInst>(TheCall))
1865       CallSiteTailKind = CI->getTailCallKind();
1866 
1867     // For inlining purposes, the "notail" marker is the same as no marker.
1868     if (CallSiteTailKind == CallInst::TCK_NoTail)
1869       CallSiteTailKind = CallInst::TCK_None;
1870 
1871     for (Function::iterator BB = FirstNewBlock, E = Caller->end(); BB != E;
1872          ++BB) {
1873       for (auto II = BB->begin(); II != BB->end();) {
1874         Instruction &I = *II++;
1875         CallInst *CI = dyn_cast<CallInst>(&I);
1876         if (!CI)
1877           continue;
1878 
1879         // Forward varargs from inlined call site to calls to the
1880         // ForwardVarArgsTo function, if requested, and to musttail calls.
1881         if (!VarArgsToForward.empty() &&
1882             ((ForwardVarArgsTo &&
1883               CI->getCalledFunction() == ForwardVarArgsTo) ||
1884              CI->isMustTailCall())) {
1885           // Collect attributes for non-vararg parameters.
1886           AttributeList Attrs = CI->getAttributes();
1887           SmallVector<AttributeSet, 8> ArgAttrs;
1888           if (!Attrs.isEmpty() || !VarArgsAttrs.empty()) {
1889             for (unsigned ArgNo = 0;
1890                  ArgNo < CI->getFunctionType()->getNumParams(); ++ArgNo)
1891               ArgAttrs.push_back(Attrs.getParamAttributes(ArgNo));
1892           }
1893 
1894           // Add VarArg attributes.
1895           ArgAttrs.append(VarArgsAttrs.begin(), VarArgsAttrs.end());
1896           Attrs = AttributeList::get(CI->getContext(), Attrs.getFnAttributes(),
1897                                      Attrs.getRetAttributes(), ArgAttrs);
1898           // Add VarArgs to existing parameters.
1899           SmallVector<Value *, 6> Params(CI->arg_operands());
1900           Params.append(VarArgsToForward.begin(), VarArgsToForward.end());
1901           CallInst *NewCI = CallInst::Create(
1902               CI->getFunctionType(), CI->getCalledOperand(), Params, "", CI);
1903           NewCI->setDebugLoc(CI->getDebugLoc());
1904           NewCI->setAttributes(Attrs);
1905           NewCI->setCallingConv(CI->getCallingConv());
1906           CI->replaceAllUsesWith(NewCI);
1907           CI->eraseFromParent();
1908           CI = NewCI;
1909         }
1910 
1911         if (Function *F = CI->getCalledFunction())
1912           InlinedDeoptimizeCalls |=
1913               F->getIntrinsicID() == Intrinsic::experimental_deoptimize;
1914 
1915         // We need to reduce the strength of any inlined tail calls.  For
1916         // musttail, we have to avoid introducing potential unbounded stack
1917         // growth.  For example, if functions 'f' and 'g' are mutually recursive
1918         // with musttail, we can inline 'g' into 'f' so long as we preserve
1919         // musttail on the cloned call to 'f'.  If either the inlined call site
1920         // or the cloned call site is *not* musttail, the program already has
1921         // one frame of stack growth, so it's safe to remove musttail.  Here is
1922         // a table of example transformations:
1923         //
1924         //    f -> musttail g -> musttail f  ==>  f -> musttail f
1925         //    f -> musttail g ->     tail f  ==>  f ->     tail f
1926         //    f ->          g -> musttail f  ==>  f ->          f
1927         //    f ->          g ->     tail f  ==>  f ->          f
1928         //
1929         // Inlined notail calls should remain notail calls.
1930         CallInst::TailCallKind ChildTCK = CI->getTailCallKind();
1931         if (ChildTCK != CallInst::TCK_NoTail)
1932           ChildTCK = std::min(CallSiteTailKind, ChildTCK);
1933         CI->setTailCallKind(ChildTCK);
1934         InlinedMustTailCalls |= CI->isMustTailCall();
1935 
1936         // Calls inlined through a 'nounwind' call site should be marked
1937         // 'nounwind'.
1938         if (MarkNoUnwind)
1939           CI->setDoesNotThrow();
1940       }
1941     }
1942   }
1943 
1944   // Leave lifetime markers for the static alloca's, scoping them to the
1945   // function we just inlined.
1946   if (InsertLifetime && !IFI.StaticAllocas.empty()) {
1947     IRBuilder<> builder(&FirstNewBlock->front());
1948     for (unsigned ai = 0, ae = IFI.StaticAllocas.size(); ai != ae; ++ai) {
1949       AllocaInst *AI = IFI.StaticAllocas[ai];
1950       // Don't mark swifterror allocas. They can't have bitcast uses.
1951       if (AI->isSwiftError())
1952         continue;
1953 
1954       // If the alloca is already scoped to something smaller than the whole
1955       // function then there's no need to add redundant, less accurate markers.
1956       if (hasLifetimeMarkers(AI))
1957         continue;
1958 
1959       // Try to determine the size of the allocation.
1960       ConstantInt *AllocaSize = nullptr;
1961       if (ConstantInt *AIArraySize =
1962           dyn_cast<ConstantInt>(AI->getArraySize())) {
1963         auto &DL = Caller->getParent()->getDataLayout();
1964         Type *AllocaType = AI->getAllocatedType();
1965         uint64_t AllocaTypeSize = DL.getTypeAllocSize(AllocaType);
1966         uint64_t AllocaArraySize = AIArraySize->getLimitedValue();
1967 
1968         // Don't add markers for zero-sized allocas.
1969         if (AllocaArraySize == 0)
1970           continue;
1971 
1972         // Check that array size doesn't saturate uint64_t and doesn't
1973         // overflow when it's multiplied by type size.
1974         if (AllocaArraySize != std::numeric_limits<uint64_t>::max() &&
1975             std::numeric_limits<uint64_t>::max() / AllocaArraySize >=
1976                 AllocaTypeSize) {
1977           AllocaSize = ConstantInt::get(Type::getInt64Ty(AI->getContext()),
1978                                         AllocaArraySize * AllocaTypeSize);
1979         }
1980       }
1981 
1982       builder.CreateLifetimeStart(AI, AllocaSize);
1983       for (ReturnInst *RI : Returns) {
1984         // Don't insert llvm.lifetime.end calls between a musttail or deoptimize
1985         // call and a return.  The return kills all local allocas.
1986         if (InlinedMustTailCalls &&
1987             RI->getParent()->getTerminatingMustTailCall())
1988           continue;
1989         if (InlinedDeoptimizeCalls &&
1990             RI->getParent()->getTerminatingDeoptimizeCall())
1991           continue;
1992         IRBuilder<>(RI).CreateLifetimeEnd(AI, AllocaSize);
1993       }
1994     }
1995   }
1996 
1997   // If the inlined code contained dynamic alloca instructions, wrap the inlined
1998   // code with llvm.stacksave/llvm.stackrestore intrinsics.
1999   if (InlinedFunctionInfo.ContainsDynamicAllocas) {
2000     Module *M = Caller->getParent();
2001     // Get the two intrinsics we care about.
2002     Function *StackSave = Intrinsic::getDeclaration(M, Intrinsic::stacksave);
2003     Function *StackRestore=Intrinsic::getDeclaration(M,Intrinsic::stackrestore);
2004 
2005     // Insert the llvm.stacksave.
2006     CallInst *SavedPtr = IRBuilder<>(&*FirstNewBlock, FirstNewBlock->begin())
2007                              .CreateCall(StackSave, {}, "savedstack");
2008 
2009     // Insert a call to llvm.stackrestore before any return instructions in the
2010     // inlined function.
2011     for (ReturnInst *RI : Returns) {
2012       // Don't insert llvm.stackrestore calls between a musttail or deoptimize
2013       // call and a return.  The return will restore the stack pointer.
2014       if (InlinedMustTailCalls && RI->getParent()->getTerminatingMustTailCall())
2015         continue;
2016       if (InlinedDeoptimizeCalls && RI->getParent()->getTerminatingDeoptimizeCall())
2017         continue;
2018       IRBuilder<>(RI).CreateCall(StackRestore, SavedPtr);
2019     }
2020   }
2021 
2022   // If we are inlining for an invoke instruction, we must make sure to rewrite
2023   // any call instructions into invoke instructions.  This is sensitive to which
2024   // funclet pads were top-level in the inlinee, so must be done before
2025   // rewriting the "parent pad" links.
2026   if (auto *II = dyn_cast<InvokeInst>(TheCall)) {
2027     BasicBlock *UnwindDest = II->getUnwindDest();
2028     Instruction *FirstNonPHI = UnwindDest->getFirstNonPHI();
2029     if (isa<LandingPadInst>(FirstNonPHI)) {
2030       HandleInlinedLandingPad(II, &*FirstNewBlock, InlinedFunctionInfo);
2031     } else {
2032       HandleInlinedEHPad(II, &*FirstNewBlock, InlinedFunctionInfo);
2033     }
2034   }
2035 
2036   // Update the lexical scopes of the new funclets and callsites.
2037   // Anything that had 'none' as its parent is now nested inside the callsite's
2038   // EHPad.
2039 
2040   if (CallSiteEHPad) {
2041     for (Function::iterator BB = FirstNewBlock->getIterator(),
2042                             E = Caller->end();
2043          BB != E; ++BB) {
2044       // Add bundle operands to any top-level call sites.
2045       SmallVector<OperandBundleDef, 1> OpBundles;
2046       for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E;) {
2047         Instruction *I = &*BBI++;
2048         CallSite CS(I);
2049         if (!CS)
2050           continue;
2051 
2052         // Skip call sites which are nounwind intrinsics.
2053         auto *CalledFn =
2054             dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts());
2055         if (CalledFn && CalledFn->isIntrinsic() && CS.doesNotThrow())
2056           continue;
2057 
2058         // Skip call sites which already have a "funclet" bundle.
2059         if (CS.getOperandBundle(LLVMContext::OB_funclet))
2060           continue;
2061 
2062         CS.getOperandBundlesAsDefs(OpBundles);
2063         OpBundles.emplace_back("funclet", CallSiteEHPad);
2064 
2065         Instruction *NewInst;
2066         if (CS.isCall())
2067           NewInst = CallInst::Create(cast<CallInst>(I), OpBundles, I);
2068         else if (CS.isCallBr())
2069           NewInst = CallBrInst::Create(cast<CallBrInst>(I), OpBundles, I);
2070         else
2071           NewInst = InvokeInst::Create(cast<InvokeInst>(I), OpBundles, I);
2072         NewInst->takeName(I);
2073         I->replaceAllUsesWith(NewInst);
2074         I->eraseFromParent();
2075 
2076         OpBundles.clear();
2077       }
2078 
2079       // It is problematic if the inlinee has a cleanupret which unwinds to
2080       // caller and we inline it into a call site which doesn't unwind but into
2081       // an EH pad that does.  Such an edge must be dynamically unreachable.
2082       // As such, we replace the cleanupret with unreachable.
2083       if (auto *CleanupRet = dyn_cast<CleanupReturnInst>(BB->getTerminator()))
2084         if (CleanupRet->unwindsToCaller() && EHPadForCallUnwindsLocally)
2085           changeToUnreachable(CleanupRet, /*UseLLVMTrap=*/false);
2086 
2087       Instruction *I = BB->getFirstNonPHI();
2088       if (!I->isEHPad())
2089         continue;
2090 
2091       if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(I)) {
2092         if (isa<ConstantTokenNone>(CatchSwitch->getParentPad()))
2093           CatchSwitch->setParentPad(CallSiteEHPad);
2094       } else {
2095         auto *FPI = cast<FuncletPadInst>(I);
2096         if (isa<ConstantTokenNone>(FPI->getParentPad()))
2097           FPI->setParentPad(CallSiteEHPad);
2098       }
2099     }
2100   }
2101 
2102   if (InlinedDeoptimizeCalls) {
2103     // We need to at least remove the deoptimizing returns from the Return set,
2104     // so that the control flow from those returns does not get merged into the
2105     // caller (but terminate it instead).  If the caller's return type does not
2106     // match the callee's return type, we also need to change the return type of
2107     // the intrinsic.
2108     if (Caller->getReturnType() == TheCall->getType()) {
2109       auto NewEnd = llvm::remove_if(Returns, [](ReturnInst *RI) {
2110         return RI->getParent()->getTerminatingDeoptimizeCall() != nullptr;
2111       });
2112       Returns.erase(NewEnd, Returns.end());
2113     } else {
2114       SmallVector<ReturnInst *, 8> NormalReturns;
2115       Function *NewDeoptIntrinsic = Intrinsic::getDeclaration(
2116           Caller->getParent(), Intrinsic::experimental_deoptimize,
2117           {Caller->getReturnType()});
2118 
2119       for (ReturnInst *RI : Returns) {
2120         CallInst *DeoptCall = RI->getParent()->getTerminatingDeoptimizeCall();
2121         if (!DeoptCall) {
2122           NormalReturns.push_back(RI);
2123           continue;
2124         }
2125 
2126         // The calling convention on the deoptimize call itself may be bogus,
2127         // since the code we're inlining may have undefined behavior (and may
2128         // never actually execute at runtime); but all
2129         // @llvm.experimental.deoptimize declarations have to have the same
2130         // calling convention in a well-formed module.
2131         auto CallingConv = DeoptCall->getCalledFunction()->getCallingConv();
2132         NewDeoptIntrinsic->setCallingConv(CallingConv);
2133         auto *CurBB = RI->getParent();
2134         RI->eraseFromParent();
2135 
2136         SmallVector<Value *, 4> CallArgs(DeoptCall->arg_begin(),
2137                                          DeoptCall->arg_end());
2138 
2139         SmallVector<OperandBundleDef, 1> OpBundles;
2140         DeoptCall->getOperandBundlesAsDefs(OpBundles);
2141         DeoptCall->eraseFromParent();
2142         assert(!OpBundles.empty() &&
2143                "Expected at least the deopt operand bundle");
2144 
2145         IRBuilder<> Builder(CurBB);
2146         CallInst *NewDeoptCall =
2147             Builder.CreateCall(NewDeoptIntrinsic, CallArgs, OpBundles);
2148         NewDeoptCall->setCallingConv(CallingConv);
2149         if (NewDeoptCall->getType()->isVoidTy())
2150           Builder.CreateRetVoid();
2151         else
2152           Builder.CreateRet(NewDeoptCall);
2153       }
2154 
2155       // Leave behind the normal returns so we can merge control flow.
2156       std::swap(Returns, NormalReturns);
2157     }
2158   }
2159 
2160   // Handle any inlined musttail call sites.  In order for a new call site to be
2161   // musttail, the source of the clone and the inlined call site must have been
2162   // musttail.  Therefore it's safe to return without merging control into the
2163   // phi below.
2164   if (InlinedMustTailCalls) {
2165     // Check if we need to bitcast the result of any musttail calls.
2166     Type *NewRetTy = Caller->getReturnType();
2167     bool NeedBitCast = !TheCall->use_empty() && TheCall->getType() != NewRetTy;
2168 
2169     // Handle the returns preceded by musttail calls separately.
2170     SmallVector<ReturnInst *, 8> NormalReturns;
2171     for (ReturnInst *RI : Returns) {
2172       CallInst *ReturnedMustTail =
2173           RI->getParent()->getTerminatingMustTailCall();
2174       if (!ReturnedMustTail) {
2175         NormalReturns.push_back(RI);
2176         continue;
2177       }
2178       if (!NeedBitCast)
2179         continue;
2180 
2181       // Delete the old return and any preceding bitcast.
2182       BasicBlock *CurBB = RI->getParent();
2183       auto *OldCast = dyn_cast_or_null<BitCastInst>(RI->getReturnValue());
2184       RI->eraseFromParent();
2185       if (OldCast)
2186         OldCast->eraseFromParent();
2187 
2188       // Insert a new bitcast and return with the right type.
2189       IRBuilder<> Builder(CurBB);
2190       Builder.CreateRet(Builder.CreateBitCast(ReturnedMustTail, NewRetTy));
2191     }
2192 
2193     // Leave behind the normal returns so we can merge control flow.
2194     std::swap(Returns, NormalReturns);
2195   }
2196 
2197   // Now that all of the transforms on the inlined code have taken place but
2198   // before we splice the inlined code into the CFG and lose track of which
2199   // blocks were actually inlined, collect the call sites. We only do this if
2200   // call graph updates weren't requested, as those provide value handle based
2201   // tracking of inlined call sites instead.
2202   if (InlinedFunctionInfo.ContainsCalls && !IFI.CG) {
2203     // Otherwise just collect the raw call sites that were inlined.
2204     for (BasicBlock &NewBB :
2205          make_range(FirstNewBlock->getIterator(), Caller->end()))
2206       for (Instruction &I : NewBB)
2207         if (auto CS = CallSite(&I))
2208           IFI.InlinedCallSites.push_back(CS);
2209   }
2210 
2211   // If we cloned in _exactly one_ basic block, and if that block ends in a
2212   // return instruction, we splice the body of the inlined callee directly into
2213   // the calling basic block.
2214   if (Returns.size() == 1 && std::distance(FirstNewBlock, Caller->end()) == 1) {
2215     // Move all of the instructions right before the call.
2216     OrigBB->getInstList().splice(TheCall->getIterator(),
2217                                  FirstNewBlock->getInstList(),
2218                                  FirstNewBlock->begin(), FirstNewBlock->end());
2219     // Remove the cloned basic block.
2220     Caller->getBasicBlockList().pop_back();
2221 
2222     // If the call site was an invoke instruction, add a branch to the normal
2223     // destination.
2224     if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
2225       BranchInst *NewBr = BranchInst::Create(II->getNormalDest(), TheCall);
2226       NewBr->setDebugLoc(Returns[0]->getDebugLoc());
2227     }
2228 
2229     // If the return instruction returned a value, replace uses of the call with
2230     // uses of the returned value.
2231     if (!TheCall->use_empty()) {
2232       ReturnInst *R = Returns[0];
2233       if (TheCall == R->getReturnValue())
2234         TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
2235       else
2236         TheCall->replaceAllUsesWith(R->getReturnValue());
2237     }
2238     // Since we are now done with the Call/Invoke, we can delete it.
2239     TheCall->eraseFromParent();
2240 
2241     // Since we are now done with the return instruction, delete it also.
2242     Returns[0]->eraseFromParent();
2243 
2244     // We are now done with the inlining.
2245     return InlineResult::success();
2246   }
2247 
2248   // Otherwise, we have the normal case, of more than one block to inline or
2249   // multiple return sites.
2250 
2251   // We want to clone the entire callee function into the hole between the
2252   // "starter" and "ender" blocks.  How we accomplish this depends on whether
2253   // this is an invoke instruction or a call instruction.
2254   BasicBlock *AfterCallBB;
2255   BranchInst *CreatedBranchToNormalDest = nullptr;
2256   if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
2257 
2258     // Add an unconditional branch to make this look like the CallInst case...
2259     CreatedBranchToNormalDest = BranchInst::Create(II->getNormalDest(), TheCall);
2260 
2261     // Split the basic block.  This guarantees that no PHI nodes will have to be
2262     // updated due to new incoming edges, and make the invoke case more
2263     // symmetric to the call case.
2264     AfterCallBB =
2265         OrigBB->splitBasicBlock(CreatedBranchToNormalDest->getIterator(),
2266                                 CalledFunc->getName() + ".exit");
2267 
2268   } else {  // It's a call
2269     // If this is a call instruction, we need to split the basic block that
2270     // the call lives in.
2271     //
2272     AfterCallBB = OrigBB->splitBasicBlock(TheCall->getIterator(),
2273                                           CalledFunc->getName() + ".exit");
2274   }
2275 
2276   if (IFI.CallerBFI) {
2277     // Copy original BB's block frequency to AfterCallBB
2278     IFI.CallerBFI->setBlockFreq(
2279         AfterCallBB, IFI.CallerBFI->getBlockFreq(OrigBB).getFrequency());
2280   }
2281 
2282   // Change the branch that used to go to AfterCallBB to branch to the first
2283   // basic block of the inlined function.
2284   //
2285   Instruction *Br = OrigBB->getTerminator();
2286   assert(Br && Br->getOpcode() == Instruction::Br &&
2287          "splitBasicBlock broken!");
2288   Br->setOperand(0, &*FirstNewBlock);
2289 
2290   // Now that the function is correct, make it a little bit nicer.  In
2291   // particular, move the basic blocks inserted from the end of the function
2292   // into the space made by splitting the source basic block.
2293   Caller->getBasicBlockList().splice(AfterCallBB->getIterator(),
2294                                      Caller->getBasicBlockList(), FirstNewBlock,
2295                                      Caller->end());
2296 
2297   // Handle all of the return instructions that we just cloned in, and eliminate
2298   // any users of the original call/invoke instruction.
2299   Type *RTy = CalledFunc->getReturnType();
2300 
2301   PHINode *PHI = nullptr;
2302   if (Returns.size() > 1) {
2303     // The PHI node should go at the front of the new basic block to merge all
2304     // possible incoming values.
2305     if (!TheCall->use_empty()) {
2306       PHI = PHINode::Create(RTy, Returns.size(), TheCall->getName(),
2307                             &AfterCallBB->front());
2308       // Anything that used the result of the function call should now use the
2309       // PHI node as their operand.
2310       TheCall->replaceAllUsesWith(PHI);
2311     }
2312 
2313     // Loop over all of the return instructions adding entries to the PHI node
2314     // as appropriate.
2315     if (PHI) {
2316       for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
2317         ReturnInst *RI = Returns[i];
2318         assert(RI->getReturnValue()->getType() == PHI->getType() &&
2319                "Ret value not consistent in function!");
2320         PHI->addIncoming(RI->getReturnValue(), RI->getParent());
2321       }
2322     }
2323 
2324     // Add a branch to the merge points and remove return instructions.
2325     DebugLoc Loc;
2326     for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
2327       ReturnInst *RI = Returns[i];
2328       BranchInst* BI = BranchInst::Create(AfterCallBB, RI);
2329       Loc = RI->getDebugLoc();
2330       BI->setDebugLoc(Loc);
2331       RI->eraseFromParent();
2332     }
2333     // We need to set the debug location to *somewhere* inside the
2334     // inlined function. The line number may be nonsensical, but the
2335     // instruction will at least be associated with the right
2336     // function.
2337     if (CreatedBranchToNormalDest)
2338       CreatedBranchToNormalDest->setDebugLoc(Loc);
2339   } else if (!Returns.empty()) {
2340     // Otherwise, if there is exactly one return value, just replace anything
2341     // using the return value of the call with the computed value.
2342     if (!TheCall->use_empty()) {
2343       if (TheCall == Returns[0]->getReturnValue())
2344         TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
2345       else
2346         TheCall->replaceAllUsesWith(Returns[0]->getReturnValue());
2347     }
2348 
2349     // Update PHI nodes that use the ReturnBB to use the AfterCallBB.
2350     BasicBlock *ReturnBB = Returns[0]->getParent();
2351     ReturnBB->replaceAllUsesWith(AfterCallBB);
2352 
2353     // Splice the code from the return block into the block that it will return
2354     // to, which contains the code that was after the call.
2355     AfterCallBB->getInstList().splice(AfterCallBB->begin(),
2356                                       ReturnBB->getInstList());
2357 
2358     if (CreatedBranchToNormalDest)
2359       CreatedBranchToNormalDest->setDebugLoc(Returns[0]->getDebugLoc());
2360 
2361     // Delete the return instruction now and empty ReturnBB now.
2362     Returns[0]->eraseFromParent();
2363     ReturnBB->eraseFromParent();
2364   } else if (!TheCall->use_empty()) {
2365     // No returns, but something is using the return value of the call.  Just
2366     // nuke the result.
2367     TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
2368   }
2369 
2370   // Since we are now done with the Call/Invoke, we can delete it.
2371   TheCall->eraseFromParent();
2372 
2373   // If we inlined any musttail calls and the original return is now
2374   // unreachable, delete it.  It can only contain a bitcast and ret.
2375   if (InlinedMustTailCalls && pred_begin(AfterCallBB) == pred_end(AfterCallBB))
2376     AfterCallBB->eraseFromParent();
2377 
2378   // We should always be able to fold the entry block of the function into the
2379   // single predecessor of the block...
2380   assert(cast<BranchInst>(Br)->isUnconditional() && "splitBasicBlock broken!");
2381   BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0);
2382 
2383   // Splice the code entry block into calling block, right before the
2384   // unconditional branch.
2385   CalleeEntry->replaceAllUsesWith(OrigBB);  // Update PHI nodes
2386   OrigBB->getInstList().splice(Br->getIterator(), CalleeEntry->getInstList());
2387 
2388   // Remove the unconditional branch.
2389   OrigBB->getInstList().erase(Br);
2390 
2391   // Now we can remove the CalleeEntry block, which is now empty.
2392   Caller->getBasicBlockList().erase(CalleeEntry);
2393 
2394   // If we inserted a phi node, check to see if it has a single value (e.g. all
2395   // the entries are the same or undef).  If so, remove the PHI so it doesn't
2396   // block other optimizations.
2397   if (PHI) {
2398     AssumptionCache *AC =
2399         IFI.GetAssumptionCache ? &(*IFI.GetAssumptionCache)(*Caller) : nullptr;
2400     auto &DL = Caller->getParent()->getDataLayout();
2401     if (Value *V = SimplifyInstruction(PHI, {DL, nullptr, nullptr, AC})) {
2402       PHI->replaceAllUsesWith(V);
2403       PHI->eraseFromParent();
2404     }
2405   }
2406 
2407   return InlineResult::success();
2408 }
2409