cafd1818fed6936656b59b075a0c82bdca06e99c
[oota-llvm.git] / lib / Transforms / Utils / InlineFunction.cpp
1 //===- InlineFunction.cpp - Code to perform function inlining -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements inlining of a function into a call site, resolving
11 // parameters and the return value as appropriate.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/Transforms/Utils/Cloning.h"
16 #include "llvm/ADT/SetVector.h"
17 #include "llvm/ADT/SmallSet.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/Analysis/AssumptionCache.h"
22 #include "llvm/Analysis/CallGraph.h"
23 #include "llvm/Analysis/CaptureTracking.h"
24 #include "llvm/Analysis/InstructionSimplify.h"
25 #include "llvm/Analysis/ValueTracking.h"
26 #include "llvm/IR/Attributes.h"
27 #include "llvm/IR/CallSite.h"
28 #include "llvm/IR/CFG.h"
29 #include "llvm/IR/Constants.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/DebugInfo.h"
32 #include "llvm/IR/DerivedTypes.h"
33 #include "llvm/IR/DIBuilder.h"
34 #include "llvm/IR/Dominators.h"
35 #include "llvm/IR/IRBuilder.h"
36 #include "llvm/IR/Instructions.h"
37 #include "llvm/IR/IntrinsicInst.h"
38 #include "llvm/IR/Intrinsics.h"
39 #include "llvm/IR/MDBuilder.h"
40 #include "llvm/IR/Module.h"
41 #include "llvm/Transforms/Utils/Local.h"
42 #include "llvm/Support/CommandLine.h"
43 #include <algorithm>
44
45 using namespace llvm;
46
47 static cl::opt<bool>
48 EnableNoAliasConversion("enable-noalias-to-md-conversion", cl::init(true),
49   cl::Hidden,
50   cl::desc("Convert noalias attributes to metadata during inlining."));
51
52 static cl::opt<bool>
53 PreserveAlignmentAssumptions("preserve-alignment-assumptions-during-inlining",
54   cl::init(true), cl::Hidden,
55   cl::desc("Convert align attributes to assumptions during inlining."));
56
57 bool llvm::InlineFunction(CallInst *CI, InlineFunctionInfo &IFI,
58                           AAResults *CalleeAAR, bool InsertLifetime) {
59   return InlineFunction(CallSite(CI), IFI, CalleeAAR, InsertLifetime);
60 }
61 bool llvm::InlineFunction(InvokeInst *II, InlineFunctionInfo &IFI,
62                           AAResults *CalleeAAR, bool InsertLifetime) {
63   return InlineFunction(CallSite(II), IFI, CalleeAAR, InsertLifetime);
64 }
65
66 namespace {
67   /// A class for recording information about inlining a landing pad.
68   class LandingPadInliningInfo {
69     BasicBlock *OuterResumeDest; ///< Destination of the invoke's unwind.
70     BasicBlock *InnerResumeDest; ///< Destination for the callee's resume.
71     LandingPadInst *CallerLPad;  ///< LandingPadInst associated with the invoke.
72     PHINode *InnerEHValuesPHI;   ///< PHI for EH values from landingpad insts.
73     SmallVector<Value*, 8> UnwindDestPHIValues;
74
75   public:
76     LandingPadInliningInfo(InvokeInst *II)
77       : OuterResumeDest(II->getUnwindDest()), InnerResumeDest(nullptr),
78         CallerLPad(nullptr), InnerEHValuesPHI(nullptr) {
79       // If there are PHI nodes in the unwind destination block, we need to keep
80       // track of which values came into them from the invoke before removing
81       // the edge from this block.
82       llvm::BasicBlock *InvokeBB = II->getParent();
83       BasicBlock::iterator I = OuterResumeDest->begin();
84       for (; isa<PHINode>(I); ++I) {
85         // Save the value to use for this edge.
86         PHINode *PHI = cast<PHINode>(I);
87         UnwindDestPHIValues.push_back(PHI->getIncomingValueForBlock(InvokeBB));
88       }
89
90       CallerLPad = cast<LandingPadInst>(I);
91     }
92
93     /// The outer unwind destination is the target of
94     /// unwind edges introduced for calls within the inlined function.
95     BasicBlock *getOuterResumeDest() const {
96       return OuterResumeDest;
97     }
98
99     BasicBlock *getInnerResumeDest();
100
101     LandingPadInst *getLandingPadInst() const { return CallerLPad; }
102
103     /// Forward the 'resume' instruction to the caller's landing pad block.
104     /// When the landing pad block has only one predecessor, this is
105     /// a simple branch. When there is more than one predecessor, we need to
106     /// split the landing pad block after the landingpad instruction and jump
107     /// to there.
108     void forwardResume(ResumeInst *RI,
109                        SmallPtrSetImpl<LandingPadInst*> &InlinedLPads);
110
111     /// Add incoming-PHI values to the unwind destination block for the given
112     /// basic block, using the values for the original invoke's source block.
113     void addIncomingPHIValuesFor(BasicBlock *BB) const {
114       addIncomingPHIValuesForInto(BB, OuterResumeDest);
115     }
116
117     void addIncomingPHIValuesForInto(BasicBlock *src, BasicBlock *dest) const {
118       BasicBlock::iterator I = dest->begin();
119       for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
120         PHINode *phi = cast<PHINode>(I);
121         phi->addIncoming(UnwindDestPHIValues[i], src);
122       }
123     }
124   };
125 } // anonymous namespace
126
127 /// Get or create a target for the branch from ResumeInsts.
128 BasicBlock *LandingPadInliningInfo::getInnerResumeDest() {
129   if (InnerResumeDest) return InnerResumeDest;
130
131   // Split the landing pad.
132   BasicBlock::iterator SplitPoint = ++CallerLPad->getIterator();
133   InnerResumeDest =
134     OuterResumeDest->splitBasicBlock(SplitPoint,
135                                      OuterResumeDest->getName() + ".body");
136
137   // The number of incoming edges we expect to the inner landing pad.
138   const unsigned PHICapacity = 2;
139
140   // Create corresponding new PHIs for all the PHIs in the outer landing pad.
141   Instruction *InsertPoint = &InnerResumeDest->front();
142   BasicBlock::iterator I = OuterResumeDest->begin();
143   for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
144     PHINode *OuterPHI = cast<PHINode>(I);
145     PHINode *InnerPHI = PHINode::Create(OuterPHI->getType(), PHICapacity,
146                                         OuterPHI->getName() + ".lpad-body",
147                                         InsertPoint);
148     OuterPHI->replaceAllUsesWith(InnerPHI);
149     InnerPHI->addIncoming(OuterPHI, OuterResumeDest);
150   }
151
152   // Create a PHI for the exception values.
153   InnerEHValuesPHI = PHINode::Create(CallerLPad->getType(), PHICapacity,
154                                      "eh.lpad-body", InsertPoint);
155   CallerLPad->replaceAllUsesWith(InnerEHValuesPHI);
156   InnerEHValuesPHI->addIncoming(CallerLPad, OuterResumeDest);
157
158   // All done.
159   return InnerResumeDest;
160 }
161
162 /// Forward the 'resume' instruction to the caller's landing pad block.
163 /// When the landing pad block has only one predecessor, this is a simple
164 /// branch. When there is more than one predecessor, we need to split the
165 /// landing pad block after the landingpad instruction and jump to there.
166 void LandingPadInliningInfo::forwardResume(
167     ResumeInst *RI, SmallPtrSetImpl<LandingPadInst *> &InlinedLPads) {
168   BasicBlock *Dest = getInnerResumeDest();
169   BasicBlock *Src = RI->getParent();
170
171   BranchInst::Create(Dest, Src);
172
173   // Update the PHIs in the destination. They were inserted in an order which
174   // makes this work.
175   addIncomingPHIValuesForInto(Src, Dest);
176
177   InnerEHValuesPHI->addIncoming(RI->getOperand(0), Src);
178   RI->eraseFromParent();
179 }
180
181 /// When we inline a basic block into an invoke,
182 /// we have to turn all of the calls that can throw into invokes.
183 /// This function analyze BB to see if there are any calls, and if so,
184 /// it rewrites them to be invokes that jump to InvokeDest and fills in the PHI
185 /// nodes in that block with the values specified in InvokeDestPHIValues.
186 static BasicBlock *
187 HandleCallsInBlockInlinedThroughInvoke(BasicBlock *BB, BasicBlock *UnwindEdge) {
188   for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
189     Instruction *I = &*BBI++;
190
191     // We only need to check for function calls: inlined invoke
192     // instructions require no special handling.
193     CallInst *CI = dyn_cast<CallInst>(I);
194
195     // If this call cannot unwind, don't convert it to an invoke.
196     // Inline asm calls cannot throw.
197     if (!CI || CI->doesNotThrow() || isa<InlineAsm>(CI->getCalledValue()))
198       continue;
199
200     // Convert this function call into an invoke instruction.  First, split the
201     // basic block.
202     BasicBlock *Split =
203         BB->splitBasicBlock(CI->getIterator(), CI->getName() + ".noexc");
204
205     // Delete the unconditional branch inserted by splitBasicBlock
206     BB->getInstList().pop_back();
207
208     // Create the new invoke instruction.
209     SmallVector<Value*, 8> InvokeArgs(CI->arg_begin(), CI->arg_end());
210     SmallVector<OperandBundleDef, 1> OpBundles;
211
212     CI->getOperandBundlesAsDefs(OpBundles);
213
214     // Note: we're round tripping operand bundles through memory here, and that
215     // can potentially be avoided with a cleverer API design that we do not have
216     // as of this time.
217
218     InvokeInst *II =
219         InvokeInst::Create(CI->getCalledValue(), Split, UnwindEdge, InvokeArgs,
220                            OpBundles, CI->getName(), BB);
221     II->setDebugLoc(CI->getDebugLoc());
222     II->setCallingConv(CI->getCallingConv());
223     II->setAttributes(CI->getAttributes());
224     
225     // Make sure that anything using the call now uses the invoke!  This also
226     // updates the CallGraph if present, because it uses a WeakVH.
227     CI->replaceAllUsesWith(II);
228
229     // Delete the original call
230     Split->getInstList().pop_front();
231     return BB;
232   }
233   return nullptr;
234 }
235
236 /// If we inlined an invoke site, we need to convert calls
237 /// in the body of the inlined function into invokes.
238 ///
239 /// II is the invoke instruction being inlined.  FirstNewBlock is the first
240 /// block of the inlined code (the last block is the end of the function),
241 /// and InlineCodeInfo is information about the code that got inlined.
242 static void HandleInlinedLandingPad(InvokeInst *II, BasicBlock *FirstNewBlock,
243                                     ClonedCodeInfo &InlinedCodeInfo) {
244   BasicBlock *InvokeDest = II->getUnwindDest();
245
246   Function *Caller = FirstNewBlock->getParent();
247
248   // The inlined code is currently at the end of the function, scan from the
249   // start of the inlined code to its end, checking for stuff we need to
250   // rewrite.
251   LandingPadInliningInfo Invoke(II);
252
253   // Get all of the inlined landing pad instructions.
254   SmallPtrSet<LandingPadInst*, 16> InlinedLPads;
255   for (Function::iterator I = FirstNewBlock->getIterator(), E = Caller->end();
256        I != E; ++I)
257     if (InvokeInst *II = dyn_cast<InvokeInst>(I->getTerminator()))
258       InlinedLPads.insert(II->getLandingPadInst());
259
260   // Append the clauses from the outer landing pad instruction into the inlined
261   // landing pad instructions.
262   LandingPadInst *OuterLPad = Invoke.getLandingPadInst();
263   for (LandingPadInst *InlinedLPad : InlinedLPads) {
264     unsigned OuterNum = OuterLPad->getNumClauses();
265     InlinedLPad->reserveClauses(OuterNum);
266     for (unsigned OuterIdx = 0; OuterIdx != OuterNum; ++OuterIdx)
267       InlinedLPad->addClause(OuterLPad->getClause(OuterIdx));
268     if (OuterLPad->isCleanup())
269       InlinedLPad->setCleanup(true);
270   }
271
272   for (Function::iterator BB = FirstNewBlock->getIterator(), E = Caller->end();
273        BB != E; ++BB) {
274     if (InlinedCodeInfo.ContainsCalls)
275       if (BasicBlock *NewBB = HandleCallsInBlockInlinedThroughInvoke(
276               &*BB, Invoke.getOuterResumeDest()))
277         // Update any PHI nodes in the exceptional block to indicate that there
278         // is now a new entry in them.
279         Invoke.addIncomingPHIValuesFor(NewBB);
280
281     // Forward any resumes that are remaining here.
282     if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator()))
283       Invoke.forwardResume(RI, InlinedLPads);
284   }
285
286   // Now that everything is happy, we have one final detail.  The PHI nodes in
287   // the exception destination block still have entries due to the original
288   // invoke instruction. Eliminate these entries (which might even delete the
289   // PHI node) now.
290   InvokeDest->removePredecessor(II->getParent());
291 }
292
293 /// If we inlined an invoke site, we need to convert calls
294 /// in the body of the inlined function into invokes.
295 ///
296 /// II is the invoke instruction being inlined.  FirstNewBlock is the first
297 /// block of the inlined code (the last block is the end of the function),
298 /// and InlineCodeInfo is information about the code that got inlined.
299 static void HandleInlinedEHPad(InvokeInst *II, BasicBlock *FirstNewBlock,
300                                ClonedCodeInfo &InlinedCodeInfo) {
301   BasicBlock *UnwindDest = II->getUnwindDest();
302   Function *Caller = FirstNewBlock->getParent();
303
304   assert(UnwindDest->getFirstNonPHI()->isEHPad() && "unexpected BasicBlock!");
305
306   // If there are PHI nodes in the unwind destination block, we need to keep
307   // track of which values came into them from the invoke before removing the
308   // edge from this block.
309   SmallVector<Value *, 8> UnwindDestPHIValues;
310   llvm::BasicBlock *InvokeBB = II->getParent();
311   for (Instruction &I : *UnwindDest) {
312     // Save the value to use for this edge.
313     PHINode *PHI = dyn_cast<PHINode>(&I);
314     if (!PHI)
315       break;
316     UnwindDestPHIValues.push_back(PHI->getIncomingValueForBlock(InvokeBB));
317   }
318
319   // Add incoming-PHI values to the unwind destination block for the given basic
320   // block, using the values for the original invoke's source block.
321   auto UpdatePHINodes = [&](BasicBlock *Src) {
322     BasicBlock::iterator I = UnwindDest->begin();
323     for (Value *V : UnwindDestPHIValues) {
324       PHINode *PHI = cast<PHINode>(I);
325       PHI->addIncoming(V, Src);
326       ++I;
327     }
328   };
329
330   // Forward EH terminator instructions to the caller's invoke destination.
331   // This is as simple as connect all the instructions which 'unwind to caller'
332   // to the invoke destination.
333   for (Function::iterator BB = FirstNewBlock->getIterator(), E = Caller->end();
334        BB != E; ++BB) {
335     Instruction *I = BB->getFirstNonPHI();
336     if (I->isEHPad()) {
337       if (auto *CEPI = dyn_cast<CatchEndPadInst>(I)) {
338         if (CEPI->unwindsToCaller()) {
339           CatchEndPadInst::Create(CEPI->getContext(), UnwindDest, CEPI);
340           CEPI->eraseFromParent();
341           UpdatePHINodes(&*BB);
342         }
343       } else if (auto *CEPI = dyn_cast<CleanupEndPadInst>(I)) {
344         if (CEPI->unwindsToCaller()) {
345           CleanupEndPadInst::Create(CEPI->getCleanupPad(), UnwindDest, CEPI);
346           CEPI->eraseFromParent();
347           UpdatePHINodes(&*BB);
348         }
349       } else if (auto *TPI = dyn_cast<TerminatePadInst>(I)) {
350         if (TPI->unwindsToCaller()) {
351           SmallVector<Value *, 3> TerminatePadArgs;
352           for (Value *ArgOperand : TPI->arg_operands())
353             TerminatePadArgs.push_back(ArgOperand);
354           TerminatePadInst::Create(TPI->getContext(), UnwindDest,
355                                    TerminatePadArgs, TPI);
356           TPI->eraseFromParent();
357           UpdatePHINodes(&*BB);
358         }
359       } else {
360         assert(isa<CatchPadInst>(I) || isa<CleanupPadInst>(I));
361       }
362     }
363
364     if (auto *CRI = dyn_cast<CleanupReturnInst>(BB->getTerminator())) {
365       if (CRI->unwindsToCaller()) {
366         CleanupReturnInst::Create(CRI->getCleanupPad(), UnwindDest, CRI);
367         CRI->eraseFromParent();
368         UpdatePHINodes(&*BB);
369       }
370     }
371   }
372
373   if (InlinedCodeInfo.ContainsCalls)
374     for (Function::iterator BB = FirstNewBlock->getIterator(),
375                             E = Caller->end();
376          BB != E; ++BB)
377       if (BasicBlock *NewBB =
378               HandleCallsInBlockInlinedThroughInvoke(&*BB, UnwindDest))
379         // Update any PHI nodes in the exceptional block to indicate that there
380         // is now a new entry in them.
381         UpdatePHINodes(NewBB);
382
383   // Now that everything is happy, we have one final detail.  The PHI nodes in
384   // the exception destination block still have entries due to the original
385   // invoke instruction. Eliminate these entries (which might even delete the
386   // PHI node) now.
387   UnwindDest->removePredecessor(InvokeBB);
388 }
389
390 /// When inlining a function that contains noalias scope metadata,
391 /// this metadata needs to be cloned so that the inlined blocks
392 /// have different "unqiue scopes" at every call site. Were this not done, then
393 /// aliasing scopes from a function inlined into a caller multiple times could
394 /// not be differentiated (and this would lead to miscompiles because the
395 /// non-aliasing property communicated by the metadata could have
396 /// call-site-specific control dependencies).
397 static void CloneAliasScopeMetadata(CallSite CS, ValueToValueMapTy &VMap) {
398   const Function *CalledFunc = CS.getCalledFunction();
399   SetVector<const MDNode *> MD;
400
401   // Note: We could only clone the metadata if it is already used in the
402   // caller. I'm omitting that check here because it might confuse
403   // inter-procedural alias analysis passes. We can revisit this if it becomes
404   // an efficiency or overhead problem.
405
406   for (Function::const_iterator I = CalledFunc->begin(), IE = CalledFunc->end();
407        I != IE; ++I)
408     for (BasicBlock::const_iterator J = I->begin(), JE = I->end(); J != JE; ++J) {
409       if (const MDNode *M = J->getMetadata(LLVMContext::MD_alias_scope))
410         MD.insert(M);
411       if (const MDNode *M = J->getMetadata(LLVMContext::MD_noalias))
412         MD.insert(M);
413     }
414
415   if (MD.empty())
416     return;
417
418   // Walk the existing metadata, adding the complete (perhaps cyclic) chain to
419   // the set.
420   SmallVector<const Metadata *, 16> Queue(MD.begin(), MD.end());
421   while (!Queue.empty()) {
422     const MDNode *M = cast<MDNode>(Queue.pop_back_val());
423     for (unsigned i = 0, ie = M->getNumOperands(); i != ie; ++i)
424       if (const MDNode *M1 = dyn_cast<MDNode>(M->getOperand(i)))
425         if (MD.insert(M1))
426           Queue.push_back(M1);
427   }
428
429   // Now we have a complete set of all metadata in the chains used to specify
430   // the noalias scopes and the lists of those scopes.
431   SmallVector<TempMDTuple, 16> DummyNodes;
432   DenseMap<const MDNode *, TrackingMDNodeRef> MDMap;
433   for (SetVector<const MDNode *>::iterator I = MD.begin(), IE = MD.end();
434        I != IE; ++I) {
435     DummyNodes.push_back(MDTuple::getTemporary(CalledFunc->getContext(), None));
436     MDMap[*I].reset(DummyNodes.back().get());
437   }
438
439   // Create new metadata nodes to replace the dummy nodes, replacing old
440   // metadata references with either a dummy node or an already-created new
441   // node.
442   for (SetVector<const MDNode *>::iterator I = MD.begin(), IE = MD.end();
443        I != IE; ++I) {
444     SmallVector<Metadata *, 4> NewOps;
445     for (unsigned i = 0, ie = (*I)->getNumOperands(); i != ie; ++i) {
446       const Metadata *V = (*I)->getOperand(i);
447       if (const MDNode *M = dyn_cast<MDNode>(V))
448         NewOps.push_back(MDMap[M]);
449       else
450         NewOps.push_back(const_cast<Metadata *>(V));
451     }
452
453     MDNode *NewM = MDNode::get(CalledFunc->getContext(), NewOps);
454     MDTuple *TempM = cast<MDTuple>(MDMap[*I]);
455     assert(TempM->isTemporary() && "Expected temporary node");
456
457     TempM->replaceAllUsesWith(NewM);
458   }
459
460   // Now replace the metadata in the new inlined instructions with the
461   // repacements from the map.
462   for (ValueToValueMapTy::iterator VMI = VMap.begin(), VMIE = VMap.end();
463        VMI != VMIE; ++VMI) {
464     if (!VMI->second)
465       continue;
466
467     Instruction *NI = dyn_cast<Instruction>(VMI->second);
468     if (!NI)
469       continue;
470
471     if (MDNode *M = NI->getMetadata(LLVMContext::MD_alias_scope)) {
472       MDNode *NewMD = MDMap[M];
473       // If the call site also had alias scope metadata (a list of scopes to
474       // which instructions inside it might belong), propagate those scopes to
475       // the inlined instructions.
476       if (MDNode *CSM =
477               CS.getInstruction()->getMetadata(LLVMContext::MD_alias_scope))
478         NewMD = MDNode::concatenate(NewMD, CSM);
479       NI->setMetadata(LLVMContext::MD_alias_scope, NewMD);
480     } else if (NI->mayReadOrWriteMemory()) {
481       if (MDNode *M =
482               CS.getInstruction()->getMetadata(LLVMContext::MD_alias_scope))
483         NI->setMetadata(LLVMContext::MD_alias_scope, M);
484     }
485
486     if (MDNode *M = NI->getMetadata(LLVMContext::MD_noalias)) {
487       MDNode *NewMD = MDMap[M];
488       // If the call site also had noalias metadata (a list of scopes with
489       // which instructions inside it don't alias), propagate those scopes to
490       // the inlined instructions.
491       if (MDNode *CSM =
492               CS.getInstruction()->getMetadata(LLVMContext::MD_noalias))
493         NewMD = MDNode::concatenate(NewMD, CSM);
494       NI->setMetadata(LLVMContext::MD_noalias, NewMD);
495     } else if (NI->mayReadOrWriteMemory()) {
496       if (MDNode *M = CS.getInstruction()->getMetadata(LLVMContext::MD_noalias))
497         NI->setMetadata(LLVMContext::MD_noalias, M);
498     }
499   }
500 }
501
502 /// If the inlined function has noalias arguments,
503 /// then add new alias scopes for each noalias argument, tag the mapped noalias
504 /// parameters with noalias metadata specifying the new scope, and tag all
505 /// non-derived loads, stores and memory intrinsics with the new alias scopes.
506 static void AddAliasScopeMetadata(CallSite CS, ValueToValueMapTy &VMap,
507                                   const DataLayout &DL, AAResults *CalleeAAR) {
508   if (!EnableNoAliasConversion)
509     return;
510
511   const Function *CalledFunc = CS.getCalledFunction();
512   SmallVector<const Argument *, 4> NoAliasArgs;
513
514   for (const Argument &I : CalledFunc->args()) {
515     if (I.hasNoAliasAttr() && !I.hasNUses(0))
516       NoAliasArgs.push_back(&I);
517   }
518
519   if (NoAliasArgs.empty())
520     return;
521
522   // To do a good job, if a noalias variable is captured, we need to know if
523   // the capture point dominates the particular use we're considering.
524   DominatorTree DT;
525   DT.recalculate(const_cast<Function&>(*CalledFunc));
526
527   // noalias indicates that pointer values based on the argument do not alias
528   // pointer values which are not based on it. So we add a new "scope" for each
529   // noalias function argument. Accesses using pointers based on that argument
530   // become part of that alias scope, accesses using pointers not based on that
531   // argument are tagged as noalias with that scope.
532
533   DenseMap<const Argument *, MDNode *> NewScopes;
534   MDBuilder MDB(CalledFunc->getContext());
535
536   // Create a new scope domain for this function.
537   MDNode *NewDomain =
538     MDB.createAnonymousAliasScopeDomain(CalledFunc->getName());
539   for (unsigned i = 0, e = NoAliasArgs.size(); i != e; ++i) {
540     const Argument *A = NoAliasArgs[i];
541
542     std::string Name = CalledFunc->getName();
543     if (A->hasName()) {
544       Name += ": %";
545       Name += A->getName();
546     } else {
547       Name += ": argument ";
548       Name += utostr(i);
549     }
550
551     // Note: We always create a new anonymous root here. This is true regardless
552     // of the linkage of the callee because the aliasing "scope" is not just a
553     // property of the callee, but also all control dependencies in the caller.
554     MDNode *NewScope = MDB.createAnonymousAliasScope(NewDomain, Name);
555     NewScopes.insert(std::make_pair(A, NewScope));
556   }
557
558   // Iterate over all new instructions in the map; for all memory-access
559   // instructions, add the alias scope metadata.
560   for (ValueToValueMapTy::iterator VMI = VMap.begin(), VMIE = VMap.end();
561        VMI != VMIE; ++VMI) {
562     if (const Instruction *I = dyn_cast<Instruction>(VMI->first)) {
563       if (!VMI->second)
564         continue;
565
566       Instruction *NI = dyn_cast<Instruction>(VMI->second);
567       if (!NI)
568         continue;
569
570       bool IsArgMemOnlyCall = false, IsFuncCall = false;
571       SmallVector<const Value *, 2> PtrArgs;
572
573       if (const LoadInst *LI = dyn_cast<LoadInst>(I))
574         PtrArgs.push_back(LI->getPointerOperand());
575       else if (const StoreInst *SI = dyn_cast<StoreInst>(I))
576         PtrArgs.push_back(SI->getPointerOperand());
577       else if (const VAArgInst *VAAI = dyn_cast<VAArgInst>(I))
578         PtrArgs.push_back(VAAI->getPointerOperand());
579       else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I))
580         PtrArgs.push_back(CXI->getPointerOperand());
581       else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I))
582         PtrArgs.push_back(RMWI->getPointerOperand());
583       else if (ImmutableCallSite ICS = ImmutableCallSite(I)) {
584         // If we know that the call does not access memory, then we'll still
585         // know that about the inlined clone of this call site, and we don't
586         // need to add metadata.
587         if (ICS.doesNotAccessMemory())
588           continue;
589
590         IsFuncCall = true;
591         if (CalleeAAR) {
592           FunctionModRefBehavior MRB = CalleeAAR->getModRefBehavior(ICS);
593           if (MRB == FMRB_OnlyAccessesArgumentPointees ||
594               MRB == FMRB_OnlyReadsArgumentPointees)
595             IsArgMemOnlyCall = true;
596         }
597
598         for (ImmutableCallSite::arg_iterator AI = ICS.arg_begin(),
599              AE = ICS.arg_end(); AI != AE; ++AI) {
600           // We need to check the underlying objects of all arguments, not just
601           // the pointer arguments, because we might be passing pointers as
602           // integers, etc.
603           // However, if we know that the call only accesses pointer arguments,
604           // then we only need to check the pointer arguments.
605           if (IsArgMemOnlyCall && !(*AI)->getType()->isPointerTy())
606             continue;
607
608           PtrArgs.push_back(*AI);
609         }
610       }
611
612       // If we found no pointers, then this instruction is not suitable for
613       // pairing with an instruction to receive aliasing metadata.
614       // However, if this is a call, this we might just alias with none of the
615       // noalias arguments.
616       if (PtrArgs.empty() && !IsFuncCall)
617         continue;
618
619       // It is possible that there is only one underlying object, but you
620       // need to go through several PHIs to see it, and thus could be
621       // repeated in the Objects list.
622       SmallPtrSet<const Value *, 4> ObjSet;
623       SmallVector<Metadata *, 4> Scopes, NoAliases;
624
625       SmallSetVector<const Argument *, 4> NAPtrArgs;
626       for (unsigned i = 0, ie = PtrArgs.size(); i != ie; ++i) {
627         SmallVector<Value *, 4> Objects;
628         GetUnderlyingObjects(const_cast<Value*>(PtrArgs[i]),
629                              Objects, DL, /* LI = */ nullptr);
630
631         for (Value *O : Objects)
632           ObjSet.insert(O);
633       }
634
635       // Figure out if we're derived from anything that is not a noalias
636       // argument.
637       bool CanDeriveViaCapture = false, UsesAliasingPtr = false;
638       for (const Value *V : ObjSet) {
639         // Is this value a constant that cannot be derived from any pointer
640         // value (we need to exclude constant expressions, for example, that
641         // are formed from arithmetic on global symbols).
642         bool IsNonPtrConst = isa<ConstantInt>(V) || isa<ConstantFP>(V) ||
643                              isa<ConstantPointerNull>(V) ||
644                              isa<ConstantDataVector>(V) || isa<UndefValue>(V);
645         if (IsNonPtrConst)
646           continue;
647
648         // If this is anything other than a noalias argument, then we cannot
649         // completely describe the aliasing properties using alias.scope
650         // metadata (and, thus, won't add any).
651         if (const Argument *A = dyn_cast<Argument>(V)) {
652           if (!A->hasNoAliasAttr())
653             UsesAliasingPtr = true;
654         } else {
655           UsesAliasingPtr = true;
656         }
657
658         // If this is not some identified function-local object (which cannot
659         // directly alias a noalias argument), or some other argument (which,
660         // by definition, also cannot alias a noalias argument), then we could
661         // alias a noalias argument that has been captured).
662         if (!isa<Argument>(V) &&
663             !isIdentifiedFunctionLocal(const_cast<Value*>(V)))
664           CanDeriveViaCapture = true;
665       }
666
667       // A function call can always get captured noalias pointers (via other
668       // parameters, globals, etc.).
669       if (IsFuncCall && !IsArgMemOnlyCall)
670         CanDeriveViaCapture = true;
671
672       // First, we want to figure out all of the sets with which we definitely
673       // don't alias. Iterate over all noalias set, and add those for which:
674       //   1. The noalias argument is not in the set of objects from which we
675       //      definitely derive.
676       //   2. The noalias argument has not yet been captured.
677       // An arbitrary function that might load pointers could see captured
678       // noalias arguments via other noalias arguments or globals, and so we
679       // must always check for prior capture.
680       for (const Argument *A : NoAliasArgs) {
681         if (!ObjSet.count(A) && (!CanDeriveViaCapture ||
682                                  // It might be tempting to skip the
683                                  // PointerMayBeCapturedBefore check if
684                                  // A->hasNoCaptureAttr() is true, but this is
685                                  // incorrect because nocapture only guarantees
686                                  // that no copies outlive the function, not
687                                  // that the value cannot be locally captured.
688                                  !PointerMayBeCapturedBefore(A,
689                                    /* ReturnCaptures */ false,
690                                    /* StoreCaptures */ false, I, &DT)))
691           NoAliases.push_back(NewScopes[A]);
692       }
693
694       if (!NoAliases.empty())
695         NI->setMetadata(LLVMContext::MD_noalias,
696                         MDNode::concatenate(
697                             NI->getMetadata(LLVMContext::MD_noalias),
698                             MDNode::get(CalledFunc->getContext(), NoAliases)));
699
700       // Next, we want to figure out all of the sets to which we might belong.
701       // We might belong to a set if the noalias argument is in the set of
702       // underlying objects. If there is some non-noalias argument in our list
703       // of underlying objects, then we cannot add a scope because the fact
704       // that some access does not alias with any set of our noalias arguments
705       // cannot itself guarantee that it does not alias with this access
706       // (because there is some pointer of unknown origin involved and the
707       // other access might also depend on this pointer). We also cannot add
708       // scopes to arbitrary functions unless we know they don't access any
709       // non-parameter pointer-values.
710       bool CanAddScopes = !UsesAliasingPtr;
711       if (CanAddScopes && IsFuncCall)
712         CanAddScopes = IsArgMemOnlyCall;
713
714       if (CanAddScopes)
715         for (const Argument *A : NoAliasArgs) {
716           if (ObjSet.count(A))
717             Scopes.push_back(NewScopes[A]);
718         }
719
720       if (!Scopes.empty())
721         NI->setMetadata(
722             LLVMContext::MD_alias_scope,
723             MDNode::concatenate(NI->getMetadata(LLVMContext::MD_alias_scope),
724                                 MDNode::get(CalledFunc->getContext(), Scopes)));
725     }
726   }
727 }
728
729 /// If the inlined function has non-byval align arguments, then
730 /// add @llvm.assume-based alignment assumptions to preserve this information.
731 static void AddAlignmentAssumptions(CallSite CS, InlineFunctionInfo &IFI) {
732   if (!PreserveAlignmentAssumptions)
733     return;
734   auto &DL = CS.getCaller()->getParent()->getDataLayout();
735
736   // To avoid inserting redundant assumptions, we should check for assumptions
737   // already in the caller. To do this, we might need a DT of the caller.
738   DominatorTree DT;
739   bool DTCalculated = false;
740
741   Function *CalledFunc = CS.getCalledFunction();
742   for (Function::arg_iterator I = CalledFunc->arg_begin(),
743                               E = CalledFunc->arg_end();
744        I != E; ++I) {
745     unsigned Align = I->getType()->isPointerTy() ? I->getParamAlignment() : 0;
746     if (Align && !I->hasByValOrInAllocaAttr() && !I->hasNUses(0)) {
747       if (!DTCalculated) {
748         DT.recalculate(const_cast<Function&>(*CS.getInstruction()->getParent()
749                                                ->getParent()));
750         DTCalculated = true;
751       }
752
753       // If we can already prove the asserted alignment in the context of the
754       // caller, then don't bother inserting the assumption.
755       Value *Arg = CS.getArgument(I->getArgNo());
756       if (getKnownAlignment(Arg, DL, CS.getInstruction(),
757                             &IFI.ACT->getAssumptionCache(*CS.getCaller()),
758                             &DT) >= Align)
759         continue;
760
761       IRBuilder<>(CS.getInstruction())
762           .CreateAlignmentAssumption(DL, Arg, Align);
763     }
764   }
765 }
766
767 /// Once we have cloned code over from a callee into the caller,
768 /// update the specified callgraph to reflect the changes we made.
769 /// Note that it's possible that not all code was copied over, so only
770 /// some edges of the callgraph may remain.
771 static void UpdateCallGraphAfterInlining(CallSite CS,
772                                          Function::iterator FirstNewBlock,
773                                          ValueToValueMapTy &VMap,
774                                          InlineFunctionInfo &IFI) {
775   CallGraph &CG = *IFI.CG;
776   const Function *Caller = CS.getInstruction()->getParent()->getParent();
777   const Function *Callee = CS.getCalledFunction();
778   CallGraphNode *CalleeNode = CG[Callee];
779   CallGraphNode *CallerNode = CG[Caller];
780
781   // Since we inlined some uninlined call sites in the callee into the caller,
782   // add edges from the caller to all of the callees of the callee.
783   CallGraphNode::iterator I = CalleeNode->begin(), E = CalleeNode->end();
784
785   // Consider the case where CalleeNode == CallerNode.
786   CallGraphNode::CalledFunctionsVector CallCache;
787   if (CalleeNode == CallerNode) {
788     CallCache.assign(I, E);
789     I = CallCache.begin();
790     E = CallCache.end();
791   }
792
793   for (; I != E; ++I) {
794     const Value *OrigCall = I->first;
795
796     ValueToValueMapTy::iterator VMI = VMap.find(OrigCall);
797     // Only copy the edge if the call was inlined!
798     if (VMI == VMap.end() || VMI->second == nullptr)
799       continue;
800     
801     // If the call was inlined, but then constant folded, there is no edge to
802     // add.  Check for this case.
803     Instruction *NewCall = dyn_cast<Instruction>(VMI->second);
804     if (!NewCall)
805       continue;
806
807     // We do not treat intrinsic calls like real function calls because we
808     // expect them to become inline code; do not add an edge for an intrinsic.
809     CallSite CS = CallSite(NewCall);
810     if (CS && CS.getCalledFunction() && CS.getCalledFunction()->isIntrinsic())
811       continue;
812     
813     // Remember that this call site got inlined for the client of
814     // InlineFunction.
815     IFI.InlinedCalls.push_back(NewCall);
816
817     // It's possible that inlining the callsite will cause it to go from an
818     // indirect to a direct call by resolving a function pointer.  If this
819     // happens, set the callee of the new call site to a more precise
820     // destination.  This can also happen if the call graph node of the caller
821     // was just unnecessarily imprecise.
822     if (!I->second->getFunction())
823       if (Function *F = CallSite(NewCall).getCalledFunction()) {
824         // Indirect call site resolved to direct call.
825         CallerNode->addCalledFunction(CallSite(NewCall), CG[F]);
826
827         continue;
828       }
829
830     CallerNode->addCalledFunction(CallSite(NewCall), I->second);
831   }
832   
833   // Update the call graph by deleting the edge from Callee to Caller.  We must
834   // do this after the loop above in case Caller and Callee are the same.
835   CallerNode->removeCallEdgeFor(CS);
836 }
837
838 static void HandleByValArgumentInit(Value *Dst, Value *Src, Module *M,
839                                     BasicBlock *InsertBlock,
840                                     InlineFunctionInfo &IFI) {
841   Type *AggTy = cast<PointerType>(Src->getType())->getElementType();
842   IRBuilder<> Builder(InsertBlock, InsertBlock->begin());
843
844   Value *Size = Builder.getInt64(M->getDataLayout().getTypeStoreSize(AggTy));
845
846   // Always generate a memcpy of alignment 1 here because we don't know
847   // the alignment of the src pointer.  Other optimizations can infer
848   // better alignment.
849   Builder.CreateMemCpy(Dst, Src, Size, /*Align=*/1);
850 }
851
852 /// When inlining a call site that has a byval argument,
853 /// we have to make the implicit memcpy explicit by adding it.
854 static Value *HandleByValArgument(Value *Arg, Instruction *TheCall,
855                                   const Function *CalledFunc,
856                                   InlineFunctionInfo &IFI,
857                                   unsigned ByValAlignment) {
858   PointerType *ArgTy = cast<PointerType>(Arg->getType());
859   Type *AggTy = ArgTy->getElementType();
860
861   Function *Caller = TheCall->getParent()->getParent();
862
863   // If the called function is readonly, then it could not mutate the caller's
864   // copy of the byval'd memory.  In this case, it is safe to elide the copy and
865   // temporary.
866   if (CalledFunc->onlyReadsMemory()) {
867     // If the byval argument has a specified alignment that is greater than the
868     // passed in pointer, then we either have to round up the input pointer or
869     // give up on this transformation.
870     if (ByValAlignment <= 1)  // 0 = unspecified, 1 = no particular alignment.
871       return Arg;
872
873     const DataLayout &DL = Caller->getParent()->getDataLayout();
874
875     // If the pointer is already known to be sufficiently aligned, or if we can
876     // round it up to a larger alignment, then we don't need a temporary.
877     if (getOrEnforceKnownAlignment(Arg, ByValAlignment, DL, TheCall,
878                                    &IFI.ACT->getAssumptionCache(*Caller)) >=
879         ByValAlignment)
880       return Arg;
881     
882     // Otherwise, we have to make a memcpy to get a safe alignment.  This is bad
883     // for code quality, but rarely happens and is required for correctness.
884   }
885
886   // Create the alloca.  If we have DataLayout, use nice alignment.
887   unsigned Align =
888       Caller->getParent()->getDataLayout().getPrefTypeAlignment(AggTy);
889
890   // If the byval had an alignment specified, we *must* use at least that
891   // alignment, as it is required by the byval argument (and uses of the
892   // pointer inside the callee).
893   Align = std::max(Align, ByValAlignment);
894   
895   Value *NewAlloca = new AllocaInst(AggTy, nullptr, Align, Arg->getName(), 
896                                     &*Caller->begin()->begin());
897   IFI.StaticAllocas.push_back(cast<AllocaInst>(NewAlloca));
898   
899   // Uses of the argument in the function should use our new alloca
900   // instead.
901   return NewAlloca;
902 }
903
904 // Check whether this Value is used by a lifetime intrinsic.
905 static bool isUsedByLifetimeMarker(Value *V) {
906   for (User *U : V->users()) {
907     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) {
908       switch (II->getIntrinsicID()) {
909       default: break;
910       case Intrinsic::lifetime_start:
911       case Intrinsic::lifetime_end:
912         return true;
913       }
914     }
915   }
916   return false;
917 }
918
919 // Check whether the given alloca already has
920 // lifetime.start or lifetime.end intrinsics.
921 static bool hasLifetimeMarkers(AllocaInst *AI) {
922   Type *Ty = AI->getType();
923   Type *Int8PtrTy = Type::getInt8PtrTy(Ty->getContext(),
924                                        Ty->getPointerAddressSpace());
925   if (Ty == Int8PtrTy)
926     return isUsedByLifetimeMarker(AI);
927
928   // Do a scan to find all the casts to i8*.
929   for (User *U : AI->users()) {
930     if (U->getType() != Int8PtrTy) continue;
931     if (U->stripPointerCasts() != AI) continue;
932     if (isUsedByLifetimeMarker(U))
933       return true;
934   }
935   return false;
936 }
937
938 /// Rebuild the entire inlined-at chain for this instruction so that the top of
939 /// the chain now is inlined-at the new call site.
940 static DebugLoc
941 updateInlinedAtInfo(DebugLoc DL, DILocation *InlinedAtNode, LLVMContext &Ctx,
942                     DenseMap<const DILocation *, DILocation *> &IANodes) {
943   SmallVector<DILocation *, 3> InlinedAtLocations;
944   DILocation *Last = InlinedAtNode;
945   DILocation *CurInlinedAt = DL;
946
947   // Gather all the inlined-at nodes
948   while (DILocation *IA = CurInlinedAt->getInlinedAt()) {
949     // Skip any we've already built nodes for
950     if (DILocation *Found = IANodes[IA]) {
951       Last = Found;
952       break;
953     }
954
955     InlinedAtLocations.push_back(IA);
956     CurInlinedAt = IA;
957   }
958
959   // Starting from the top, rebuild the nodes to point to the new inlined-at
960   // location (then rebuilding the rest of the chain behind it) and update the
961   // map of already-constructed inlined-at nodes.
962   for (const DILocation *MD : make_range(InlinedAtLocations.rbegin(),
963                                          InlinedAtLocations.rend())) {
964     Last = IANodes[MD] = DILocation::getDistinct(
965         Ctx, MD->getLine(), MD->getColumn(), MD->getScope(), Last);
966   }
967
968   // And finally create the normal location for this instruction, referring to
969   // the new inlined-at chain.
970   return DebugLoc::get(DL.getLine(), DL.getCol(), DL.getScope(), Last);
971 }
972
973 /// Update inlined instructions' line numbers to
974 /// to encode location where these instructions are inlined.
975 static void fixupLineNumbers(Function *Fn, Function::iterator FI,
976                              Instruction *TheCall) {
977   DebugLoc TheCallDL = TheCall->getDebugLoc();
978   if (!TheCallDL)
979     return;
980
981   auto &Ctx = Fn->getContext();
982   DILocation *InlinedAtNode = TheCallDL;
983
984   // Create a unique call site, not to be confused with any other call from the
985   // same location.
986   InlinedAtNode = DILocation::getDistinct(
987       Ctx, InlinedAtNode->getLine(), InlinedAtNode->getColumn(),
988       InlinedAtNode->getScope(), InlinedAtNode->getInlinedAt());
989
990   // Cache the inlined-at nodes as they're built so they are reused, without
991   // this every instruction's inlined-at chain would become distinct from each
992   // other.
993   DenseMap<const DILocation *, DILocation *> IANodes;
994
995   for (; FI != Fn->end(); ++FI) {
996     for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
997          BI != BE; ++BI) {
998       DebugLoc DL = BI->getDebugLoc();
999       if (!DL) {
1000         // If the inlined instruction has no line number, make it look as if it
1001         // originates from the call location. This is important for
1002         // ((__always_inline__, __nodebug__)) functions which must use caller
1003         // location for all instructions in their function body.
1004
1005         // Don't update static allocas, as they may get moved later.
1006         if (auto *AI = dyn_cast<AllocaInst>(BI))
1007           if (isa<Constant>(AI->getArraySize()))
1008             continue;
1009
1010         BI->setDebugLoc(TheCallDL);
1011       } else {
1012         BI->setDebugLoc(updateInlinedAtInfo(DL, InlinedAtNode, BI->getContext(), IANodes));
1013       }
1014     }
1015   }
1016 }
1017
1018 /// This function inlines the called function into the basic block of the
1019 /// caller. This returns false if it is not possible to inline this call.
1020 /// The program is still in a well defined state if this occurs though.
1021 ///
1022 /// Note that this only does one level of inlining.  For example, if the
1023 /// instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
1024 /// exists in the instruction stream.  Similarly this will inline a recursive
1025 /// function by one level.
1026 bool llvm::InlineFunction(CallSite CS, InlineFunctionInfo &IFI,
1027                           AAResults *CalleeAAR, bool InsertLifetime) {
1028   Instruction *TheCall = CS.getInstruction();
1029   assert(TheCall->getParent() && TheCall->getParent()->getParent() &&
1030          "Instruction not in function!");
1031
1032   // If IFI has any state in it, zap it before we fill it in.
1033   IFI.reset();
1034   
1035   const Function *CalledFunc = CS.getCalledFunction();
1036   if (!CalledFunc ||              // Can't inline external function or indirect
1037       CalledFunc->isDeclaration() || // call, or call to a vararg function!
1038       CalledFunc->getFunctionType()->isVarArg()) return false;
1039
1040   // The inliner does not know how to inline through calls with operand bundles
1041   // in general ...
1042   if (CS.hasOperandBundles()) {
1043     // ... but it knows how to inline through "deopt" operand bundles.
1044     bool CanInline =
1045         CS.getNumOperandBundles() == 1 &&
1046         CS.getOperandBundleAt(0).getTagID() == LLVMContext::OB_deopt;
1047     if (!CanInline)
1048       return false;
1049   }
1050
1051   // If the call to the callee cannot throw, set the 'nounwind' flag on any
1052   // calls that we inline.
1053   bool MarkNoUnwind = CS.doesNotThrow();
1054
1055   BasicBlock *OrigBB = TheCall->getParent();
1056   Function *Caller = OrigBB->getParent();
1057
1058   // GC poses two hazards to inlining, which only occur when the callee has GC:
1059   //  1. If the caller has no GC, then the callee's GC must be propagated to the
1060   //     caller.
1061   //  2. If the caller has a differing GC, it is invalid to inline.
1062   if (CalledFunc->hasGC()) {
1063     if (!Caller->hasGC())
1064       Caller->setGC(CalledFunc->getGC());
1065     else if (CalledFunc->getGC() != Caller->getGC())
1066       return false;
1067   }
1068
1069   // Get the personality function from the callee if it contains a landing pad.
1070   Constant *CalledPersonality =
1071       CalledFunc->hasPersonalityFn()
1072           ? CalledFunc->getPersonalityFn()->stripPointerCasts()
1073           : nullptr;
1074
1075   // Find the personality function used by the landing pads of the caller. If it
1076   // exists, then check to see that it matches the personality function used in
1077   // the callee.
1078   Constant *CallerPersonality =
1079       Caller->hasPersonalityFn()
1080           ? Caller->getPersonalityFn()->stripPointerCasts()
1081           : nullptr;
1082   if (CalledPersonality) {
1083     if (!CallerPersonality)
1084       Caller->setPersonalityFn(CalledPersonality);
1085     // If the personality functions match, then we can perform the
1086     // inlining. Otherwise, we can't inline.
1087     // TODO: This isn't 100% true. Some personality functions are proper
1088     //       supersets of others and can be used in place of the other.
1089     else if (CalledPersonality != CallerPersonality)
1090       return false;
1091   }
1092
1093   // Get an iterator to the last basic block in the function, which will have
1094   // the new function inlined after it.
1095   Function::iterator LastBlock = --Caller->end();
1096
1097   // Make sure to capture all of the return instructions from the cloned
1098   // function.
1099   SmallVector<ReturnInst*, 8> Returns;
1100   ClonedCodeInfo InlinedFunctionInfo;
1101   Function::iterator FirstNewBlock;
1102
1103   { // Scope to destroy VMap after cloning.
1104     ValueToValueMapTy VMap;
1105     // Keep a list of pair (dst, src) to emit byval initializations.
1106     SmallVector<std::pair<Value*, Value*>, 4> ByValInit;
1107
1108     auto &DL = Caller->getParent()->getDataLayout();
1109
1110     assert(CalledFunc->arg_size() == CS.arg_size() &&
1111            "No varargs calls can be inlined!");
1112
1113     // Calculate the vector of arguments to pass into the function cloner, which
1114     // matches up the formal to the actual argument values.
1115     CallSite::arg_iterator AI = CS.arg_begin();
1116     unsigned ArgNo = 0;
1117     for (Function::const_arg_iterator I = CalledFunc->arg_begin(),
1118          E = CalledFunc->arg_end(); I != E; ++I, ++AI, ++ArgNo) {
1119       Value *ActualArg = *AI;
1120
1121       // When byval arguments actually inlined, we need to make the copy implied
1122       // by them explicit.  However, we don't do this if the callee is readonly
1123       // or readnone, because the copy would be unneeded: the callee doesn't
1124       // modify the struct.
1125       if (CS.isByValArgument(ArgNo)) {
1126         ActualArg = HandleByValArgument(ActualArg, TheCall, CalledFunc, IFI,
1127                                         CalledFunc->getParamAlignment(ArgNo+1));
1128         if (ActualArg != *AI)
1129           ByValInit.push_back(std::make_pair(ActualArg, (Value*) *AI));
1130       }
1131
1132       VMap[&*I] = ActualArg;
1133     }
1134
1135     // Add alignment assumptions if necessary. We do this before the inlined
1136     // instructions are actually cloned into the caller so that we can easily
1137     // check what will be known at the start of the inlined code.
1138     AddAlignmentAssumptions(CS, IFI);
1139
1140     // We want the inliner to prune the code as it copies.  We would LOVE to
1141     // have no dead or constant instructions leftover after inlining occurs
1142     // (which can happen, e.g., because an argument was constant), but we'll be
1143     // happy with whatever the cloner can do.
1144     CloneAndPruneFunctionInto(Caller, CalledFunc, VMap,
1145                               /*ModuleLevelChanges=*/false, Returns, ".i",
1146                               &InlinedFunctionInfo, TheCall);
1147
1148     // Remember the first block that is newly cloned over.
1149     FirstNewBlock = LastBlock; ++FirstNewBlock;
1150
1151     // Inject byval arguments initialization.
1152     for (std::pair<Value*, Value*> &Init : ByValInit)
1153       HandleByValArgumentInit(Init.first, Init.second, Caller->getParent(),
1154                               &*FirstNewBlock, IFI);
1155
1156     if (CS.hasOperandBundles()) {
1157       auto ParentDeopt = CS.getOperandBundleAt(0);
1158       assert(ParentDeopt.getTagID() == LLVMContext::OB_deopt &&
1159              "Checked on entry!");
1160
1161       SmallVector<OperandBundleDef, 2> OpDefs;
1162
1163       for (auto &VH : InlinedFunctionInfo.OperandBundleCallSites) {
1164         if (!VH) continue;  // instruction was DCE'd after being cloned
1165
1166         Instruction *I = cast<Instruction>(VH);
1167
1168         OpDefs.clear();
1169
1170         CallSite ICS(I);
1171         OpDefs.reserve(ICS.getNumOperandBundles());
1172
1173         for (unsigned i = 0, e = ICS.getNumOperandBundles(); i < e; ++i) {
1174           auto ChildOB = ICS.getOperandBundleAt(i);
1175           if (ChildOB.getTagID() != LLVMContext::OB_deopt) {
1176             // If the inlined call has other operand bundles, let them be
1177             OpDefs.emplace_back(ChildOB);
1178             continue;
1179           }
1180
1181           // It may be useful to separate this logic (of handling operand
1182           // bundles) out to a separate "policy" component if this gets crowded.
1183           // Prepend the parent's deoptimization continuation to the newly
1184           // inlined call's deoptimization continuation.
1185           std::vector<Value *> MergedDeoptArgs;
1186           MergedDeoptArgs.reserve(ParentDeopt.Inputs.size() +
1187                                   ChildOB.Inputs.size());
1188
1189           MergedDeoptArgs.insert(MergedDeoptArgs.end(),
1190                                  ParentDeopt.Inputs.begin(),
1191                                  ParentDeopt.Inputs.end());
1192           MergedDeoptArgs.insert(MergedDeoptArgs.end(), ChildOB.Inputs.begin(),
1193                                  ChildOB.Inputs.end());
1194
1195           OpDefs.emplace_back("deopt", std::move(MergedDeoptArgs));
1196         }
1197
1198         Instruction *NewI = nullptr;
1199         if (isa<CallInst>(I))
1200           NewI = CallInst::Create(cast<CallInst>(I), OpDefs, I);
1201         else
1202           NewI = InvokeInst::Create(cast<InvokeInst>(I), OpDefs, I);
1203
1204         // Note: the RAUW does the appropriate fixup in VMap, so we need to do
1205         // this even if the call returns void.
1206         I->replaceAllUsesWith(NewI);
1207
1208         VH = nullptr;
1209         I->eraseFromParent();
1210       }
1211     }
1212
1213     // Update the callgraph if requested.
1214     if (IFI.CG)
1215       UpdateCallGraphAfterInlining(CS, FirstNewBlock, VMap, IFI);
1216
1217     // Update inlined instructions' line number information.
1218     fixupLineNumbers(Caller, FirstNewBlock, TheCall);
1219
1220     // Clone existing noalias metadata if necessary.
1221     CloneAliasScopeMetadata(CS, VMap);
1222
1223     // Add noalias metadata if necessary.
1224     AddAliasScopeMetadata(CS, VMap, DL, CalleeAAR);
1225
1226     // FIXME: We could register any cloned assumptions instead of clearing the
1227     // whole function's cache.
1228     if (IFI.ACT)
1229       IFI.ACT->getAssumptionCache(*Caller).clear();
1230   }
1231
1232   // If there are any alloca instructions in the block that used to be the entry
1233   // block for the callee, move them to the entry block of the caller.  First
1234   // calculate which instruction they should be inserted before.  We insert the
1235   // instructions at the end of the current alloca list.
1236   {
1237     BasicBlock::iterator InsertPoint = Caller->begin()->begin();
1238     for (BasicBlock::iterator I = FirstNewBlock->begin(),
1239          E = FirstNewBlock->end(); I != E; ) {
1240       AllocaInst *AI = dyn_cast<AllocaInst>(I++);
1241       if (!AI) continue;
1242       
1243       // If the alloca is now dead, remove it.  This often occurs due to code
1244       // specialization.
1245       if (AI->use_empty()) {
1246         AI->eraseFromParent();
1247         continue;
1248       }
1249
1250       if (!isa<Constant>(AI->getArraySize()))
1251         continue;
1252       
1253       // Keep track of the static allocas that we inline into the caller.
1254       IFI.StaticAllocas.push_back(AI);
1255       
1256       // Scan for the block of allocas that we can move over, and move them
1257       // all at once.
1258       while (isa<AllocaInst>(I) &&
1259              isa<Constant>(cast<AllocaInst>(I)->getArraySize())) {
1260         IFI.StaticAllocas.push_back(cast<AllocaInst>(I));
1261         ++I;
1262       }
1263
1264       // Transfer all of the allocas over in a block.  Using splice means
1265       // that the instructions aren't removed from the symbol table, then
1266       // reinserted.
1267       Caller->getEntryBlock().getInstList().splice(
1268           InsertPoint, FirstNewBlock->getInstList(), AI->getIterator(), I);
1269     }
1270     // Move any dbg.declares describing the allocas into the entry basic block.
1271     DIBuilder DIB(*Caller->getParent());
1272     for (auto &AI : IFI.StaticAllocas)
1273       replaceDbgDeclareForAlloca(AI, AI, DIB, /*Deref=*/false);
1274   }
1275
1276   bool InlinedMustTailCalls = false;
1277   if (InlinedFunctionInfo.ContainsCalls) {
1278     CallInst::TailCallKind CallSiteTailKind = CallInst::TCK_None;
1279     if (CallInst *CI = dyn_cast<CallInst>(TheCall))
1280       CallSiteTailKind = CI->getTailCallKind();
1281
1282     for (Function::iterator BB = FirstNewBlock, E = Caller->end(); BB != E;
1283          ++BB) {
1284       for (Instruction &I : *BB) {
1285         CallInst *CI = dyn_cast<CallInst>(&I);
1286         if (!CI)
1287           continue;
1288
1289         // We need to reduce the strength of any inlined tail calls.  For
1290         // musttail, we have to avoid introducing potential unbounded stack
1291         // growth.  For example, if functions 'f' and 'g' are mutually recursive
1292         // with musttail, we can inline 'g' into 'f' so long as we preserve
1293         // musttail on the cloned call to 'f'.  If either the inlined call site
1294         // or the cloned call site is *not* musttail, the program already has
1295         // one frame of stack growth, so it's safe to remove musttail.  Here is
1296         // a table of example transformations:
1297         //
1298         //    f -> musttail g -> musttail f  ==>  f -> musttail f
1299         //    f -> musttail g ->     tail f  ==>  f ->     tail f
1300         //    f ->          g -> musttail f  ==>  f ->          f
1301         //    f ->          g ->     tail f  ==>  f ->          f
1302         CallInst::TailCallKind ChildTCK = CI->getTailCallKind();
1303         ChildTCK = std::min(CallSiteTailKind, ChildTCK);
1304         CI->setTailCallKind(ChildTCK);
1305         InlinedMustTailCalls |= CI->isMustTailCall();
1306
1307         // Calls inlined through a 'nounwind' call site should be marked
1308         // 'nounwind'.
1309         if (MarkNoUnwind)
1310           CI->setDoesNotThrow();
1311       }
1312     }
1313   }
1314
1315   // Leave lifetime markers for the static alloca's, scoping them to the
1316   // function we just inlined.
1317   if (InsertLifetime && !IFI.StaticAllocas.empty()) {
1318     IRBuilder<> builder(&FirstNewBlock->front());
1319     for (unsigned ai = 0, ae = IFI.StaticAllocas.size(); ai != ae; ++ai) {
1320       AllocaInst *AI = IFI.StaticAllocas[ai];
1321
1322       // If the alloca is already scoped to something smaller than the whole
1323       // function then there's no need to add redundant, less accurate markers.
1324       if (hasLifetimeMarkers(AI))
1325         continue;
1326
1327       // Try to determine the size of the allocation.
1328       ConstantInt *AllocaSize = nullptr;
1329       if (ConstantInt *AIArraySize =
1330           dyn_cast<ConstantInt>(AI->getArraySize())) {
1331         auto &DL = Caller->getParent()->getDataLayout();
1332         Type *AllocaType = AI->getAllocatedType();
1333         uint64_t AllocaTypeSize = DL.getTypeAllocSize(AllocaType);
1334         uint64_t AllocaArraySize = AIArraySize->getLimitedValue();
1335
1336         // Don't add markers for zero-sized allocas.
1337         if (AllocaArraySize == 0)
1338           continue;
1339
1340         // Check that array size doesn't saturate uint64_t and doesn't
1341         // overflow when it's multiplied by type size.
1342         if (AllocaArraySize != ~0ULL &&
1343             UINT64_MAX / AllocaArraySize >= AllocaTypeSize) {
1344           AllocaSize = ConstantInt::get(Type::getInt64Ty(AI->getContext()),
1345                                         AllocaArraySize * AllocaTypeSize);
1346         }
1347       }
1348
1349       builder.CreateLifetimeStart(AI, AllocaSize);
1350       for (ReturnInst *RI : Returns) {
1351         // Don't insert llvm.lifetime.end calls between a musttail call and a
1352         // return.  The return kills all local allocas.
1353         if (InlinedMustTailCalls &&
1354             RI->getParent()->getTerminatingMustTailCall())
1355           continue;
1356         IRBuilder<>(RI).CreateLifetimeEnd(AI, AllocaSize);
1357       }
1358     }
1359   }
1360
1361   // If the inlined code contained dynamic alloca instructions, wrap the inlined
1362   // code with llvm.stacksave/llvm.stackrestore intrinsics.
1363   if (InlinedFunctionInfo.ContainsDynamicAllocas) {
1364     Module *M = Caller->getParent();
1365     // Get the two intrinsics we care about.
1366     Function *StackSave = Intrinsic::getDeclaration(M, Intrinsic::stacksave);
1367     Function *StackRestore=Intrinsic::getDeclaration(M,Intrinsic::stackrestore);
1368
1369     // Insert the llvm.stacksave.
1370     CallInst *SavedPtr = IRBuilder<>(&*FirstNewBlock, FirstNewBlock->begin())
1371                              .CreateCall(StackSave, {}, "savedstack");
1372
1373     // Insert a call to llvm.stackrestore before any return instructions in the
1374     // inlined function.
1375     for (ReturnInst *RI : Returns) {
1376       // Don't insert llvm.stackrestore calls between a musttail call and a
1377       // return.  The return will restore the stack pointer.
1378       if (InlinedMustTailCalls && RI->getParent()->getTerminatingMustTailCall())
1379         continue;
1380       IRBuilder<>(RI).CreateCall(StackRestore, SavedPtr);
1381     }
1382   }
1383
1384   // If we are inlining for an invoke instruction, we must make sure to rewrite
1385   // any call instructions into invoke instructions.
1386   if (auto *II = dyn_cast<InvokeInst>(TheCall)) {
1387     BasicBlock *UnwindDest = II->getUnwindDest();
1388     Instruction *FirstNonPHI = UnwindDest->getFirstNonPHI();
1389     if (isa<LandingPadInst>(FirstNonPHI)) {
1390       HandleInlinedLandingPad(II, &*FirstNewBlock, InlinedFunctionInfo);
1391     } else {
1392       HandleInlinedEHPad(II, &*FirstNewBlock, InlinedFunctionInfo);
1393     }
1394   }
1395
1396   // Handle any inlined musttail call sites.  In order for a new call site to be
1397   // musttail, the source of the clone and the inlined call site must have been
1398   // musttail.  Therefore it's safe to return without merging control into the
1399   // phi below.
1400   if (InlinedMustTailCalls) {
1401     // Check if we need to bitcast the result of any musttail calls.
1402     Type *NewRetTy = Caller->getReturnType();
1403     bool NeedBitCast = !TheCall->use_empty() && TheCall->getType() != NewRetTy;
1404
1405     // Handle the returns preceded by musttail calls separately.
1406     SmallVector<ReturnInst *, 8> NormalReturns;
1407     for (ReturnInst *RI : Returns) {
1408       CallInst *ReturnedMustTail =
1409           RI->getParent()->getTerminatingMustTailCall();
1410       if (!ReturnedMustTail) {
1411         NormalReturns.push_back(RI);
1412         continue;
1413       }
1414       if (!NeedBitCast)
1415         continue;
1416
1417       // Delete the old return and any preceding bitcast.
1418       BasicBlock *CurBB = RI->getParent();
1419       auto *OldCast = dyn_cast_or_null<BitCastInst>(RI->getReturnValue());
1420       RI->eraseFromParent();
1421       if (OldCast)
1422         OldCast->eraseFromParent();
1423
1424       // Insert a new bitcast and return with the right type.
1425       IRBuilder<> Builder(CurBB);
1426       Builder.CreateRet(Builder.CreateBitCast(ReturnedMustTail, NewRetTy));
1427     }
1428
1429     // Leave behind the normal returns so we can merge control flow.
1430     std::swap(Returns, NormalReturns);
1431   }
1432
1433   // If we cloned in _exactly one_ basic block, and if that block ends in a
1434   // return instruction, we splice the body of the inlined callee directly into
1435   // the calling basic block.
1436   if (Returns.size() == 1 && std::distance(FirstNewBlock, Caller->end()) == 1) {
1437     // Move all of the instructions right before the call.
1438     OrigBB->getInstList().splice(TheCall->getIterator(),
1439                                  FirstNewBlock->getInstList(),
1440                                  FirstNewBlock->begin(), FirstNewBlock->end());
1441     // Remove the cloned basic block.
1442     Caller->getBasicBlockList().pop_back();
1443
1444     // If the call site was an invoke instruction, add a branch to the normal
1445     // destination.
1446     if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
1447       BranchInst *NewBr = BranchInst::Create(II->getNormalDest(), TheCall);
1448       NewBr->setDebugLoc(Returns[0]->getDebugLoc());
1449     }
1450
1451     // If the return instruction returned a value, replace uses of the call with
1452     // uses of the returned value.
1453     if (!TheCall->use_empty()) {
1454       ReturnInst *R = Returns[0];
1455       if (TheCall == R->getReturnValue())
1456         TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
1457       else
1458         TheCall->replaceAllUsesWith(R->getReturnValue());
1459     }
1460     // Since we are now done with the Call/Invoke, we can delete it.
1461     TheCall->eraseFromParent();
1462
1463     // Since we are now done with the return instruction, delete it also.
1464     Returns[0]->eraseFromParent();
1465
1466     // We are now done with the inlining.
1467     return true;
1468   }
1469
1470   // Otherwise, we have the normal case, of more than one block to inline or
1471   // multiple return sites.
1472
1473   // We want to clone the entire callee function into the hole between the
1474   // "starter" and "ender" blocks.  How we accomplish this depends on whether
1475   // this is an invoke instruction or a call instruction.
1476   BasicBlock *AfterCallBB;
1477   BranchInst *CreatedBranchToNormalDest = nullptr;
1478   if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
1479
1480     // Add an unconditional branch to make this look like the CallInst case...
1481     CreatedBranchToNormalDest = BranchInst::Create(II->getNormalDest(), TheCall);
1482
1483     // Split the basic block.  This guarantees that no PHI nodes will have to be
1484     // updated due to new incoming edges, and make the invoke case more
1485     // symmetric to the call case.
1486     AfterCallBB =
1487         OrigBB->splitBasicBlock(CreatedBranchToNormalDest->getIterator(),
1488                                 CalledFunc->getName() + ".exit");
1489
1490   } else {  // It's a call
1491     // If this is a call instruction, we need to split the basic block that
1492     // the call lives in.
1493     //
1494     AfterCallBB = OrigBB->splitBasicBlock(TheCall->getIterator(),
1495                                           CalledFunc->getName() + ".exit");
1496   }
1497
1498   // Change the branch that used to go to AfterCallBB to branch to the first
1499   // basic block of the inlined function.
1500   //
1501   TerminatorInst *Br = OrigBB->getTerminator();
1502   assert(Br && Br->getOpcode() == Instruction::Br &&
1503          "splitBasicBlock broken!");
1504   Br->setOperand(0, &*FirstNewBlock);
1505
1506   // Now that the function is correct, make it a little bit nicer.  In
1507   // particular, move the basic blocks inserted from the end of the function
1508   // into the space made by splitting the source basic block.
1509   Caller->getBasicBlockList().splice(AfterCallBB->getIterator(),
1510                                      Caller->getBasicBlockList(), FirstNewBlock,
1511                                      Caller->end());
1512
1513   // Handle all of the return instructions that we just cloned in, and eliminate
1514   // any users of the original call/invoke instruction.
1515   Type *RTy = CalledFunc->getReturnType();
1516
1517   PHINode *PHI = nullptr;
1518   if (Returns.size() > 1) {
1519     // The PHI node should go at the front of the new basic block to merge all
1520     // possible incoming values.
1521     if (!TheCall->use_empty()) {
1522       PHI = PHINode::Create(RTy, Returns.size(), TheCall->getName(),
1523                             &AfterCallBB->front());
1524       // Anything that used the result of the function call should now use the
1525       // PHI node as their operand.
1526       TheCall->replaceAllUsesWith(PHI);
1527     }
1528
1529     // Loop over all of the return instructions adding entries to the PHI node
1530     // as appropriate.
1531     if (PHI) {
1532       for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
1533         ReturnInst *RI = Returns[i];
1534         assert(RI->getReturnValue()->getType() == PHI->getType() &&
1535                "Ret value not consistent in function!");
1536         PHI->addIncoming(RI->getReturnValue(), RI->getParent());
1537       }
1538     }
1539
1540     // Add a branch to the merge points and remove return instructions.
1541     DebugLoc Loc;
1542     for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
1543       ReturnInst *RI = Returns[i];
1544       BranchInst* BI = BranchInst::Create(AfterCallBB, RI);
1545       Loc = RI->getDebugLoc();
1546       BI->setDebugLoc(Loc);
1547       RI->eraseFromParent();
1548     }
1549     // We need to set the debug location to *somewhere* inside the
1550     // inlined function. The line number may be nonsensical, but the
1551     // instruction will at least be associated with the right
1552     // function.
1553     if (CreatedBranchToNormalDest)
1554       CreatedBranchToNormalDest->setDebugLoc(Loc);
1555   } else if (!Returns.empty()) {
1556     // Otherwise, if there is exactly one return value, just replace anything
1557     // using the return value of the call with the computed value.
1558     if (!TheCall->use_empty()) {
1559       if (TheCall == Returns[0]->getReturnValue())
1560         TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
1561       else
1562         TheCall->replaceAllUsesWith(Returns[0]->getReturnValue());
1563     }
1564
1565     // Update PHI nodes that use the ReturnBB to use the AfterCallBB.
1566     BasicBlock *ReturnBB = Returns[0]->getParent();
1567     ReturnBB->replaceAllUsesWith(AfterCallBB);
1568
1569     // Splice the code from the return block into the block that it will return
1570     // to, which contains the code that was after the call.
1571     AfterCallBB->getInstList().splice(AfterCallBB->begin(),
1572                                       ReturnBB->getInstList());
1573
1574     if (CreatedBranchToNormalDest)
1575       CreatedBranchToNormalDest->setDebugLoc(Returns[0]->getDebugLoc());
1576
1577     // Delete the return instruction now and empty ReturnBB now.
1578     Returns[0]->eraseFromParent();
1579     ReturnBB->eraseFromParent();
1580   } else if (!TheCall->use_empty()) {
1581     // No returns, but something is using the return value of the call.  Just
1582     // nuke the result.
1583     TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
1584   }
1585
1586   // Since we are now done with the Call/Invoke, we can delete it.
1587   TheCall->eraseFromParent();
1588
1589   // If we inlined any musttail calls and the original return is now
1590   // unreachable, delete it.  It can only contain a bitcast and ret.
1591   if (InlinedMustTailCalls && pred_begin(AfterCallBB) == pred_end(AfterCallBB))
1592     AfterCallBB->eraseFromParent();
1593
1594   // We should always be able to fold the entry block of the function into the
1595   // single predecessor of the block...
1596   assert(cast<BranchInst>(Br)->isUnconditional() && "splitBasicBlock broken!");
1597   BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0);
1598
1599   // Splice the code entry block into calling block, right before the
1600   // unconditional branch.
1601   CalleeEntry->replaceAllUsesWith(OrigBB);  // Update PHI nodes
1602   OrigBB->getInstList().splice(Br->getIterator(), CalleeEntry->getInstList());
1603
1604   // Remove the unconditional branch.
1605   OrigBB->getInstList().erase(Br);
1606
1607   // Now we can remove the CalleeEntry block, which is now empty.
1608   Caller->getBasicBlockList().erase(CalleeEntry);
1609
1610   // If we inserted a phi node, check to see if it has a single value (e.g. all
1611   // the entries are the same or undef).  If so, remove the PHI so it doesn't
1612   // block other optimizations.
1613   if (PHI) {
1614     auto &DL = Caller->getParent()->getDataLayout();
1615     if (Value *V = SimplifyInstruction(PHI, DL, nullptr, nullptr,
1616                                        &IFI.ACT->getAssumptionCache(*Caller))) {
1617       PHI->replaceAllUsesWith(V);
1618       PHI->eraseFromParent();
1619     }
1620   }
1621
1622   return true;
1623 }