InlineFunction.cpp 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420
  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 Value *, 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 *, TrackingVH<MDNode> > 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] = 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<Value *, 4> NewOps;
  290. for (unsigned i = 0, ie = (*I)->getNumOperands(); i != ie; ++i) {
  291. const Value *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<Value *>(V));
  296. }
  297. MDNode *NewM = MDNode::get(CalledFunc->getContext(), NewOps),
  298. *TempM = 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 =
  335. CS.getInstruction()->getMetadata(LLVMContext::MD_noalias))
  336. NI->setMetadata(LLVMContext::MD_noalias, M);
  337. }
  338. }
  339. // Now that everything has been replaced, delete the dummy nodes.
  340. for (unsigned i = 0, ie = DummyNodes.size(); i != ie; ++i)
  341. MDNode::deleteTemporary(DummyNodes[i]);
  342. }
  343. /// AddAliasScopeMetadata - If the inlined function has noalias arguments, then
  344. /// add new alias scopes for each noalias argument, tag the mapped noalias
  345. /// parameters with noalias metadata specifying the new scope, and tag all
  346. /// non-derived loads, stores and memory intrinsics with the new alias scopes.
  347. static void AddAliasScopeMetadata(CallSite CS, ValueToValueMapTy &VMap,
  348. const DataLayout *DL, AliasAnalysis *AA) {
  349. if (!EnableNoAliasConversion)
  350. return;
  351. const Function *CalledFunc = CS.getCalledFunction();
  352. SmallVector<const Argument *, 4> NoAliasArgs;
  353. for (Function::const_arg_iterator I = CalledFunc->arg_begin(),
  354. E = CalledFunc->arg_end(); I != E; ++I) {
  355. if (I->hasNoAliasAttr() && !I->hasNUses(0))
  356. NoAliasArgs.push_back(I);
  357. }
  358. if (NoAliasArgs.empty())
  359. return;
  360. // To do a good job, if a noalias variable is captured, we need to know if
  361. // the capture point dominates the particular use we're considering.
  362. DominatorTree DT;
  363. DT.recalculate(const_cast<Function&>(*CalledFunc));
  364. // noalias indicates that pointer values based on the argument do not alias
  365. // pointer values which are not based on it. So we add a new "scope" for each
  366. // noalias function argument. Accesses using pointers based on that argument
  367. // become part of that alias scope, accesses using pointers not based on that
  368. // argument are tagged as noalias with that scope.
  369. DenseMap<const Argument *, MDNode *> NewScopes;
  370. MDBuilder MDB(CalledFunc->getContext());
  371. // Create a new scope domain for this function.
  372. MDNode *NewDomain =
  373. MDB.createAnonymousAliasScopeDomain(CalledFunc->getName());
  374. for (unsigned i = 0, e = NoAliasArgs.size(); i != e; ++i) {
  375. const Argument *A = NoAliasArgs[i];
  376. std::string Name = CalledFunc->getName();
  377. if (A->hasName()) {
  378. Name += ": %";
  379. Name += A->getName();
  380. } else {
  381. Name += ": argument ";
  382. Name += utostr(i);
  383. }
  384. // Note: We always create a new anonymous root here. This is true regardless
  385. // of the linkage of the callee because the aliasing "scope" is not just a
  386. // property of the callee, but also all control dependencies in the caller.
  387. MDNode *NewScope = MDB.createAnonymousAliasScope(NewDomain, Name);
  388. NewScopes.insert(std::make_pair(A, NewScope));
  389. }
  390. // Iterate over all new instructions in the map; for all memory-access
  391. // instructions, add the alias scope metadata.
  392. for (ValueToValueMapTy::iterator VMI = VMap.begin(), VMIE = VMap.end();
  393. VMI != VMIE; ++VMI) {
  394. if (const Instruction *I = dyn_cast<Instruction>(VMI->first)) {
  395. if (!VMI->second)
  396. continue;
  397. Instruction *NI = dyn_cast<Instruction>(VMI->second);
  398. if (!NI)
  399. continue;
  400. bool IsArgMemOnlyCall = false, IsFuncCall = false;
  401. SmallVector<const Value *, 2> PtrArgs;
  402. if (const LoadInst *LI = dyn_cast<LoadInst>(I))
  403. PtrArgs.push_back(LI->getPointerOperand());
  404. else if (const StoreInst *SI = dyn_cast<StoreInst>(I))
  405. PtrArgs.push_back(SI->getPointerOperand());
  406. else if (const VAArgInst *VAAI = dyn_cast<VAArgInst>(I))
  407. PtrArgs.push_back(VAAI->getPointerOperand());
  408. else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I))
  409. PtrArgs.push_back(CXI->getPointerOperand());
  410. else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I))
  411. PtrArgs.push_back(RMWI->getPointerOperand());
  412. else if (ImmutableCallSite ICS = ImmutableCallSite(I)) {
  413. // If we know that the call does not access memory, then we'll still
  414. // know that about the inlined clone of this call site, and we don't
  415. // need to add metadata.
  416. if (ICS.doesNotAccessMemory())
  417. continue;
  418. IsFuncCall = true;
  419. if (AA) {
  420. AliasAnalysis::ModRefBehavior MRB = AA->getModRefBehavior(ICS);
  421. if (MRB == AliasAnalysis::OnlyAccessesArgumentPointees ||
  422. MRB == AliasAnalysis::OnlyReadsArgumentPointees)
  423. IsArgMemOnlyCall = true;
  424. }
  425. for (ImmutableCallSite::arg_iterator AI = ICS.arg_begin(),
  426. AE = ICS.arg_end(); AI != AE; ++AI) {
  427. // We need to check the underlying objects of all arguments, not just
  428. // the pointer arguments, because we might be passing pointers as
  429. // integers, etc.
  430. // However, if we know that the call only accesses pointer arguments,
  431. // then we only need to check the pointer arguments.
  432. if (IsArgMemOnlyCall && !(*AI)->getType()->isPointerTy())
  433. continue;
  434. PtrArgs.push_back(*AI);
  435. }
  436. }
  437. // If we found no pointers, then this instruction is not suitable for
  438. // pairing with an instruction to receive aliasing metadata.
  439. // However, if this is a call, this we might just alias with none of the
  440. // noalias arguments.
  441. if (PtrArgs.empty() && !IsFuncCall)
  442. continue;
  443. // It is possible that there is only one underlying object, but you
  444. // need to go through several PHIs to see it, and thus could be
  445. // repeated in the Objects list.
  446. SmallPtrSet<const Value *, 4> ObjSet;
  447. SmallVector<Value *, 4> Scopes, NoAliases;
  448. SmallSetVector<const Argument *, 4> NAPtrArgs;
  449. for (unsigned i = 0, ie = PtrArgs.size(); i != ie; ++i) {
  450. SmallVector<Value *, 4> Objects;
  451. GetUnderlyingObjects(const_cast<Value*>(PtrArgs[i]),
  452. Objects, DL, /* MaxLookup = */ 0);
  453. for (Value *O : Objects)
  454. ObjSet.insert(O);
  455. }
  456. // Figure out if we're derived from anything that is not a noalias
  457. // argument.
  458. bool CanDeriveViaCapture = false, UsesAliasingPtr = false;
  459. for (const Value *V : ObjSet) {
  460. // Is this value a constant that cannot be derived from any pointer
  461. // value (we need to exclude constant expressions, for example, that
  462. // are formed from arithmetic on global symbols).
  463. bool IsNonPtrConst = isa<ConstantInt>(V) || isa<ConstantFP>(V) ||
  464. isa<ConstantPointerNull>(V) ||
  465. isa<ConstantDataVector>(V) || isa<UndefValue>(V);
  466. if (IsNonPtrConst)
  467. continue;
  468. // If this is anything other than a noalias argument, then we cannot
  469. // completely describe the aliasing properties using alias.scope
  470. // metadata (and, thus, won't add any).
  471. if (const Argument *A = dyn_cast<Argument>(V)) {
  472. if (!A->hasNoAliasAttr())
  473. UsesAliasingPtr = true;
  474. } else {
  475. UsesAliasingPtr = true;
  476. }
  477. // If this is not some identified function-local object (which cannot
  478. // directly alias a noalias argument), or some other argument (which,
  479. // by definition, also cannot alias a noalias argument), then we could
  480. // alias a noalias argument that has been captured).
  481. if (!isa<Argument>(V) &&
  482. !isIdentifiedFunctionLocal(const_cast<Value*>(V)))
  483. CanDeriveViaCapture = true;
  484. }
  485. // A function call can always get captured noalias pointers (via other
  486. // parameters, globals, etc.).
  487. if (IsFuncCall && !IsArgMemOnlyCall)
  488. CanDeriveViaCapture = true;
  489. // First, we want to figure out all of the sets with which we definitely
  490. // don't alias. Iterate over all noalias set, and add those for which:
  491. // 1. The noalias argument is not in the set of objects from which we
  492. // definitely derive.
  493. // 2. The noalias argument has not yet been captured.
  494. // An arbitrary function that might load pointers could see captured
  495. // noalias arguments via other noalias arguments or globals, and so we
  496. // must always check for prior capture.
  497. for (const Argument *A : NoAliasArgs) {
  498. if (!ObjSet.count(A) && (!CanDeriveViaCapture ||
  499. // It might be tempting to skip the
  500. // PointerMayBeCapturedBefore check if
  501. // A->hasNoCaptureAttr() is true, but this is
  502. // incorrect because nocapture only guarantees
  503. // that no copies outlive the function, not
  504. // that the value cannot be locally captured.
  505. !PointerMayBeCapturedBefore(A,
  506. /* ReturnCaptures */ false,
  507. /* StoreCaptures */ false, I, &DT)))
  508. NoAliases.push_back(NewScopes[A]);
  509. }
  510. if (!NoAliases.empty())
  511. NI->setMetadata(LLVMContext::MD_noalias, 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(LLVMContext::MD_alias_scope, MDNode::concatenate(
  534. NI->getMetadata(LLVMContext::MD_alias_scope),
  535. MDNode::get(CalledFunc->getContext(), Scopes)));
  536. }
  537. }
  538. }
  539. /// If the inlined function has non-byval align arguments, then
  540. /// add @llvm.assume-based alignment assumptions to preserve this information.
  541. static void AddAlignmentAssumptions(CallSite CS, InlineFunctionInfo &IFI) {
  542. if (!PreserveAlignmentAssumptions || !IFI.DL)
  543. return;
  544. // To avoid inserting redundant assumptions, we should check for assumptions
  545. // already in the caller. To do this, we might need a DT of the caller.
  546. DominatorTree DT;
  547. bool DTCalculated = false;
  548. const Function *CalledFunc = CS.getCalledFunction();
  549. for (Function::const_arg_iterator I = CalledFunc->arg_begin(),
  550. E = CalledFunc->arg_end(); I != E; ++I) {
  551. unsigned Align = I->getType()->isPointerTy() ? I->getParamAlignment() : 0;
  552. if (Align && !I->hasByValOrInAllocaAttr() && !I->hasNUses(0)) {
  553. if (!DTCalculated) {
  554. DT.recalculate(const_cast<Function&>(*CS.getInstruction()->getParent()
  555. ->getParent()));
  556. DTCalculated = true;
  557. }
  558. // If we can already prove the asserted alignment in the context of the
  559. // caller, then don't bother inserting the assumption.
  560. Value *Arg = CS.getArgument(I->getArgNo());
  561. if (getKnownAlignment(Arg, IFI.DL, IFI.AT, CS.getInstruction(),
  562. &DT) >= Align)
  563. continue;
  564. IRBuilder<>(CS.getInstruction()).CreateAlignmentAssumption(*IFI.DL, Arg,
  565. Align);
  566. }
  567. }
  568. }
  569. /// UpdateCallGraphAfterInlining - Once we have cloned code over from a callee
  570. /// into the caller, update the specified callgraph to reflect the changes we
  571. /// made. Note that it's possible that not all code was copied over, so only
  572. /// some edges of the callgraph may remain.
  573. static void UpdateCallGraphAfterInlining(CallSite CS,
  574. Function::iterator FirstNewBlock,
  575. ValueToValueMapTy &VMap,
  576. InlineFunctionInfo &IFI) {
  577. CallGraph &CG = *IFI.CG;
  578. const Function *Caller = CS.getInstruction()->getParent()->getParent();
  579. const Function *Callee = CS.getCalledFunction();
  580. CallGraphNode *CalleeNode = CG[Callee];
  581. CallGraphNode *CallerNode = CG[Caller];
  582. // Since we inlined some uninlined call sites in the callee into the caller,
  583. // add edges from the caller to all of the callees of the callee.
  584. CallGraphNode::iterator I = CalleeNode->begin(), E = CalleeNode->end();
  585. // Consider the case where CalleeNode == CallerNode.
  586. CallGraphNode::CalledFunctionsVector CallCache;
  587. if (CalleeNode == CallerNode) {
  588. CallCache.assign(I, E);
  589. I = CallCache.begin();
  590. E = CallCache.end();
  591. }
  592. for (; I != E; ++I) {
  593. const Value *OrigCall = I->first;
  594. ValueToValueMapTy::iterator VMI = VMap.find(OrigCall);
  595. // Only copy the edge if the call was inlined!
  596. if (VMI == VMap.end() || VMI->second == nullptr)
  597. continue;
  598. // If the call was inlined, but then constant folded, there is no edge to
  599. // add. Check for this case.
  600. Instruction *NewCall = dyn_cast<Instruction>(VMI->second);
  601. if (!NewCall) continue;
  602. // Remember that this call site got inlined for the client of
  603. // InlineFunction.
  604. IFI.InlinedCalls.push_back(NewCall);
  605. // It's possible that inlining the callsite will cause it to go from an
  606. // indirect to a direct call by resolving a function pointer. If this
  607. // happens, set the callee of the new call site to a more precise
  608. // destination. This can also happen if the call graph node of the caller
  609. // was just unnecessarily imprecise.
  610. if (!I->second->getFunction())
  611. if (Function *F = CallSite(NewCall).getCalledFunction()) {
  612. // Indirect call site resolved to direct call.
  613. CallerNode->addCalledFunction(CallSite(NewCall), CG[F]);
  614. continue;
  615. }
  616. CallerNode->addCalledFunction(CallSite(NewCall), I->second);
  617. }
  618. // Update the call graph by deleting the edge from Callee to Caller. We must
  619. // do this after the loop above in case Caller and Callee are the same.
  620. CallerNode->removeCallEdgeFor(CS);
  621. }
  622. static void HandleByValArgumentInit(Value *Dst, Value *Src, Module *M,
  623. BasicBlock *InsertBlock,
  624. InlineFunctionInfo &IFI) {
  625. Type *AggTy = cast<PointerType>(Src->getType())->getElementType();
  626. IRBuilder<> Builder(InsertBlock->begin());
  627. Value *Size;
  628. if (IFI.DL == nullptr)
  629. Size = ConstantExpr::getSizeOf(AggTy);
  630. else
  631. Size = Builder.getInt64(IFI.DL->getTypeStoreSize(AggTy));
  632. // Always generate a memcpy of alignment 1 here because we don't know
  633. // the alignment of the src pointer. Other optimizations can infer
  634. // better alignment.
  635. Builder.CreateMemCpy(Dst, Src, Size, /*Align=*/1);
  636. }
  637. /// HandleByValArgument - When inlining a call site that has a byval argument,
  638. /// we have to make the implicit memcpy explicit by adding it.
  639. static Value *HandleByValArgument(Value *Arg, Instruction *TheCall,
  640. const Function *CalledFunc,
  641. InlineFunctionInfo &IFI,
  642. unsigned ByValAlignment,
  643. bool &AddedNewAllocas) {
  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. AddedNewAllocas = true;
  678. return NewAlloca;
  679. }
  680. // isUsedByLifetimeMarker - Check whether this Value is used by a lifetime
  681. // intrinsic.
  682. static bool isUsedByLifetimeMarker(Value *V) {
  683. for (User *U : V->users()) {
  684. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) {
  685. switch (II->getIntrinsicID()) {
  686. default: break;
  687. case Intrinsic::lifetime_start:
  688. case Intrinsic::lifetime_end:
  689. return true;
  690. }
  691. }
  692. }
  693. return false;
  694. }
  695. // hasLifetimeMarkers - Check whether the given alloca already has
  696. // lifetime.start or lifetime.end intrinsics.
  697. static bool hasLifetimeMarkers(AllocaInst *AI) {
  698. Type *Ty = AI->getType();
  699. Type *Int8PtrTy = Type::getInt8PtrTy(Ty->getContext(),
  700. Ty->getPointerAddressSpace());
  701. if (Ty == Int8PtrTy)
  702. return isUsedByLifetimeMarker(AI);
  703. // Do a scan to find all the casts to i8*.
  704. for (User *U : AI->users()) {
  705. if (U->getType() != Int8PtrTy) continue;
  706. if (U->stripPointerCasts() != AI) continue;
  707. if (isUsedByLifetimeMarker(U))
  708. return true;
  709. }
  710. return false;
  711. }
  712. /// updateInlinedAtInfo - Helper function used by fixupLineNumbers to
  713. /// recursively update InlinedAtEntry of a DebugLoc.
  714. static DebugLoc updateInlinedAtInfo(const DebugLoc &DL,
  715. const DebugLoc &InlinedAtDL,
  716. LLVMContext &Ctx) {
  717. if (MDNode *IA = DL.getInlinedAt(Ctx)) {
  718. DebugLoc NewInlinedAtDL
  719. = updateInlinedAtInfo(DebugLoc::getFromDILocation(IA), InlinedAtDL, Ctx);
  720. return DebugLoc::get(DL.getLine(), DL.getCol(), DL.getScope(Ctx),
  721. NewInlinedAtDL.getAsMDNode(Ctx));
  722. }
  723. return DebugLoc::get(DL.getLine(), DL.getCol(), DL.getScope(Ctx),
  724. InlinedAtDL.getAsMDNode(Ctx));
  725. }
  726. /// fixupLineNumbers - Update inlined instructions' line numbers to
  727. /// to encode location where these instructions are inlined.
  728. static void fixupLineNumbers(Function *Fn, Function::iterator FI,
  729. Instruction *TheCall) {
  730. DebugLoc TheCallDL = TheCall->getDebugLoc();
  731. if (TheCallDL.isUnknown())
  732. return;
  733. for (; FI != Fn->end(); ++FI) {
  734. for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
  735. BI != BE; ++BI) {
  736. DebugLoc DL = BI->getDebugLoc();
  737. if (DL.isUnknown()) {
  738. // If the inlined instruction has no line number, make it look as if it
  739. // originates from the call location. This is important for
  740. // ((__always_inline__, __nodebug__)) functions which must use caller
  741. // location for all instructions in their function body.
  742. // Don't update static allocas, as they may get moved later.
  743. if (auto *AI = dyn_cast<AllocaInst>(BI))
  744. if (isa<Constant>(AI->getArraySize()))
  745. continue;
  746. BI->setDebugLoc(TheCallDL);
  747. } else {
  748. BI->setDebugLoc(updateInlinedAtInfo(DL, TheCallDL, BI->getContext()));
  749. if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(BI)) {
  750. LLVMContext &Ctx = BI->getContext();
  751. MDNode *InlinedAt = BI->getDebugLoc().getInlinedAt(Ctx);
  752. DVI->setOperand(2, createInlinedVariable(DVI->getVariable(),
  753. InlinedAt, Ctx));
  754. }
  755. }
  756. }
  757. }
  758. }
  759. /// InlineFunction - This function inlines the called function into the basic
  760. /// block of the caller. This returns false if it is not possible to inline
  761. /// this call. The program is still in a well defined state if this occurs
  762. /// though.
  763. ///
  764. /// Note that this only does one level of inlining. For example, if the
  765. /// instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
  766. /// exists in the instruction stream. Similarly this will inline a recursive
  767. /// function by one level.
  768. bool llvm::InlineFunction(CallSite CS, InlineFunctionInfo &IFI,
  769. bool InsertLifetime) {
  770. Instruction *TheCall = CS.getInstruction();
  771. assert(TheCall->getParent() && TheCall->getParent()->getParent() &&
  772. "Instruction not in function!");
  773. // If IFI has any state in it, zap it before we fill it in.
  774. IFI.reset();
  775. const Function *CalledFunc = CS.getCalledFunction();
  776. if (!CalledFunc || // Can't inline external function or indirect
  777. CalledFunc->isDeclaration() || // call, or call to a vararg function!
  778. CalledFunc->getFunctionType()->isVarArg()) return false;
  779. // If the call to the callee cannot throw, set the 'nounwind' flag on any
  780. // calls that we inline.
  781. bool MarkNoUnwind = CS.doesNotThrow();
  782. BasicBlock *OrigBB = TheCall->getParent();
  783. Function *Caller = OrigBB->getParent();
  784. // GC poses two hazards to inlining, which only occur when the callee has GC:
  785. // 1. If the caller has no GC, then the callee's GC must be propagated to the
  786. // caller.
  787. // 2. If the caller has a differing GC, it is invalid to inline.
  788. if (CalledFunc->hasGC()) {
  789. if (!Caller->hasGC())
  790. Caller->setGC(CalledFunc->getGC());
  791. else if (CalledFunc->getGC() != Caller->getGC())
  792. return false;
  793. }
  794. // Get the personality function from the callee if it contains a landing pad.
  795. Value *CalleePersonality = nullptr;
  796. for (Function::const_iterator I = CalledFunc->begin(), E = CalledFunc->end();
  797. I != E; ++I)
  798. if (const InvokeInst *II = dyn_cast<InvokeInst>(I->getTerminator())) {
  799. const BasicBlock *BB = II->getUnwindDest();
  800. const LandingPadInst *LP = BB->getLandingPadInst();
  801. CalleePersonality = LP->getPersonalityFn();
  802. break;
  803. }
  804. // Find the personality function used by the landing pads of the caller. If it
  805. // exists, then check to see that it matches the personality function used in
  806. // the callee.
  807. if (CalleePersonality) {
  808. for (Function::const_iterator I = Caller->begin(), E = Caller->end();
  809. I != E; ++I)
  810. if (const InvokeInst *II = dyn_cast<InvokeInst>(I->getTerminator())) {
  811. const BasicBlock *BB = II->getUnwindDest();
  812. const LandingPadInst *LP = BB->getLandingPadInst();
  813. // If the personality functions match, then we can perform the
  814. // inlining. Otherwise, we can't inline.
  815. // TODO: This isn't 100% true. Some personality functions are proper
  816. // supersets of others and can be used in place of the other.
  817. if (LP->getPersonalityFn() != CalleePersonality)
  818. return false;
  819. break;
  820. }
  821. }
  822. // Get an iterator to the last basic block in the function, which will have
  823. // the new function inlined after it.
  824. Function::iterator LastBlock = &Caller->back();
  825. // Make sure to capture all of the return instructions from the cloned
  826. // function.
  827. SmallVector<ReturnInst*, 8> Returns;
  828. ClonedCodeInfo InlinedFunctionInfo;
  829. Function::iterator FirstNewBlock;
  830. bool AddedNewAllocas = false;
  831. { // Scope to destroy VMap after cloning.
  832. ValueToValueMapTy VMap;
  833. // Keep a list of pair (dst, src) to emit byval initializations.
  834. SmallVector<std::pair<Value*, Value*>, 4> ByValInit;
  835. assert(CalledFunc->arg_size() == CS.arg_size() &&
  836. "No varargs calls can be inlined!");
  837. // Calculate the vector of arguments to pass into the function cloner, which
  838. // matches up the formal to the actual argument values.
  839. CallSite::arg_iterator AI = CS.arg_begin();
  840. unsigned ArgNo = 0;
  841. for (Function::const_arg_iterator I = CalledFunc->arg_begin(),
  842. E = CalledFunc->arg_end(); I != E; ++I, ++AI, ++ArgNo) {
  843. Value *ActualArg = *AI;
  844. // When byval arguments actually inlined, we need to make the copy implied
  845. // by them explicit. However, we don't do this if the callee is readonly
  846. // or readnone, because the copy would be unneeded: the callee doesn't
  847. // modify the struct.
  848. if (CS.isByValArgument(ArgNo)) {
  849. ActualArg = HandleByValArgument(ActualArg, TheCall, CalledFunc, IFI,
  850. CalledFunc->getParamAlignment(ArgNo+1),
  851. AddedNewAllocas);
  852. if (ActualArg != *AI)
  853. ByValInit.push_back(std::make_pair(ActualArg, (Value*) *AI));
  854. }
  855. VMap[I] = ActualArg;
  856. }
  857. // Add alignment assumptions if necessary. We do this before the inlined
  858. // instructions are actually cloned into the caller so that we can easily
  859. // check what will be known at the start of the inlined code.
  860. AddAlignmentAssumptions(CS, IFI);
  861. // We want the inliner to prune the code as it copies. We would LOVE to
  862. // have no dead or constant instructions leftover after inlining occurs
  863. // (which can happen, e.g., because an argument was constant), but we'll be
  864. // happy with whatever the cloner can do.
  865. CloneAndPruneFunctionInto(Caller, CalledFunc, VMap,
  866. /*ModuleLevelChanges=*/false, Returns, ".i",
  867. &InlinedFunctionInfo, IFI.DL, TheCall);
  868. // Remember the first block that is newly cloned over.
  869. FirstNewBlock = LastBlock; ++FirstNewBlock;
  870. // Inject byval arguments initialization.
  871. for (std::pair<Value*, Value*> &Init : ByValInit)
  872. HandleByValArgumentInit(Init.first, Init.second, Caller->getParent(),
  873. FirstNewBlock, IFI);
  874. // Update the callgraph if requested.
  875. if (IFI.CG)
  876. UpdateCallGraphAfterInlining(CS, FirstNewBlock, VMap, IFI);
  877. // Update inlined instructions' line number information.
  878. fixupLineNumbers(Caller, FirstNewBlock, TheCall);
  879. // Clone existing noalias metadata if necessary.
  880. CloneAliasScopeMetadata(CS, VMap);
  881. // Add noalias metadata if necessary.
  882. AddAliasScopeMetadata(CS, VMap, IFI.DL, IFI.AA);
  883. // FIXME: We could register any cloned assumptions instead of clearing the
  884. // whole function's cache.
  885. if (IFI.AT)
  886. IFI.AT->forgetCachedAssumptions(Caller);
  887. }
  888. // If there are any alloca instructions in the block that used to be the entry
  889. // block for the callee, move them to the entry block of the caller. First
  890. // calculate which instruction they should be inserted before. We insert the
  891. // instructions at the end of the current alloca list.
  892. {
  893. BasicBlock::iterator InsertPoint = Caller->begin()->begin();
  894. for (BasicBlock::iterator I = FirstNewBlock->begin(),
  895. E = FirstNewBlock->end(); I != E; ) {
  896. AllocaInst *AI = dyn_cast<AllocaInst>(I++);
  897. if (!AI) continue;
  898. // If the alloca is now dead, remove it. This often occurs due to code
  899. // specialization.
  900. if (AI->use_empty()) {
  901. AI->eraseFromParent();
  902. continue;
  903. }
  904. if (!isa<Constant>(AI->getArraySize()))
  905. continue;
  906. // Keep track of the static allocas that we inline into the caller.
  907. IFI.StaticAllocas.push_back(AI);
  908. // Scan for the block of allocas that we can move over, and move them
  909. // all at once.
  910. while (isa<AllocaInst>(I) &&
  911. isa<Constant>(cast<AllocaInst>(I)->getArraySize())) {
  912. IFI.StaticAllocas.push_back(cast<AllocaInst>(I));
  913. ++I;
  914. }
  915. // Transfer all of the allocas over in a block. Using splice means
  916. // that the instructions aren't removed from the symbol table, then
  917. // reinserted.
  918. Caller->getEntryBlock().getInstList().splice(InsertPoint,
  919. FirstNewBlock->getInstList(),
  920. AI, I);
  921. }
  922. }
  923. bool InlinedMustTailCalls = false;
  924. if (InlinedFunctionInfo.ContainsCalls) {
  925. CallInst::TailCallKind CallSiteTailKind = CallInst::TCK_None;
  926. if (CallInst *CI = dyn_cast<CallInst>(TheCall))
  927. CallSiteTailKind = CI->getTailCallKind();
  928. for (Function::iterator BB = FirstNewBlock, E = Caller->end(); BB != E;
  929. ++BB) {
  930. for (Instruction &I : *BB) {
  931. CallInst *CI = dyn_cast<CallInst>(&I);
  932. if (!CI)
  933. continue;
  934. // We need to reduce the strength of any inlined tail calls. For
  935. // musttail, we have to avoid introducing potential unbounded stack
  936. // growth. For example, if functions 'f' and 'g' are mutually recursive
  937. // with musttail, we can inline 'g' into 'f' so long as we preserve
  938. // musttail on the cloned call to 'f'. If either the inlined call site
  939. // or the cloned call site is *not* musttail, the program already has
  940. // one frame of stack growth, so it's safe to remove musttail. Here is
  941. // a table of example transformations:
  942. //
  943. // f -> musttail g -> musttail f ==> f -> musttail f
  944. // f -> musttail g -> tail f ==> f -> tail f
  945. // f -> g -> musttail f ==> f -> f
  946. // f -> g -> tail f ==> f -> f
  947. //
  948. // If an alloca was introduced in the frame due to a byval parameter
  949. // being passed to a subsequent call, tail calls must have the tail
  950. // stripped as they may not access variables in the caller's stack.
  951. // A single alloca ripples through out as the alloca may be aliased by
  952. // bitcasts or may escape and be mutated outside of the function.
  953. CallInst::TailCallKind ChildTCK = CI->getTailCallKind();
  954. ChildTCK = std::min(CallSiteTailKind, ChildTCK);
  955. if (AddedNewAllocas)
  956. CI->setTailCallKind(CallInst::TCK_None);
  957. else
  958. CI->setTailCallKind(ChildTCK);
  959. InlinedMustTailCalls |= CI->isMustTailCall();
  960. // Calls inlined through a 'nounwind' call site should be marked
  961. // 'nounwind'.
  962. if (MarkNoUnwind)
  963. CI->setDoesNotThrow();
  964. }
  965. }
  966. }
  967. // Leave lifetime markers for the static alloca's, scoping them to the
  968. // function we just inlined.
  969. if (InsertLifetime && !IFI.StaticAllocas.empty()) {
  970. IRBuilder<> builder(FirstNewBlock->begin());
  971. for (unsigned ai = 0, ae = IFI.StaticAllocas.size(); ai != ae; ++ai) {
  972. AllocaInst *AI = IFI.StaticAllocas[ai];
  973. // If the alloca is already scoped to something smaller than the whole
  974. // function then there's no need to add redundant, less accurate markers.
  975. if (hasLifetimeMarkers(AI))
  976. continue;
  977. // Try to determine the size of the allocation.
  978. ConstantInt *AllocaSize = nullptr;
  979. if (ConstantInt *AIArraySize =
  980. dyn_cast<ConstantInt>(AI->getArraySize())) {
  981. if (IFI.DL) {
  982. Type *AllocaType = AI->getAllocatedType();
  983. uint64_t AllocaTypeSize = IFI.DL->getTypeAllocSize(AllocaType);
  984. uint64_t AllocaArraySize = AIArraySize->getLimitedValue();
  985. assert(AllocaArraySize > 0 && "array size of AllocaInst is zero");
  986. // Check that array size doesn't saturate uint64_t and doesn't
  987. // overflow when it's multiplied by type size.
  988. if (AllocaArraySize != ~0ULL &&
  989. UINT64_MAX / AllocaArraySize >= AllocaTypeSize) {
  990. AllocaSize = ConstantInt::get(Type::getInt64Ty(AI->getContext()),
  991. AllocaArraySize * AllocaTypeSize);
  992. }
  993. }
  994. }
  995. builder.CreateLifetimeStart(AI, AllocaSize);
  996. for (ReturnInst *RI : Returns) {
  997. // Don't insert llvm.lifetime.end calls between a musttail call and a
  998. // return. The return kills all local allocas.
  999. if (InlinedMustTailCalls &&
  1000. RI->getParent()->getTerminatingMustTailCall())
  1001. continue;
  1002. IRBuilder<>(RI).CreateLifetimeEnd(AI, AllocaSize);
  1003. }
  1004. }
  1005. }
  1006. // If the inlined code contained dynamic alloca instructions, wrap the inlined
  1007. // code with llvm.stacksave/llvm.stackrestore intrinsics.
  1008. if (InlinedFunctionInfo.ContainsDynamicAllocas) {
  1009. Module *M = Caller->getParent();
  1010. // Get the two intrinsics we care about.
  1011. Function *StackSave = Intrinsic::getDeclaration(M, Intrinsic::stacksave);
  1012. Function *StackRestore=Intrinsic::getDeclaration(M,Intrinsic::stackrestore);
  1013. // Insert the llvm.stacksave.
  1014. CallInst *SavedPtr = IRBuilder<>(FirstNewBlock, FirstNewBlock->begin())
  1015. .CreateCall(StackSave, "savedstack");
  1016. // Insert a call to llvm.stackrestore before any return instructions in the
  1017. // inlined function.
  1018. for (ReturnInst *RI : Returns) {
  1019. // Don't insert llvm.stackrestore calls between a musttail call and a
  1020. // return. The return will restore the stack pointer.
  1021. if (InlinedMustTailCalls && RI->getParent()->getTerminatingMustTailCall())
  1022. continue;
  1023. IRBuilder<>(RI).CreateCall(StackRestore, SavedPtr);
  1024. }
  1025. }
  1026. // If we are inlining for an invoke instruction, we must make sure to rewrite
  1027. // any call instructions into invoke instructions.
  1028. if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
  1029. HandleInlinedInvoke(II, FirstNewBlock, InlinedFunctionInfo);
  1030. // Handle any inlined musttail call sites. In order for a new call site to be
  1031. // musttail, the source of the clone and the inlined call site must have been
  1032. // musttail. Therefore it's safe to return without merging control into the
  1033. // phi below.
  1034. if (InlinedMustTailCalls) {
  1035. // Check if we need to bitcast the result of any musttail calls.
  1036. Type *NewRetTy = Caller->getReturnType();
  1037. bool NeedBitCast = !TheCall->use_empty() && TheCall->getType() != NewRetTy;
  1038. // Handle the returns preceded by musttail calls separately.
  1039. SmallVector<ReturnInst *, 8> NormalReturns;
  1040. for (ReturnInst *RI : Returns) {
  1041. CallInst *ReturnedMustTail =
  1042. RI->getParent()->getTerminatingMustTailCall();
  1043. if (!ReturnedMustTail) {
  1044. NormalReturns.push_back(RI);
  1045. continue;
  1046. }
  1047. if (!NeedBitCast)
  1048. continue;
  1049. // Delete the old return and any preceding bitcast.
  1050. BasicBlock *CurBB = RI->getParent();
  1051. auto *OldCast = dyn_cast_or_null<BitCastInst>(RI->getReturnValue());
  1052. RI->eraseFromParent();
  1053. if (OldCast)
  1054. OldCast->eraseFromParent();
  1055. // Insert a new bitcast and return with the right type.
  1056. IRBuilder<> Builder(CurBB);
  1057. Builder.CreateRet(Builder.CreateBitCast(ReturnedMustTail, NewRetTy));
  1058. }
  1059. // Leave behind the normal returns so we can merge control flow.
  1060. std::swap(Returns, NormalReturns);
  1061. }
  1062. // If we cloned in _exactly one_ basic block, and if that block ends in a
  1063. // return instruction, we splice the body of the inlined callee directly into
  1064. // the calling basic block.
  1065. if (Returns.size() == 1 && std::distance(FirstNewBlock, Caller->end()) == 1) {
  1066. // Move all of the instructions right before the call.
  1067. OrigBB->getInstList().splice(TheCall, FirstNewBlock->getInstList(),
  1068. FirstNewBlock->begin(), FirstNewBlock->end());
  1069. // Remove the cloned basic block.
  1070. Caller->getBasicBlockList().pop_back();
  1071. // If the call site was an invoke instruction, add a branch to the normal
  1072. // destination.
  1073. if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
  1074. BranchInst *NewBr = BranchInst::Create(II->getNormalDest(), TheCall);
  1075. NewBr->setDebugLoc(Returns[0]->getDebugLoc());
  1076. }
  1077. // If the return instruction returned a value, replace uses of the call with
  1078. // uses of the returned value.
  1079. if (!TheCall->use_empty()) {
  1080. ReturnInst *R = Returns[0];
  1081. if (TheCall == R->getReturnValue())
  1082. TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
  1083. else
  1084. TheCall->replaceAllUsesWith(R->getReturnValue());
  1085. }
  1086. // Since we are now done with the Call/Invoke, we can delete it.
  1087. TheCall->eraseFromParent();
  1088. // Since we are now done with the return instruction, delete it also.
  1089. Returns[0]->eraseFromParent();
  1090. // We are now done with the inlining.
  1091. return true;
  1092. }
  1093. // Otherwise, we have the normal case, of more than one block to inline or
  1094. // multiple return sites.
  1095. // We want to clone the entire callee function into the hole between the
  1096. // "starter" and "ender" blocks. How we accomplish this depends on whether
  1097. // this is an invoke instruction or a call instruction.
  1098. BasicBlock *AfterCallBB;
  1099. BranchInst *CreatedBranchToNormalDest = nullptr;
  1100. if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
  1101. // Add an unconditional branch to make this look like the CallInst case...
  1102. CreatedBranchToNormalDest = BranchInst::Create(II->getNormalDest(), TheCall);
  1103. // Split the basic block. This guarantees that no PHI nodes will have to be
  1104. // updated due to new incoming edges, and make the invoke case more
  1105. // symmetric to the call case.
  1106. AfterCallBB = OrigBB->splitBasicBlock(CreatedBranchToNormalDest,
  1107. CalledFunc->getName()+".exit");
  1108. } else { // It's a call
  1109. // If this is a call instruction, we need to split the basic block that
  1110. // the call lives in.
  1111. //
  1112. AfterCallBB = OrigBB->splitBasicBlock(TheCall,
  1113. CalledFunc->getName()+".exit");
  1114. }
  1115. // Change the branch that used to go to AfterCallBB to branch to the first
  1116. // basic block of the inlined function.
  1117. //
  1118. TerminatorInst *Br = OrigBB->getTerminator();
  1119. assert(Br && Br->getOpcode() == Instruction::Br &&
  1120. "splitBasicBlock broken!");
  1121. Br->setOperand(0, FirstNewBlock);
  1122. // Now that the function is correct, make it a little bit nicer. In
  1123. // particular, move the basic blocks inserted from the end of the function
  1124. // into the space made by splitting the source basic block.
  1125. Caller->getBasicBlockList().splice(AfterCallBB, Caller->getBasicBlockList(),
  1126. FirstNewBlock, Caller->end());
  1127. // Handle all of the return instructions that we just cloned in, and eliminate
  1128. // any users of the original call/invoke instruction.
  1129. Type *RTy = CalledFunc->getReturnType();
  1130. PHINode *PHI = nullptr;
  1131. if (Returns.size() > 1) {
  1132. // The PHI node should go at the front of the new basic block to merge all
  1133. // possible incoming values.
  1134. if (!TheCall->use_empty()) {
  1135. PHI = PHINode::Create(RTy, Returns.size(), TheCall->getName(),
  1136. AfterCallBB->begin());
  1137. // Anything that used the result of the function call should now use the
  1138. // PHI node as their operand.
  1139. TheCall->replaceAllUsesWith(PHI);
  1140. }
  1141. // Loop over all of the return instructions adding entries to the PHI node
  1142. // as appropriate.
  1143. if (PHI) {
  1144. for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
  1145. ReturnInst *RI = Returns[i];
  1146. assert(RI->getReturnValue()->getType() == PHI->getType() &&
  1147. "Ret value not consistent in function!");
  1148. PHI->addIncoming(RI->getReturnValue(), RI->getParent());
  1149. }
  1150. }
  1151. // Add a branch to the merge points and remove return instructions.
  1152. DebugLoc Loc;
  1153. for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
  1154. ReturnInst *RI = Returns[i];
  1155. BranchInst* BI = BranchInst::Create(AfterCallBB, RI);
  1156. Loc = RI->getDebugLoc();
  1157. BI->setDebugLoc(Loc);
  1158. RI->eraseFromParent();
  1159. }
  1160. // We need to set the debug location to *somewhere* inside the
  1161. // inlined function. The line number may be nonsensical, but the
  1162. // instruction will at least be associated with the right
  1163. // function.
  1164. if (CreatedBranchToNormalDest)
  1165. CreatedBranchToNormalDest->setDebugLoc(Loc);
  1166. } else if (!Returns.empty()) {
  1167. // Otherwise, if there is exactly one return value, just replace anything
  1168. // using the return value of the call with the computed value.
  1169. if (!TheCall->use_empty()) {
  1170. if (TheCall == Returns[0]->getReturnValue())
  1171. TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
  1172. else
  1173. TheCall->replaceAllUsesWith(Returns[0]->getReturnValue());
  1174. }
  1175. // Update PHI nodes that use the ReturnBB to use the AfterCallBB.
  1176. BasicBlock *ReturnBB = Returns[0]->getParent();
  1177. ReturnBB->replaceAllUsesWith(AfterCallBB);
  1178. // Splice the code from the return block into the block that it will return
  1179. // to, which contains the code that was after the call.
  1180. AfterCallBB->getInstList().splice(AfterCallBB->begin(),
  1181. ReturnBB->getInstList());
  1182. if (CreatedBranchToNormalDest)
  1183. CreatedBranchToNormalDest->setDebugLoc(Returns[0]->getDebugLoc());
  1184. // Delete the return instruction now and empty ReturnBB now.
  1185. Returns[0]->eraseFromParent();
  1186. ReturnBB->eraseFromParent();
  1187. } else if (!TheCall->use_empty()) {
  1188. // No returns, but something is using the return value of the call. Just
  1189. // nuke the result.
  1190. TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
  1191. }
  1192. // Since we are now done with the Call/Invoke, we can delete it.
  1193. TheCall->eraseFromParent();
  1194. // If we inlined any musttail calls and the original return is now
  1195. // unreachable, delete it. It can only contain a bitcast and ret.
  1196. if (InlinedMustTailCalls && pred_begin(AfterCallBB) == pred_end(AfterCallBB))
  1197. AfterCallBB->eraseFromParent();
  1198. // We should always be able to fold the entry block of the function into the
  1199. // single predecessor of the block...
  1200. assert(cast<BranchInst>(Br)->isUnconditional() && "splitBasicBlock broken!");
  1201. BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0);
  1202. // Splice the code entry block into calling block, right before the
  1203. // unconditional branch.
  1204. CalleeEntry->replaceAllUsesWith(OrigBB); // Update PHI nodes
  1205. OrigBB->getInstList().splice(Br, CalleeEntry->getInstList());
  1206. // Remove the unconditional branch.
  1207. OrigBB->getInstList().erase(Br);
  1208. // Now we can remove the CalleeEntry block, which is now empty.
  1209. Caller->getBasicBlockList().erase(CalleeEntry);
  1210. // If we inserted a phi node, check to see if it has a single value (e.g. all
  1211. // the entries are the same or undef). If so, remove the PHI so it doesn't
  1212. // block other optimizations.
  1213. if (PHI) {
  1214. if (Value *V = SimplifyInstruction(PHI, IFI.DL, nullptr, nullptr, IFI.AT)) {
  1215. PHI->replaceAllUsesWith(V);
  1216. PHI->eraseFromParent();
  1217. }
  1218. }
  1219. return true;
  1220. }