InlineFunction.cpp 59 KB

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