InlineFunction.cpp 99 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379
  1. //===- InlineFunction.cpp - Code to perform function inlining -------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements inlining of a function into a call site, resolving
  10. // parameters and the return value as appropriate.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/ADT/DenseMap.h"
  14. #include "llvm/ADT/None.h"
  15. #include "llvm/ADT/Optional.h"
  16. #include "llvm/ADT/STLExtras.h"
  17. #include "llvm/ADT/SetVector.h"
  18. #include "llvm/ADT/SmallPtrSet.h"
  19. #include "llvm/ADT/SmallVector.h"
  20. #include "llvm/ADT/StringExtras.h"
  21. #include "llvm/ADT/iterator_range.h"
  22. #include "llvm/Analysis/AliasAnalysis.h"
  23. #include "llvm/Analysis/AssumptionCache.h"
  24. #include "llvm/Analysis/BlockFrequencyInfo.h"
  25. #include "llvm/Analysis/CallGraph.h"
  26. #include "llvm/Analysis/CaptureTracking.h"
  27. #include "llvm/Analysis/EHPersonalities.h"
  28. #include "llvm/Analysis/InstructionSimplify.h"
  29. #include "llvm/Analysis/ProfileSummaryInfo.h"
  30. #include "llvm/Transforms/Utils/Local.h"
  31. #include "llvm/Analysis/ValueTracking.h"
  32. #include "llvm/Analysis/VectorUtils.h"
  33. #include "llvm/IR/Argument.h"
  34. #include "llvm/IR/BasicBlock.h"
  35. #include "llvm/IR/CFG.h"
  36. #include "llvm/IR/CallSite.h"
  37. #include "llvm/IR/Constant.h"
  38. #include "llvm/IR/Constants.h"
  39. #include "llvm/IR/DIBuilder.h"
  40. #include "llvm/IR/DataLayout.h"
  41. #include "llvm/IR/DebugInfoMetadata.h"
  42. #include "llvm/IR/DebugLoc.h"
  43. #include "llvm/IR/DerivedTypes.h"
  44. #include "llvm/IR/Dominators.h"
  45. #include "llvm/IR/Function.h"
  46. #include "llvm/IR/IRBuilder.h"
  47. #include "llvm/IR/InstrTypes.h"
  48. #include "llvm/IR/Instruction.h"
  49. #include "llvm/IR/Instructions.h"
  50. #include "llvm/IR/IntrinsicInst.h"
  51. #include "llvm/IR/Intrinsics.h"
  52. #include "llvm/IR/LLVMContext.h"
  53. #include "llvm/IR/MDBuilder.h"
  54. #include "llvm/IR/Metadata.h"
  55. #include "llvm/IR/Module.h"
  56. #include "llvm/IR/Type.h"
  57. #include "llvm/IR/User.h"
  58. #include "llvm/IR/Value.h"
  59. #include "llvm/Support/Casting.h"
  60. #include "llvm/Support/CommandLine.h"
  61. #include "llvm/Support/ErrorHandling.h"
  62. #include "llvm/Transforms/Utils/Cloning.h"
  63. #include "llvm/Transforms/Utils/ValueMapper.h"
  64. #include <algorithm>
  65. #include <cassert>
  66. #include <cstdint>
  67. #include <iterator>
  68. #include <limits>
  69. #include <string>
  70. #include <utility>
  71. #include <vector>
  72. using namespace llvm;
  73. using ProfileCount = Function::ProfileCount;
  74. static cl::opt<bool>
  75. EnableNoAliasConversion("enable-noalias-to-md-conversion", cl::init(true),
  76. cl::Hidden,
  77. cl::desc("Convert noalias attributes to metadata during inlining."));
  78. static cl::opt<bool>
  79. PreserveAlignmentAssumptions("preserve-alignment-assumptions-during-inlining",
  80. cl::init(true), cl::Hidden,
  81. cl::desc("Convert align attributes to assumptions during inlining."));
  82. llvm::InlineResult llvm::InlineFunction(CallInst *CI, InlineFunctionInfo &IFI,
  83. AAResults *CalleeAAR,
  84. bool InsertLifetime) {
  85. return InlineFunction(CallSite(CI), IFI, CalleeAAR, InsertLifetime);
  86. }
  87. llvm::InlineResult llvm::InlineFunction(InvokeInst *II, InlineFunctionInfo &IFI,
  88. AAResults *CalleeAAR,
  89. bool InsertLifetime) {
  90. return InlineFunction(CallSite(II), IFI, CalleeAAR, InsertLifetime);
  91. }
  92. namespace {
  93. /// A class for recording information about inlining a landing pad.
  94. class LandingPadInliningInfo {
  95. /// Destination of the invoke's unwind.
  96. BasicBlock *OuterResumeDest;
  97. /// Destination for the callee's resume.
  98. BasicBlock *InnerResumeDest = nullptr;
  99. /// LandingPadInst associated with the invoke.
  100. LandingPadInst *CallerLPad = nullptr;
  101. /// PHI for EH values from landingpad insts.
  102. PHINode *InnerEHValuesPHI = nullptr;
  103. SmallVector<Value*, 8> UnwindDestPHIValues;
  104. public:
  105. LandingPadInliningInfo(InvokeInst *II)
  106. : OuterResumeDest(II->getUnwindDest()) {
  107. // If there are PHI nodes in the unwind destination block, we need to keep
  108. // track of which values came into them from the invoke before removing
  109. // the edge from this block.
  110. BasicBlock *InvokeBB = II->getParent();
  111. BasicBlock::iterator I = OuterResumeDest->begin();
  112. for (; isa<PHINode>(I); ++I) {
  113. // Save the value to use for this edge.
  114. PHINode *PHI = cast<PHINode>(I);
  115. UnwindDestPHIValues.push_back(PHI->getIncomingValueForBlock(InvokeBB));
  116. }
  117. CallerLPad = cast<LandingPadInst>(I);
  118. }
  119. /// The outer unwind destination is the target of
  120. /// unwind edges introduced for calls within the inlined function.
  121. BasicBlock *getOuterResumeDest() const {
  122. return OuterResumeDest;
  123. }
  124. BasicBlock *getInnerResumeDest();
  125. LandingPadInst *getLandingPadInst() const { return CallerLPad; }
  126. /// Forward the 'resume' instruction to the caller's landing pad block.
  127. /// When the landing pad block has only one predecessor, this is
  128. /// a simple branch. When there is more than one predecessor, we need to
  129. /// split the landing pad block after the landingpad instruction and jump
  130. /// to there.
  131. void forwardResume(ResumeInst *RI,
  132. SmallPtrSetImpl<LandingPadInst*> &InlinedLPads);
  133. /// Add incoming-PHI values to the unwind destination block for the given
  134. /// basic block, using the values for the original invoke's source block.
  135. void addIncomingPHIValuesFor(BasicBlock *BB) const {
  136. addIncomingPHIValuesForInto(BB, OuterResumeDest);
  137. }
  138. void addIncomingPHIValuesForInto(BasicBlock *src, BasicBlock *dest) const {
  139. BasicBlock::iterator I = dest->begin();
  140. for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
  141. PHINode *phi = cast<PHINode>(I);
  142. phi->addIncoming(UnwindDestPHIValues[i], src);
  143. }
  144. }
  145. };
  146. } // end anonymous namespace
  147. /// Get or create a target for the branch from ResumeInsts.
  148. BasicBlock *LandingPadInliningInfo::getInnerResumeDest() {
  149. if (InnerResumeDest) return InnerResumeDest;
  150. // Split the landing pad.
  151. BasicBlock::iterator SplitPoint = ++CallerLPad->getIterator();
  152. InnerResumeDest =
  153. OuterResumeDest->splitBasicBlock(SplitPoint,
  154. OuterResumeDest->getName() + ".body");
  155. // The number of incoming edges we expect to the inner landing pad.
  156. const unsigned PHICapacity = 2;
  157. // Create corresponding new PHIs for all the PHIs in the outer landing pad.
  158. Instruction *InsertPoint = &InnerResumeDest->front();
  159. BasicBlock::iterator I = OuterResumeDest->begin();
  160. for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
  161. PHINode *OuterPHI = cast<PHINode>(I);
  162. PHINode *InnerPHI = PHINode::Create(OuterPHI->getType(), PHICapacity,
  163. OuterPHI->getName() + ".lpad-body",
  164. InsertPoint);
  165. OuterPHI->replaceAllUsesWith(InnerPHI);
  166. InnerPHI->addIncoming(OuterPHI, OuterResumeDest);
  167. }
  168. // Create a PHI for the exception values.
  169. InnerEHValuesPHI = PHINode::Create(CallerLPad->getType(), PHICapacity,
  170. "eh.lpad-body", InsertPoint);
  171. CallerLPad->replaceAllUsesWith(InnerEHValuesPHI);
  172. InnerEHValuesPHI->addIncoming(CallerLPad, OuterResumeDest);
  173. // All done.
  174. return InnerResumeDest;
  175. }
  176. /// Forward the 'resume' instruction to the caller's landing pad block.
  177. /// When the landing pad block has only one predecessor, this is a simple
  178. /// branch. When there is more than one predecessor, we need to split the
  179. /// landing pad block after the landingpad instruction and jump to there.
  180. void LandingPadInliningInfo::forwardResume(
  181. ResumeInst *RI, SmallPtrSetImpl<LandingPadInst *> &InlinedLPads) {
  182. BasicBlock *Dest = getInnerResumeDest();
  183. BasicBlock *Src = RI->getParent();
  184. BranchInst::Create(Dest, Src);
  185. // Update the PHIs in the destination. They were inserted in an order which
  186. // makes this work.
  187. addIncomingPHIValuesForInto(Src, Dest);
  188. InnerEHValuesPHI->addIncoming(RI->getOperand(0), Src);
  189. RI->eraseFromParent();
  190. }
  191. /// Helper for getUnwindDestToken/getUnwindDestTokenHelper.
  192. static Value *getParentPad(Value *EHPad) {
  193. if (auto *FPI = dyn_cast<FuncletPadInst>(EHPad))
  194. return FPI->getParentPad();
  195. return cast<CatchSwitchInst>(EHPad)->getParentPad();
  196. }
  197. using UnwindDestMemoTy = DenseMap<Instruction *, Value *>;
  198. /// Helper for getUnwindDestToken that does the descendant-ward part of
  199. /// the search.
  200. static Value *getUnwindDestTokenHelper(Instruction *EHPad,
  201. UnwindDestMemoTy &MemoMap) {
  202. SmallVector<Instruction *, 8> Worklist(1, EHPad);
  203. while (!Worklist.empty()) {
  204. Instruction *CurrentPad = Worklist.pop_back_val();
  205. // We only put pads on the worklist that aren't in the MemoMap. When
  206. // we find an unwind dest for a pad we may update its ancestors, but
  207. // the queue only ever contains uncles/great-uncles/etc. of CurrentPad,
  208. // so they should never get updated while queued on the worklist.
  209. assert(!MemoMap.count(CurrentPad));
  210. Value *UnwindDestToken = nullptr;
  211. if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(CurrentPad)) {
  212. if (CatchSwitch->hasUnwindDest()) {
  213. UnwindDestToken = CatchSwitch->getUnwindDest()->getFirstNonPHI();
  214. } else {
  215. // Catchswitch doesn't have a 'nounwind' variant, and one might be
  216. // annotated as "unwinds to caller" when really it's nounwind (see
  217. // e.g. SimplifyCFGOpt::SimplifyUnreachable), so we can't infer the
  218. // parent's unwind dest from this. We can check its catchpads'
  219. // descendants, since they might include a cleanuppad with an
  220. // "unwinds to caller" cleanupret, which can be trusted.
  221. for (auto HI = CatchSwitch->handler_begin(),
  222. HE = CatchSwitch->handler_end();
  223. HI != HE && !UnwindDestToken; ++HI) {
  224. BasicBlock *HandlerBlock = *HI;
  225. auto *CatchPad = cast<CatchPadInst>(HandlerBlock->getFirstNonPHI());
  226. for (User *Child : CatchPad->users()) {
  227. // Intentionally ignore invokes here -- since the catchswitch is
  228. // marked "unwind to caller", it would be a verifier error if it
  229. // contained an invoke which unwinds out of it, so any invoke we'd
  230. // encounter must unwind to some child of the catch.
  231. if (!isa<CleanupPadInst>(Child) && !isa<CatchSwitchInst>(Child))
  232. continue;
  233. Instruction *ChildPad = cast<Instruction>(Child);
  234. auto Memo = MemoMap.find(ChildPad);
  235. if (Memo == MemoMap.end()) {
  236. // Haven't figured out this child pad yet; queue it.
  237. Worklist.push_back(ChildPad);
  238. continue;
  239. }
  240. // We've already checked this child, but might have found that
  241. // it offers no proof either way.
  242. Value *ChildUnwindDestToken = Memo->second;
  243. if (!ChildUnwindDestToken)
  244. continue;
  245. // We already know the child's unwind dest, which can either
  246. // be ConstantTokenNone to indicate unwind to caller, or can
  247. // be another child of the catchpad. Only the former indicates
  248. // the unwind dest of the catchswitch.
  249. if (isa<ConstantTokenNone>(ChildUnwindDestToken)) {
  250. UnwindDestToken = ChildUnwindDestToken;
  251. break;
  252. }
  253. assert(getParentPad(ChildUnwindDestToken) == CatchPad);
  254. }
  255. }
  256. }
  257. } else {
  258. auto *CleanupPad = cast<CleanupPadInst>(CurrentPad);
  259. for (User *U : CleanupPad->users()) {
  260. if (auto *CleanupRet = dyn_cast<CleanupReturnInst>(U)) {
  261. if (BasicBlock *RetUnwindDest = CleanupRet->getUnwindDest())
  262. UnwindDestToken = RetUnwindDest->getFirstNonPHI();
  263. else
  264. UnwindDestToken = ConstantTokenNone::get(CleanupPad->getContext());
  265. break;
  266. }
  267. Value *ChildUnwindDestToken;
  268. if (auto *Invoke = dyn_cast<InvokeInst>(U)) {
  269. ChildUnwindDestToken = Invoke->getUnwindDest()->getFirstNonPHI();
  270. } else if (isa<CleanupPadInst>(U) || isa<CatchSwitchInst>(U)) {
  271. Instruction *ChildPad = cast<Instruction>(U);
  272. auto Memo = MemoMap.find(ChildPad);
  273. if (Memo == MemoMap.end()) {
  274. // Haven't resolved this child yet; queue it and keep searching.
  275. Worklist.push_back(ChildPad);
  276. continue;
  277. }
  278. // We've checked this child, but still need to ignore it if it
  279. // had no proof either way.
  280. ChildUnwindDestToken = Memo->second;
  281. if (!ChildUnwindDestToken)
  282. continue;
  283. } else {
  284. // Not a relevant user of the cleanuppad
  285. continue;
  286. }
  287. // In a well-formed program, the child/invoke must either unwind to
  288. // an(other) child of the cleanup, or exit the cleanup. In the
  289. // first case, continue searching.
  290. if (isa<Instruction>(ChildUnwindDestToken) &&
  291. getParentPad(ChildUnwindDestToken) == CleanupPad)
  292. continue;
  293. UnwindDestToken = ChildUnwindDestToken;
  294. break;
  295. }
  296. }
  297. // If we haven't found an unwind dest for CurrentPad, we may have queued its
  298. // children, so move on to the next in the worklist.
  299. if (!UnwindDestToken)
  300. continue;
  301. // Now we know that CurrentPad unwinds to UnwindDestToken. It also exits
  302. // any ancestors of CurrentPad up to but not including UnwindDestToken's
  303. // parent pad. Record this in the memo map, and check to see if the
  304. // original EHPad being queried is one of the ones exited.
  305. Value *UnwindParent;
  306. if (auto *UnwindPad = dyn_cast<Instruction>(UnwindDestToken))
  307. UnwindParent = getParentPad(UnwindPad);
  308. else
  309. UnwindParent = nullptr;
  310. bool ExitedOriginalPad = false;
  311. for (Instruction *ExitedPad = CurrentPad;
  312. ExitedPad && ExitedPad != UnwindParent;
  313. ExitedPad = dyn_cast<Instruction>(getParentPad(ExitedPad))) {
  314. // Skip over catchpads since they just follow their catchswitches.
  315. if (isa<CatchPadInst>(ExitedPad))
  316. continue;
  317. MemoMap[ExitedPad] = UnwindDestToken;
  318. ExitedOriginalPad |= (ExitedPad == EHPad);
  319. }
  320. if (ExitedOriginalPad)
  321. return UnwindDestToken;
  322. // Continue the search.
  323. }
  324. // No definitive information is contained within this funclet.
  325. return nullptr;
  326. }
  327. /// Given an EH pad, find where it unwinds. If it unwinds to an EH pad,
  328. /// return that pad instruction. If it unwinds to caller, return
  329. /// ConstantTokenNone. If it does not have a definitive unwind destination,
  330. /// return nullptr.
  331. ///
  332. /// This routine gets invoked for calls in funclets in inlinees when inlining
  333. /// an invoke. Since many funclets don't have calls inside them, it's queried
  334. /// on-demand rather than building a map of pads to unwind dests up front.
  335. /// Determining a funclet's unwind dest may require recursively searching its
  336. /// descendants, and also ancestors and cousins if the descendants don't provide
  337. /// an answer. Since most funclets will have their unwind dest immediately
  338. /// available as the unwind dest of a catchswitch or cleanupret, this routine
  339. /// searches top-down from the given pad and then up. To avoid worst-case
  340. /// quadratic run-time given that approach, it uses a memo map to avoid
  341. /// re-processing funclet trees. The callers that rewrite the IR as they go
  342. /// take advantage of this, for correctness, by checking/forcing rewritten
  343. /// pads' entries to match the original callee view.
  344. static Value *getUnwindDestToken(Instruction *EHPad,
  345. UnwindDestMemoTy &MemoMap) {
  346. // Catchpads unwind to the same place as their catchswitch;
  347. // redirct any queries on catchpads so the code below can
  348. // deal with just catchswitches and cleanuppads.
  349. if (auto *CPI = dyn_cast<CatchPadInst>(EHPad))
  350. EHPad = CPI->getCatchSwitch();
  351. // Check if we've already determined the unwind dest for this pad.
  352. auto Memo = MemoMap.find(EHPad);
  353. if (Memo != MemoMap.end())
  354. return Memo->second;
  355. // Search EHPad and, if necessary, its descendants.
  356. Value *UnwindDestToken = getUnwindDestTokenHelper(EHPad, MemoMap);
  357. assert((UnwindDestToken == nullptr) != (MemoMap.count(EHPad) != 0));
  358. if (UnwindDestToken)
  359. return UnwindDestToken;
  360. // No information is available for this EHPad from itself or any of its
  361. // descendants. An unwind all the way out to a pad in the caller would
  362. // need also to agree with the unwind dest of the parent funclet, so
  363. // search up the chain to try to find a funclet with information. Put
  364. // null entries in the memo map to avoid re-processing as we go up.
  365. MemoMap[EHPad] = nullptr;
  366. #ifndef NDEBUG
  367. SmallPtrSet<Instruction *, 4> TempMemos;
  368. TempMemos.insert(EHPad);
  369. #endif
  370. Instruction *LastUselessPad = EHPad;
  371. Value *AncestorToken;
  372. for (AncestorToken = getParentPad(EHPad);
  373. auto *AncestorPad = dyn_cast<Instruction>(AncestorToken);
  374. AncestorToken = getParentPad(AncestorToken)) {
  375. // Skip over catchpads since they just follow their catchswitches.
  376. if (isa<CatchPadInst>(AncestorPad))
  377. continue;
  378. // If the MemoMap had an entry mapping AncestorPad to nullptr, since we
  379. // haven't yet called getUnwindDestTokenHelper for AncestorPad in this
  380. // call to getUnwindDestToken, that would mean that AncestorPad had no
  381. // information in itself, its descendants, or its ancestors. If that
  382. // were the case, then we should also have recorded the lack of information
  383. // for the descendant that we're coming from. So assert that we don't
  384. // find a null entry in the MemoMap for AncestorPad.
  385. assert(!MemoMap.count(AncestorPad) || MemoMap[AncestorPad]);
  386. auto AncestorMemo = MemoMap.find(AncestorPad);
  387. if (AncestorMemo == MemoMap.end()) {
  388. UnwindDestToken = getUnwindDestTokenHelper(AncestorPad, MemoMap);
  389. } else {
  390. UnwindDestToken = AncestorMemo->second;
  391. }
  392. if (UnwindDestToken)
  393. break;
  394. LastUselessPad = AncestorPad;
  395. MemoMap[LastUselessPad] = nullptr;
  396. #ifndef NDEBUG
  397. TempMemos.insert(LastUselessPad);
  398. #endif
  399. }
  400. // We know that getUnwindDestTokenHelper was called on LastUselessPad and
  401. // returned nullptr (and likewise for EHPad and any of its ancestors up to
  402. // LastUselessPad), so LastUselessPad has no information from below. Since
  403. // getUnwindDestTokenHelper must investigate all downward paths through
  404. // no-information nodes to prove that a node has no information like this,
  405. // and since any time it finds information it records it in the MemoMap for
  406. // not just the immediately-containing funclet but also any ancestors also
  407. // exited, it must be the case that, walking downward from LastUselessPad,
  408. // visiting just those nodes which have not been mapped to an unwind dest
  409. // by getUnwindDestTokenHelper (the nullptr TempMemos notwithstanding, since
  410. // they are just used to keep getUnwindDestTokenHelper from repeating work),
  411. // any node visited must have been exhaustively searched with no information
  412. // for it found.
  413. SmallVector<Instruction *, 8> Worklist(1, LastUselessPad);
  414. while (!Worklist.empty()) {
  415. Instruction *UselessPad = Worklist.pop_back_val();
  416. auto Memo = MemoMap.find(UselessPad);
  417. if (Memo != MemoMap.end() && Memo->second) {
  418. // Here the name 'UselessPad' is a bit of a misnomer, because we've found
  419. // that it is a funclet that does have information about unwinding to
  420. // a particular destination; its parent was a useless pad.
  421. // Since its parent has no information, the unwind edge must not escape
  422. // the parent, and must target a sibling of this pad. This local unwind
  423. // gives us no information about EHPad. Leave it and the subtree rooted
  424. // at it alone.
  425. assert(getParentPad(Memo->second) == getParentPad(UselessPad));
  426. continue;
  427. }
  428. // We know we don't have information for UselesPad. If it has an entry in
  429. // the MemoMap (mapping it to nullptr), it must be one of the TempMemos
  430. // added on this invocation of getUnwindDestToken; if a previous invocation
  431. // recorded nullptr, it would have had to prove that the ancestors of
  432. // UselessPad, which include LastUselessPad, had no information, and that
  433. // in turn would have required proving that the descendants of
  434. // LastUselesPad, which include EHPad, have no information about
  435. // LastUselessPad, which would imply that EHPad was mapped to nullptr in
  436. // the MemoMap on that invocation, which isn't the case if we got here.
  437. assert(!MemoMap.count(UselessPad) || TempMemos.count(UselessPad));
  438. // Assert as we enumerate users that 'UselessPad' doesn't have any unwind
  439. // information that we'd be contradicting by making a map entry for it
  440. // (which is something that getUnwindDestTokenHelper must have proved for
  441. // us to get here). Just assert on is direct users here; the checks in
  442. // this downward walk at its descendants will verify that they don't have
  443. // any unwind edges that exit 'UselessPad' either (i.e. they either have no
  444. // unwind edges or unwind to a sibling).
  445. MemoMap[UselessPad] = UnwindDestToken;
  446. if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(UselessPad)) {
  447. assert(CatchSwitch->getUnwindDest() == nullptr && "Expected useless pad");
  448. for (BasicBlock *HandlerBlock : CatchSwitch->handlers()) {
  449. auto *CatchPad = HandlerBlock->getFirstNonPHI();
  450. for (User *U : CatchPad->users()) {
  451. assert(
  452. (!isa<InvokeInst>(U) ||
  453. (getParentPad(
  454. cast<InvokeInst>(U)->getUnwindDest()->getFirstNonPHI()) ==
  455. CatchPad)) &&
  456. "Expected useless pad");
  457. if (isa<CatchSwitchInst>(U) || isa<CleanupPadInst>(U))
  458. Worklist.push_back(cast<Instruction>(U));
  459. }
  460. }
  461. } else {
  462. assert(isa<CleanupPadInst>(UselessPad));
  463. for (User *U : UselessPad->users()) {
  464. assert(!isa<CleanupReturnInst>(U) && "Expected useless pad");
  465. assert((!isa<InvokeInst>(U) ||
  466. (getParentPad(
  467. cast<InvokeInst>(U)->getUnwindDest()->getFirstNonPHI()) ==
  468. UselessPad)) &&
  469. "Expected useless pad");
  470. if (isa<CatchSwitchInst>(U) || isa<CleanupPadInst>(U))
  471. Worklist.push_back(cast<Instruction>(U));
  472. }
  473. }
  474. }
  475. return UnwindDestToken;
  476. }
  477. /// When we inline a basic block into an invoke,
  478. /// we have to turn all of the calls that can throw into invokes.
  479. /// This function analyze BB to see if there are any calls, and if so,
  480. /// it rewrites them to be invokes that jump to InvokeDest and fills in the PHI
  481. /// nodes in that block with the values specified in InvokeDestPHIValues.
  482. static BasicBlock *HandleCallsInBlockInlinedThroughInvoke(
  483. BasicBlock *BB, BasicBlock *UnwindEdge,
  484. UnwindDestMemoTy *FuncletUnwindMap = nullptr) {
  485. for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
  486. Instruction *I = &*BBI++;
  487. // We only need to check for function calls: inlined invoke
  488. // instructions require no special handling.
  489. CallInst *CI = dyn_cast<CallInst>(I);
  490. if (!CI || CI->doesNotThrow() || isa<InlineAsm>(CI->getCalledValue()))
  491. continue;
  492. // We do not need to (and in fact, cannot) convert possibly throwing calls
  493. // to @llvm.experimental_deoptimize (resp. @llvm.experimental.guard) into
  494. // invokes. The caller's "segment" of the deoptimization continuation
  495. // attached to the newly inlined @llvm.experimental_deoptimize
  496. // (resp. @llvm.experimental.guard) call should contain the exception
  497. // handling logic, if any.
  498. if (auto *F = CI->getCalledFunction())
  499. if (F->getIntrinsicID() == Intrinsic::experimental_deoptimize ||
  500. F->getIntrinsicID() == Intrinsic::experimental_guard)
  501. continue;
  502. if (auto FuncletBundle = CI->getOperandBundle(LLVMContext::OB_funclet)) {
  503. // This call is nested inside a funclet. If that funclet has an unwind
  504. // destination within the inlinee, then unwinding out of this call would
  505. // be UB. Rewriting this call to an invoke which targets the inlined
  506. // invoke's unwind dest would give the call's parent funclet multiple
  507. // unwind destinations, which is something that subsequent EH table
  508. // generation can't handle and that the veirifer rejects. So when we
  509. // see such a call, leave it as a call.
  510. auto *FuncletPad = cast<Instruction>(FuncletBundle->Inputs[0]);
  511. Value *UnwindDestToken =
  512. getUnwindDestToken(FuncletPad, *FuncletUnwindMap);
  513. if (UnwindDestToken && !isa<ConstantTokenNone>(UnwindDestToken))
  514. continue;
  515. #ifndef NDEBUG
  516. Instruction *MemoKey;
  517. if (auto *CatchPad = dyn_cast<CatchPadInst>(FuncletPad))
  518. MemoKey = CatchPad->getCatchSwitch();
  519. else
  520. MemoKey = FuncletPad;
  521. assert(FuncletUnwindMap->count(MemoKey) &&
  522. (*FuncletUnwindMap)[MemoKey] == UnwindDestToken &&
  523. "must get memoized to avoid confusing later searches");
  524. #endif // NDEBUG
  525. }
  526. changeToInvokeAndSplitBasicBlock(CI, UnwindEdge);
  527. return BB;
  528. }
  529. return nullptr;
  530. }
  531. /// If we inlined an invoke site, we need to convert calls
  532. /// in the body of the inlined function into invokes.
  533. ///
  534. /// II is the invoke instruction being inlined. FirstNewBlock is the first
  535. /// block of the inlined code (the last block is the end of the function),
  536. /// and InlineCodeInfo is information about the code that got inlined.
  537. static void HandleInlinedLandingPad(InvokeInst *II, BasicBlock *FirstNewBlock,
  538. ClonedCodeInfo &InlinedCodeInfo) {
  539. BasicBlock *InvokeDest = II->getUnwindDest();
  540. Function *Caller = FirstNewBlock->getParent();
  541. // The inlined code is currently at the end of the function, scan from the
  542. // start of the inlined code to its end, checking for stuff we need to
  543. // rewrite.
  544. LandingPadInliningInfo Invoke(II);
  545. // Get all of the inlined landing pad instructions.
  546. SmallPtrSet<LandingPadInst*, 16> InlinedLPads;
  547. for (Function::iterator I = FirstNewBlock->getIterator(), E = Caller->end();
  548. I != E; ++I)
  549. if (InvokeInst *II = dyn_cast<InvokeInst>(I->getTerminator()))
  550. InlinedLPads.insert(II->getLandingPadInst());
  551. // Append the clauses from the outer landing pad instruction into the inlined
  552. // landing pad instructions.
  553. LandingPadInst *OuterLPad = Invoke.getLandingPadInst();
  554. for (LandingPadInst *InlinedLPad : InlinedLPads) {
  555. unsigned OuterNum = OuterLPad->getNumClauses();
  556. InlinedLPad->reserveClauses(OuterNum);
  557. for (unsigned OuterIdx = 0; OuterIdx != OuterNum; ++OuterIdx)
  558. InlinedLPad->addClause(OuterLPad->getClause(OuterIdx));
  559. if (OuterLPad->isCleanup())
  560. InlinedLPad->setCleanup(true);
  561. }
  562. for (Function::iterator BB = FirstNewBlock->getIterator(), E = Caller->end();
  563. BB != E; ++BB) {
  564. if (InlinedCodeInfo.ContainsCalls)
  565. if (BasicBlock *NewBB = HandleCallsInBlockInlinedThroughInvoke(
  566. &*BB, Invoke.getOuterResumeDest()))
  567. // Update any PHI nodes in the exceptional block to indicate that there
  568. // is now a new entry in them.
  569. Invoke.addIncomingPHIValuesFor(NewBB);
  570. // Forward any resumes that are remaining here.
  571. if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator()))
  572. Invoke.forwardResume(RI, InlinedLPads);
  573. }
  574. // Now that everything is happy, we have one final detail. The PHI nodes in
  575. // the exception destination block still have entries due to the original
  576. // invoke instruction. Eliminate these entries (which might even delete the
  577. // PHI node) now.
  578. InvokeDest->removePredecessor(II->getParent());
  579. }
  580. /// If we inlined an invoke site, we need to convert calls
  581. /// in the body of the inlined function into invokes.
  582. ///
  583. /// II is the invoke instruction being inlined. FirstNewBlock is the first
  584. /// block of the inlined code (the last block is the end of the function),
  585. /// and InlineCodeInfo is information about the code that got inlined.
  586. static void HandleInlinedEHPad(InvokeInst *II, BasicBlock *FirstNewBlock,
  587. ClonedCodeInfo &InlinedCodeInfo) {
  588. BasicBlock *UnwindDest = II->getUnwindDest();
  589. Function *Caller = FirstNewBlock->getParent();
  590. assert(UnwindDest->getFirstNonPHI()->isEHPad() && "unexpected BasicBlock!");
  591. // If there are PHI nodes in the unwind destination block, we need to keep
  592. // track of which values came into them from the invoke before removing the
  593. // edge from this block.
  594. SmallVector<Value *, 8> UnwindDestPHIValues;
  595. BasicBlock *InvokeBB = II->getParent();
  596. for (Instruction &I : *UnwindDest) {
  597. // Save the value to use for this edge.
  598. PHINode *PHI = dyn_cast<PHINode>(&I);
  599. if (!PHI)
  600. break;
  601. UnwindDestPHIValues.push_back(PHI->getIncomingValueForBlock(InvokeBB));
  602. }
  603. // Add incoming-PHI values to the unwind destination block for the given basic
  604. // block, using the values for the original invoke's source block.
  605. auto UpdatePHINodes = [&](BasicBlock *Src) {
  606. BasicBlock::iterator I = UnwindDest->begin();
  607. for (Value *V : UnwindDestPHIValues) {
  608. PHINode *PHI = cast<PHINode>(I);
  609. PHI->addIncoming(V, Src);
  610. ++I;
  611. }
  612. };
  613. // This connects all the instructions which 'unwind to caller' to the invoke
  614. // destination.
  615. UnwindDestMemoTy FuncletUnwindMap;
  616. for (Function::iterator BB = FirstNewBlock->getIterator(), E = Caller->end();
  617. BB != E; ++BB) {
  618. if (auto *CRI = dyn_cast<CleanupReturnInst>(BB->getTerminator())) {
  619. if (CRI->unwindsToCaller()) {
  620. auto *CleanupPad = CRI->getCleanupPad();
  621. CleanupReturnInst::Create(CleanupPad, UnwindDest, CRI);
  622. CRI->eraseFromParent();
  623. UpdatePHINodes(&*BB);
  624. // Finding a cleanupret with an unwind destination would confuse
  625. // subsequent calls to getUnwindDestToken, so map the cleanuppad
  626. // to short-circuit any such calls and recognize this as an "unwind
  627. // to caller" cleanup.
  628. assert(!FuncletUnwindMap.count(CleanupPad) ||
  629. isa<ConstantTokenNone>(FuncletUnwindMap[CleanupPad]));
  630. FuncletUnwindMap[CleanupPad] =
  631. ConstantTokenNone::get(Caller->getContext());
  632. }
  633. }
  634. Instruction *I = BB->getFirstNonPHI();
  635. if (!I->isEHPad())
  636. continue;
  637. Instruction *Replacement = nullptr;
  638. if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(I)) {
  639. if (CatchSwitch->unwindsToCaller()) {
  640. Value *UnwindDestToken;
  641. if (auto *ParentPad =
  642. dyn_cast<Instruction>(CatchSwitch->getParentPad())) {
  643. // This catchswitch is nested inside another funclet. If that
  644. // funclet has an unwind destination within the inlinee, then
  645. // unwinding out of this catchswitch would be UB. Rewriting this
  646. // catchswitch to unwind to the inlined invoke's unwind dest would
  647. // give the parent funclet multiple unwind destinations, which is
  648. // something that subsequent EH table generation can't handle and
  649. // that the veirifer rejects. So when we see such a call, leave it
  650. // as "unwind to caller".
  651. UnwindDestToken = getUnwindDestToken(ParentPad, FuncletUnwindMap);
  652. if (UnwindDestToken && !isa<ConstantTokenNone>(UnwindDestToken))
  653. continue;
  654. } else {
  655. // This catchswitch has no parent to inherit constraints from, and
  656. // none of its descendants can have an unwind edge that exits it and
  657. // targets another funclet in the inlinee. It may or may not have a
  658. // descendant that definitively has an unwind to caller. In either
  659. // case, we'll have to assume that any unwinds out of it may need to
  660. // be routed to the caller, so treat it as though it has a definitive
  661. // unwind to caller.
  662. UnwindDestToken = ConstantTokenNone::get(Caller->getContext());
  663. }
  664. auto *NewCatchSwitch = CatchSwitchInst::Create(
  665. CatchSwitch->getParentPad(), UnwindDest,
  666. CatchSwitch->getNumHandlers(), CatchSwitch->getName(),
  667. CatchSwitch);
  668. for (BasicBlock *PadBB : CatchSwitch->handlers())
  669. NewCatchSwitch->addHandler(PadBB);
  670. // Propagate info for the old catchswitch over to the new one in
  671. // the unwind map. This also serves to short-circuit any subsequent
  672. // checks for the unwind dest of this catchswitch, which would get
  673. // confused if they found the outer handler in the callee.
  674. FuncletUnwindMap[NewCatchSwitch] = UnwindDestToken;
  675. Replacement = NewCatchSwitch;
  676. }
  677. } else if (!isa<FuncletPadInst>(I)) {
  678. llvm_unreachable("unexpected EHPad!");
  679. }
  680. if (Replacement) {
  681. Replacement->takeName(I);
  682. I->replaceAllUsesWith(Replacement);
  683. I->eraseFromParent();
  684. UpdatePHINodes(&*BB);
  685. }
  686. }
  687. if (InlinedCodeInfo.ContainsCalls)
  688. for (Function::iterator BB = FirstNewBlock->getIterator(),
  689. E = Caller->end();
  690. BB != E; ++BB)
  691. if (BasicBlock *NewBB = HandleCallsInBlockInlinedThroughInvoke(
  692. &*BB, UnwindDest, &FuncletUnwindMap))
  693. // Update any PHI nodes in the exceptional block to indicate that there
  694. // is now a new entry in them.
  695. UpdatePHINodes(NewBB);
  696. // Now that everything is happy, we have one final detail. The PHI nodes in
  697. // the exception destination block still have entries due to the original
  698. // invoke instruction. Eliminate these entries (which might even delete the
  699. // PHI node) now.
  700. UnwindDest->removePredecessor(InvokeBB);
  701. }
  702. /// When inlining a call site that has !llvm.mem.parallel_loop_access or
  703. /// llvm.access.group metadata, that metadata should be propagated to all
  704. /// memory-accessing cloned instructions.
  705. static void PropagateParallelLoopAccessMetadata(CallSite CS,
  706. ValueToValueMapTy &VMap) {
  707. MDNode *M =
  708. CS.getInstruction()->getMetadata(LLVMContext::MD_mem_parallel_loop_access);
  709. MDNode *CallAccessGroup =
  710. CS.getInstruction()->getMetadata(LLVMContext::MD_access_group);
  711. if (!M && !CallAccessGroup)
  712. return;
  713. for (ValueToValueMapTy::iterator VMI = VMap.begin(), VMIE = VMap.end();
  714. VMI != VMIE; ++VMI) {
  715. if (!VMI->second)
  716. continue;
  717. Instruction *NI = dyn_cast<Instruction>(VMI->second);
  718. if (!NI)
  719. continue;
  720. if (M) {
  721. if (MDNode *PM =
  722. NI->getMetadata(LLVMContext::MD_mem_parallel_loop_access)) {
  723. M = MDNode::concatenate(PM, M);
  724. NI->setMetadata(LLVMContext::MD_mem_parallel_loop_access, M);
  725. } else if (NI->mayReadOrWriteMemory()) {
  726. NI->setMetadata(LLVMContext::MD_mem_parallel_loop_access, M);
  727. }
  728. }
  729. if (NI->mayReadOrWriteMemory()) {
  730. MDNode *UnitedAccGroups = uniteAccessGroups(
  731. NI->getMetadata(LLVMContext::MD_access_group), CallAccessGroup);
  732. NI->setMetadata(LLVMContext::MD_access_group, UnitedAccGroups);
  733. }
  734. }
  735. }
  736. /// When inlining a function that contains noalias scope metadata,
  737. /// this metadata needs to be cloned so that the inlined blocks
  738. /// have different "unique scopes" at every call site. Were this not done, then
  739. /// aliasing scopes from a function inlined into a caller multiple times could
  740. /// not be differentiated (and this would lead to miscompiles because the
  741. /// non-aliasing property communicated by the metadata could have
  742. /// call-site-specific control dependencies).
  743. static void CloneAliasScopeMetadata(CallSite CS, ValueToValueMapTy &VMap) {
  744. const Function *CalledFunc = CS.getCalledFunction();
  745. SetVector<const MDNode *> MD;
  746. // Note: We could only clone the metadata if it is already used in the
  747. // caller. I'm omitting that check here because it might confuse
  748. // inter-procedural alias analysis passes. We can revisit this if it becomes
  749. // an efficiency or overhead problem.
  750. for (const BasicBlock &I : *CalledFunc)
  751. for (const Instruction &J : I) {
  752. if (const MDNode *M = J.getMetadata(LLVMContext::MD_alias_scope))
  753. MD.insert(M);
  754. if (const MDNode *M = J.getMetadata(LLVMContext::MD_noalias))
  755. MD.insert(M);
  756. }
  757. if (MD.empty())
  758. return;
  759. // Walk the existing metadata, adding the complete (perhaps cyclic) chain to
  760. // the set.
  761. SmallVector<const Metadata *, 16> Queue(MD.begin(), MD.end());
  762. while (!Queue.empty()) {
  763. const MDNode *M = cast<MDNode>(Queue.pop_back_val());
  764. for (unsigned i = 0, ie = M->getNumOperands(); i != ie; ++i)
  765. if (const MDNode *M1 = dyn_cast<MDNode>(M->getOperand(i)))
  766. if (MD.insert(M1))
  767. Queue.push_back(M1);
  768. }
  769. // Now we have a complete set of all metadata in the chains used to specify
  770. // the noalias scopes and the lists of those scopes.
  771. SmallVector<TempMDTuple, 16> DummyNodes;
  772. DenseMap<const MDNode *, TrackingMDNodeRef> MDMap;
  773. for (const MDNode *I : MD) {
  774. DummyNodes.push_back(MDTuple::getTemporary(CalledFunc->getContext(), None));
  775. MDMap[I].reset(DummyNodes.back().get());
  776. }
  777. // Create new metadata nodes to replace the dummy nodes, replacing old
  778. // metadata references with either a dummy node or an already-created new
  779. // node.
  780. for (const MDNode *I : MD) {
  781. SmallVector<Metadata *, 4> NewOps;
  782. for (unsigned i = 0, ie = I->getNumOperands(); i != ie; ++i) {
  783. const Metadata *V = I->getOperand(i);
  784. if (const MDNode *M = dyn_cast<MDNode>(V))
  785. NewOps.push_back(MDMap[M]);
  786. else
  787. NewOps.push_back(const_cast<Metadata *>(V));
  788. }
  789. MDNode *NewM = MDNode::get(CalledFunc->getContext(), NewOps);
  790. MDTuple *TempM = cast<MDTuple>(MDMap[I]);
  791. assert(TempM->isTemporary() && "Expected temporary node");
  792. TempM->replaceAllUsesWith(NewM);
  793. }
  794. // Now replace the metadata in the new inlined instructions with the
  795. // repacements from the map.
  796. for (ValueToValueMapTy::iterator VMI = VMap.begin(), VMIE = VMap.end();
  797. VMI != VMIE; ++VMI) {
  798. if (!VMI->second)
  799. continue;
  800. Instruction *NI = dyn_cast<Instruction>(VMI->second);
  801. if (!NI)
  802. continue;
  803. if (MDNode *M = NI->getMetadata(LLVMContext::MD_alias_scope)) {
  804. MDNode *NewMD = MDMap[M];
  805. // If the call site also had alias scope metadata (a list of scopes to
  806. // which instructions inside it might belong), propagate those scopes to
  807. // the inlined instructions.
  808. if (MDNode *CSM =
  809. CS.getInstruction()->getMetadata(LLVMContext::MD_alias_scope))
  810. NewMD = MDNode::concatenate(NewMD, CSM);
  811. NI->setMetadata(LLVMContext::MD_alias_scope, NewMD);
  812. } else if (NI->mayReadOrWriteMemory()) {
  813. if (MDNode *M =
  814. CS.getInstruction()->getMetadata(LLVMContext::MD_alias_scope))
  815. NI->setMetadata(LLVMContext::MD_alias_scope, M);
  816. }
  817. if (MDNode *M = NI->getMetadata(LLVMContext::MD_noalias)) {
  818. MDNode *NewMD = MDMap[M];
  819. // If the call site also had noalias metadata (a list of scopes with
  820. // which instructions inside it don't alias), propagate those scopes to
  821. // the inlined instructions.
  822. if (MDNode *CSM =
  823. CS.getInstruction()->getMetadata(LLVMContext::MD_noalias))
  824. NewMD = MDNode::concatenate(NewMD, CSM);
  825. NI->setMetadata(LLVMContext::MD_noalias, NewMD);
  826. } else if (NI->mayReadOrWriteMemory()) {
  827. if (MDNode *M = CS.getInstruction()->getMetadata(LLVMContext::MD_noalias))
  828. NI->setMetadata(LLVMContext::MD_noalias, M);
  829. }
  830. }
  831. }
  832. /// If the inlined function has noalias arguments,
  833. /// then add new alias scopes for each noalias argument, tag the mapped noalias
  834. /// parameters with noalias metadata specifying the new scope, and tag all
  835. /// non-derived loads, stores and memory intrinsics with the new alias scopes.
  836. static void AddAliasScopeMetadata(CallSite CS, ValueToValueMapTy &VMap,
  837. const DataLayout &DL, AAResults *CalleeAAR) {
  838. if (!EnableNoAliasConversion)
  839. return;
  840. const Function *CalledFunc = CS.getCalledFunction();
  841. SmallVector<const Argument *, 4> NoAliasArgs;
  842. for (const Argument &Arg : CalledFunc->args())
  843. if (Arg.hasNoAliasAttr() && !Arg.use_empty())
  844. NoAliasArgs.push_back(&Arg);
  845. if (NoAliasArgs.empty())
  846. return;
  847. // To do a good job, if a noalias variable is captured, we need to know if
  848. // the capture point dominates the particular use we're considering.
  849. DominatorTree DT;
  850. DT.recalculate(const_cast<Function&>(*CalledFunc));
  851. // noalias indicates that pointer values based on the argument do not alias
  852. // pointer values which are not based on it. So we add a new "scope" for each
  853. // noalias function argument. Accesses using pointers based on that argument
  854. // become part of that alias scope, accesses using pointers not based on that
  855. // argument are tagged as noalias with that scope.
  856. DenseMap<const Argument *, MDNode *> NewScopes;
  857. MDBuilder MDB(CalledFunc->getContext());
  858. // Create a new scope domain for this function.
  859. MDNode *NewDomain =
  860. MDB.createAnonymousAliasScopeDomain(CalledFunc->getName());
  861. for (unsigned i = 0, e = NoAliasArgs.size(); i != e; ++i) {
  862. const Argument *A = NoAliasArgs[i];
  863. std::string Name = CalledFunc->getName();
  864. if (A->hasName()) {
  865. Name += ": %";
  866. Name += A->getName();
  867. } else {
  868. Name += ": argument ";
  869. Name += utostr(i);
  870. }
  871. // Note: We always create a new anonymous root here. This is true regardless
  872. // of the linkage of the callee because the aliasing "scope" is not just a
  873. // property of the callee, but also all control dependencies in the caller.
  874. MDNode *NewScope = MDB.createAnonymousAliasScope(NewDomain, Name);
  875. NewScopes.insert(std::make_pair(A, NewScope));
  876. }
  877. // Iterate over all new instructions in the map; for all memory-access
  878. // instructions, add the alias scope metadata.
  879. for (ValueToValueMapTy::iterator VMI = VMap.begin(), VMIE = VMap.end();
  880. VMI != VMIE; ++VMI) {
  881. if (const Instruction *I = dyn_cast<Instruction>(VMI->first)) {
  882. if (!VMI->second)
  883. continue;
  884. Instruction *NI = dyn_cast<Instruction>(VMI->second);
  885. if (!NI)
  886. continue;
  887. bool IsArgMemOnlyCall = false, IsFuncCall = false;
  888. SmallVector<const Value *, 2> PtrArgs;
  889. if (const LoadInst *LI = dyn_cast<LoadInst>(I))
  890. PtrArgs.push_back(LI->getPointerOperand());
  891. else if (const StoreInst *SI = dyn_cast<StoreInst>(I))
  892. PtrArgs.push_back(SI->getPointerOperand());
  893. else if (const VAArgInst *VAAI = dyn_cast<VAArgInst>(I))
  894. PtrArgs.push_back(VAAI->getPointerOperand());
  895. else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I))
  896. PtrArgs.push_back(CXI->getPointerOperand());
  897. else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I))
  898. PtrArgs.push_back(RMWI->getPointerOperand());
  899. else if (const auto *Call = dyn_cast<CallBase>(I)) {
  900. // If we know that the call does not access memory, then we'll still
  901. // know that about the inlined clone of this call site, and we don't
  902. // need to add metadata.
  903. if (Call->doesNotAccessMemory())
  904. continue;
  905. IsFuncCall = true;
  906. if (CalleeAAR) {
  907. FunctionModRefBehavior MRB = CalleeAAR->getModRefBehavior(Call);
  908. if (MRB == FMRB_OnlyAccessesArgumentPointees ||
  909. MRB == FMRB_OnlyReadsArgumentPointees)
  910. IsArgMemOnlyCall = true;
  911. }
  912. for (Value *Arg : Call->args()) {
  913. // We need to check the underlying objects of all arguments, not just
  914. // the pointer arguments, because we might be passing pointers as
  915. // integers, etc.
  916. // However, if we know that the call only accesses pointer arguments,
  917. // then we only need to check the pointer arguments.
  918. if (IsArgMemOnlyCall && !Arg->getType()->isPointerTy())
  919. continue;
  920. PtrArgs.push_back(Arg);
  921. }
  922. }
  923. // If we found no pointers, then this instruction is not suitable for
  924. // pairing with an instruction to receive aliasing metadata.
  925. // However, if this is a call, this we might just alias with none of the
  926. // noalias arguments.
  927. if (PtrArgs.empty() && !IsFuncCall)
  928. continue;
  929. // It is possible that there is only one underlying object, but you
  930. // need to go through several PHIs to see it, and thus could be
  931. // repeated in the Objects list.
  932. SmallPtrSet<const Value *, 4> ObjSet;
  933. SmallVector<Metadata *, 4> Scopes, NoAliases;
  934. SmallSetVector<const Argument *, 4> NAPtrArgs;
  935. for (const Value *V : PtrArgs) {
  936. SmallVector<const Value *, 4> Objects;
  937. GetUnderlyingObjects(V, Objects, DL, /* LI = */ nullptr);
  938. for (const Value *O : Objects)
  939. ObjSet.insert(O);
  940. }
  941. // Figure out if we're derived from anything that is not a noalias
  942. // argument.
  943. bool CanDeriveViaCapture = false, UsesAliasingPtr = false;
  944. for (const Value *V : ObjSet) {
  945. // Is this value a constant that cannot be derived from any pointer
  946. // value (we need to exclude constant expressions, for example, that
  947. // are formed from arithmetic on global symbols).
  948. bool IsNonPtrConst = isa<ConstantInt>(V) || isa<ConstantFP>(V) ||
  949. isa<ConstantPointerNull>(V) ||
  950. isa<ConstantDataVector>(V) || isa<UndefValue>(V);
  951. if (IsNonPtrConst)
  952. continue;
  953. // If this is anything other than a noalias argument, then we cannot
  954. // completely describe the aliasing properties using alias.scope
  955. // metadata (and, thus, won't add any).
  956. if (const Argument *A = dyn_cast<Argument>(V)) {
  957. if (!A->hasNoAliasAttr())
  958. UsesAliasingPtr = true;
  959. } else {
  960. UsesAliasingPtr = true;
  961. }
  962. // If this is not some identified function-local object (which cannot
  963. // directly alias a noalias argument), or some other argument (which,
  964. // by definition, also cannot alias a noalias argument), then we could
  965. // alias a noalias argument that has been captured).
  966. if (!isa<Argument>(V) &&
  967. !isIdentifiedFunctionLocal(const_cast<Value*>(V)))
  968. CanDeriveViaCapture = true;
  969. }
  970. // A function call can always get captured noalias pointers (via other
  971. // parameters, globals, etc.).
  972. if (IsFuncCall && !IsArgMemOnlyCall)
  973. CanDeriveViaCapture = true;
  974. // First, we want to figure out all of the sets with which we definitely
  975. // don't alias. Iterate over all noalias set, and add those for which:
  976. // 1. The noalias argument is not in the set of objects from which we
  977. // definitely derive.
  978. // 2. The noalias argument has not yet been captured.
  979. // An arbitrary function that might load pointers could see captured
  980. // noalias arguments via other noalias arguments or globals, and so we
  981. // must always check for prior capture.
  982. for (const Argument *A : NoAliasArgs) {
  983. if (!ObjSet.count(A) && (!CanDeriveViaCapture ||
  984. // It might be tempting to skip the
  985. // PointerMayBeCapturedBefore check if
  986. // A->hasNoCaptureAttr() is true, but this is
  987. // incorrect because nocapture only guarantees
  988. // that no copies outlive the function, not
  989. // that the value cannot be locally captured.
  990. !PointerMayBeCapturedBefore(A,
  991. /* ReturnCaptures */ false,
  992. /* StoreCaptures */ false, I, &DT)))
  993. NoAliases.push_back(NewScopes[A]);
  994. }
  995. if (!NoAliases.empty())
  996. NI->setMetadata(LLVMContext::MD_noalias,
  997. MDNode::concatenate(
  998. NI->getMetadata(LLVMContext::MD_noalias),
  999. MDNode::get(CalledFunc->getContext(), NoAliases)));
  1000. // Next, we want to figure out all of the sets to which we might belong.
  1001. // We might belong to a set if the noalias argument is in the set of
  1002. // underlying objects. If there is some non-noalias argument in our list
  1003. // of underlying objects, then we cannot add a scope because the fact
  1004. // that some access does not alias with any set of our noalias arguments
  1005. // cannot itself guarantee that it does not alias with this access
  1006. // (because there is some pointer of unknown origin involved and the
  1007. // other access might also depend on this pointer). We also cannot add
  1008. // scopes to arbitrary functions unless we know they don't access any
  1009. // non-parameter pointer-values.
  1010. bool CanAddScopes = !UsesAliasingPtr;
  1011. if (CanAddScopes && IsFuncCall)
  1012. CanAddScopes = IsArgMemOnlyCall;
  1013. if (CanAddScopes)
  1014. for (const Argument *A : NoAliasArgs) {
  1015. if (ObjSet.count(A))
  1016. Scopes.push_back(NewScopes[A]);
  1017. }
  1018. if (!Scopes.empty())
  1019. NI->setMetadata(
  1020. LLVMContext::MD_alias_scope,
  1021. MDNode::concatenate(NI->getMetadata(LLVMContext::MD_alias_scope),
  1022. MDNode::get(CalledFunc->getContext(), Scopes)));
  1023. }
  1024. }
  1025. }
  1026. /// If the inlined function has non-byval align arguments, then
  1027. /// add @llvm.assume-based alignment assumptions to preserve this information.
  1028. static void AddAlignmentAssumptions(CallSite CS, InlineFunctionInfo &IFI) {
  1029. if (!PreserveAlignmentAssumptions || !IFI.GetAssumptionCache)
  1030. return;
  1031. AssumptionCache *AC = &(*IFI.GetAssumptionCache)(*CS.getCaller());
  1032. auto &DL = CS.getCaller()->getParent()->getDataLayout();
  1033. // To avoid inserting redundant assumptions, we should check for assumptions
  1034. // already in the caller. To do this, we might need a DT of the caller.
  1035. DominatorTree DT;
  1036. bool DTCalculated = false;
  1037. Function *CalledFunc = CS.getCalledFunction();
  1038. for (Argument &Arg : CalledFunc->args()) {
  1039. unsigned Align = Arg.getType()->isPointerTy() ? Arg.getParamAlignment() : 0;
  1040. if (Align && !Arg.hasByValOrInAllocaAttr() && !Arg.hasNUses(0)) {
  1041. if (!DTCalculated) {
  1042. DT.recalculate(*CS.getCaller());
  1043. DTCalculated = true;
  1044. }
  1045. // If we can already prove the asserted alignment in the context of the
  1046. // caller, then don't bother inserting the assumption.
  1047. Value *ArgVal = CS.getArgument(Arg.getArgNo());
  1048. if (getKnownAlignment(ArgVal, DL, CS.getInstruction(), AC, &DT) >= Align)
  1049. continue;
  1050. CallInst *NewAsmp = IRBuilder<>(CS.getInstruction())
  1051. .CreateAlignmentAssumption(DL, ArgVal, Align);
  1052. AC->registerAssumption(NewAsmp);
  1053. }
  1054. }
  1055. }
  1056. /// Once we have cloned code over from a callee into the caller,
  1057. /// update the specified callgraph to reflect the changes we made.
  1058. /// Note that it's possible that not all code was copied over, so only
  1059. /// some edges of the callgraph may remain.
  1060. static void UpdateCallGraphAfterInlining(CallSite CS,
  1061. Function::iterator FirstNewBlock,
  1062. ValueToValueMapTy &VMap,
  1063. InlineFunctionInfo &IFI) {
  1064. CallGraph &CG = *IFI.CG;
  1065. const Function *Caller = CS.getCaller();
  1066. const Function *Callee = CS.getCalledFunction();
  1067. CallGraphNode *CalleeNode = CG[Callee];
  1068. CallGraphNode *CallerNode = CG[Caller];
  1069. // Since we inlined some uninlined call sites in the callee into the caller,
  1070. // add edges from the caller to all of the callees of the callee.
  1071. CallGraphNode::iterator I = CalleeNode->begin(), E = CalleeNode->end();
  1072. // Consider the case where CalleeNode == CallerNode.
  1073. CallGraphNode::CalledFunctionsVector CallCache;
  1074. if (CalleeNode == CallerNode) {
  1075. CallCache.assign(I, E);
  1076. I = CallCache.begin();
  1077. E = CallCache.end();
  1078. }
  1079. for (; I != E; ++I) {
  1080. const Value *OrigCall = I->first;
  1081. ValueToValueMapTy::iterator VMI = VMap.find(OrigCall);
  1082. // Only copy the edge if the call was inlined!
  1083. if (VMI == VMap.end() || VMI->second == nullptr)
  1084. continue;
  1085. // If the call was inlined, but then constant folded, there is no edge to
  1086. // add. Check for this case.
  1087. auto *NewCall = dyn_cast<CallBase>(VMI->second);
  1088. if (!NewCall)
  1089. continue;
  1090. // We do not treat intrinsic calls like real function calls because we
  1091. // expect them to become inline code; do not add an edge for an intrinsic.
  1092. if (NewCall->getCalledFunction() &&
  1093. NewCall->getCalledFunction()->isIntrinsic())
  1094. continue;
  1095. // Remember that this call site got inlined for the client of
  1096. // InlineFunction.
  1097. IFI.InlinedCalls.push_back(NewCall);
  1098. // It's possible that inlining the callsite will cause it to go from an
  1099. // indirect to a direct call by resolving a function pointer. If this
  1100. // happens, set the callee of the new call site to a more precise
  1101. // destination. This can also happen if the call graph node of the caller
  1102. // was just unnecessarily imprecise.
  1103. if (!I->second->getFunction())
  1104. if (Function *F = NewCall->getCalledFunction()) {
  1105. // Indirect call site resolved to direct call.
  1106. CallerNode->addCalledFunction(NewCall, CG[F]);
  1107. continue;
  1108. }
  1109. CallerNode->addCalledFunction(NewCall, I->second);
  1110. }
  1111. // Update the call graph by deleting the edge from Callee to Caller. We must
  1112. // do this after the loop above in case Caller and Callee are the same.
  1113. CallerNode->removeCallEdgeFor(*cast<CallBase>(CS.getInstruction()));
  1114. }
  1115. static void HandleByValArgumentInit(Value *Dst, Value *Src, Module *M,
  1116. BasicBlock *InsertBlock,
  1117. InlineFunctionInfo &IFI) {
  1118. Type *AggTy = cast<PointerType>(Src->getType())->getElementType();
  1119. IRBuilder<> Builder(InsertBlock, InsertBlock->begin());
  1120. Value *Size = Builder.getInt64(M->getDataLayout().getTypeStoreSize(AggTy));
  1121. // Always generate a memcpy of alignment 1 here because we don't know
  1122. // the alignment of the src pointer. Other optimizations can infer
  1123. // better alignment.
  1124. Builder.CreateMemCpy(Dst, /*DstAlign*/1, Src, /*SrcAlign*/1, Size);
  1125. }
  1126. /// When inlining a call site that has a byval argument,
  1127. /// we have to make the implicit memcpy explicit by adding it.
  1128. static Value *HandleByValArgument(Value *Arg, Instruction *TheCall,
  1129. const Function *CalledFunc,
  1130. InlineFunctionInfo &IFI,
  1131. unsigned ByValAlignment) {
  1132. PointerType *ArgTy = cast<PointerType>(Arg->getType());
  1133. Type *AggTy = ArgTy->getElementType();
  1134. Function *Caller = TheCall->getFunction();
  1135. const DataLayout &DL = Caller->getParent()->getDataLayout();
  1136. // If the called function is readonly, then it could not mutate the caller's
  1137. // copy of the byval'd memory. In this case, it is safe to elide the copy and
  1138. // temporary.
  1139. if (CalledFunc->onlyReadsMemory()) {
  1140. // If the byval argument has a specified alignment that is greater than the
  1141. // passed in pointer, then we either have to round up the input pointer or
  1142. // give up on this transformation.
  1143. if (ByValAlignment <= 1) // 0 = unspecified, 1 = no particular alignment.
  1144. return Arg;
  1145. AssumptionCache *AC =
  1146. IFI.GetAssumptionCache ? &(*IFI.GetAssumptionCache)(*Caller) : nullptr;
  1147. // If the pointer is already known to be sufficiently aligned, or if we can
  1148. // round it up to a larger alignment, then we don't need a temporary.
  1149. if (getOrEnforceKnownAlignment(Arg, ByValAlignment, DL, TheCall, AC) >=
  1150. ByValAlignment)
  1151. return Arg;
  1152. // Otherwise, we have to make a memcpy to get a safe alignment. This is bad
  1153. // for code quality, but rarely happens and is required for correctness.
  1154. }
  1155. // Create the alloca. If we have DataLayout, use nice alignment.
  1156. unsigned Align = DL.getPrefTypeAlignment(AggTy);
  1157. // If the byval had an alignment specified, we *must* use at least that
  1158. // alignment, as it is required by the byval argument (and uses of the
  1159. // pointer inside the callee).
  1160. Align = std::max(Align, ByValAlignment);
  1161. Value *NewAlloca = new AllocaInst(AggTy, DL.getAllocaAddrSpace(),
  1162. nullptr, Align, Arg->getName(),
  1163. &*Caller->begin()->begin());
  1164. IFI.StaticAllocas.push_back(cast<AllocaInst>(NewAlloca));
  1165. // Uses of the argument in the function should use our new alloca
  1166. // instead.
  1167. return NewAlloca;
  1168. }
  1169. // Check whether this Value is used by a lifetime intrinsic.
  1170. static bool isUsedByLifetimeMarker(Value *V) {
  1171. for (User *U : V->users())
  1172. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U))
  1173. if (II->isLifetimeStartOrEnd())
  1174. return true;
  1175. return false;
  1176. }
  1177. // Check whether the given alloca already has
  1178. // lifetime.start or lifetime.end intrinsics.
  1179. static bool hasLifetimeMarkers(AllocaInst *AI) {
  1180. Type *Ty = AI->getType();
  1181. Type *Int8PtrTy = Type::getInt8PtrTy(Ty->getContext(),
  1182. Ty->getPointerAddressSpace());
  1183. if (Ty == Int8PtrTy)
  1184. return isUsedByLifetimeMarker(AI);
  1185. // Do a scan to find all the casts to i8*.
  1186. for (User *U : AI->users()) {
  1187. if (U->getType() != Int8PtrTy) continue;
  1188. if (U->stripPointerCasts() != AI) continue;
  1189. if (isUsedByLifetimeMarker(U))
  1190. return true;
  1191. }
  1192. return false;
  1193. }
  1194. /// Return the result of AI->isStaticAlloca() if AI were moved to the entry
  1195. /// block. Allocas used in inalloca calls and allocas of dynamic array size
  1196. /// cannot be static.
  1197. static bool allocaWouldBeStaticInEntry(const AllocaInst *AI ) {
  1198. return isa<Constant>(AI->getArraySize()) && !AI->isUsedWithInAlloca();
  1199. }
  1200. /// Update inlined instructions' line numbers to
  1201. /// to encode location where these instructions are inlined.
  1202. static void fixupLineNumbers(Function *Fn, Function::iterator FI,
  1203. Instruction *TheCall, bool CalleeHasDebugInfo) {
  1204. const DebugLoc &TheCallDL = TheCall->getDebugLoc();
  1205. if (!TheCallDL)
  1206. return;
  1207. auto &Ctx = Fn->getContext();
  1208. DILocation *InlinedAtNode = TheCallDL;
  1209. // Create a unique call site, not to be confused with any other call from the
  1210. // same location.
  1211. InlinedAtNode = DILocation::getDistinct(
  1212. Ctx, InlinedAtNode->getLine(), InlinedAtNode->getColumn(),
  1213. InlinedAtNode->getScope(), InlinedAtNode->getInlinedAt());
  1214. // Cache the inlined-at nodes as they're built so they are reused, without
  1215. // this every instruction's inlined-at chain would become distinct from each
  1216. // other.
  1217. DenseMap<const MDNode *, MDNode *> IANodes;
  1218. for (; FI != Fn->end(); ++FI) {
  1219. for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
  1220. BI != BE; ++BI) {
  1221. if (DebugLoc DL = BI->getDebugLoc()) {
  1222. auto IA = DebugLoc::appendInlinedAt(DL, InlinedAtNode, BI->getContext(),
  1223. IANodes);
  1224. auto IDL = DebugLoc::get(DL.getLine(), DL.getCol(), DL.getScope(), IA);
  1225. BI->setDebugLoc(IDL);
  1226. continue;
  1227. }
  1228. if (CalleeHasDebugInfo)
  1229. continue;
  1230. // If the inlined instruction has no line number, make it look as if it
  1231. // originates from the call location. This is important for
  1232. // ((__always_inline__, __nodebug__)) functions which must use caller
  1233. // location for all instructions in their function body.
  1234. // Don't update static allocas, as they may get moved later.
  1235. if (auto *AI = dyn_cast<AllocaInst>(BI))
  1236. if (allocaWouldBeStaticInEntry(AI))
  1237. continue;
  1238. BI->setDebugLoc(TheCallDL);
  1239. }
  1240. }
  1241. }
  1242. /// Update the block frequencies of the caller after a callee has been inlined.
  1243. ///
  1244. /// Each block cloned into the caller has its block frequency scaled by the
  1245. /// ratio of CallSiteFreq/CalleeEntryFreq. This ensures that the cloned copy of
  1246. /// callee's entry block gets the same frequency as the callsite block and the
  1247. /// relative frequencies of all cloned blocks remain the same after cloning.
  1248. static void updateCallerBFI(BasicBlock *CallSiteBlock,
  1249. const ValueToValueMapTy &VMap,
  1250. BlockFrequencyInfo *CallerBFI,
  1251. BlockFrequencyInfo *CalleeBFI,
  1252. const BasicBlock &CalleeEntryBlock) {
  1253. SmallPtrSet<BasicBlock *, 16> ClonedBBs;
  1254. for (auto const &Entry : VMap) {
  1255. if (!isa<BasicBlock>(Entry.first) || !Entry.second)
  1256. continue;
  1257. auto *OrigBB = cast<BasicBlock>(Entry.first);
  1258. auto *ClonedBB = cast<BasicBlock>(Entry.second);
  1259. uint64_t Freq = CalleeBFI->getBlockFreq(OrigBB).getFrequency();
  1260. if (!ClonedBBs.insert(ClonedBB).second) {
  1261. // Multiple blocks in the callee might get mapped to one cloned block in
  1262. // the caller since we prune the callee as we clone it. When that happens,
  1263. // we want to use the maximum among the original blocks' frequencies.
  1264. uint64_t NewFreq = CallerBFI->getBlockFreq(ClonedBB).getFrequency();
  1265. if (NewFreq > Freq)
  1266. Freq = NewFreq;
  1267. }
  1268. CallerBFI->setBlockFreq(ClonedBB, Freq);
  1269. }
  1270. BasicBlock *EntryClone = cast<BasicBlock>(VMap.lookup(&CalleeEntryBlock));
  1271. CallerBFI->setBlockFreqAndScale(
  1272. EntryClone, CallerBFI->getBlockFreq(CallSiteBlock).getFrequency(),
  1273. ClonedBBs);
  1274. }
  1275. /// Update the branch metadata for cloned call instructions.
  1276. static void updateCallProfile(Function *Callee, const ValueToValueMapTy &VMap,
  1277. const ProfileCount &CalleeEntryCount,
  1278. const Instruction *TheCall,
  1279. ProfileSummaryInfo *PSI,
  1280. BlockFrequencyInfo *CallerBFI) {
  1281. if (!CalleeEntryCount.hasValue() || CalleeEntryCount.isSynthetic() ||
  1282. CalleeEntryCount.getCount() < 1)
  1283. return;
  1284. auto CallSiteCount = PSI ? PSI->getProfileCount(TheCall, CallerBFI) : None;
  1285. int64_t CallCount =
  1286. std::min(CallSiteCount.hasValue() ? CallSiteCount.getValue() : 0,
  1287. CalleeEntryCount.getCount());
  1288. updateProfileCallee(Callee, -CallCount, &VMap);
  1289. }
  1290. void llvm::updateProfileCallee(
  1291. Function *Callee, int64_t entryDelta,
  1292. const ValueMap<const Value *, WeakTrackingVH> *VMap) {
  1293. auto CalleeCount = Callee->getEntryCount();
  1294. if (!CalleeCount.hasValue())
  1295. return;
  1296. uint64_t priorEntryCount = CalleeCount.getCount();
  1297. uint64_t newEntryCount = priorEntryCount;
  1298. // Since CallSiteCount is an estimate, it could exceed the original callee
  1299. // count and has to be set to 0 so guard against underflow.
  1300. if (entryDelta < 0 && static_cast<uint64_t>(-entryDelta) > priorEntryCount)
  1301. newEntryCount = 0;
  1302. else
  1303. newEntryCount = priorEntryCount + entryDelta;
  1304. Callee->setEntryCount(newEntryCount);
  1305. // During inlining ?
  1306. if (VMap) {
  1307. uint64_t cloneEntryCount = priorEntryCount - newEntryCount;
  1308. for (auto const &Entry : *VMap)
  1309. if (isa<CallInst>(Entry.first))
  1310. if (auto *CI = dyn_cast_or_null<CallInst>(Entry.second))
  1311. CI->updateProfWeight(cloneEntryCount, priorEntryCount);
  1312. }
  1313. for (BasicBlock &BB : *Callee)
  1314. // No need to update the callsite if it is pruned during inlining.
  1315. if (!VMap || VMap->count(&BB))
  1316. for (Instruction &I : BB)
  1317. if (CallInst *CI = dyn_cast<CallInst>(&I))
  1318. CI->updateProfWeight(newEntryCount, priorEntryCount);
  1319. }
  1320. /// This function inlines the called function into the basic block of the
  1321. /// caller. This returns false if it is not possible to inline this call.
  1322. /// The program is still in a well defined state if this occurs though.
  1323. ///
  1324. /// Note that this only does one level of inlining. For example, if the
  1325. /// instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
  1326. /// exists in the instruction stream. Similarly this will inline a recursive
  1327. /// function by one level.
  1328. llvm::InlineResult llvm::InlineFunction(CallSite CS, InlineFunctionInfo &IFI,
  1329. AAResults *CalleeAAR,
  1330. bool InsertLifetime,
  1331. Function *ForwardVarArgsTo) {
  1332. Instruction *TheCall = CS.getInstruction();
  1333. assert(TheCall->getParent() && TheCall->getFunction()
  1334. && "Instruction not in function!");
  1335. // FIXME: we don't inline callbr yet.
  1336. if (isa<CallBrInst>(TheCall))
  1337. return false;
  1338. // If IFI has any state in it, zap it before we fill it in.
  1339. IFI.reset();
  1340. Function *CalledFunc = CS.getCalledFunction();
  1341. if (!CalledFunc || // Can't inline external function or indirect
  1342. CalledFunc->isDeclaration()) // call!
  1343. return "external or indirect";
  1344. // The inliner does not know how to inline through calls with operand bundles
  1345. // in general ...
  1346. if (CS.hasOperandBundles()) {
  1347. for (int i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
  1348. uint32_t Tag = CS.getOperandBundleAt(i).getTagID();
  1349. // ... but it knows how to inline through "deopt" operand bundles ...
  1350. if (Tag == LLVMContext::OB_deopt)
  1351. continue;
  1352. // ... and "funclet" operand bundles.
  1353. if (Tag == LLVMContext::OB_funclet)
  1354. continue;
  1355. return "unsupported operand bundle";
  1356. }
  1357. }
  1358. // If the call to the callee cannot throw, set the 'nounwind' flag on any
  1359. // calls that we inline.
  1360. bool MarkNoUnwind = CS.doesNotThrow();
  1361. BasicBlock *OrigBB = TheCall->getParent();
  1362. Function *Caller = OrigBB->getParent();
  1363. // GC poses two hazards to inlining, which only occur when the callee has GC:
  1364. // 1. If the caller has no GC, then the callee's GC must be propagated to the
  1365. // caller.
  1366. // 2. If the caller has a differing GC, it is invalid to inline.
  1367. if (CalledFunc->hasGC()) {
  1368. if (!Caller->hasGC())
  1369. Caller->setGC(CalledFunc->getGC());
  1370. else if (CalledFunc->getGC() != Caller->getGC())
  1371. return "incompatible GC";
  1372. }
  1373. // Get the personality function from the callee if it contains a landing pad.
  1374. Constant *CalledPersonality =
  1375. CalledFunc->hasPersonalityFn()
  1376. ? CalledFunc->getPersonalityFn()->stripPointerCasts()
  1377. : nullptr;
  1378. // Find the personality function used by the landing pads of the caller. If it
  1379. // exists, then check to see that it matches the personality function used in
  1380. // the callee.
  1381. Constant *CallerPersonality =
  1382. Caller->hasPersonalityFn()
  1383. ? Caller->getPersonalityFn()->stripPointerCasts()
  1384. : nullptr;
  1385. if (CalledPersonality) {
  1386. if (!CallerPersonality)
  1387. Caller->setPersonalityFn(CalledPersonality);
  1388. // If the personality functions match, then we can perform the
  1389. // inlining. Otherwise, we can't inline.
  1390. // TODO: This isn't 100% true. Some personality functions are proper
  1391. // supersets of others and can be used in place of the other.
  1392. else if (CalledPersonality != CallerPersonality)
  1393. return "incompatible personality";
  1394. }
  1395. // We need to figure out which funclet the callsite was in so that we may
  1396. // properly nest the callee.
  1397. Instruction *CallSiteEHPad = nullptr;
  1398. if (CallerPersonality) {
  1399. EHPersonality Personality = classifyEHPersonality(CallerPersonality);
  1400. if (isScopedEHPersonality(Personality)) {
  1401. Optional<OperandBundleUse> ParentFunclet =
  1402. CS.getOperandBundle(LLVMContext::OB_funclet);
  1403. if (ParentFunclet)
  1404. CallSiteEHPad = cast<FuncletPadInst>(ParentFunclet->Inputs.front());
  1405. // OK, the inlining site is legal. What about the target function?
  1406. if (CallSiteEHPad) {
  1407. if (Personality == EHPersonality::MSVC_CXX) {
  1408. // The MSVC personality cannot tolerate catches getting inlined into
  1409. // cleanup funclets.
  1410. if (isa<CleanupPadInst>(CallSiteEHPad)) {
  1411. // Ok, the call site is within a cleanuppad. Let's check the callee
  1412. // for catchpads.
  1413. for (const BasicBlock &CalledBB : *CalledFunc) {
  1414. if (isa<CatchSwitchInst>(CalledBB.getFirstNonPHI()))
  1415. return "catch in cleanup funclet";
  1416. }
  1417. }
  1418. } else if (isAsynchronousEHPersonality(Personality)) {
  1419. // SEH is even less tolerant, there may not be any sort of exceptional
  1420. // funclet in the callee.
  1421. for (const BasicBlock &CalledBB : *CalledFunc) {
  1422. if (CalledBB.isEHPad())
  1423. return "SEH in cleanup funclet";
  1424. }
  1425. }
  1426. }
  1427. }
  1428. }
  1429. // Determine if we are dealing with a call in an EHPad which does not unwind
  1430. // to caller.
  1431. bool EHPadForCallUnwindsLocally = false;
  1432. if (CallSiteEHPad && CS.isCall()) {
  1433. UnwindDestMemoTy FuncletUnwindMap;
  1434. Value *CallSiteUnwindDestToken =
  1435. getUnwindDestToken(CallSiteEHPad, FuncletUnwindMap);
  1436. EHPadForCallUnwindsLocally =
  1437. CallSiteUnwindDestToken &&
  1438. !isa<ConstantTokenNone>(CallSiteUnwindDestToken);
  1439. }
  1440. // Get an iterator to the last basic block in the function, which will have
  1441. // the new function inlined after it.
  1442. Function::iterator LastBlock = --Caller->end();
  1443. // Make sure to capture all of the return instructions from the cloned
  1444. // function.
  1445. SmallVector<ReturnInst*, 8> Returns;
  1446. ClonedCodeInfo InlinedFunctionInfo;
  1447. Function::iterator FirstNewBlock;
  1448. { // Scope to destroy VMap after cloning.
  1449. ValueToValueMapTy VMap;
  1450. // Keep a list of pair (dst, src) to emit byval initializations.
  1451. SmallVector<std::pair<Value*, Value*>, 4> ByValInit;
  1452. auto &DL = Caller->getParent()->getDataLayout();
  1453. // Calculate the vector of arguments to pass into the function cloner, which
  1454. // matches up the formal to the actual argument values.
  1455. CallSite::arg_iterator AI = CS.arg_begin();
  1456. unsigned ArgNo = 0;
  1457. for (Function::arg_iterator I = CalledFunc->arg_begin(),
  1458. E = CalledFunc->arg_end(); I != E; ++I, ++AI, ++ArgNo) {
  1459. Value *ActualArg = *AI;
  1460. // When byval arguments actually inlined, we need to make the copy implied
  1461. // by them explicit. However, we don't do this if the callee is readonly
  1462. // or readnone, because the copy would be unneeded: the callee doesn't
  1463. // modify the struct.
  1464. if (CS.isByValArgument(ArgNo)) {
  1465. ActualArg = HandleByValArgument(ActualArg, TheCall, CalledFunc, IFI,
  1466. CalledFunc->getParamAlignment(ArgNo));
  1467. if (ActualArg != *AI)
  1468. ByValInit.push_back(std::make_pair(ActualArg, (Value*) *AI));
  1469. }
  1470. VMap[&*I] = ActualArg;
  1471. }
  1472. // Add alignment assumptions if necessary. We do this before the inlined
  1473. // instructions are actually cloned into the caller so that we can easily
  1474. // check what will be known at the start of the inlined code.
  1475. AddAlignmentAssumptions(CS, IFI);
  1476. // We want the inliner to prune the code as it copies. We would LOVE to
  1477. // have no dead or constant instructions leftover after inlining occurs
  1478. // (which can happen, e.g., because an argument was constant), but we'll be
  1479. // happy with whatever the cloner can do.
  1480. CloneAndPruneFunctionInto(Caller, CalledFunc, VMap,
  1481. /*ModuleLevelChanges=*/false, Returns, ".i",
  1482. &InlinedFunctionInfo, TheCall);
  1483. // Remember the first block that is newly cloned over.
  1484. FirstNewBlock = LastBlock; ++FirstNewBlock;
  1485. if (IFI.CallerBFI != nullptr && IFI.CalleeBFI != nullptr)
  1486. // Update the BFI of blocks cloned into the caller.
  1487. updateCallerBFI(OrigBB, VMap, IFI.CallerBFI, IFI.CalleeBFI,
  1488. CalledFunc->front());
  1489. updateCallProfile(CalledFunc, VMap, CalledFunc->getEntryCount(), TheCall,
  1490. IFI.PSI, IFI.CallerBFI);
  1491. // Inject byval arguments initialization.
  1492. for (std::pair<Value*, Value*> &Init : ByValInit)
  1493. HandleByValArgumentInit(Init.first, Init.second, Caller->getParent(),
  1494. &*FirstNewBlock, IFI);
  1495. Optional<OperandBundleUse> ParentDeopt =
  1496. CS.getOperandBundle(LLVMContext::OB_deopt);
  1497. if (ParentDeopt) {
  1498. SmallVector<OperandBundleDef, 2> OpDefs;
  1499. for (auto &VH : InlinedFunctionInfo.OperandBundleCallSites) {
  1500. Instruction *I = dyn_cast_or_null<Instruction>(VH);
  1501. if (!I) continue; // instruction was DCE'd or RAUW'ed to undef
  1502. OpDefs.clear();
  1503. CallSite ICS(I);
  1504. OpDefs.reserve(ICS.getNumOperandBundles());
  1505. for (unsigned i = 0, e = ICS.getNumOperandBundles(); i < e; ++i) {
  1506. auto ChildOB = ICS.getOperandBundleAt(i);
  1507. if (ChildOB.getTagID() != LLVMContext::OB_deopt) {
  1508. // If the inlined call has other operand bundles, let them be
  1509. OpDefs.emplace_back(ChildOB);
  1510. continue;
  1511. }
  1512. // It may be useful to separate this logic (of handling operand
  1513. // bundles) out to a separate "policy" component if this gets crowded.
  1514. // Prepend the parent's deoptimization continuation to the newly
  1515. // inlined call's deoptimization continuation.
  1516. std::vector<Value *> MergedDeoptArgs;
  1517. MergedDeoptArgs.reserve(ParentDeopt->Inputs.size() +
  1518. ChildOB.Inputs.size());
  1519. MergedDeoptArgs.insert(MergedDeoptArgs.end(),
  1520. ParentDeopt->Inputs.begin(),
  1521. ParentDeopt->Inputs.end());
  1522. MergedDeoptArgs.insert(MergedDeoptArgs.end(), ChildOB.Inputs.begin(),
  1523. ChildOB.Inputs.end());
  1524. OpDefs.emplace_back("deopt", std::move(MergedDeoptArgs));
  1525. }
  1526. Instruction *NewI = nullptr;
  1527. if (isa<CallInst>(I))
  1528. NewI = CallInst::Create(cast<CallInst>(I), OpDefs, I);
  1529. else if (isa<CallBrInst>(I))
  1530. NewI = CallBrInst::Create(cast<CallBrInst>(I), OpDefs, I);
  1531. else
  1532. NewI = InvokeInst::Create(cast<InvokeInst>(I), OpDefs, I);
  1533. // Note: the RAUW does the appropriate fixup in VMap, so we need to do
  1534. // this even if the call returns void.
  1535. I->replaceAllUsesWith(NewI);
  1536. VH = nullptr;
  1537. I->eraseFromParent();
  1538. }
  1539. }
  1540. // Update the callgraph if requested.
  1541. if (IFI.CG)
  1542. UpdateCallGraphAfterInlining(CS, FirstNewBlock, VMap, IFI);
  1543. // For 'nodebug' functions, the associated DISubprogram is always null.
  1544. // Conservatively avoid propagating the callsite debug location to
  1545. // instructions inlined from a function whose DISubprogram is not null.
  1546. fixupLineNumbers(Caller, FirstNewBlock, TheCall,
  1547. CalledFunc->getSubprogram() != nullptr);
  1548. // Clone existing noalias metadata if necessary.
  1549. CloneAliasScopeMetadata(CS, VMap);
  1550. // Add noalias metadata if necessary.
  1551. AddAliasScopeMetadata(CS, VMap, DL, CalleeAAR);
  1552. // Propagate llvm.mem.parallel_loop_access if necessary.
  1553. PropagateParallelLoopAccessMetadata(CS, VMap);
  1554. // Register any cloned assumptions.
  1555. if (IFI.GetAssumptionCache)
  1556. for (BasicBlock &NewBlock :
  1557. make_range(FirstNewBlock->getIterator(), Caller->end()))
  1558. for (Instruction &I : NewBlock) {
  1559. if (auto *II = dyn_cast<IntrinsicInst>(&I))
  1560. if (II->getIntrinsicID() == Intrinsic::assume)
  1561. (*IFI.GetAssumptionCache)(*Caller).registerAssumption(II);
  1562. }
  1563. }
  1564. // If there are any alloca instructions in the block that used to be the entry
  1565. // block for the callee, move them to the entry block of the caller. First
  1566. // calculate which instruction they should be inserted before. We insert the
  1567. // instructions at the end of the current alloca list.
  1568. {
  1569. BasicBlock::iterator InsertPoint = Caller->begin()->begin();
  1570. for (BasicBlock::iterator I = FirstNewBlock->begin(),
  1571. E = FirstNewBlock->end(); I != E; ) {
  1572. AllocaInst *AI = dyn_cast<AllocaInst>(I++);
  1573. if (!AI) continue;
  1574. // If the alloca is now dead, remove it. This often occurs due to code
  1575. // specialization.
  1576. if (AI->use_empty()) {
  1577. AI->eraseFromParent();
  1578. continue;
  1579. }
  1580. if (!allocaWouldBeStaticInEntry(AI))
  1581. continue;
  1582. // Keep track of the static allocas that we inline into the caller.
  1583. IFI.StaticAllocas.push_back(AI);
  1584. // Scan for the block of allocas that we can move over, and move them
  1585. // all at once.
  1586. while (isa<AllocaInst>(I) &&
  1587. allocaWouldBeStaticInEntry(cast<AllocaInst>(I))) {
  1588. IFI.StaticAllocas.push_back(cast<AllocaInst>(I));
  1589. ++I;
  1590. }
  1591. // Transfer all of the allocas over in a block. Using splice means
  1592. // that the instructions aren't removed from the symbol table, then
  1593. // reinserted.
  1594. Caller->getEntryBlock().getInstList().splice(
  1595. InsertPoint, FirstNewBlock->getInstList(), AI->getIterator(), I);
  1596. }
  1597. // Move any dbg.declares describing the allocas into the entry basic block.
  1598. DIBuilder DIB(*Caller->getParent());
  1599. for (auto &AI : IFI.StaticAllocas)
  1600. replaceDbgDeclareForAlloca(AI, AI, DIB, DIExpression::NoDeref, 0,
  1601. DIExpression::NoDeref);
  1602. }
  1603. SmallVector<Value*,4> VarArgsToForward;
  1604. SmallVector<AttributeSet, 4> VarArgsAttrs;
  1605. for (unsigned i = CalledFunc->getFunctionType()->getNumParams();
  1606. i < CS.getNumArgOperands(); i++) {
  1607. VarArgsToForward.push_back(CS.getArgOperand(i));
  1608. VarArgsAttrs.push_back(CS.getAttributes().getParamAttributes(i));
  1609. }
  1610. bool InlinedMustTailCalls = false, InlinedDeoptimizeCalls = false;
  1611. if (InlinedFunctionInfo.ContainsCalls) {
  1612. CallInst::TailCallKind CallSiteTailKind = CallInst::TCK_None;
  1613. if (CallInst *CI = dyn_cast<CallInst>(TheCall))
  1614. CallSiteTailKind = CI->getTailCallKind();
  1615. // For inlining purposes, the "notail" marker is the same as no marker.
  1616. if (CallSiteTailKind == CallInst::TCK_NoTail)
  1617. CallSiteTailKind = CallInst::TCK_None;
  1618. for (Function::iterator BB = FirstNewBlock, E = Caller->end(); BB != E;
  1619. ++BB) {
  1620. for (auto II = BB->begin(); II != BB->end();) {
  1621. Instruction &I = *II++;
  1622. CallInst *CI = dyn_cast<CallInst>(&I);
  1623. if (!CI)
  1624. continue;
  1625. // Forward varargs from inlined call site to calls to the
  1626. // ForwardVarArgsTo function, if requested, and to musttail calls.
  1627. if (!VarArgsToForward.empty() &&
  1628. ((ForwardVarArgsTo &&
  1629. CI->getCalledFunction() == ForwardVarArgsTo) ||
  1630. CI->isMustTailCall())) {
  1631. // Collect attributes for non-vararg parameters.
  1632. AttributeList Attrs = CI->getAttributes();
  1633. SmallVector<AttributeSet, 8> ArgAttrs;
  1634. if (!Attrs.isEmpty() || !VarArgsAttrs.empty()) {
  1635. for (unsigned ArgNo = 0;
  1636. ArgNo < CI->getFunctionType()->getNumParams(); ++ArgNo)
  1637. ArgAttrs.push_back(Attrs.getParamAttributes(ArgNo));
  1638. }
  1639. // Add VarArg attributes.
  1640. ArgAttrs.append(VarArgsAttrs.begin(), VarArgsAttrs.end());
  1641. Attrs = AttributeList::get(CI->getContext(), Attrs.getFnAttributes(),
  1642. Attrs.getRetAttributes(), ArgAttrs);
  1643. // Add VarArgs to existing parameters.
  1644. SmallVector<Value *, 6> Params(CI->arg_operands());
  1645. Params.append(VarArgsToForward.begin(), VarArgsToForward.end());
  1646. CallInst *NewCI = CallInst::Create(
  1647. CI->getFunctionType(), CI->getCalledOperand(), Params, "", CI);
  1648. NewCI->setDebugLoc(CI->getDebugLoc());
  1649. NewCI->setAttributes(Attrs);
  1650. NewCI->setCallingConv(CI->getCallingConv());
  1651. CI->replaceAllUsesWith(NewCI);
  1652. CI->eraseFromParent();
  1653. CI = NewCI;
  1654. }
  1655. if (Function *F = CI->getCalledFunction())
  1656. InlinedDeoptimizeCalls |=
  1657. F->getIntrinsicID() == Intrinsic::experimental_deoptimize;
  1658. // We need to reduce the strength of any inlined tail calls. For
  1659. // musttail, we have to avoid introducing potential unbounded stack
  1660. // growth. For example, if functions 'f' and 'g' are mutually recursive
  1661. // with musttail, we can inline 'g' into 'f' so long as we preserve
  1662. // musttail on the cloned call to 'f'. If either the inlined call site
  1663. // or the cloned call site is *not* musttail, the program already has
  1664. // one frame of stack growth, so it's safe to remove musttail. Here is
  1665. // a table of example transformations:
  1666. //
  1667. // f -> musttail g -> musttail f ==> f -> musttail f
  1668. // f -> musttail g -> tail f ==> f -> tail f
  1669. // f -> g -> musttail f ==> f -> f
  1670. // f -> g -> tail f ==> f -> f
  1671. //
  1672. // Inlined notail calls should remain notail calls.
  1673. CallInst::TailCallKind ChildTCK = CI->getTailCallKind();
  1674. if (ChildTCK != CallInst::TCK_NoTail)
  1675. ChildTCK = std::min(CallSiteTailKind, ChildTCK);
  1676. CI->setTailCallKind(ChildTCK);
  1677. InlinedMustTailCalls |= CI->isMustTailCall();
  1678. // Calls inlined through a 'nounwind' call site should be marked
  1679. // 'nounwind'.
  1680. if (MarkNoUnwind)
  1681. CI->setDoesNotThrow();
  1682. }
  1683. }
  1684. }
  1685. // Leave lifetime markers for the static alloca's, scoping them to the
  1686. // function we just inlined.
  1687. if (InsertLifetime && !IFI.StaticAllocas.empty()) {
  1688. IRBuilder<> builder(&FirstNewBlock->front());
  1689. for (unsigned ai = 0, ae = IFI.StaticAllocas.size(); ai != ae; ++ai) {
  1690. AllocaInst *AI = IFI.StaticAllocas[ai];
  1691. // Don't mark swifterror allocas. They can't have bitcast uses.
  1692. if (AI->isSwiftError())
  1693. continue;
  1694. // If the alloca is already scoped to something smaller than the whole
  1695. // function then there's no need to add redundant, less accurate markers.
  1696. if (hasLifetimeMarkers(AI))
  1697. continue;
  1698. // Try to determine the size of the allocation.
  1699. ConstantInt *AllocaSize = nullptr;
  1700. if (ConstantInt *AIArraySize =
  1701. dyn_cast<ConstantInt>(AI->getArraySize())) {
  1702. auto &DL = Caller->getParent()->getDataLayout();
  1703. Type *AllocaType = AI->getAllocatedType();
  1704. uint64_t AllocaTypeSize = DL.getTypeAllocSize(AllocaType);
  1705. uint64_t AllocaArraySize = AIArraySize->getLimitedValue();
  1706. // Don't add markers for zero-sized allocas.
  1707. if (AllocaArraySize == 0)
  1708. continue;
  1709. // Check that array size doesn't saturate uint64_t and doesn't
  1710. // overflow when it's multiplied by type size.
  1711. if (AllocaArraySize != std::numeric_limits<uint64_t>::max() &&
  1712. std::numeric_limits<uint64_t>::max() / AllocaArraySize >=
  1713. AllocaTypeSize) {
  1714. AllocaSize = ConstantInt::get(Type::getInt64Ty(AI->getContext()),
  1715. AllocaArraySize * AllocaTypeSize);
  1716. }
  1717. }
  1718. builder.CreateLifetimeStart(AI, AllocaSize);
  1719. for (ReturnInst *RI : Returns) {
  1720. // Don't insert llvm.lifetime.end calls between a musttail or deoptimize
  1721. // call and a return. The return kills all local allocas.
  1722. if (InlinedMustTailCalls &&
  1723. RI->getParent()->getTerminatingMustTailCall())
  1724. continue;
  1725. if (InlinedDeoptimizeCalls &&
  1726. RI->getParent()->getTerminatingDeoptimizeCall())
  1727. continue;
  1728. IRBuilder<>(RI).CreateLifetimeEnd(AI, AllocaSize);
  1729. }
  1730. }
  1731. }
  1732. // If the inlined code contained dynamic alloca instructions, wrap the inlined
  1733. // code with llvm.stacksave/llvm.stackrestore intrinsics.
  1734. if (InlinedFunctionInfo.ContainsDynamicAllocas) {
  1735. Module *M = Caller->getParent();
  1736. // Get the two intrinsics we care about.
  1737. Function *StackSave = Intrinsic::getDeclaration(M, Intrinsic::stacksave);
  1738. Function *StackRestore=Intrinsic::getDeclaration(M,Intrinsic::stackrestore);
  1739. // Insert the llvm.stacksave.
  1740. CallInst *SavedPtr = IRBuilder<>(&*FirstNewBlock, FirstNewBlock->begin())
  1741. .CreateCall(StackSave, {}, "savedstack");
  1742. // Insert a call to llvm.stackrestore before any return instructions in the
  1743. // inlined function.
  1744. for (ReturnInst *RI : Returns) {
  1745. // Don't insert llvm.stackrestore calls between a musttail or deoptimize
  1746. // call and a return. The return will restore the stack pointer.
  1747. if (InlinedMustTailCalls && RI->getParent()->getTerminatingMustTailCall())
  1748. continue;
  1749. if (InlinedDeoptimizeCalls && RI->getParent()->getTerminatingDeoptimizeCall())
  1750. continue;
  1751. IRBuilder<>(RI).CreateCall(StackRestore, SavedPtr);
  1752. }
  1753. }
  1754. // If we are inlining for an invoke instruction, we must make sure to rewrite
  1755. // any call instructions into invoke instructions. This is sensitive to which
  1756. // funclet pads were top-level in the inlinee, so must be done before
  1757. // rewriting the "parent pad" links.
  1758. if (auto *II = dyn_cast<InvokeInst>(TheCall)) {
  1759. BasicBlock *UnwindDest = II->getUnwindDest();
  1760. Instruction *FirstNonPHI = UnwindDest->getFirstNonPHI();
  1761. if (isa<LandingPadInst>(FirstNonPHI)) {
  1762. HandleInlinedLandingPad(II, &*FirstNewBlock, InlinedFunctionInfo);
  1763. } else {
  1764. HandleInlinedEHPad(II, &*FirstNewBlock, InlinedFunctionInfo);
  1765. }
  1766. }
  1767. // Update the lexical scopes of the new funclets and callsites.
  1768. // Anything that had 'none' as its parent is now nested inside the callsite's
  1769. // EHPad.
  1770. if (CallSiteEHPad) {
  1771. for (Function::iterator BB = FirstNewBlock->getIterator(),
  1772. E = Caller->end();
  1773. BB != E; ++BB) {
  1774. // Add bundle operands to any top-level call sites.
  1775. SmallVector<OperandBundleDef, 1> OpBundles;
  1776. for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E;) {
  1777. Instruction *I = &*BBI++;
  1778. CallSite CS(I);
  1779. if (!CS)
  1780. continue;
  1781. // Skip call sites which are nounwind intrinsics.
  1782. auto *CalledFn =
  1783. dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts());
  1784. if (CalledFn && CalledFn->isIntrinsic() && CS.doesNotThrow())
  1785. continue;
  1786. // Skip call sites which already have a "funclet" bundle.
  1787. if (CS.getOperandBundle(LLVMContext::OB_funclet))
  1788. continue;
  1789. CS.getOperandBundlesAsDefs(OpBundles);
  1790. OpBundles.emplace_back("funclet", CallSiteEHPad);
  1791. Instruction *NewInst;
  1792. if (CS.isCall())
  1793. NewInst = CallInst::Create(cast<CallInst>(I), OpBundles, I);
  1794. else if (CS.isCallBr())
  1795. NewInst = CallBrInst::Create(cast<CallBrInst>(I), OpBundles, I);
  1796. else
  1797. NewInst = InvokeInst::Create(cast<InvokeInst>(I), OpBundles, I);
  1798. NewInst->takeName(I);
  1799. I->replaceAllUsesWith(NewInst);
  1800. I->eraseFromParent();
  1801. OpBundles.clear();
  1802. }
  1803. // It is problematic if the inlinee has a cleanupret which unwinds to
  1804. // caller and we inline it into a call site which doesn't unwind but into
  1805. // an EH pad that does. Such an edge must be dynamically unreachable.
  1806. // As such, we replace the cleanupret with unreachable.
  1807. if (auto *CleanupRet = dyn_cast<CleanupReturnInst>(BB->getTerminator()))
  1808. if (CleanupRet->unwindsToCaller() && EHPadForCallUnwindsLocally)
  1809. changeToUnreachable(CleanupRet, /*UseLLVMTrap=*/false);
  1810. Instruction *I = BB->getFirstNonPHI();
  1811. if (!I->isEHPad())
  1812. continue;
  1813. if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(I)) {
  1814. if (isa<ConstantTokenNone>(CatchSwitch->getParentPad()))
  1815. CatchSwitch->setParentPad(CallSiteEHPad);
  1816. } else {
  1817. auto *FPI = cast<FuncletPadInst>(I);
  1818. if (isa<ConstantTokenNone>(FPI->getParentPad()))
  1819. FPI->setParentPad(CallSiteEHPad);
  1820. }
  1821. }
  1822. }
  1823. if (InlinedDeoptimizeCalls) {
  1824. // We need to at least remove the deoptimizing returns from the Return set,
  1825. // so that the control flow from those returns does not get merged into the
  1826. // caller (but terminate it instead). If the caller's return type does not
  1827. // match the callee's return type, we also need to change the return type of
  1828. // the intrinsic.
  1829. if (Caller->getReturnType() == TheCall->getType()) {
  1830. auto NewEnd = llvm::remove_if(Returns, [](ReturnInst *RI) {
  1831. return RI->getParent()->getTerminatingDeoptimizeCall() != nullptr;
  1832. });
  1833. Returns.erase(NewEnd, Returns.end());
  1834. } else {
  1835. SmallVector<ReturnInst *, 8> NormalReturns;
  1836. Function *NewDeoptIntrinsic = Intrinsic::getDeclaration(
  1837. Caller->getParent(), Intrinsic::experimental_deoptimize,
  1838. {Caller->getReturnType()});
  1839. for (ReturnInst *RI : Returns) {
  1840. CallInst *DeoptCall = RI->getParent()->getTerminatingDeoptimizeCall();
  1841. if (!DeoptCall) {
  1842. NormalReturns.push_back(RI);
  1843. continue;
  1844. }
  1845. // The calling convention on the deoptimize call itself may be bogus,
  1846. // since the code we're inlining may have undefined behavior (and may
  1847. // never actually execute at runtime); but all
  1848. // @llvm.experimental.deoptimize declarations have to have the same
  1849. // calling convention in a well-formed module.
  1850. auto CallingConv = DeoptCall->getCalledFunction()->getCallingConv();
  1851. NewDeoptIntrinsic->setCallingConv(CallingConv);
  1852. auto *CurBB = RI->getParent();
  1853. RI->eraseFromParent();
  1854. SmallVector<Value *, 4> CallArgs(DeoptCall->arg_begin(),
  1855. DeoptCall->arg_end());
  1856. SmallVector<OperandBundleDef, 1> OpBundles;
  1857. DeoptCall->getOperandBundlesAsDefs(OpBundles);
  1858. DeoptCall->eraseFromParent();
  1859. assert(!OpBundles.empty() &&
  1860. "Expected at least the deopt operand bundle");
  1861. IRBuilder<> Builder(CurBB);
  1862. CallInst *NewDeoptCall =
  1863. Builder.CreateCall(NewDeoptIntrinsic, CallArgs, OpBundles);
  1864. NewDeoptCall->setCallingConv(CallingConv);
  1865. if (NewDeoptCall->getType()->isVoidTy())
  1866. Builder.CreateRetVoid();
  1867. else
  1868. Builder.CreateRet(NewDeoptCall);
  1869. }
  1870. // Leave behind the normal returns so we can merge control flow.
  1871. std::swap(Returns, NormalReturns);
  1872. }
  1873. }
  1874. // Handle any inlined musttail call sites. In order for a new call site to be
  1875. // musttail, the source of the clone and the inlined call site must have been
  1876. // musttail. Therefore it's safe to return without merging control into the
  1877. // phi below.
  1878. if (InlinedMustTailCalls) {
  1879. // Check if we need to bitcast the result of any musttail calls.
  1880. Type *NewRetTy = Caller->getReturnType();
  1881. bool NeedBitCast = !TheCall->use_empty() && TheCall->getType() != NewRetTy;
  1882. // Handle the returns preceded by musttail calls separately.
  1883. SmallVector<ReturnInst *, 8> NormalReturns;
  1884. for (ReturnInst *RI : Returns) {
  1885. CallInst *ReturnedMustTail =
  1886. RI->getParent()->getTerminatingMustTailCall();
  1887. if (!ReturnedMustTail) {
  1888. NormalReturns.push_back(RI);
  1889. continue;
  1890. }
  1891. if (!NeedBitCast)
  1892. continue;
  1893. // Delete the old return and any preceding bitcast.
  1894. BasicBlock *CurBB = RI->getParent();
  1895. auto *OldCast = dyn_cast_or_null<BitCastInst>(RI->getReturnValue());
  1896. RI->eraseFromParent();
  1897. if (OldCast)
  1898. OldCast->eraseFromParent();
  1899. // Insert a new bitcast and return with the right type.
  1900. IRBuilder<> Builder(CurBB);
  1901. Builder.CreateRet(Builder.CreateBitCast(ReturnedMustTail, NewRetTy));
  1902. }
  1903. // Leave behind the normal returns so we can merge control flow.
  1904. std::swap(Returns, NormalReturns);
  1905. }
  1906. // Now that all of the transforms on the inlined code have taken place but
  1907. // before we splice the inlined code into the CFG and lose track of which
  1908. // blocks were actually inlined, collect the call sites. We only do this if
  1909. // call graph updates weren't requested, as those provide value handle based
  1910. // tracking of inlined call sites instead.
  1911. if (InlinedFunctionInfo.ContainsCalls && !IFI.CG) {
  1912. // Otherwise just collect the raw call sites that were inlined.
  1913. for (BasicBlock &NewBB :
  1914. make_range(FirstNewBlock->getIterator(), Caller->end()))
  1915. for (Instruction &I : NewBB)
  1916. if (auto CS = CallSite(&I))
  1917. IFI.InlinedCallSites.push_back(CS);
  1918. }
  1919. // If we cloned in _exactly one_ basic block, and if that block ends in a
  1920. // return instruction, we splice the body of the inlined callee directly into
  1921. // the calling basic block.
  1922. if (Returns.size() == 1 && std::distance(FirstNewBlock, Caller->end()) == 1) {
  1923. // Move all of the instructions right before the call.
  1924. OrigBB->getInstList().splice(TheCall->getIterator(),
  1925. FirstNewBlock->getInstList(),
  1926. FirstNewBlock->begin(), FirstNewBlock->end());
  1927. // Remove the cloned basic block.
  1928. Caller->getBasicBlockList().pop_back();
  1929. // If the call site was an invoke instruction, add a branch to the normal
  1930. // destination.
  1931. if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
  1932. BranchInst *NewBr = BranchInst::Create(II->getNormalDest(), TheCall);
  1933. NewBr->setDebugLoc(Returns[0]->getDebugLoc());
  1934. }
  1935. // If the return instruction returned a value, replace uses of the call with
  1936. // uses of the returned value.
  1937. if (!TheCall->use_empty()) {
  1938. ReturnInst *R = Returns[0];
  1939. if (TheCall == R->getReturnValue())
  1940. TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
  1941. else
  1942. TheCall->replaceAllUsesWith(R->getReturnValue());
  1943. }
  1944. // Since we are now done with the Call/Invoke, we can delete it.
  1945. TheCall->eraseFromParent();
  1946. // Since we are now done with the return instruction, delete it also.
  1947. Returns[0]->eraseFromParent();
  1948. // We are now done with the inlining.
  1949. return true;
  1950. }
  1951. // Otherwise, we have the normal case, of more than one block to inline or
  1952. // multiple return sites.
  1953. // We want to clone the entire callee function into the hole between the
  1954. // "starter" and "ender" blocks. How we accomplish this depends on whether
  1955. // this is an invoke instruction or a call instruction.
  1956. BasicBlock *AfterCallBB;
  1957. BranchInst *CreatedBranchToNormalDest = nullptr;
  1958. if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
  1959. // Add an unconditional branch to make this look like the CallInst case...
  1960. CreatedBranchToNormalDest = BranchInst::Create(II->getNormalDest(), TheCall);
  1961. // Split the basic block. This guarantees that no PHI nodes will have to be
  1962. // updated due to new incoming edges, and make the invoke case more
  1963. // symmetric to the call case.
  1964. AfterCallBB =
  1965. OrigBB->splitBasicBlock(CreatedBranchToNormalDest->getIterator(),
  1966. CalledFunc->getName() + ".exit");
  1967. } else { // It's a call
  1968. // If this is a call instruction, we need to split the basic block that
  1969. // the call lives in.
  1970. //
  1971. AfterCallBB = OrigBB->splitBasicBlock(TheCall->getIterator(),
  1972. CalledFunc->getName() + ".exit");
  1973. }
  1974. if (IFI.CallerBFI) {
  1975. // Copy original BB's block frequency to AfterCallBB
  1976. IFI.CallerBFI->setBlockFreq(
  1977. AfterCallBB, IFI.CallerBFI->getBlockFreq(OrigBB).getFrequency());
  1978. }
  1979. // Change the branch that used to go to AfterCallBB to branch to the first
  1980. // basic block of the inlined function.
  1981. //
  1982. Instruction *Br = OrigBB->getTerminator();
  1983. assert(Br && Br->getOpcode() == Instruction::Br &&
  1984. "splitBasicBlock broken!");
  1985. Br->setOperand(0, &*FirstNewBlock);
  1986. // Now that the function is correct, make it a little bit nicer. In
  1987. // particular, move the basic blocks inserted from the end of the function
  1988. // into the space made by splitting the source basic block.
  1989. Caller->getBasicBlockList().splice(AfterCallBB->getIterator(),
  1990. Caller->getBasicBlockList(), FirstNewBlock,
  1991. Caller->end());
  1992. // Handle all of the return instructions that we just cloned in, and eliminate
  1993. // any users of the original call/invoke instruction.
  1994. Type *RTy = CalledFunc->getReturnType();
  1995. PHINode *PHI = nullptr;
  1996. if (Returns.size() > 1) {
  1997. // The PHI node should go at the front of the new basic block to merge all
  1998. // possible incoming values.
  1999. if (!TheCall->use_empty()) {
  2000. PHI = PHINode::Create(RTy, Returns.size(), TheCall->getName(),
  2001. &AfterCallBB->front());
  2002. // Anything that used the result of the function call should now use the
  2003. // PHI node as their operand.
  2004. TheCall->replaceAllUsesWith(PHI);
  2005. }
  2006. // Loop over all of the return instructions adding entries to the PHI node
  2007. // as appropriate.
  2008. if (PHI) {
  2009. for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
  2010. ReturnInst *RI = Returns[i];
  2011. assert(RI->getReturnValue()->getType() == PHI->getType() &&
  2012. "Ret value not consistent in function!");
  2013. PHI->addIncoming(RI->getReturnValue(), RI->getParent());
  2014. }
  2015. }
  2016. // Add a branch to the merge points and remove return instructions.
  2017. DebugLoc Loc;
  2018. for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
  2019. ReturnInst *RI = Returns[i];
  2020. BranchInst* BI = BranchInst::Create(AfterCallBB, RI);
  2021. Loc = RI->getDebugLoc();
  2022. BI->setDebugLoc(Loc);
  2023. RI->eraseFromParent();
  2024. }
  2025. // We need to set the debug location to *somewhere* inside the
  2026. // inlined function. The line number may be nonsensical, but the
  2027. // instruction will at least be associated with the right
  2028. // function.
  2029. if (CreatedBranchToNormalDest)
  2030. CreatedBranchToNormalDest->setDebugLoc(Loc);
  2031. } else if (!Returns.empty()) {
  2032. // Otherwise, if there is exactly one return value, just replace anything
  2033. // using the return value of the call with the computed value.
  2034. if (!TheCall->use_empty()) {
  2035. if (TheCall == Returns[0]->getReturnValue())
  2036. TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
  2037. else
  2038. TheCall->replaceAllUsesWith(Returns[0]->getReturnValue());
  2039. }
  2040. // Update PHI nodes that use the ReturnBB to use the AfterCallBB.
  2041. BasicBlock *ReturnBB = Returns[0]->getParent();
  2042. ReturnBB->replaceAllUsesWith(AfterCallBB);
  2043. // Splice the code from the return block into the block that it will return
  2044. // to, which contains the code that was after the call.
  2045. AfterCallBB->getInstList().splice(AfterCallBB->begin(),
  2046. ReturnBB->getInstList());
  2047. if (CreatedBranchToNormalDest)
  2048. CreatedBranchToNormalDest->setDebugLoc(Returns[0]->getDebugLoc());
  2049. // Delete the return instruction now and empty ReturnBB now.
  2050. Returns[0]->eraseFromParent();
  2051. ReturnBB->eraseFromParent();
  2052. } else if (!TheCall->use_empty()) {
  2053. // No returns, but something is using the return value of the call. Just
  2054. // nuke the result.
  2055. TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
  2056. }
  2057. // Since we are now done with the Call/Invoke, we can delete it.
  2058. TheCall->eraseFromParent();
  2059. // If we inlined any musttail calls and the original return is now
  2060. // unreachable, delete it. It can only contain a bitcast and ret.
  2061. if (InlinedMustTailCalls && pred_begin(AfterCallBB) == pred_end(AfterCallBB))
  2062. AfterCallBB->eraseFromParent();
  2063. // We should always be able to fold the entry block of the function into the
  2064. // single predecessor of the block...
  2065. assert(cast<BranchInst>(Br)->isUnconditional() && "splitBasicBlock broken!");
  2066. BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0);
  2067. // Splice the code entry block into calling block, right before the
  2068. // unconditional branch.
  2069. CalleeEntry->replaceAllUsesWith(OrigBB); // Update PHI nodes
  2070. OrigBB->getInstList().splice(Br->getIterator(), CalleeEntry->getInstList());
  2071. // Remove the unconditional branch.
  2072. OrigBB->getInstList().erase(Br);
  2073. // Now we can remove the CalleeEntry block, which is now empty.
  2074. Caller->getBasicBlockList().erase(CalleeEntry);
  2075. // If we inserted a phi node, check to see if it has a single value (e.g. all
  2076. // the entries are the same or undef). If so, remove the PHI so it doesn't
  2077. // block other optimizations.
  2078. if (PHI) {
  2079. AssumptionCache *AC =
  2080. IFI.GetAssumptionCache ? &(*IFI.GetAssumptionCache)(*Caller) : nullptr;
  2081. auto &DL = Caller->getParent()->getDataLayout();
  2082. if (Value *V = SimplifyInstruction(PHI, {DL, nullptr, nullptr, AC})) {
  2083. PHI->replaceAllUsesWith(V);
  2084. PHI->eraseFromParent();
  2085. }
  2086. }
  2087. return true;
  2088. }