InlineFunction.cpp 58 KB

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