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