InlineFunction.cpp 60 KB

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