InlineFunction.cpp 109 KB

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