CallSiteSplitting.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  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/TargetLibraryInfo.h"
  60. #include "llvm/Analysis/TargetTransformInfo.h"
  61. #include "llvm/IR/IntrinsicInst.h"
  62. #include "llvm/IR/PatternMatch.h"
  63. #include "llvm/InitializePasses.h"
  64. #include "llvm/Support/CommandLine.h"
  65. #include "llvm/Support/Debug.h"
  66. #include "llvm/Transforms/Scalar.h"
  67. #include "llvm/Transforms/Utils/BasicBlockUtils.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. typedef std::pair<ICmpInst *, unsigned> ConditionTy;
  117. typedef SmallVector<ConditionTy, 2> ConditionsTy;
  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 (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(
  276. CallBase &CB,
  277. const SmallVectorImpl<std::pair<BasicBlock *, ConditionsTy>> &Preds,
  278. DomTreeUpdater &DTU) {
  279. BasicBlock *TailBB = CB.getParent();
  280. bool IsMustTailCall = CB.isMustTailCall();
  281. PHINode *CallPN = nullptr;
  282. // `musttail` calls must be followed by optional `bitcast`, and `ret`. The
  283. // split blocks will be terminated right after that so there're no users for
  284. // this phi in a `TailBB`.
  285. if (!IsMustTailCall && !CB.use_empty()) {
  286. CallPN = PHINode::Create(CB.getType(), Preds.size(), "phi.call");
  287. CallPN->setDebugLoc(CB.getDebugLoc());
  288. }
  289. LLVM_DEBUG(dbgs() << "split call-site : " << CB << " into \n");
  290. assert(Preds.size() == 2 && "The ValueToValueMaps array has size 2.");
  291. // ValueToValueMapTy is neither copy nor moveable, so we use a simple array
  292. // here.
  293. ValueToValueMapTy ValueToValueMaps[2];
  294. for (unsigned i = 0; i < Preds.size(); i++) {
  295. BasicBlock *PredBB = Preds[i].first;
  296. BasicBlock *SplitBlock = DuplicateInstructionsInSplitBetween(
  297. TailBB, PredBB, &*std::next(CB.getIterator()), ValueToValueMaps[i],
  298. DTU);
  299. assert(SplitBlock && "Unexpected new basic block split.");
  300. auto *NewCI =
  301. cast<CallBase>(&*std::prev(SplitBlock->getTerminator()->getIterator()));
  302. addConditions(*NewCI, Preds[i].second);
  303. // Handle PHIs used as arguments in the call-site.
  304. for (PHINode &PN : TailBB->phis()) {
  305. unsigned ArgNo = 0;
  306. for (auto &CI : CB.args()) {
  307. if (&*CI == &PN) {
  308. NewCI->setArgOperand(ArgNo, PN.getIncomingValueForBlock(SplitBlock));
  309. }
  310. ++ArgNo;
  311. }
  312. }
  313. LLVM_DEBUG(dbgs() << " " << *NewCI << " in " << SplitBlock->getName()
  314. << "\n");
  315. if (CallPN)
  316. CallPN->addIncoming(NewCI, SplitBlock);
  317. // Clone and place bitcast and return instructions before `TI`
  318. if (IsMustTailCall)
  319. copyMustTailReturn(SplitBlock, &CB, NewCI);
  320. }
  321. NumCallSiteSplit++;
  322. // FIXME: remove TI in `copyMustTailReturn`
  323. if (IsMustTailCall) {
  324. // Remove superfluous `br` terminators from the end of the Split blocks
  325. // NOTE: Removing terminator removes the SplitBlock from the TailBB's
  326. // predecessors. Therefore we must get complete list of Splits before
  327. // attempting removal.
  328. SmallVector<BasicBlock *, 2> Splits(predecessors((TailBB)));
  329. assert(Splits.size() == 2 && "Expected exactly 2 splits!");
  330. for (unsigned i = 0; i < Splits.size(); i++) {
  331. Splits[i]->getTerminator()->eraseFromParent();
  332. DTU.applyUpdatesPermissive({{DominatorTree::Delete, Splits[i], TailBB}});
  333. }
  334. // Erase the tail block once done with musttail patching
  335. DTU.deleteBB(TailBB);
  336. return;
  337. }
  338. auto *OriginalBegin = &*TailBB->begin();
  339. // Replace users of the original call with a PHI mering call-sites split.
  340. if (CallPN) {
  341. CallPN->insertBefore(OriginalBegin);
  342. CB.replaceAllUsesWith(CallPN);
  343. }
  344. // Remove instructions moved to split blocks from TailBB, from the duplicated
  345. // call instruction to the beginning of the basic block. If an instruction
  346. // has any uses, add a new PHI node to combine the values coming from the
  347. // split blocks. The new PHI nodes are placed before the first original
  348. // instruction, so we do not end up deleting them. By using reverse-order, we
  349. // do not introduce unnecessary PHI nodes for def-use chains from the call
  350. // instruction to the beginning of the block.
  351. auto I = CB.getReverseIterator();
  352. while (I != TailBB->rend()) {
  353. Instruction *CurrentI = &*I++;
  354. if (!CurrentI->use_empty()) {
  355. // If an existing PHI has users after the call, there is no need to create
  356. // a new one.
  357. if (isa<PHINode>(CurrentI))
  358. continue;
  359. PHINode *NewPN = PHINode::Create(CurrentI->getType(), Preds.size());
  360. NewPN->setDebugLoc(CurrentI->getDebugLoc());
  361. for (auto &Mapping : ValueToValueMaps)
  362. NewPN->addIncoming(Mapping[CurrentI],
  363. cast<Instruction>(Mapping[CurrentI])->getParent());
  364. NewPN->insertBefore(&*TailBB->begin());
  365. CurrentI->replaceAllUsesWith(NewPN);
  366. }
  367. CurrentI->eraseFromParent();
  368. // We are done once we handled the first original instruction in TailBB.
  369. if (CurrentI == OriginalBegin)
  370. break;
  371. }
  372. }
  373. // Return true if the call-site has an argument which is a PHI with only
  374. // constant incoming values.
  375. static bool isPredicatedOnPHI(CallBase &CB) {
  376. BasicBlock *Parent = CB.getParent();
  377. if (&CB != Parent->getFirstNonPHIOrDbg())
  378. return false;
  379. for (auto &PN : Parent->phis()) {
  380. for (auto &Arg : CB.args()) {
  381. if (&*Arg != &PN)
  382. continue;
  383. assert(PN.getNumIncomingValues() == 2 &&
  384. "Unexpected number of incoming values");
  385. if (PN.getIncomingBlock(0) == PN.getIncomingBlock(1))
  386. return false;
  387. if (PN.getIncomingValue(0) == PN.getIncomingValue(1))
  388. continue;
  389. if (isa<Constant>(PN.getIncomingValue(0)) &&
  390. isa<Constant>(PN.getIncomingValue(1)))
  391. return true;
  392. }
  393. }
  394. return false;
  395. }
  396. using PredsWithCondsTy = SmallVector<std::pair<BasicBlock *, ConditionsTy>, 2>;
  397. // Check if any of the arguments in CS are predicated on a PHI node and return
  398. // the set of predecessors we should use for splitting.
  399. static PredsWithCondsTy shouldSplitOnPHIPredicatedArgument(CallBase &CB) {
  400. if (!isPredicatedOnPHI(CB))
  401. return {};
  402. auto Preds = getTwoPredecessors(CB.getParent());
  403. return {{Preds[0], {}}, {Preds[1], {}}};
  404. }
  405. // Checks if any of the arguments in CS are predicated in a predecessor and
  406. // returns a list of predecessors with the conditions that hold on their edges
  407. // to CS.
  408. static PredsWithCondsTy shouldSplitOnPredicatedArgument(CallBase &CB,
  409. DomTreeUpdater &DTU) {
  410. auto Preds = getTwoPredecessors(CB.getParent());
  411. if (Preds[0] == Preds[1])
  412. return {};
  413. // We can stop recording conditions once we reached the immediate dominator
  414. // for the block containing the call site. Conditions in predecessors of the
  415. // that node will be the same for all paths to the call site and splitting
  416. // is not beneficial.
  417. assert(DTU.hasDomTree() && "We need a DTU with a valid DT!");
  418. auto *CSDTNode = DTU.getDomTree().getNode(CB.getParent());
  419. BasicBlock *StopAt = CSDTNode ? CSDTNode->getIDom()->getBlock() : nullptr;
  420. SmallVector<std::pair<BasicBlock *, ConditionsTy>, 2> PredsCS;
  421. for (auto *Pred : llvm::reverse(Preds)) {
  422. ConditionsTy Conditions;
  423. // Record condition on edge BB(CS) <- Pred
  424. recordCondition(CB, Pred, CB.getParent(), Conditions);
  425. // Record conditions following Pred's single predecessors.
  426. recordConditions(CB, Pred, Conditions, StopAt);
  427. PredsCS.push_back({Pred, Conditions});
  428. }
  429. if (all_of(PredsCS, [](const std::pair<BasicBlock *, ConditionsTy> &P) {
  430. return P.second.empty();
  431. }))
  432. return {};
  433. return PredsCS;
  434. }
  435. static bool tryToSplitCallSite(CallBase &CB, TargetTransformInfo &TTI,
  436. DomTreeUpdater &DTU) {
  437. // Check if we can split the call site.
  438. if (!CB.arg_size() || !canSplitCallSite(CB, TTI))
  439. return false;
  440. auto PredsWithConds = shouldSplitOnPredicatedArgument(CB, DTU);
  441. if (PredsWithConds.empty())
  442. PredsWithConds = shouldSplitOnPHIPredicatedArgument(CB);
  443. if (PredsWithConds.empty())
  444. return false;
  445. splitCallSite(CB, PredsWithConds, DTU);
  446. return true;
  447. }
  448. static bool doCallSiteSplitting(Function &F, TargetLibraryInfo &TLI,
  449. TargetTransformInfo &TTI, DominatorTree &DT) {
  450. DomTreeUpdater DTU(&DT, DomTreeUpdater::UpdateStrategy::Lazy);
  451. bool Changed = false;
  452. for (BasicBlock &BB : llvm::make_early_inc_range(F)) {
  453. auto II = BB.getFirstNonPHIOrDbg()->getIterator();
  454. auto IE = BB.getTerminator()->getIterator();
  455. // Iterate until we reach the terminator instruction. tryToSplitCallSite
  456. // can replace BB's terminator in case BB is a successor of itself. In that
  457. // case, IE will be invalidated and we also have to check the current
  458. // terminator.
  459. while (II != IE && &*II != BB.getTerminator()) {
  460. CallBase *CB = dyn_cast<CallBase>(&*II++);
  461. if (!CB || isa<IntrinsicInst>(CB) || isInstructionTriviallyDead(CB, &TLI))
  462. continue;
  463. Function *Callee = CB->getCalledFunction();
  464. if (!Callee || Callee->isDeclaration())
  465. continue;
  466. // Successful musttail call-site splits result in erased CI and erased BB.
  467. // Check if such path is possible before attempting the splitting.
  468. bool IsMustTail = CB->isMustTailCall();
  469. Changed |= tryToSplitCallSite(*CB, TTI, DTU);
  470. // There're no interesting instructions after this. The call site
  471. // itself might have been erased on splitting.
  472. if (IsMustTail)
  473. break;
  474. }
  475. }
  476. return Changed;
  477. }
  478. namespace {
  479. struct CallSiteSplittingLegacyPass : public FunctionPass {
  480. static char ID;
  481. CallSiteSplittingLegacyPass() : FunctionPass(ID) {
  482. initializeCallSiteSplittingLegacyPassPass(*PassRegistry::getPassRegistry());
  483. }
  484. void getAnalysisUsage(AnalysisUsage &AU) const override {
  485. AU.addRequired<TargetLibraryInfoWrapperPass>();
  486. AU.addRequired<TargetTransformInfoWrapperPass>();
  487. AU.addRequired<DominatorTreeWrapperPass>();
  488. AU.addPreserved<DominatorTreeWrapperPass>();
  489. FunctionPass::getAnalysisUsage(AU);
  490. }
  491. bool runOnFunction(Function &F) override {
  492. if (skipFunction(F))
  493. return false;
  494. auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
  495. auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
  496. auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  497. return doCallSiteSplitting(F, TLI, TTI, DT);
  498. }
  499. };
  500. } // namespace
  501. char CallSiteSplittingLegacyPass::ID = 0;
  502. INITIALIZE_PASS_BEGIN(CallSiteSplittingLegacyPass, "callsite-splitting",
  503. "Call-site splitting", false, false)
  504. INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
  505. INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
  506. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  507. INITIALIZE_PASS_END(CallSiteSplittingLegacyPass, "callsite-splitting",
  508. "Call-site splitting", false, false)
  509. FunctionPass *llvm::createCallSiteSplittingPass() {
  510. return new CallSiteSplittingLegacyPass();
  511. }
  512. PreservedAnalyses CallSiteSplittingPass::run(Function &F,
  513. FunctionAnalysisManager &AM) {
  514. auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
  515. auto &TTI = AM.getResult<TargetIRAnalysis>(F);
  516. auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
  517. if (!doCallSiteSplitting(F, TLI, TTI, DT))
  518. return PreservedAnalyses::all();
  519. PreservedAnalyses PA;
  520. PA.preserve<DominatorTreeAnalysis>();
  521. return PA;
  522. }