CallSiteSplitting.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  1. //===- CallSiteSplitting.cpp ----------------------------------------------===//
  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 a transformation that tries to split a call-site to pass
  10. // more constrained arguments if its argument is predicated in the control flow
  11. // so that we can expose better context to the later passes (e.g, inliner, jump
  12. // threading, or IPA-CP based function cloning, etc.).
  13. // As of now we support two cases :
  14. //
  15. // 1) Try to a split call-site with constrained arguments, if any constraints
  16. // on any argument can be found by following the single predecessors of the
  17. // all site's predecessors. Currently this pass only handles call-sites with 2
  18. // predecessors. For example, in the code below, we try to split the call-site
  19. // since we can predicate the argument(ptr) based on the OR condition.
  20. //
  21. // Split from :
  22. // if (!ptr || c)
  23. // callee(ptr);
  24. // to :
  25. // if (!ptr)
  26. // callee(null) // set the known constant value
  27. // else if (c)
  28. // callee(nonnull ptr) // set non-null attribute in the argument
  29. //
  30. // 2) We can also split a call-site based on constant incoming values of a PHI
  31. // For example,
  32. // from :
  33. // Header:
  34. // %c = icmp eq i32 %i1, %i2
  35. // br i1 %c, label %Tail, label %TBB
  36. // TBB:
  37. // br label Tail%
  38. // Tail:
  39. // %p = phi i32 [ 0, %Header], [ 1, %TBB]
  40. // call void @bar(i32 %p)
  41. // to
  42. // Header:
  43. // %c = icmp eq i32 %i1, %i2
  44. // br i1 %c, label %Tail-split0, label %TBB
  45. // TBB:
  46. // br label %Tail-split1
  47. // Tail-split0:
  48. // call void @bar(i32 0)
  49. // br label %Tail
  50. // Tail-split1:
  51. // call void @bar(i32 1)
  52. // br label %Tail
  53. // Tail:
  54. // %p = phi i32 [ 0, %Tail-split0 ], [ 1, %Tail-split1 ]
  55. //
  56. //===----------------------------------------------------------------------===//
  57. #include "llvm/Transforms/Scalar/CallSiteSplitting.h"
  58. #include "llvm/ADT/Statistic.h"
  59. #include "llvm/Analysis/DomTreeUpdater.h"
  60. #include "llvm/Analysis/TargetLibraryInfo.h"
  61. #include "llvm/Analysis/TargetTransformInfo.h"
  62. #include "llvm/IR/IntrinsicInst.h"
  63. #include "llvm/IR/PatternMatch.h"
  64. #include "llvm/InitializePasses.h"
  65. #include "llvm/Support/CommandLine.h"
  66. #include "llvm/Support/Debug.h"
  67. #include "llvm/Transforms/Scalar.h"
  68. #include "llvm/Transforms/Utils/Cloning.h"
  69. #include "llvm/Transforms/Utils/Local.h"
  70. using namespace llvm;
  71. using namespace PatternMatch;
  72. #define DEBUG_TYPE "callsite-splitting"
  73. STATISTIC(NumCallSiteSplit, "Number of call-site split");
  74. /// Only allow instructions before a call, if their CodeSize cost is below
  75. /// DuplicationThreshold. Those instructions need to be duplicated in all
  76. /// split blocks.
  77. static cl::opt<unsigned>
  78. DuplicationThreshold("callsite-splitting-duplication-threshold", cl::Hidden,
  79. cl::desc("Only allow instructions before a call, if "
  80. "their cost is below DuplicationThreshold"),
  81. cl::init(5));
  82. static void addNonNullAttribute(CallBase &CB, Value *Op) {
  83. unsigned ArgNo = 0;
  84. for (auto &I : CB.args()) {
  85. if (&*I == Op)
  86. CB.addParamAttr(ArgNo, Attribute::NonNull);
  87. ++ArgNo;
  88. }
  89. }
  90. static void setConstantInArgument(CallBase &CB, Value *Op,
  91. Constant *ConstValue) {
  92. unsigned ArgNo = 0;
  93. for (auto &I : CB.args()) {
  94. if (&*I == Op) {
  95. // It is possible we have already added the non-null attribute to the
  96. // parameter by using an earlier constraining condition.
  97. CB.removeParamAttr(ArgNo, Attribute::NonNull);
  98. CB.setArgOperand(ArgNo, ConstValue);
  99. }
  100. ++ArgNo;
  101. }
  102. }
  103. static bool isCondRelevantToAnyCallArgument(ICmpInst *Cmp, CallBase &CB) {
  104. assert(isa<Constant>(Cmp->getOperand(1)) && "Expected a constant operand.");
  105. Value *Op0 = Cmp->getOperand(0);
  106. unsigned ArgNo = 0;
  107. for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I, ++ArgNo) {
  108. // Don't consider constant or arguments that are already known non-null.
  109. if (isa<Constant>(*I) || CB.paramHasAttr(ArgNo, Attribute::NonNull))
  110. continue;
  111. if (*I == Op0)
  112. return true;
  113. }
  114. return false;
  115. }
  116. using ConditionTy = std::pair<ICmpInst *, unsigned>;
  117. using ConditionsTy = SmallVector<ConditionTy, 2>;
  118. /// If From has a conditional jump to To, add the condition to Conditions,
  119. /// if it is relevant to any argument at CB.
  120. static void recordCondition(CallBase &CB, BasicBlock *From, BasicBlock *To,
  121. ConditionsTy &Conditions) {
  122. auto *BI = dyn_cast<BranchInst>(From->getTerminator());
  123. if (!BI || !BI->isConditional())
  124. return;
  125. CmpInst::Predicate Pred;
  126. Value *Cond = BI->getCondition();
  127. if (!match(Cond, m_ICmp(Pred, m_Value(), m_Constant())))
  128. return;
  129. ICmpInst *Cmp = cast<ICmpInst>(Cond);
  130. if (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE)
  131. if (isCondRelevantToAnyCallArgument(Cmp, CB))
  132. Conditions.push_back({Cmp, From->getTerminator()->getSuccessor(0) == To
  133. ? Pred
  134. : Cmp->getInversePredicate()});
  135. }
  136. /// Record ICmp conditions relevant to any argument in CB following Pred's
  137. /// single predecessors. If there are conflicting conditions along a path, like
  138. /// x == 1 and x == 0, the first condition will be used. We stop once we reach
  139. /// an edge to StopAt.
  140. static void recordConditions(CallBase &CB, BasicBlock *Pred,
  141. ConditionsTy &Conditions, BasicBlock *StopAt) {
  142. BasicBlock *From = Pred;
  143. BasicBlock *To = Pred;
  144. SmallPtrSet<BasicBlock *, 4> Visited;
  145. while (To != StopAt && !Visited.count(From->getSinglePredecessor()) &&
  146. (From = From->getSinglePredecessor())) {
  147. recordCondition(CB, From, To, Conditions);
  148. Visited.insert(From);
  149. To = From;
  150. }
  151. }
  152. static void addConditions(CallBase &CB, const ConditionsTy &Conditions) {
  153. for (const auto &Cond : Conditions) {
  154. Value *Arg = Cond.first->getOperand(0);
  155. Constant *ConstVal = cast<Constant>(Cond.first->getOperand(1));
  156. if (Cond.second == ICmpInst::ICMP_EQ)
  157. setConstantInArgument(CB, Arg, ConstVal);
  158. else if (ConstVal->getType()->isPointerTy() && ConstVal->isNullValue()) {
  159. assert(Cond.second == ICmpInst::ICMP_NE);
  160. addNonNullAttribute(CB, Arg);
  161. }
  162. }
  163. }
  164. static SmallVector<BasicBlock *, 2> getTwoPredecessors(BasicBlock *BB) {
  165. SmallVector<BasicBlock *, 2> Preds(predecessors((BB)));
  166. assert(Preds.size() == 2 && "Expected exactly 2 predecessors!");
  167. return Preds;
  168. }
  169. static bool canSplitCallSite(CallBase &CB, TargetTransformInfo &TTI) {
  170. if (CB.isConvergent() || CB.cannotDuplicate())
  171. return false;
  172. // FIXME: As of now we handle only CallInst. InvokeInst could be handled
  173. // without too much effort.
  174. if (!isa<CallInst>(CB))
  175. return false;
  176. BasicBlock *CallSiteBB = CB.getParent();
  177. // Need 2 predecessors and cannot split an edge from an IndirectBrInst.
  178. SmallVector<BasicBlock *, 2> Preds(predecessors(CallSiteBB));
  179. if (Preds.size() != 2 || isa<IndirectBrInst>(Preds[0]->getTerminator()) ||
  180. isa<IndirectBrInst>(Preds[1]->getTerminator()))
  181. return false;
  182. // BasicBlock::canSplitPredecessors is more aggressive, so checking for
  183. // BasicBlock::isEHPad as well.
  184. if (!CallSiteBB->canSplitPredecessors() || CallSiteBB->isEHPad())
  185. return false;
  186. // Allow splitting a call-site only when the CodeSize cost of the
  187. // instructions before the call is less then DuplicationThreshold. The
  188. // instructions before the call will be duplicated in the split blocks and
  189. // corresponding uses will be updated.
  190. InstructionCost Cost = 0;
  191. for (auto &InstBeforeCall :
  192. llvm::make_range(CallSiteBB->begin(), CB.getIterator())) {
  193. Cost += TTI.getInstructionCost(&InstBeforeCall,
  194. TargetTransformInfo::TCK_CodeSize);
  195. if (Cost >= DuplicationThreshold)
  196. return false;
  197. }
  198. return true;
  199. }
  200. static Instruction *cloneInstForMustTail(Instruction *I, Instruction *Before,
  201. Value *V) {
  202. Instruction *Copy = I->clone();
  203. Copy->setName(I->getName());
  204. Copy->insertBefore(Before);
  205. if (V)
  206. Copy->setOperand(0, V);
  207. return Copy;
  208. }
  209. /// Copy mandatory `musttail` return sequence that follows original `CI`, and
  210. /// link it up to `NewCI` value instead:
  211. ///
  212. /// * (optional) `bitcast NewCI to ...`
  213. /// * `ret bitcast or NewCI`
  214. ///
  215. /// Insert this sequence right before `SplitBB`'s terminator, which will be
  216. /// cleaned up later in `splitCallSite` below.
  217. static void copyMustTailReturn(BasicBlock *SplitBB, Instruction *CI,
  218. Instruction *NewCI) {
  219. bool IsVoid = SplitBB->getParent()->getReturnType()->isVoidTy();
  220. auto II = std::next(CI->getIterator());
  221. BitCastInst* BCI = dyn_cast<BitCastInst>(&*II);
  222. if (BCI)
  223. ++II;
  224. ReturnInst* RI = dyn_cast<ReturnInst>(&*II);
  225. assert(RI && "`musttail` call must be followed by `ret` instruction");
  226. Instruction *TI = SplitBB->getTerminator();
  227. Value *V = NewCI;
  228. if (BCI)
  229. V = cloneInstForMustTail(BCI, TI, V);
  230. cloneInstForMustTail(RI, TI, IsVoid ? nullptr : V);
  231. // FIXME: remove TI here, `DuplicateInstructionsInSplitBetween` has a bug
  232. // that prevents doing this now.
  233. }
  234. /// For each (predecessor, conditions from predecessors) pair, it will split the
  235. /// basic block containing the call site, hook it up to the predecessor and
  236. /// replace the call instruction with new call instructions, which contain
  237. /// constraints based on the conditions from their predecessors.
  238. /// For example, in the IR below with an OR condition, the call-site can
  239. /// be split. In this case, Preds for Tail is [(Header, a == null),
  240. /// (TBB, a != null, b == null)]. Tail is replaced by 2 split blocks, containing
  241. /// CallInst1, which has constraints based on the conditions from Head and
  242. /// CallInst2, which has constraints based on the conditions coming from TBB.
  243. ///
  244. /// From :
  245. ///
  246. /// Header:
  247. /// %c = icmp eq i32* %a, null
  248. /// br i1 %c %Tail, %TBB
  249. /// TBB:
  250. /// %c2 = icmp eq i32* %b, null
  251. /// br i1 %c %Tail, %End
  252. /// Tail:
  253. /// %ca = call i1 @callee (i32* %a, i32* %b)
  254. ///
  255. /// to :
  256. ///
  257. /// Header: // PredBB1 is Header
  258. /// %c = icmp eq i32* %a, null
  259. /// br i1 %c %Tail-split1, %TBB
  260. /// TBB: // PredBB2 is TBB
  261. /// %c2 = icmp eq i32* %b, null
  262. /// br i1 %c %Tail-split2, %End
  263. /// Tail-split1:
  264. /// %ca1 = call @callee (i32* null, i32* %b) // CallInst1
  265. /// br %Tail
  266. /// Tail-split2:
  267. /// %ca2 = call @callee (i32* nonnull %a, i32* null) // CallInst2
  268. /// br %Tail
  269. /// Tail:
  270. /// %p = phi i1 [%ca1, %Tail-split1],[%ca2, %Tail-split2]
  271. ///
  272. /// Note that in case any arguments at the call-site are constrained by its
  273. /// predecessors, new call-sites with more constrained arguments will be
  274. /// created in createCallSitesOnPredicatedArgument().
  275. static void splitCallSite(CallBase &CB,
  276. ArrayRef<std::pair<BasicBlock *, ConditionsTy>> Preds,
  277. DomTreeUpdater &DTU) {
  278. BasicBlock *TailBB = CB.getParent();
  279. bool IsMustTailCall = CB.isMustTailCall();
  280. PHINode *CallPN = nullptr;
  281. // `musttail` calls must be followed by optional `bitcast`, and `ret`. The
  282. // split blocks will be terminated right after that so there're no users for
  283. // this phi in a `TailBB`.
  284. if (!IsMustTailCall && !CB.use_empty()) {
  285. CallPN = PHINode::Create(CB.getType(), Preds.size(), "phi.call");
  286. CallPN->setDebugLoc(CB.getDebugLoc());
  287. }
  288. LLVM_DEBUG(dbgs() << "split call-site : " << CB << " into \n");
  289. assert(Preds.size() == 2 && "The ValueToValueMaps array has size 2.");
  290. // ValueToValueMapTy is neither copy nor moveable, so we use a simple array
  291. // here.
  292. ValueToValueMapTy ValueToValueMaps[2];
  293. for (unsigned i = 0; i < Preds.size(); i++) {
  294. BasicBlock *PredBB = Preds[i].first;
  295. BasicBlock *SplitBlock = DuplicateInstructionsInSplitBetween(
  296. TailBB, PredBB, &*std::next(CB.getIterator()), ValueToValueMaps[i],
  297. DTU);
  298. assert(SplitBlock && "Unexpected new basic block split.");
  299. auto *NewCI =
  300. cast<CallBase>(&*std::prev(SplitBlock->getTerminator()->getIterator()));
  301. addConditions(*NewCI, Preds[i].second);
  302. // Handle PHIs used as arguments in the call-site.
  303. for (PHINode &PN : TailBB->phis()) {
  304. unsigned ArgNo = 0;
  305. for (auto &CI : CB.args()) {
  306. if (&*CI == &PN) {
  307. NewCI->setArgOperand(ArgNo, PN.getIncomingValueForBlock(SplitBlock));
  308. }
  309. ++ArgNo;
  310. }
  311. }
  312. LLVM_DEBUG(dbgs() << " " << *NewCI << " in " << SplitBlock->getName()
  313. << "\n");
  314. if (CallPN)
  315. CallPN->addIncoming(NewCI, SplitBlock);
  316. // Clone and place bitcast and return instructions before `TI`
  317. if (IsMustTailCall)
  318. copyMustTailReturn(SplitBlock, &CB, NewCI);
  319. }
  320. NumCallSiteSplit++;
  321. // FIXME: remove TI in `copyMustTailReturn`
  322. if (IsMustTailCall) {
  323. // Remove superfluous `br` terminators from the end of the Split blocks
  324. // NOTE: Removing terminator removes the SplitBlock from the TailBB's
  325. // predecessors. Therefore we must get complete list of Splits before
  326. // attempting removal.
  327. SmallVector<BasicBlock *, 2> Splits(predecessors((TailBB)));
  328. assert(Splits.size() == 2 && "Expected exactly 2 splits!");
  329. for (BasicBlock *BB : Splits) {
  330. BB->getTerminator()->eraseFromParent();
  331. DTU.applyUpdatesPermissive({{DominatorTree::Delete, BB, TailBB}});
  332. }
  333. // Erase the tail block once done with musttail patching
  334. DTU.deleteBB(TailBB);
  335. return;
  336. }
  337. auto *OriginalBegin = &*TailBB->begin();
  338. // Replace users of the original call with a PHI mering call-sites split.
  339. if (CallPN) {
  340. CallPN->insertBefore(OriginalBegin);
  341. CB.replaceAllUsesWith(CallPN);
  342. }
  343. // Remove instructions moved to split blocks from TailBB, from the duplicated
  344. // call instruction to the beginning of the basic block. If an instruction
  345. // has any uses, add a new PHI node to combine the values coming from the
  346. // split blocks. The new PHI nodes are placed before the first original
  347. // instruction, so we do not end up deleting them. By using reverse-order, we
  348. // do not introduce unnecessary PHI nodes for def-use chains from the call
  349. // instruction to the beginning of the block.
  350. auto I = CB.getReverseIterator();
  351. while (I != TailBB->rend()) {
  352. Instruction *CurrentI = &*I++;
  353. if (!CurrentI->use_empty()) {
  354. // If an existing PHI has users after the call, there is no need to create
  355. // a new one.
  356. if (isa<PHINode>(CurrentI))
  357. continue;
  358. PHINode *NewPN = PHINode::Create(CurrentI->getType(), Preds.size());
  359. NewPN->setDebugLoc(CurrentI->getDebugLoc());
  360. for (auto &Mapping : ValueToValueMaps)
  361. NewPN->addIncoming(Mapping[CurrentI],
  362. cast<Instruction>(Mapping[CurrentI])->getParent());
  363. NewPN->insertBefore(&*TailBB->begin());
  364. CurrentI->replaceAllUsesWith(NewPN);
  365. }
  366. CurrentI->eraseFromParent();
  367. // We are done once we handled the first original instruction in TailBB.
  368. if (CurrentI == OriginalBegin)
  369. break;
  370. }
  371. }
  372. // Return true if the call-site has an argument which is a PHI with only
  373. // constant incoming values.
  374. static bool isPredicatedOnPHI(CallBase &CB) {
  375. BasicBlock *Parent = CB.getParent();
  376. if (&CB != Parent->getFirstNonPHIOrDbg())
  377. return false;
  378. for (auto &PN : Parent->phis()) {
  379. for (auto &Arg : CB.args()) {
  380. if (&*Arg != &PN)
  381. continue;
  382. assert(PN.getNumIncomingValues() == 2 &&
  383. "Unexpected number of incoming values");
  384. if (PN.getIncomingBlock(0) == PN.getIncomingBlock(1))
  385. return false;
  386. if (PN.getIncomingValue(0) == PN.getIncomingValue(1))
  387. continue;
  388. if (isa<Constant>(PN.getIncomingValue(0)) &&
  389. isa<Constant>(PN.getIncomingValue(1)))
  390. return true;
  391. }
  392. }
  393. return false;
  394. }
  395. using PredsWithCondsTy = SmallVector<std::pair<BasicBlock *, ConditionsTy>, 2>;
  396. // Check if any of the arguments in CS are predicated on a PHI node and return
  397. // the set of predecessors we should use for splitting.
  398. static PredsWithCondsTy shouldSplitOnPHIPredicatedArgument(CallBase &CB) {
  399. if (!isPredicatedOnPHI(CB))
  400. return {};
  401. auto Preds = getTwoPredecessors(CB.getParent());
  402. return {{Preds[0], {}}, {Preds[1], {}}};
  403. }
  404. // Checks if any of the arguments in CS are predicated in a predecessor and
  405. // returns a list of predecessors with the conditions that hold on their edges
  406. // to CS.
  407. static PredsWithCondsTy shouldSplitOnPredicatedArgument(CallBase &CB,
  408. DomTreeUpdater &DTU) {
  409. auto Preds = getTwoPredecessors(CB.getParent());
  410. if (Preds[0] == Preds[1])
  411. return {};
  412. // We can stop recording conditions once we reached the immediate dominator
  413. // for the block containing the call site. Conditions in predecessors of the
  414. // that node will be the same for all paths to the call site and splitting
  415. // is not beneficial.
  416. assert(DTU.hasDomTree() && "We need a DTU with a valid DT!");
  417. auto *CSDTNode = DTU.getDomTree().getNode(CB.getParent());
  418. BasicBlock *StopAt = CSDTNode ? CSDTNode->getIDom()->getBlock() : nullptr;
  419. SmallVector<std::pair<BasicBlock *, ConditionsTy>, 2> PredsCS;
  420. for (auto *Pred : llvm::reverse(Preds)) {
  421. ConditionsTy Conditions;
  422. // Record condition on edge BB(CS) <- Pred
  423. recordCondition(CB, Pred, CB.getParent(), Conditions);
  424. // Record conditions following Pred's single predecessors.
  425. recordConditions(CB, Pred, Conditions, StopAt);
  426. PredsCS.push_back({Pred, Conditions});
  427. }
  428. if (all_of(PredsCS, [](const std::pair<BasicBlock *, ConditionsTy> &P) {
  429. return P.second.empty();
  430. }))
  431. return {};
  432. return PredsCS;
  433. }
  434. static bool tryToSplitCallSite(CallBase &CB, TargetTransformInfo &TTI,
  435. DomTreeUpdater &DTU) {
  436. // Check if we can split the call site.
  437. if (!CB.arg_size() || !canSplitCallSite(CB, TTI))
  438. return false;
  439. auto PredsWithConds = shouldSplitOnPredicatedArgument(CB, DTU);
  440. if (PredsWithConds.empty())
  441. PredsWithConds = shouldSplitOnPHIPredicatedArgument(CB);
  442. if (PredsWithConds.empty())
  443. return false;
  444. splitCallSite(CB, PredsWithConds, DTU);
  445. return true;
  446. }
  447. static bool doCallSiteSplitting(Function &F, TargetLibraryInfo &TLI,
  448. TargetTransformInfo &TTI, DominatorTree &DT) {
  449. DomTreeUpdater DTU(&DT, DomTreeUpdater::UpdateStrategy::Lazy);
  450. bool Changed = false;
  451. for (BasicBlock &BB : llvm::make_early_inc_range(F)) {
  452. auto II = BB.getFirstNonPHIOrDbg()->getIterator();
  453. auto IE = BB.getTerminator()->getIterator();
  454. // Iterate until we reach the terminator instruction. tryToSplitCallSite
  455. // can replace BB's terminator in case BB is a successor of itself. In that
  456. // case, IE will be invalidated and we also have to check the current
  457. // terminator.
  458. while (II != IE && &*II != BB.getTerminator()) {
  459. CallBase *CB = dyn_cast<CallBase>(&*II++);
  460. if (!CB || isa<IntrinsicInst>(CB) || isInstructionTriviallyDead(CB, &TLI))
  461. continue;
  462. Function *Callee = CB->getCalledFunction();
  463. if (!Callee || Callee->isDeclaration())
  464. continue;
  465. // Successful musttail call-site splits result in erased CI and erased BB.
  466. // Check if such path is possible before attempting the splitting.
  467. bool IsMustTail = CB->isMustTailCall();
  468. Changed |= tryToSplitCallSite(*CB, TTI, DTU);
  469. // There're no interesting instructions after this. The call site
  470. // itself might have been erased on splitting.
  471. if (IsMustTail)
  472. break;
  473. }
  474. }
  475. return Changed;
  476. }
  477. namespace {
  478. struct CallSiteSplittingLegacyPass : public FunctionPass {
  479. static char ID;
  480. CallSiteSplittingLegacyPass() : FunctionPass(ID) {
  481. initializeCallSiteSplittingLegacyPassPass(*PassRegistry::getPassRegistry());
  482. }
  483. void getAnalysisUsage(AnalysisUsage &AU) const override {
  484. AU.addRequired<TargetLibraryInfoWrapperPass>();
  485. AU.addRequired<TargetTransformInfoWrapperPass>();
  486. AU.addRequired<DominatorTreeWrapperPass>();
  487. AU.addPreserved<DominatorTreeWrapperPass>();
  488. FunctionPass::getAnalysisUsage(AU);
  489. }
  490. bool runOnFunction(Function &F) override {
  491. if (skipFunction(F))
  492. return false;
  493. auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
  494. auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
  495. auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  496. return doCallSiteSplitting(F, TLI, TTI, DT);
  497. }
  498. };
  499. } // namespace
  500. char CallSiteSplittingLegacyPass::ID = 0;
  501. INITIALIZE_PASS_BEGIN(CallSiteSplittingLegacyPass, "callsite-splitting",
  502. "Call-site splitting", false, false)
  503. INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
  504. INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
  505. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  506. INITIALIZE_PASS_END(CallSiteSplittingLegacyPass, "callsite-splitting",
  507. "Call-site splitting", false, false)
  508. FunctionPass *llvm::createCallSiteSplittingPass() {
  509. return new CallSiteSplittingLegacyPass();
  510. }
  511. PreservedAnalyses CallSiteSplittingPass::run(Function &F,
  512. FunctionAnalysisManager &AM) {
  513. auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
  514. auto &TTI = AM.getResult<TargetIRAnalysis>(F);
  515. auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
  516. if (!doCallSiteSplitting(F, TLI, TTI, DT))
  517. return PreservedAnalyses::all();
  518. PreservedAnalyses PA;
  519. PA.preserve<DominatorTreeAnalysis>();
  520. return PA;
  521. }