LLVM API Documentation

InlineFunction.cpp
Go to the documentation of this file.
00001 //===- InlineFunction.cpp - Code to perform function inlining -------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements inlining of a function into a call site, resolving
00011 // parameters and the return value as appropriate.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "llvm/Transforms/Utils/Cloning.h"
00016 #include "llvm/ADT/SmallSet.h"
00017 #include "llvm/ADT/SmallVector.h"
00018 #include "llvm/ADT/SetVector.h"
00019 #include "llvm/ADT/StringExtras.h"
00020 #include "llvm/Analysis/AliasAnalysis.h"
00021 #include "llvm/Analysis/CallGraph.h"
00022 #include "llvm/Analysis/CaptureTracking.h"
00023 #include "llvm/Analysis/InstructionSimplify.h"
00024 #include "llvm/Analysis/ValueTracking.h"
00025 #include "llvm/IR/Attributes.h"
00026 #include "llvm/IR/CallSite.h"
00027 #include "llvm/IR/CFG.h"
00028 #include "llvm/IR/Constants.h"
00029 #include "llvm/IR/DataLayout.h"
00030 #include "llvm/IR/DebugInfo.h"
00031 #include "llvm/IR/DerivedTypes.h"
00032 #include "llvm/IR/Dominators.h"
00033 #include "llvm/IR/IRBuilder.h"
00034 #include "llvm/IR/Instructions.h"
00035 #include "llvm/IR/IntrinsicInst.h"
00036 #include "llvm/IR/Intrinsics.h"
00037 #include "llvm/IR/MDBuilder.h"
00038 #include "llvm/IR/Module.h"
00039 #include "llvm/Transforms/Utils/Local.h"
00040 #include "llvm/Support/CommandLine.h"
00041 #include <algorithm>
00042 using namespace llvm;
00043 
00044 static cl::opt<bool>
00045 EnableNoAliasConversion("enable-noalias-to-md-conversion", cl::init(false),
00046   cl::Hidden,
00047   cl::desc("Convert noalias attributes to metadata during inlining."));
00048 
00049 bool llvm::InlineFunction(CallInst *CI, InlineFunctionInfo &IFI,
00050                           bool InsertLifetime) {
00051   return InlineFunction(CallSite(CI), IFI, InsertLifetime);
00052 }
00053 bool llvm::InlineFunction(InvokeInst *II, InlineFunctionInfo &IFI,
00054                           bool InsertLifetime) {
00055   return InlineFunction(CallSite(II), IFI, InsertLifetime);
00056 }
00057 
00058 namespace {
00059   /// A class for recording information about inlining through an invoke.
00060   class InvokeInliningInfo {
00061     BasicBlock *OuterResumeDest; ///< Destination of the invoke's unwind.
00062     BasicBlock *InnerResumeDest; ///< Destination for the callee's resume.
00063     LandingPadInst *CallerLPad;  ///< LandingPadInst associated with the invoke.
00064     PHINode *InnerEHValuesPHI;   ///< PHI for EH values from landingpad insts.
00065     SmallVector<Value*, 8> UnwindDestPHIValues;
00066 
00067   public:
00068     InvokeInliningInfo(InvokeInst *II)
00069       : OuterResumeDest(II->getUnwindDest()), InnerResumeDest(nullptr),
00070         CallerLPad(nullptr), InnerEHValuesPHI(nullptr) {
00071       // If there are PHI nodes in the unwind destination block, we need to keep
00072       // track of which values came into them from the invoke before removing
00073       // the edge from this block.
00074       llvm::BasicBlock *InvokeBB = II->getParent();
00075       BasicBlock::iterator I = OuterResumeDest->begin();
00076       for (; isa<PHINode>(I); ++I) {
00077         // Save the value to use for this edge.
00078         PHINode *PHI = cast<PHINode>(I);
00079         UnwindDestPHIValues.push_back(PHI->getIncomingValueForBlock(InvokeBB));
00080       }
00081 
00082       CallerLPad = cast<LandingPadInst>(I);
00083     }
00084 
00085     /// getOuterResumeDest - The outer unwind destination is the target of
00086     /// unwind edges introduced for calls within the inlined function.
00087     BasicBlock *getOuterResumeDest() const {
00088       return OuterResumeDest;
00089     }
00090 
00091     BasicBlock *getInnerResumeDest();
00092 
00093     LandingPadInst *getLandingPadInst() const { return CallerLPad; }
00094 
00095     /// forwardResume - Forward the 'resume' instruction to the caller's landing
00096     /// pad block. When the landing pad block has only one predecessor, this is
00097     /// a simple branch. When there is more than one predecessor, we need to
00098     /// split the landing pad block after the landingpad instruction and jump
00099     /// to there.
00100     void forwardResume(ResumeInst *RI,
00101                        SmallPtrSet<LandingPadInst*, 16> &InlinedLPads);
00102 
00103     /// addIncomingPHIValuesFor - Add incoming-PHI values to the unwind
00104     /// destination block for the given basic block, using the values for the
00105     /// original invoke's source block.
00106     void addIncomingPHIValuesFor(BasicBlock *BB) const {
00107       addIncomingPHIValuesForInto(BB, OuterResumeDest);
00108     }
00109 
00110     void addIncomingPHIValuesForInto(BasicBlock *src, BasicBlock *dest) const {
00111       BasicBlock::iterator I = dest->begin();
00112       for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
00113         PHINode *phi = cast<PHINode>(I);
00114         phi->addIncoming(UnwindDestPHIValues[i], src);
00115       }
00116     }
00117   };
00118 }
00119 
00120 /// getInnerResumeDest - Get or create a target for the branch from ResumeInsts.
00121 BasicBlock *InvokeInliningInfo::getInnerResumeDest() {
00122   if (InnerResumeDest) return InnerResumeDest;
00123 
00124   // Split the landing pad.
00125   BasicBlock::iterator SplitPoint = CallerLPad; ++SplitPoint;
00126   InnerResumeDest =
00127     OuterResumeDest->splitBasicBlock(SplitPoint,
00128                                      OuterResumeDest->getName() + ".body");
00129 
00130   // The number of incoming edges we expect to the inner landing pad.
00131   const unsigned PHICapacity = 2;
00132 
00133   // Create corresponding new PHIs for all the PHIs in the outer landing pad.
00134   BasicBlock::iterator InsertPoint = InnerResumeDest->begin();
00135   BasicBlock::iterator I = OuterResumeDest->begin();
00136   for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
00137     PHINode *OuterPHI = cast<PHINode>(I);
00138     PHINode *InnerPHI = PHINode::Create(OuterPHI->getType(), PHICapacity,
00139                                         OuterPHI->getName() + ".lpad-body",
00140                                         InsertPoint);
00141     OuterPHI->replaceAllUsesWith(InnerPHI);
00142     InnerPHI->addIncoming(OuterPHI, OuterResumeDest);
00143   }
00144 
00145   // Create a PHI for the exception values.
00146   InnerEHValuesPHI = PHINode::Create(CallerLPad->getType(), PHICapacity,
00147                                      "eh.lpad-body", InsertPoint);
00148   CallerLPad->replaceAllUsesWith(InnerEHValuesPHI);
00149   InnerEHValuesPHI->addIncoming(CallerLPad, OuterResumeDest);
00150 
00151   // All done.
00152   return InnerResumeDest;
00153 }
00154 
00155 /// forwardResume - Forward the 'resume' instruction to the caller's landing pad
00156 /// block. When the landing pad block has only one predecessor, this is a simple
00157 /// branch. When there is more than one predecessor, we need to split the
00158 /// landing pad block after the landingpad instruction and jump to there.
00159 void InvokeInliningInfo::forwardResume(ResumeInst *RI,
00160                                SmallPtrSet<LandingPadInst*, 16> &InlinedLPads) {
00161   BasicBlock *Dest = getInnerResumeDest();
00162   BasicBlock *Src = RI->getParent();
00163 
00164   BranchInst::Create(Dest, Src);
00165 
00166   // Update the PHIs in the destination. They were inserted in an order which
00167   // makes this work.
00168   addIncomingPHIValuesForInto(Src, Dest);
00169 
00170   InnerEHValuesPHI->addIncoming(RI->getOperand(0), Src);
00171   RI->eraseFromParent();
00172 }
00173 
00174 /// HandleCallsInBlockInlinedThroughInvoke - When we inline a basic block into
00175 /// an invoke, we have to turn all of the calls that can throw into
00176 /// invokes.  This function analyze BB to see if there are any calls, and if so,
00177 /// it rewrites them to be invokes that jump to InvokeDest and fills in the PHI
00178 /// nodes in that block with the values specified in InvokeDestPHIValues.
00179 static void HandleCallsInBlockInlinedThroughInvoke(BasicBlock *BB,
00180                                                    InvokeInliningInfo &Invoke) {
00181   for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
00182     Instruction *I = BBI++;
00183 
00184     // We only need to check for function calls: inlined invoke
00185     // instructions require no special handling.
00186     CallInst *CI = dyn_cast<CallInst>(I);
00187 
00188     // If this call cannot unwind, don't convert it to an invoke.
00189     // Inline asm calls cannot throw.
00190     if (!CI || CI->doesNotThrow() || isa<InlineAsm>(CI->getCalledValue()))
00191       continue;
00192 
00193     // Convert this function call into an invoke instruction.  First, split the
00194     // basic block.
00195     BasicBlock *Split = BB->splitBasicBlock(CI, CI->getName()+".noexc");
00196 
00197     // Delete the unconditional branch inserted by splitBasicBlock
00198     BB->getInstList().pop_back();
00199 
00200     // Create the new invoke instruction.
00201     ImmutableCallSite CS(CI);
00202     SmallVector<Value*, 8> InvokeArgs(CS.arg_begin(), CS.arg_end());
00203     InvokeInst *II = InvokeInst::Create(CI->getCalledValue(), Split,
00204                                         Invoke.getOuterResumeDest(),
00205                                         InvokeArgs, CI->getName(), BB);
00206     II->setDebugLoc(CI->getDebugLoc());
00207     II->setCallingConv(CI->getCallingConv());
00208     II->setAttributes(CI->getAttributes());
00209     
00210     // Make sure that anything using the call now uses the invoke!  This also
00211     // updates the CallGraph if present, because it uses a WeakVH.
00212     CI->replaceAllUsesWith(II);
00213 
00214     // Delete the original call
00215     Split->getInstList().pop_front();
00216 
00217     // Update any PHI nodes in the exceptional block to indicate that there is
00218     // now a new entry in them.
00219     Invoke.addIncomingPHIValuesFor(BB);
00220     return;
00221   }
00222 }
00223 
00224 /// HandleInlinedInvoke - If we inlined an invoke site, we need to convert calls
00225 /// in the body of the inlined function into invokes.
00226 ///
00227 /// II is the invoke instruction being inlined.  FirstNewBlock is the first
00228 /// block of the inlined code (the last block is the end of the function),
00229 /// and InlineCodeInfo is information about the code that got inlined.
00230 static void HandleInlinedInvoke(InvokeInst *II, BasicBlock *FirstNewBlock,
00231                                 ClonedCodeInfo &InlinedCodeInfo) {
00232   BasicBlock *InvokeDest = II->getUnwindDest();
00233 
00234   Function *Caller = FirstNewBlock->getParent();
00235 
00236   // The inlined code is currently at the end of the function, scan from the
00237   // start of the inlined code to its end, checking for stuff we need to
00238   // rewrite.
00239   InvokeInliningInfo Invoke(II);
00240 
00241   // Get all of the inlined landing pad instructions.
00242   SmallPtrSet<LandingPadInst*, 16> InlinedLPads;
00243   for (Function::iterator I = FirstNewBlock, E = Caller->end(); I != E; ++I)
00244     if (InvokeInst *II = dyn_cast<InvokeInst>(I->getTerminator()))
00245       InlinedLPads.insert(II->getLandingPadInst());
00246 
00247   // Append the clauses from the outer landing pad instruction into the inlined
00248   // landing pad instructions.
00249   LandingPadInst *OuterLPad = Invoke.getLandingPadInst();
00250   for (SmallPtrSet<LandingPadInst*, 16>::iterator I = InlinedLPads.begin(),
00251          E = InlinedLPads.end(); I != E; ++I) {
00252     LandingPadInst *InlinedLPad = *I;
00253     unsigned OuterNum = OuterLPad->getNumClauses();
00254     InlinedLPad->reserveClauses(OuterNum);
00255     for (unsigned OuterIdx = 0; OuterIdx != OuterNum; ++OuterIdx)
00256       InlinedLPad->addClause(OuterLPad->getClause(OuterIdx));
00257     if (OuterLPad->isCleanup())
00258       InlinedLPad->setCleanup(true);
00259   }
00260 
00261   for (Function::iterator BB = FirstNewBlock, E = Caller->end(); BB != E; ++BB){
00262     if (InlinedCodeInfo.ContainsCalls)
00263       HandleCallsInBlockInlinedThroughInvoke(BB, Invoke);
00264 
00265     // Forward any resumes that are remaining here.
00266     if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator()))
00267       Invoke.forwardResume(RI, InlinedLPads);
00268   }
00269 
00270   // Now that everything is happy, we have one final detail.  The PHI nodes in
00271   // the exception destination block still have entries due to the original
00272   // invoke instruction. Eliminate these entries (which might even delete the
00273   // PHI node) now.
00274   InvokeDest->removePredecessor(II->getParent());
00275 }
00276 
00277 /// CloneAliasScopeMetadata - When inlining a function that contains noalias
00278 /// scope metadata, this metadata needs to be cloned so that the inlined blocks
00279 /// have different "unqiue scopes" at every call site. Were this not done, then
00280 /// aliasing scopes from a function inlined into a caller multiple times could
00281 /// not be differentiated (and this would lead to miscompiles because the
00282 /// non-aliasing property communicated by the metadata could have
00283 /// call-site-specific control dependencies).
00284 static void CloneAliasScopeMetadata(CallSite CS, ValueToValueMapTy &VMap) {
00285   const Function *CalledFunc = CS.getCalledFunction();
00286   SetVector<const MDNode *> MD;
00287 
00288   // Note: We could only clone the metadata if it is already used in the
00289   // caller. I'm omitting that check here because it might confuse
00290   // inter-procedural alias analysis passes. We can revisit this if it becomes
00291   // an efficiency or overhead problem.
00292 
00293   for (Function::const_iterator I = CalledFunc->begin(), IE = CalledFunc->end();
00294        I != IE; ++I)
00295     for (BasicBlock::const_iterator J = I->begin(), JE = I->end(); J != JE; ++J) {
00296       if (const MDNode *M = J->getMetadata(LLVMContext::MD_alias_scope))
00297         MD.insert(M);
00298       if (const MDNode *M = J->getMetadata(LLVMContext::MD_noalias))
00299         MD.insert(M);
00300     }
00301 
00302   if (MD.empty())
00303     return;
00304 
00305   // Walk the existing metadata, adding the complete (perhaps cyclic) chain to
00306   // the set.
00307   SmallVector<const Value *, 16> Queue(MD.begin(), MD.end());
00308   while (!Queue.empty()) {
00309     const MDNode *M = cast<MDNode>(Queue.pop_back_val());
00310     for (unsigned i = 0, ie = M->getNumOperands(); i != ie; ++i)
00311       if (const MDNode *M1 = dyn_cast<MDNode>(M->getOperand(i)))
00312         if (MD.insert(M1))
00313           Queue.push_back(M1);
00314   }
00315 
00316   // Now we have a complete set of all metadata in the chains used to specify
00317   // the noalias scopes and the lists of those scopes.
00318   SmallVector<MDNode *, 16> DummyNodes;
00319   DenseMap<const MDNode *, TrackingVH<MDNode> > MDMap;
00320   for (SetVector<const MDNode *>::iterator I = MD.begin(), IE = MD.end();
00321        I != IE; ++I) {
00322     MDNode *Dummy = MDNode::getTemporary(CalledFunc->getContext(),
00323                                          ArrayRef<Value*>());
00324     DummyNodes.push_back(Dummy);
00325     MDMap[*I] = Dummy;
00326   }
00327 
00328   // Create new metadata nodes to replace the dummy nodes, replacing old
00329   // metadata references with either a dummy node or an already-created new
00330   // node.
00331   for (SetVector<const MDNode *>::iterator I = MD.begin(), IE = MD.end();
00332        I != IE; ++I) {
00333     SmallVector<Value *, 4> NewOps;
00334     for (unsigned i = 0, ie = (*I)->getNumOperands(); i != ie; ++i) {
00335       const Value *V = (*I)->getOperand(i);
00336       if (const MDNode *M = dyn_cast<MDNode>(V))
00337         NewOps.push_back(MDMap[M]);
00338       else
00339         NewOps.push_back(const_cast<Value *>(V));
00340     }
00341 
00342     MDNode *NewM = MDNode::get(CalledFunc->getContext(), NewOps),
00343            *TempM = MDMap[*I];
00344 
00345     TempM->replaceAllUsesWith(NewM);
00346   }
00347 
00348   // Now replace the metadata in the new inlined instructions with the
00349   // repacements from the map.
00350   for (ValueToValueMapTy::iterator VMI = VMap.begin(), VMIE = VMap.end();
00351        VMI != VMIE; ++VMI) {
00352     if (!VMI->second)
00353       continue;
00354 
00355     Instruction *NI = dyn_cast<Instruction>(VMI->second);
00356     if (!NI)
00357       continue;
00358 
00359     if (MDNode *M = NI->getMetadata(LLVMContext::MD_alias_scope)) {
00360       MDNode *NewMD = MDMap[M];
00361       // If the call site also had alias scope metadata (a list of scopes to
00362       // which instructions inside it might belong), propagate those scopes to
00363       // the inlined instructions.
00364       if (MDNode *CSM =
00365           CS.getInstruction()->getMetadata(LLVMContext::MD_alias_scope))
00366         NewMD = MDNode::concatenate(NewMD, CSM);
00367       NI->setMetadata(LLVMContext::MD_alias_scope, NewMD);
00368     } else if (NI->mayReadOrWriteMemory()) {
00369       if (MDNode *M =
00370           CS.getInstruction()->getMetadata(LLVMContext::MD_alias_scope))
00371         NI->setMetadata(LLVMContext::MD_alias_scope, M);
00372     }
00373 
00374     if (MDNode *M = NI->getMetadata(LLVMContext::MD_noalias)) {
00375       MDNode *NewMD = MDMap[M];
00376       // If the call site also had noalias metadata (a list of scopes with
00377       // which instructions inside it don't alias), propagate those scopes to
00378       // the inlined instructions.
00379       if (MDNode *CSM =
00380           CS.getInstruction()->getMetadata(LLVMContext::MD_noalias))
00381         NewMD = MDNode::concatenate(NewMD, CSM);
00382       NI->setMetadata(LLVMContext::MD_noalias, NewMD);
00383     } else if (NI->mayReadOrWriteMemory()) {
00384       if (MDNode *M =
00385           CS.getInstruction()->getMetadata(LLVMContext::MD_noalias))
00386         NI->setMetadata(LLVMContext::MD_noalias, M);
00387     }
00388   }
00389 
00390   // Now that everything has been replaced, delete the dummy nodes.
00391   for (unsigned i = 0, ie = DummyNodes.size(); i != ie; ++i)
00392     MDNode::deleteTemporary(DummyNodes[i]);
00393 }
00394 
00395 /// AddAliasScopeMetadata - If the inlined function has noalias arguments, then
00396 /// add new alias scopes for each noalias argument, tag the mapped noalias
00397 /// parameters with noalias metadata specifying the new scope, and tag all
00398 /// non-derived loads, stores and memory intrinsics with the new alias scopes.
00399 static void AddAliasScopeMetadata(CallSite CS, ValueToValueMapTy &VMap,
00400                                   const DataLayout *DL) {
00401   if (!EnableNoAliasConversion)
00402     return;
00403 
00404   const Function *CalledFunc = CS.getCalledFunction();
00405   SmallVector<const Argument *, 4> NoAliasArgs;
00406 
00407   for (Function::const_arg_iterator I = CalledFunc->arg_begin(),
00408        E = CalledFunc->arg_end(); I != E; ++I) {
00409     if (I->hasNoAliasAttr() && !I->hasNUses(0))
00410       NoAliasArgs.push_back(I);
00411   }
00412 
00413   if (NoAliasArgs.empty())
00414     return;
00415 
00416   // To do a good job, if a noalias variable is captured, we need to know if
00417   // the capture point dominates the particular use we're considering.
00418   DominatorTree DT;
00419   DT.recalculate(const_cast<Function&>(*CalledFunc));
00420 
00421   // noalias indicates that pointer values based on the argument do not alias
00422   // pointer values which are not based on it. So we add a new "scope" for each
00423   // noalias function argument. Accesses using pointers based on that argument
00424   // become part of that alias scope, accesses using pointers not based on that
00425   // argument are tagged as noalias with that scope.
00426 
00427   DenseMap<const Argument *, MDNode *> NewScopes;
00428   MDBuilder MDB(CalledFunc->getContext());
00429 
00430   // Create a new scope domain for this function.
00431   MDNode *NewDomain =
00432     MDB.createAnonymousAliasScopeDomain(CalledFunc->getName());
00433   for (unsigned i = 0, e = NoAliasArgs.size(); i != e; ++i) {
00434     const Argument *A = NoAliasArgs[i];
00435 
00436     std::string Name = CalledFunc->getName();
00437     if (A->hasName()) {
00438       Name += ": %";
00439       Name += A->getName();
00440     } else {
00441       Name += ": argument ";
00442       Name += utostr(i);
00443     }
00444 
00445     // Note: We always create a new anonymous root here. This is true regardless
00446     // of the linkage of the callee because the aliasing "scope" is not just a
00447     // property of the callee, but also all control dependencies in the caller.
00448     MDNode *NewScope = MDB.createAnonymousAliasScope(NewDomain, Name);
00449     NewScopes.insert(std::make_pair(A, NewScope));
00450   }
00451 
00452   // Iterate over all new instructions in the map; for all memory-access
00453   // instructions, add the alias scope metadata.
00454   for (ValueToValueMapTy::iterator VMI = VMap.begin(), VMIE = VMap.end();
00455        VMI != VMIE; ++VMI) {
00456     if (const Instruction *I = dyn_cast<Instruction>(VMI->first)) {
00457       if (!VMI->second)
00458         continue;
00459 
00460       Instruction *NI = dyn_cast<Instruction>(VMI->second);
00461       if (!NI)
00462         continue;
00463 
00464       SmallVector<const Value *, 2> PtrArgs;
00465 
00466       if (const LoadInst *LI = dyn_cast<LoadInst>(I))
00467         PtrArgs.push_back(LI->getPointerOperand());
00468       else if (const StoreInst *SI = dyn_cast<StoreInst>(I))
00469         PtrArgs.push_back(SI->getPointerOperand());
00470       else if (const VAArgInst *VAAI = dyn_cast<VAArgInst>(I))
00471         PtrArgs.push_back(VAAI->getPointerOperand());
00472       else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I))
00473         PtrArgs.push_back(CXI->getPointerOperand());
00474       else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I))
00475         PtrArgs.push_back(RMWI->getPointerOperand());
00476       else if (ImmutableCallSite ICS = ImmutableCallSite(I)) {
00477   // If we know that the call does not access memory, then we'll still
00478   // know that about the inlined clone of this call site, and we don't
00479   // need to add metadata.
00480         if (ICS.doesNotAccessMemory())
00481           continue;
00482 
00483         for (ImmutableCallSite::arg_iterator AI = ICS.arg_begin(),
00484              AE = ICS.arg_end(); AI != AE; ++AI)
00485     // We need to check the underlying objects of all arguments, not just
00486     // the pointer arguments, because we might be passing pointers as
00487     // integers, etc.
00488           // FIXME: If we know that the call only accesses pointer arguments,
00489           // then we only need to check the pointer arguments.
00490           PtrArgs.push_back(*AI);
00491       }
00492 
00493       // If we found no pointers, then this instruction is not suitable for
00494       // pairing with an instruction to receive aliasing metadata.
00495       // However, if this is a call, this we might just alias with none of the
00496       // noalias arguments.
00497       if (PtrArgs.empty() && !isa<CallInst>(I) && !isa<InvokeInst>(I))
00498         continue;
00499 
00500       // It is possible that there is only one underlying object, but you
00501       // need to go through several PHIs to see it, and thus could be
00502       // repeated in the Objects list.
00503       SmallPtrSet<const Value *, 4> ObjSet;
00504       SmallVector<Value *, 4> Scopes, NoAliases;
00505 
00506       SmallSetVector<const Argument *, 4> NAPtrArgs;
00507       for (unsigned i = 0, ie = PtrArgs.size(); i != ie; ++i) {
00508         SmallVector<Value *, 4> Objects;
00509         GetUnderlyingObjects(const_cast<Value*>(PtrArgs[i]),
00510                              Objects, DL, /* MaxLookup = */ 0);
00511 
00512         for (Value *O : Objects)
00513           ObjSet.insert(O);
00514       }
00515 
00516       // Figure out if we're derived from anyhing that is not a noalias
00517       // argument.
00518       bool CanDeriveViaCapture = false;
00519       for (const Value *V : ObjSet)
00520         if (!isIdentifiedFunctionLocal(const_cast<Value*>(V))) {
00521           CanDeriveViaCapture = true;
00522           break;
00523         }
00524   
00525       // First, we want to figure out all of the sets with which we definitely
00526       // don't alias. Iterate over all noalias set, and add those for which:
00527       //   1. The noalias argument is not in the set of objects from which we
00528       //      definitely derive.
00529       //   2. The noalias argument has not yet been captured.
00530       for (const Argument *A : NoAliasArgs) {
00531         if (!ObjSet.count(A) && (!CanDeriveViaCapture ||
00532                                  A->hasNoCaptureAttr() ||
00533                                  !PointerMayBeCapturedBefore(A,
00534                                    /* ReturnCaptures */ false,
00535                                    /* StoreCaptures */ false, I, &DT)))
00536           NoAliases.push_back(NewScopes[A]);
00537       }
00538 
00539       if (!NoAliases.empty())
00540         NI->setMetadata(LLVMContext::MD_noalias, MDNode::concatenate(
00541           NI->getMetadata(LLVMContext::MD_noalias),
00542             MDNode::get(CalledFunc->getContext(), NoAliases)));
00543       // Next, we want to figure out all of the sets to which we might belong.
00544       // We might below to a set if:
00545       //  1. The noalias argument is in the set of underlying objects
00546       // or
00547       //  2. There is some non-noalias argument in our list and the no-alias
00548       //     argument has been captured.
00549       
00550       for (const Argument *A : NoAliasArgs) {
00551         if (ObjSet.count(A) || (CanDeriveViaCapture &&
00552                                 PointerMayBeCapturedBefore(A,
00553                                   /* ReturnCaptures */ false,
00554                                   /* StoreCaptures */ false,
00555                                   I, &DT)))
00556           Scopes.push_back(NewScopes[A]);
00557       }
00558 
00559       if (!Scopes.empty())
00560         NI->setMetadata(LLVMContext::MD_alias_scope, MDNode::concatenate(
00561           NI->getMetadata(LLVMContext::MD_alias_scope),
00562             MDNode::get(CalledFunc->getContext(), Scopes)));
00563     }
00564   }
00565 }
00566 
00567 /// UpdateCallGraphAfterInlining - Once we have cloned code over from a callee
00568 /// into the caller, update the specified callgraph to reflect the changes we
00569 /// made.  Note that it's possible that not all code was copied over, so only
00570 /// some edges of the callgraph may remain.
00571 static void UpdateCallGraphAfterInlining(CallSite CS,
00572                                          Function::iterator FirstNewBlock,
00573                                          ValueToValueMapTy &VMap,
00574                                          InlineFunctionInfo &IFI) {
00575   CallGraph &CG = *IFI.CG;
00576   const Function *Caller = CS.getInstruction()->getParent()->getParent();
00577   const Function *Callee = CS.getCalledFunction();
00578   CallGraphNode *CalleeNode = CG[Callee];
00579   CallGraphNode *CallerNode = CG[Caller];
00580 
00581   // Since we inlined some uninlined call sites in the callee into the caller,
00582   // add edges from the caller to all of the callees of the callee.
00583   CallGraphNode::iterator I = CalleeNode->begin(), E = CalleeNode->end();
00584 
00585   // Consider the case where CalleeNode == CallerNode.
00586   CallGraphNode::CalledFunctionsVector CallCache;
00587   if (CalleeNode == CallerNode) {
00588     CallCache.assign(I, E);
00589     I = CallCache.begin();
00590     E = CallCache.end();
00591   }
00592 
00593   for (; I != E; ++I) {
00594     const Value *OrigCall = I->first;
00595 
00596     ValueToValueMapTy::iterator VMI = VMap.find(OrigCall);
00597     // Only copy the edge if the call was inlined!
00598     if (VMI == VMap.end() || VMI->second == nullptr)
00599       continue;
00600     
00601     // If the call was inlined, but then constant folded, there is no edge to
00602     // add.  Check for this case.
00603     Instruction *NewCall = dyn_cast<Instruction>(VMI->second);
00604     if (!NewCall) continue;
00605 
00606     // Remember that this call site got inlined for the client of
00607     // InlineFunction.
00608     IFI.InlinedCalls.push_back(NewCall);
00609 
00610     // It's possible that inlining the callsite will cause it to go from an
00611     // indirect to a direct call by resolving a function pointer.  If this
00612     // happens, set the callee of the new call site to a more precise
00613     // destination.  This can also happen if the call graph node of the caller
00614     // was just unnecessarily imprecise.
00615     if (!I->second->getFunction())
00616       if (Function *F = CallSite(NewCall).getCalledFunction()) {
00617         // Indirect call site resolved to direct call.
00618         CallerNode->addCalledFunction(CallSite(NewCall), CG[F]);
00619 
00620         continue;
00621       }
00622 
00623     CallerNode->addCalledFunction(CallSite(NewCall), I->second);
00624   }
00625   
00626   // Update the call graph by deleting the edge from Callee to Caller.  We must
00627   // do this after the loop above in case Caller and Callee are the same.
00628   CallerNode->removeCallEdgeFor(CS);
00629 }
00630 
00631 static void HandleByValArgumentInit(Value *Dst, Value *Src, Module *M,
00632                                     BasicBlock *InsertBlock,
00633                                     InlineFunctionInfo &IFI) {
00634   LLVMContext &Context = Src->getContext();
00635   Type *VoidPtrTy = Type::getInt8PtrTy(Context);
00636   Type *AggTy = cast<PointerType>(Src->getType())->getElementType();
00637   Type *Tys[3] = { VoidPtrTy, VoidPtrTy, Type::getInt64Ty(Context) };
00638   Function *MemCpyFn = Intrinsic::getDeclaration(M, Intrinsic::memcpy, Tys);
00639   IRBuilder<> builder(InsertBlock->begin());
00640   Value *DstCast = builder.CreateBitCast(Dst, VoidPtrTy, "tmp");
00641   Value *SrcCast = builder.CreateBitCast(Src, VoidPtrTy, "tmp");
00642 
00643   Value *Size;
00644   if (IFI.DL == nullptr)
00645     Size = ConstantExpr::getSizeOf(AggTy);
00646   else
00647     Size = ConstantInt::get(Type::getInt64Ty(Context),
00648                             IFI.DL->getTypeStoreSize(AggTy));
00649 
00650   // Always generate a memcpy of alignment 1 here because we don't know
00651   // the alignment of the src pointer.  Other optimizations can infer
00652   // better alignment.
00653   Value *CallArgs[] = {
00654     DstCast, SrcCast, Size,
00655     ConstantInt::get(Type::getInt32Ty(Context), 1),
00656     ConstantInt::getFalse(Context) // isVolatile
00657   };
00658   builder.CreateCall(MemCpyFn, CallArgs);
00659 }
00660 
00661 /// HandleByValArgument - When inlining a call site that has a byval argument,
00662 /// we have to make the implicit memcpy explicit by adding it.
00663 static Value *HandleByValArgument(Value *Arg, Instruction *TheCall,
00664                                   const Function *CalledFunc,
00665                                   InlineFunctionInfo &IFI,
00666                                   unsigned ByValAlignment) {
00667   PointerType *ArgTy = cast<PointerType>(Arg->getType());
00668   Type *AggTy = ArgTy->getElementType();
00669 
00670   // If the called function is readonly, then it could not mutate the caller's
00671   // copy of the byval'd memory.  In this case, it is safe to elide the copy and
00672   // temporary.
00673   if (CalledFunc->onlyReadsMemory()) {
00674     // If the byval argument has a specified alignment that is greater than the
00675     // passed in pointer, then we either have to round up the input pointer or
00676     // give up on this transformation.
00677     if (ByValAlignment <= 1)  // 0 = unspecified, 1 = no particular alignment.
00678       return Arg;
00679 
00680     // If the pointer is already known to be sufficiently aligned, or if we can
00681     // round it up to a larger alignment, then we don't need a temporary.
00682     if (getOrEnforceKnownAlignment(Arg, ByValAlignment,
00683                                    IFI.DL) >= ByValAlignment)
00684       return Arg;
00685     
00686     // Otherwise, we have to make a memcpy to get a safe alignment.  This is bad
00687     // for code quality, but rarely happens and is required for correctness.
00688   }
00689 
00690   // Create the alloca.  If we have DataLayout, use nice alignment.
00691   unsigned Align = 1;
00692   if (IFI.DL)
00693     Align = IFI.DL->getPrefTypeAlignment(AggTy);
00694   
00695   // If the byval had an alignment specified, we *must* use at least that
00696   // alignment, as it is required by the byval argument (and uses of the
00697   // pointer inside the callee).
00698   Align = std::max(Align, ByValAlignment);
00699   
00700   Function *Caller = TheCall->getParent()->getParent(); 
00701   
00702   Value *NewAlloca = new AllocaInst(AggTy, nullptr, Align, Arg->getName(), 
00703                                     &*Caller->begin()->begin());
00704   IFI.StaticAllocas.push_back(cast<AllocaInst>(NewAlloca));
00705   
00706   // Uses of the argument in the function should use our new alloca
00707   // instead.
00708   return NewAlloca;
00709 }
00710 
00711 // isUsedByLifetimeMarker - Check whether this Value is used by a lifetime
00712 // intrinsic.
00713 static bool isUsedByLifetimeMarker(Value *V) {
00714   for (User *U : V->users()) {
00715     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) {
00716       switch (II->getIntrinsicID()) {
00717       default: break;
00718       case Intrinsic::lifetime_start:
00719       case Intrinsic::lifetime_end:
00720         return true;
00721       }
00722     }
00723   }
00724   return false;
00725 }
00726 
00727 // hasLifetimeMarkers - Check whether the given alloca already has
00728 // lifetime.start or lifetime.end intrinsics.
00729 static bool hasLifetimeMarkers(AllocaInst *AI) {
00730   Type *Ty = AI->getType();
00731   Type *Int8PtrTy = Type::getInt8PtrTy(Ty->getContext(),
00732                                        Ty->getPointerAddressSpace());
00733   if (Ty == Int8PtrTy)
00734     return isUsedByLifetimeMarker(AI);
00735 
00736   // Do a scan to find all the casts to i8*.
00737   for (User *U : AI->users()) {
00738     if (U->getType() != Int8PtrTy) continue;
00739     if (U->stripPointerCasts() != AI) continue;
00740     if (isUsedByLifetimeMarker(U))
00741       return true;
00742   }
00743   return false;
00744 }
00745 
00746 /// updateInlinedAtInfo - Helper function used by fixupLineNumbers to
00747 /// recursively update InlinedAtEntry of a DebugLoc.
00748 static DebugLoc updateInlinedAtInfo(const DebugLoc &DL, 
00749                                     const DebugLoc &InlinedAtDL,
00750                                     LLVMContext &Ctx) {
00751   if (MDNode *IA = DL.getInlinedAt(Ctx)) {
00752     DebugLoc NewInlinedAtDL 
00753       = updateInlinedAtInfo(DebugLoc::getFromDILocation(IA), InlinedAtDL, Ctx);
00754     return DebugLoc::get(DL.getLine(), DL.getCol(), DL.getScope(Ctx),
00755                          NewInlinedAtDL.getAsMDNode(Ctx));
00756   }
00757 
00758   return DebugLoc::get(DL.getLine(), DL.getCol(), DL.getScope(Ctx),
00759                        InlinedAtDL.getAsMDNode(Ctx));
00760 }
00761 
00762 /// fixupLineNumbers - Update inlined instructions' line numbers to 
00763 /// to encode location where these instructions are inlined.
00764 static void fixupLineNumbers(Function *Fn, Function::iterator FI,
00765                              Instruction *TheCall) {
00766   DebugLoc TheCallDL = TheCall->getDebugLoc();
00767   if (TheCallDL.isUnknown())
00768     return;
00769 
00770   for (; FI != Fn->end(); ++FI) {
00771     for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
00772          BI != BE; ++BI) {
00773       DebugLoc DL = BI->getDebugLoc();
00774       if (DL.isUnknown()) {
00775         // If the inlined instruction has no line number, make it look as if it
00776         // originates from the call location. This is important for
00777         // ((__always_inline__, __nodebug__)) functions which must use caller
00778         // location for all instructions in their function body.
00779         BI->setDebugLoc(TheCallDL);
00780       } else {
00781         BI->setDebugLoc(updateInlinedAtInfo(DL, TheCallDL, BI->getContext()));
00782         if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(BI)) {
00783           LLVMContext &Ctx = BI->getContext();
00784           MDNode *InlinedAt = BI->getDebugLoc().getInlinedAt(Ctx);
00785           DVI->setOperand(2, createInlinedVariable(DVI->getVariable(), 
00786                                                    InlinedAt, Ctx));
00787         }
00788       }
00789     }
00790   }
00791 }
00792 
00793 /// InlineFunction - This function inlines the called function into the basic
00794 /// block of the caller.  This returns false if it is not possible to inline
00795 /// this call.  The program is still in a well defined state if this occurs
00796 /// though.
00797 ///
00798 /// Note that this only does one level of inlining.  For example, if the
00799 /// instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
00800 /// exists in the instruction stream.  Similarly this will inline a recursive
00801 /// function by one level.
00802 bool llvm::InlineFunction(CallSite CS, InlineFunctionInfo &IFI,
00803                           bool InsertLifetime) {
00804   Instruction *TheCall = CS.getInstruction();
00805   assert(TheCall->getParent() && TheCall->getParent()->getParent() &&
00806          "Instruction not in function!");
00807 
00808   // If IFI has any state in it, zap it before we fill it in.
00809   IFI.reset();
00810   
00811   const Function *CalledFunc = CS.getCalledFunction();
00812   if (!CalledFunc ||              // Can't inline external function or indirect
00813       CalledFunc->isDeclaration() || // call, or call to a vararg function!
00814       CalledFunc->getFunctionType()->isVarArg()) return false;
00815 
00816   // If the call to the callee cannot throw, set the 'nounwind' flag on any
00817   // calls that we inline.
00818   bool MarkNoUnwind = CS.doesNotThrow();
00819 
00820   BasicBlock *OrigBB = TheCall->getParent();
00821   Function *Caller = OrigBB->getParent();
00822 
00823   // GC poses two hazards to inlining, which only occur when the callee has GC:
00824   //  1. If the caller has no GC, then the callee's GC must be propagated to the
00825   //     caller.
00826   //  2. If the caller has a differing GC, it is invalid to inline.
00827   if (CalledFunc->hasGC()) {
00828     if (!Caller->hasGC())
00829       Caller->setGC(CalledFunc->getGC());
00830     else if (CalledFunc->getGC() != Caller->getGC())
00831       return false;
00832   }
00833 
00834   // Get the personality function from the callee if it contains a landing pad.
00835   Value *CalleePersonality = nullptr;
00836   for (Function::const_iterator I = CalledFunc->begin(), E = CalledFunc->end();
00837        I != E; ++I)
00838     if (const InvokeInst *II = dyn_cast<InvokeInst>(I->getTerminator())) {
00839       const BasicBlock *BB = II->getUnwindDest();
00840       const LandingPadInst *LP = BB->getLandingPadInst();
00841       CalleePersonality = LP->getPersonalityFn();
00842       break;
00843     }
00844 
00845   // Find the personality function used by the landing pads of the caller. If it
00846   // exists, then check to see that it matches the personality function used in
00847   // the callee.
00848   if (CalleePersonality) {
00849     for (Function::const_iterator I = Caller->begin(), E = Caller->end();
00850          I != E; ++I)
00851       if (const InvokeInst *II = dyn_cast<InvokeInst>(I->getTerminator())) {
00852         const BasicBlock *BB = II->getUnwindDest();
00853         const LandingPadInst *LP = BB->getLandingPadInst();
00854 
00855         // If the personality functions match, then we can perform the
00856         // inlining. Otherwise, we can't inline.
00857         // TODO: This isn't 100% true. Some personality functions are proper
00858         //       supersets of others and can be used in place of the other.
00859         if (LP->getPersonalityFn() != CalleePersonality)
00860           return false;
00861 
00862         break;
00863       }
00864   }
00865 
00866   // Get an iterator to the last basic block in the function, which will have
00867   // the new function inlined after it.
00868   Function::iterator LastBlock = &Caller->back();
00869 
00870   // Make sure to capture all of the return instructions from the cloned
00871   // function.
00872   SmallVector<ReturnInst*, 8> Returns;
00873   ClonedCodeInfo InlinedFunctionInfo;
00874   Function::iterator FirstNewBlock;
00875 
00876   { // Scope to destroy VMap after cloning.
00877     ValueToValueMapTy VMap;
00878     // Keep a list of pair (dst, src) to emit byval initializations.
00879     SmallVector<std::pair<Value*, Value*>, 4> ByValInit;
00880 
00881     assert(CalledFunc->arg_size() == CS.arg_size() &&
00882            "No varargs calls can be inlined!");
00883 
00884     // Calculate the vector of arguments to pass into the function cloner, which
00885     // matches up the formal to the actual argument values.
00886     CallSite::arg_iterator AI = CS.arg_begin();
00887     unsigned ArgNo = 0;
00888     for (Function::const_arg_iterator I = CalledFunc->arg_begin(),
00889          E = CalledFunc->arg_end(); I != E; ++I, ++AI, ++ArgNo) {
00890       Value *ActualArg = *AI;
00891 
00892       // When byval arguments actually inlined, we need to make the copy implied
00893       // by them explicit.  However, we don't do this if the callee is readonly
00894       // or readnone, because the copy would be unneeded: the callee doesn't
00895       // modify the struct.
00896       if (CS.isByValArgument(ArgNo)) {
00897         ActualArg = HandleByValArgument(ActualArg, TheCall, CalledFunc, IFI,
00898                                         CalledFunc->getParamAlignment(ArgNo+1));
00899         if (ActualArg != *AI)
00900           ByValInit.push_back(std::make_pair(ActualArg, (Value*) *AI));
00901       }
00902 
00903       VMap[I] = ActualArg;
00904     }
00905 
00906     // We want the inliner to prune the code as it copies.  We would LOVE to
00907     // have no dead or constant instructions leftover after inlining occurs
00908     // (which can happen, e.g., because an argument was constant), but we'll be
00909     // happy with whatever the cloner can do.
00910     CloneAndPruneFunctionInto(Caller, CalledFunc, VMap, 
00911                               /*ModuleLevelChanges=*/false, Returns, ".i",
00912                               &InlinedFunctionInfo, IFI.DL, TheCall);
00913 
00914     // Remember the first block that is newly cloned over.
00915     FirstNewBlock = LastBlock; ++FirstNewBlock;
00916 
00917     // Inject byval arguments initialization.
00918     for (std::pair<Value*, Value*> &Init : ByValInit)
00919       HandleByValArgumentInit(Init.first, Init.second, Caller->getParent(),
00920                               FirstNewBlock, IFI);
00921 
00922     // Update the callgraph if requested.
00923     if (IFI.CG)
00924       UpdateCallGraphAfterInlining(CS, FirstNewBlock, VMap, IFI);
00925 
00926     // Update inlined instructions' line number information.
00927     fixupLineNumbers(Caller, FirstNewBlock, TheCall);
00928 
00929     // Clone existing noalias metadata if necessary.
00930     CloneAliasScopeMetadata(CS, VMap);
00931 
00932     // Add noalias metadata if necessary.
00933     AddAliasScopeMetadata(CS, VMap, IFI.DL);
00934   }
00935 
00936   // If there are any alloca instructions in the block that used to be the entry
00937   // block for the callee, move them to the entry block of the caller.  First
00938   // calculate which instruction they should be inserted before.  We insert the
00939   // instructions at the end of the current alloca list.
00940   {
00941     BasicBlock::iterator InsertPoint = Caller->begin()->begin();
00942     for (BasicBlock::iterator I = FirstNewBlock->begin(),
00943          E = FirstNewBlock->end(); I != E; ) {
00944       AllocaInst *AI = dyn_cast<AllocaInst>(I++);
00945       if (!AI) continue;
00946       
00947       // If the alloca is now dead, remove it.  This often occurs due to code
00948       // specialization.
00949       if (AI->use_empty()) {
00950         AI->eraseFromParent();
00951         continue;
00952       }
00953 
00954       if (!isa<Constant>(AI->getArraySize()))
00955         continue;
00956       
00957       // Keep track of the static allocas that we inline into the caller.
00958       IFI.StaticAllocas.push_back(AI);
00959       
00960       // Scan for the block of allocas that we can move over, and move them
00961       // all at once.
00962       while (isa<AllocaInst>(I) &&
00963              isa<Constant>(cast<AllocaInst>(I)->getArraySize())) {
00964         IFI.StaticAllocas.push_back(cast<AllocaInst>(I));
00965         ++I;
00966       }
00967 
00968       // Transfer all of the allocas over in a block.  Using splice means
00969       // that the instructions aren't removed from the symbol table, then
00970       // reinserted.
00971       Caller->getEntryBlock().getInstList().splice(InsertPoint,
00972                                                    FirstNewBlock->getInstList(),
00973                                                    AI, I);
00974     }
00975   }
00976 
00977   bool InlinedMustTailCalls = false;
00978   if (InlinedFunctionInfo.ContainsCalls) {
00979     CallInst::TailCallKind CallSiteTailKind = CallInst::TCK_None;
00980     if (CallInst *CI = dyn_cast<CallInst>(TheCall))
00981       CallSiteTailKind = CI->getTailCallKind();
00982 
00983     for (Function::iterator BB = FirstNewBlock, E = Caller->end(); BB != E;
00984          ++BB) {
00985       for (Instruction &I : *BB) {
00986         CallInst *CI = dyn_cast<CallInst>(&I);
00987         if (!CI)
00988           continue;
00989 
00990         // We need to reduce the strength of any inlined tail calls.  For
00991         // musttail, we have to avoid introducing potential unbounded stack
00992         // growth.  For example, if functions 'f' and 'g' are mutually recursive
00993         // with musttail, we can inline 'g' into 'f' so long as we preserve
00994         // musttail on the cloned call to 'f'.  If either the inlined call site
00995         // or the cloned call site is *not* musttail, the program already has
00996         // one frame of stack growth, so it's safe to remove musttail.  Here is
00997         // a table of example transformations:
00998         //
00999         //    f -> musttail g -> musttail f  ==>  f -> musttail f
01000         //    f -> musttail g ->     tail f  ==>  f ->     tail f
01001         //    f ->          g -> musttail f  ==>  f ->          f
01002         //    f ->          g ->     tail f  ==>  f ->          f
01003         CallInst::TailCallKind ChildTCK = CI->getTailCallKind();
01004         ChildTCK = std::min(CallSiteTailKind, ChildTCK);
01005         CI->setTailCallKind(ChildTCK);
01006         InlinedMustTailCalls |= CI->isMustTailCall();
01007 
01008         // Calls inlined through a 'nounwind' call site should be marked
01009         // 'nounwind'.
01010         if (MarkNoUnwind)
01011           CI->setDoesNotThrow();
01012       }
01013     }
01014   }
01015 
01016   // Leave lifetime markers for the static alloca's, scoping them to the
01017   // function we just inlined.
01018   if (InsertLifetime && !IFI.StaticAllocas.empty()) {
01019     IRBuilder<> builder(FirstNewBlock->begin());
01020     for (unsigned ai = 0, ae = IFI.StaticAllocas.size(); ai != ae; ++ai) {
01021       AllocaInst *AI = IFI.StaticAllocas[ai];
01022 
01023       // If the alloca is already scoped to something smaller than the whole
01024       // function then there's no need to add redundant, less accurate markers.
01025       if (hasLifetimeMarkers(AI))
01026         continue;
01027 
01028       // Try to determine the size of the allocation.
01029       ConstantInt *AllocaSize = nullptr;
01030       if (ConstantInt *AIArraySize =
01031           dyn_cast<ConstantInt>(AI->getArraySize())) {
01032         if (IFI.DL) {
01033           Type *AllocaType = AI->getAllocatedType();
01034           uint64_t AllocaTypeSize = IFI.DL->getTypeAllocSize(AllocaType);
01035           uint64_t AllocaArraySize = AIArraySize->getLimitedValue();
01036           assert(AllocaArraySize > 0 && "array size of AllocaInst is zero");
01037           // Check that array size doesn't saturate uint64_t and doesn't
01038           // overflow when it's multiplied by type size.
01039           if (AllocaArraySize != ~0ULL &&
01040               UINT64_MAX / AllocaArraySize >= AllocaTypeSize) {
01041             AllocaSize = ConstantInt::get(Type::getInt64Ty(AI->getContext()),
01042                                           AllocaArraySize * AllocaTypeSize);
01043           }
01044         }
01045       }
01046 
01047       builder.CreateLifetimeStart(AI, AllocaSize);
01048       for (ReturnInst *RI : Returns) {
01049         // Don't insert llvm.lifetime.end calls between a musttail call and a
01050         // return.  The return kills all local allocas.
01051         if (InlinedMustTailCalls &&
01052             RI->getParent()->getTerminatingMustTailCall())
01053           continue;
01054         IRBuilder<>(RI).CreateLifetimeEnd(AI, AllocaSize);
01055       }
01056     }
01057   }
01058 
01059   // If the inlined code contained dynamic alloca instructions, wrap the inlined
01060   // code with llvm.stacksave/llvm.stackrestore intrinsics.
01061   if (InlinedFunctionInfo.ContainsDynamicAllocas) {
01062     Module *M = Caller->getParent();
01063     // Get the two intrinsics we care about.
01064     Function *StackSave = Intrinsic::getDeclaration(M, Intrinsic::stacksave);
01065     Function *StackRestore=Intrinsic::getDeclaration(M,Intrinsic::stackrestore);
01066 
01067     // Insert the llvm.stacksave.
01068     CallInst *SavedPtr = IRBuilder<>(FirstNewBlock, FirstNewBlock->begin())
01069       .CreateCall(StackSave, "savedstack");
01070 
01071     // Insert a call to llvm.stackrestore before any return instructions in the
01072     // inlined function.
01073     for (ReturnInst *RI : Returns) {
01074       // Don't insert llvm.stackrestore calls between a musttail call and a
01075       // return.  The return will restore the stack pointer.
01076       if (InlinedMustTailCalls && RI->getParent()->getTerminatingMustTailCall())
01077         continue;
01078       IRBuilder<>(RI).CreateCall(StackRestore, SavedPtr);
01079     }
01080   }
01081 
01082   // If we are inlining for an invoke instruction, we must make sure to rewrite
01083   // any call instructions into invoke instructions.
01084   if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
01085     HandleInlinedInvoke(II, FirstNewBlock, InlinedFunctionInfo);
01086 
01087   // Handle any inlined musttail call sites.  In order for a new call site to be
01088   // musttail, the source of the clone and the inlined call site must have been
01089   // musttail.  Therefore it's safe to return without merging control into the
01090   // phi below.
01091   if (InlinedMustTailCalls) {
01092     // Check if we need to bitcast the result of any musttail calls.
01093     Type *NewRetTy = Caller->getReturnType();
01094     bool NeedBitCast = !TheCall->use_empty() && TheCall->getType() != NewRetTy;
01095 
01096     // Handle the returns preceded by musttail calls separately.
01097     SmallVector<ReturnInst *, 8> NormalReturns;
01098     for (ReturnInst *RI : Returns) {
01099       CallInst *ReturnedMustTail =
01100           RI->getParent()->getTerminatingMustTailCall();
01101       if (!ReturnedMustTail) {
01102         NormalReturns.push_back(RI);
01103         continue;
01104       }
01105       if (!NeedBitCast)
01106         continue;
01107 
01108       // Delete the old return and any preceding bitcast.
01109       BasicBlock *CurBB = RI->getParent();
01110       auto *OldCast = dyn_cast_or_null<BitCastInst>(RI->getReturnValue());
01111       RI->eraseFromParent();
01112       if (OldCast)
01113         OldCast->eraseFromParent();
01114 
01115       // Insert a new bitcast and return with the right type.
01116       IRBuilder<> Builder(CurBB);
01117       Builder.CreateRet(Builder.CreateBitCast(ReturnedMustTail, NewRetTy));
01118     }
01119 
01120     // Leave behind the normal returns so we can merge control flow.
01121     std::swap(Returns, NormalReturns);
01122   }
01123 
01124   // If we cloned in _exactly one_ basic block, and if that block ends in a
01125   // return instruction, we splice the body of the inlined callee directly into
01126   // the calling basic block.
01127   if (Returns.size() == 1 && std::distance(FirstNewBlock, Caller->end()) == 1) {
01128     // Move all of the instructions right before the call.
01129     OrigBB->getInstList().splice(TheCall, FirstNewBlock->getInstList(),
01130                                  FirstNewBlock->begin(), FirstNewBlock->end());
01131     // Remove the cloned basic block.
01132     Caller->getBasicBlockList().pop_back();
01133 
01134     // If the call site was an invoke instruction, add a branch to the normal
01135     // destination.
01136     if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
01137       BranchInst *NewBr = BranchInst::Create(II->getNormalDest(), TheCall);
01138       NewBr->setDebugLoc(Returns[0]->getDebugLoc());
01139     }
01140 
01141     // If the return instruction returned a value, replace uses of the call with
01142     // uses of the returned value.
01143     if (!TheCall->use_empty()) {
01144       ReturnInst *R = Returns[0];
01145       if (TheCall == R->getReturnValue())
01146         TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
01147       else
01148         TheCall->replaceAllUsesWith(R->getReturnValue());
01149     }
01150     // Since we are now done with the Call/Invoke, we can delete it.
01151     TheCall->eraseFromParent();
01152 
01153     // Since we are now done with the return instruction, delete it also.
01154     Returns[0]->eraseFromParent();
01155 
01156     // We are now done with the inlining.
01157     return true;
01158   }
01159 
01160   // Otherwise, we have the normal case, of more than one block to inline or
01161   // multiple return sites.
01162 
01163   // We want to clone the entire callee function into the hole between the
01164   // "starter" and "ender" blocks.  How we accomplish this depends on whether
01165   // this is an invoke instruction or a call instruction.
01166   BasicBlock *AfterCallBB;
01167   BranchInst *CreatedBranchToNormalDest = nullptr;
01168   if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
01169 
01170     // Add an unconditional branch to make this look like the CallInst case...
01171     CreatedBranchToNormalDest = BranchInst::Create(II->getNormalDest(), TheCall);
01172 
01173     // Split the basic block.  This guarantees that no PHI nodes will have to be
01174     // updated due to new incoming edges, and make the invoke case more
01175     // symmetric to the call case.
01176     AfterCallBB = OrigBB->splitBasicBlock(CreatedBranchToNormalDest,
01177                                           CalledFunc->getName()+".exit");
01178 
01179   } else {  // It's a call
01180     // If this is a call instruction, we need to split the basic block that
01181     // the call lives in.
01182     //
01183     AfterCallBB = OrigBB->splitBasicBlock(TheCall,
01184                                           CalledFunc->getName()+".exit");
01185   }
01186 
01187   // Change the branch that used to go to AfterCallBB to branch to the first
01188   // basic block of the inlined function.
01189   //
01190   TerminatorInst *Br = OrigBB->getTerminator();
01191   assert(Br && Br->getOpcode() == Instruction::Br &&
01192          "splitBasicBlock broken!");
01193   Br->setOperand(0, FirstNewBlock);
01194 
01195 
01196   // Now that the function is correct, make it a little bit nicer.  In
01197   // particular, move the basic blocks inserted from the end of the function
01198   // into the space made by splitting the source basic block.
01199   Caller->getBasicBlockList().splice(AfterCallBB, Caller->getBasicBlockList(),
01200                                      FirstNewBlock, Caller->end());
01201 
01202   // Handle all of the return instructions that we just cloned in, and eliminate
01203   // any users of the original call/invoke instruction.
01204   Type *RTy = CalledFunc->getReturnType();
01205 
01206   PHINode *PHI = nullptr;
01207   if (Returns.size() > 1) {
01208     // The PHI node should go at the front of the new basic block to merge all
01209     // possible incoming values.
01210     if (!TheCall->use_empty()) {
01211       PHI = PHINode::Create(RTy, Returns.size(), TheCall->getName(),
01212                             AfterCallBB->begin());
01213       // Anything that used the result of the function call should now use the
01214       // PHI node as their operand.
01215       TheCall->replaceAllUsesWith(PHI);
01216     }
01217 
01218     // Loop over all of the return instructions adding entries to the PHI node
01219     // as appropriate.
01220     if (PHI) {
01221       for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
01222         ReturnInst *RI = Returns[i];
01223         assert(RI->getReturnValue()->getType() == PHI->getType() &&
01224                "Ret value not consistent in function!");
01225         PHI->addIncoming(RI->getReturnValue(), RI->getParent());
01226       }
01227     }
01228 
01229 
01230     // Add a branch to the merge points and remove return instructions.
01231     DebugLoc Loc;
01232     for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
01233       ReturnInst *RI = Returns[i];
01234       BranchInst* BI = BranchInst::Create(AfterCallBB, RI);
01235       Loc = RI->getDebugLoc();
01236       BI->setDebugLoc(Loc);
01237       RI->eraseFromParent();
01238     }
01239     // We need to set the debug location to *somewhere* inside the
01240     // inlined function. The line number may be nonsensical, but the
01241     // instruction will at least be associated with the right
01242     // function.
01243     if (CreatedBranchToNormalDest)
01244       CreatedBranchToNormalDest->setDebugLoc(Loc);
01245   } else if (!Returns.empty()) {
01246     // Otherwise, if there is exactly one return value, just replace anything
01247     // using the return value of the call with the computed value.
01248     if (!TheCall->use_empty()) {
01249       if (TheCall == Returns[0]->getReturnValue())
01250         TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
01251       else
01252         TheCall->replaceAllUsesWith(Returns[0]->getReturnValue());
01253     }
01254 
01255     // Update PHI nodes that use the ReturnBB to use the AfterCallBB.
01256     BasicBlock *ReturnBB = Returns[0]->getParent();
01257     ReturnBB->replaceAllUsesWith(AfterCallBB);
01258 
01259     // Splice the code from the return block into the block that it will return
01260     // to, which contains the code that was after the call.
01261     AfterCallBB->getInstList().splice(AfterCallBB->begin(),
01262                                       ReturnBB->getInstList());
01263 
01264     if (CreatedBranchToNormalDest)
01265       CreatedBranchToNormalDest->setDebugLoc(Returns[0]->getDebugLoc());
01266 
01267     // Delete the return instruction now and empty ReturnBB now.
01268     Returns[0]->eraseFromParent();
01269     ReturnBB->eraseFromParent();
01270   } else if (!TheCall->use_empty()) {
01271     // No returns, but something is using the return value of the call.  Just
01272     // nuke the result.
01273     TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
01274   }
01275 
01276   // Since we are now done with the Call/Invoke, we can delete it.
01277   TheCall->eraseFromParent();
01278 
01279   // If we inlined any musttail calls and the original return is now
01280   // unreachable, delete it.  It can only contain a bitcast and ret.
01281   if (InlinedMustTailCalls && pred_begin(AfterCallBB) == pred_end(AfterCallBB))
01282     AfterCallBB->eraseFromParent();
01283 
01284   // We should always be able to fold the entry block of the function into the
01285   // single predecessor of the block...
01286   assert(cast<BranchInst>(Br)->isUnconditional() && "splitBasicBlock broken!");
01287   BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0);
01288 
01289   // Splice the code entry block into calling block, right before the
01290   // unconditional branch.
01291   CalleeEntry->replaceAllUsesWith(OrigBB);  // Update PHI nodes
01292   OrigBB->getInstList().splice(Br, CalleeEntry->getInstList());
01293 
01294   // Remove the unconditional branch.
01295   OrigBB->getInstList().erase(Br);
01296 
01297   // Now we can remove the CalleeEntry block, which is now empty.
01298   Caller->getBasicBlockList().erase(CalleeEntry);
01299 
01300   // If we inserted a phi node, check to see if it has a single value (e.g. all
01301   // the entries are the same or undef).  If so, remove the PHI so it doesn't
01302   // block other optimizations.
01303   if (PHI) {
01304     if (Value *V = SimplifyInstruction(PHI, IFI.DL)) {
01305       PHI->replaceAllUsesWith(V);
01306       PHI->eraseFromParent();
01307     }
01308   }
01309 
01310   return true;
01311 }