10c99007dSJun Bum Lim //===- CallSiteSplitting.cpp ----------------------------------------------===//
20c99007dSJun Bum Lim //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60c99007dSJun Bum Lim //
70c99007dSJun Bum Lim //===----------------------------------------------------------------------===//
80c99007dSJun Bum Lim //
90c99007dSJun Bum Lim // This file implements a transformation that tries to split a call-site to pass
100c99007dSJun Bum Lim // more constrained arguments if its argument is predicated in the control flow
110c99007dSJun Bum Lim // so that we can expose better context to the later passes (e.g, inliner, jump
120c99007dSJun Bum Lim // threading, or IPA-CP based function cloning, etc.).
130c99007dSJun Bum Lim // As of now we support two cases :
140c99007dSJun Bum Lim //
157e932890SFlorian Hahn // 1) Try to a split call-site with constrained arguments, if any constraints
167e932890SFlorian Hahn // on any argument can be found by following the single predecessors of the
177e932890SFlorian Hahn // all site's predecessors. Currently this pass only handles call-sites with 2
187e932890SFlorian Hahn // predecessors. For example, in the code below, we try to split the call-site
197e932890SFlorian Hahn // since we can predicate the argument(ptr) based on the OR condition.
200c99007dSJun Bum Lim //
210c99007dSJun Bum Lim // Split from :
220c99007dSJun Bum Lim //   if (!ptr || c)
230c99007dSJun Bum Lim //     callee(ptr);
240c99007dSJun Bum Lim // to :
250c99007dSJun Bum Lim //   if (!ptr)
260c99007dSJun Bum Lim //     callee(null)         // set the known constant value
270c99007dSJun Bum Lim //   else if (c)
280c99007dSJun Bum Lim //     callee(nonnull ptr)  // set non-null attribute in the argument
290c99007dSJun Bum Lim //
300c99007dSJun Bum Lim // 2) We can also split a call-site based on constant incoming values of a PHI
310c99007dSJun Bum Lim // For example,
320c99007dSJun Bum Lim // from :
330c99007dSJun Bum Lim //   Header:
340c99007dSJun Bum Lim //    %c = icmp eq i32 %i1, %i2
350c99007dSJun Bum Lim //    br i1 %c, label %Tail, label %TBB
360c99007dSJun Bum Lim //   TBB:
370c99007dSJun Bum Lim //    br label Tail%
380c99007dSJun Bum Lim //   Tail:
390c99007dSJun Bum Lim //    %p = phi i32 [ 0, %Header], [ 1, %TBB]
400c99007dSJun Bum Lim //    call void @bar(i32 %p)
410c99007dSJun Bum Lim // to
420c99007dSJun Bum Lim //   Header:
430c99007dSJun Bum Lim //    %c = icmp eq i32 %i1, %i2
440c99007dSJun Bum Lim //    br i1 %c, label %Tail-split0, label %TBB
450c99007dSJun Bum Lim //   TBB:
460c99007dSJun Bum Lim //    br label %Tail-split1
470c99007dSJun Bum Lim //   Tail-split0:
480c99007dSJun Bum Lim //    call void @bar(i32 0)
490c99007dSJun Bum Lim //    br label %Tail
500c99007dSJun Bum Lim //   Tail-split1:
510c99007dSJun Bum Lim //    call void @bar(i32 1)
520c99007dSJun Bum Lim //    br label %Tail
530c99007dSJun Bum Lim //   Tail:
540c99007dSJun Bum Lim //    %p = phi i32 [ 0, %Tail-split0 ], [ 1, %Tail-split1 ]
550c99007dSJun Bum Lim //
560c99007dSJun Bum Lim //===----------------------------------------------------------------------===//
570c99007dSJun Bum Lim 
580c99007dSJun Bum Lim #include "llvm/Transforms/Scalar/CallSiteSplitting.h"
590c99007dSJun Bum Lim #include "llvm/ADT/Statistic.h"
60a494ae43Sserge-sans-paille #include "llvm/Analysis/DomTreeUpdater.h"
610c99007dSJun Bum Lim #include "llvm/Analysis/TargetLibraryInfo.h"
62b4e3bad8SFlorian Hahn #include "llvm/Analysis/TargetTransformInfo.h"
630c99007dSJun Bum Lim #include "llvm/IR/IntrinsicInst.h"
640c99007dSJun Bum Lim #include "llvm/IR/PatternMatch.h"
6505da2fe5SReid Kleckner #include "llvm/InitializePasses.h"
664c1a1d3cSReid Kleckner #include "llvm/Support/CommandLine.h"
670c99007dSJun Bum Lim #include "llvm/Support/Debug.h"
680c99007dSJun Bum Lim #include "llvm/Transforms/Scalar.h"
69b4e3bad8SFlorian Hahn #include "llvm/Transforms/Utils/Cloning.h"
7005da2fe5SReid Kleckner #include "llvm/Transforms/Utils/Local.h"
710c99007dSJun Bum Lim 
720c99007dSJun Bum Lim using namespace llvm;
730c99007dSJun Bum Lim using namespace PatternMatch;
740c99007dSJun Bum Lim 
750c99007dSJun Bum Lim #define DEBUG_TYPE "callsite-splitting"
760c99007dSJun Bum Lim 
770c99007dSJun Bum Lim STATISTIC(NumCallSiteSplit, "Number of call-site split");
780c99007dSJun Bum Lim 
79b4e3bad8SFlorian Hahn /// Only allow instructions before a call, if their CodeSize cost is below
80b4e3bad8SFlorian Hahn /// DuplicationThreshold. Those instructions need to be duplicated in all
81b4e3bad8SFlorian Hahn /// split blocks.
82b4e3bad8SFlorian Hahn static cl::opt<unsigned>
83b4e3bad8SFlorian Hahn     DuplicationThreshold("callsite-splitting-duplication-threshold", cl::Hidden,
84b4e3bad8SFlorian Hahn                          cl::desc("Only allow instructions before a call, if "
85b4e3bad8SFlorian Hahn                                   "their cost is below DuplicationThreshold"),
86b4e3bad8SFlorian Hahn                          cl::init(5));
87b4e3bad8SFlorian Hahn 
addNonNullAttribute(CallBase & CB,Value * Op)8824072566SCraig Topper static void addNonNullAttribute(CallBase &CB, Value *Op) {
890c99007dSJun Bum Lim   unsigned ArgNo = 0;
9024072566SCraig Topper   for (auto &I : CB.args()) {
910c99007dSJun Bum Lim     if (&*I == Op)
9224072566SCraig Topper       CB.addParamAttr(ArgNo, Attribute::NonNull);
930c99007dSJun Bum Lim     ++ArgNo;
940c99007dSJun Bum Lim   }
950c99007dSJun Bum Lim }
960c99007dSJun Bum Lim 
setConstantInArgument(CallBase & CB,Value * Op,Constant * ConstValue)9724072566SCraig Topper static void setConstantInArgument(CallBase &CB, Value *Op,
98c6c89bffSFlorian Hahn                                   Constant *ConstValue) {
990c99007dSJun Bum Lim   unsigned ArgNo = 0;
10024072566SCraig Topper   for (auto &I : CB.args()) {
1018edff279SXin Tong     if (&*I == Op) {
1028edff279SXin Tong       // It is possible we have already added the non-null attribute to the
1038edff279SXin Tong       // parameter by using an earlier constraining condition.
10424072566SCraig Topper       CB.removeParamAttr(ArgNo, Attribute::NonNull);
10524072566SCraig Topper       CB.setArgOperand(ArgNo, ConstValue);
1068edff279SXin Tong     }
1070c99007dSJun Bum Lim     ++ArgNo;
1080c99007dSJun Bum Lim   }
1090c99007dSJun Bum Lim }
1100c99007dSJun Bum Lim 
isCondRelevantToAnyCallArgument(ICmpInst * Cmp,CallBase & CB)11124072566SCraig Topper static bool isCondRelevantToAnyCallArgument(ICmpInst *Cmp, CallBase &CB) {
1122a266a34SFlorian Hahn   assert(isa<Constant>(Cmp->getOperand(1)) && "Expected a constant operand.");
1132a266a34SFlorian Hahn   Value *Op0 = Cmp->getOperand(0);
1142a266a34SFlorian Hahn   unsigned ArgNo = 0;
11524072566SCraig Topper   for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I, ++ArgNo) {
1162a266a34SFlorian Hahn     // Don't consider constant or arguments that are already known non-null.
11724072566SCraig Topper     if (isa<Constant>(*I) || CB.paramHasAttr(ArgNo, Attribute::NonNull))
1182a266a34SFlorian Hahn       continue;
1192a266a34SFlorian Hahn 
1202a266a34SFlorian Hahn     if (*I == Op0)
1212a266a34SFlorian Hahn       return true;
1222a266a34SFlorian Hahn   }
1232a266a34SFlorian Hahn   return false;
1242a266a34SFlorian Hahn }
1252a266a34SFlorian Hahn 
126*f827ee67SAlexander Shaposhnikov using ConditionTy = std::pair<ICmpInst *, unsigned>;
127*f827ee67SAlexander Shaposhnikov using ConditionsTy = SmallVector<ConditionTy, 2>;
128c6c89bffSFlorian Hahn 
129beda7d51SFlorian Hahn /// If From has a conditional jump to To, add the condition to Conditions,
13024072566SCraig Topper /// if it is relevant to any argument at CB.
recordCondition(CallBase & CB,BasicBlock * From,BasicBlock * To,ConditionsTy & Conditions)13124072566SCraig Topper static void recordCondition(CallBase &CB, BasicBlock *From, BasicBlock *To,
132c6c89bffSFlorian Hahn                             ConditionsTy &Conditions) {
133beda7d51SFlorian Hahn   auto *BI = dyn_cast<BranchInst>(From->getTerminator());
134beda7d51SFlorian Hahn   if (!BI || !BI->isConditional())
135beda7d51SFlorian Hahn     return;
1362a266a34SFlorian Hahn 
1372a266a34SFlorian Hahn   CmpInst::Predicate Pred;
138beda7d51SFlorian Hahn   Value *Cond = BI->getCondition();
1392a266a34SFlorian Hahn   if (!match(Cond, m_ICmp(Pred, m_Value(), m_Constant())))
140beda7d51SFlorian Hahn     return;
141beda7d51SFlorian Hahn 
1422a266a34SFlorian Hahn   ICmpInst *Cmp = cast<ICmpInst>(Cond);
1432a266a34SFlorian Hahn   if (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE)
14424072566SCraig Topper     if (isCondRelevantToAnyCallArgument(Cmp, CB))
145beda7d51SFlorian Hahn       Conditions.push_back({Cmp, From->getTerminator()->getSuccessor(0) == To
146beda7d51SFlorian Hahn                                      ? Pred
147beda7d51SFlorian Hahn                                      : Cmp->getInversePredicate()});
1482a266a34SFlorian Hahn }
1492a266a34SFlorian Hahn 
15024072566SCraig Topper /// Record ICmp conditions relevant to any argument in CB following Pred's
151d83c883dSXin Tong /// single predecessors. If there are conflicting conditions along a path, like
152505091a8SFlorian Hahn /// x == 1 and x == 0, the first condition will be used. We stop once we reach
153505091a8SFlorian Hahn /// an edge to StopAt.
recordConditions(CallBase & CB,BasicBlock * Pred,ConditionsTy & Conditions,BasicBlock * StopAt)15424072566SCraig Topper static void recordConditions(CallBase &CB, BasicBlock *Pred,
155505091a8SFlorian Hahn                              ConditionsTy &Conditions, BasicBlock *StopAt) {
156beda7d51SFlorian Hahn   BasicBlock *From = Pred;
157beda7d51SFlorian Hahn   BasicBlock *To = Pred;
158212afb9fSFlorian Hahn   SmallPtrSet<BasicBlock *, 4> Visited;
159505091a8SFlorian Hahn   while (To != StopAt && !Visited.count(From->getSinglePredecessor()) &&
160beda7d51SFlorian Hahn          (From = From->getSinglePredecessor())) {
16124072566SCraig Topper     recordCondition(CB, From, To, Conditions);
162212afb9fSFlorian Hahn     Visited.insert(From);
163beda7d51SFlorian Hahn     To = From;
1640c99007dSJun Bum Lim   }
1650c99007dSJun Bum Lim }
166beda7d51SFlorian Hahn 
addConditions(CallBase & CB,const ConditionsTy & Conditions)16724072566SCraig Topper static void addConditions(CallBase &CB, const ConditionsTy &Conditions) {
168beda7d51SFlorian Hahn   for (auto &Cond : Conditions) {
169beda7d51SFlorian Hahn     Value *Arg = Cond.first->getOperand(0);
170beda7d51SFlorian Hahn     Constant *ConstVal = cast<Constant>(Cond.first->getOperand(1));
171beda7d51SFlorian Hahn     if (Cond.second == ICmpInst::ICMP_EQ)
17224072566SCraig Topper       setConstantInArgument(CB, Arg, ConstVal);
173beda7d51SFlorian Hahn     else if (ConstVal->getType()->isPointerTy() && ConstVal->isNullValue()) {
174beda7d51SFlorian Hahn       assert(Cond.second == ICmpInst::ICMP_NE);
17524072566SCraig Topper       addNonNullAttribute(CB, Arg);
176beda7d51SFlorian Hahn     }
177beda7d51SFlorian Hahn   }
178beda7d51SFlorian Hahn }
179beda7d51SFlorian Hahn 
getTwoPredecessors(BasicBlock * BB)180beda7d51SFlorian Hahn static SmallVector<BasicBlock *, 2> getTwoPredecessors(BasicBlock *BB) {
181beda7d51SFlorian Hahn   SmallVector<BasicBlock *, 2> Preds(predecessors((BB)));
182beda7d51SFlorian Hahn   assert(Preds.size() == 2 && "Expected exactly 2 predecessors!");
183beda7d51SFlorian Hahn   return Preds;
1840c99007dSJun Bum Lim }
1850c99007dSJun Bum Lim 
canSplitCallSite(CallBase & CB,TargetTransformInfo & TTI)18624072566SCraig Topper static bool canSplitCallSite(CallBase &CB, TargetTransformInfo &TTI) {
18724072566SCraig Topper   if (CB.isConvergent() || CB.cannotDuplicate())
188f80c4241SMatt Arsenault     return false;
189f80c4241SMatt Arsenault 
1900c99007dSJun Bum Lim   // FIXME: As of now we handle only CallInst. InvokeInst could be handled
1910c99007dSJun Bum Lim   // without too much effort.
19224072566SCraig Topper   if (!isa<CallInst>(CB))
1930c99007dSJun Bum Lim     return false;
1940c99007dSJun Bum Lim 
19524072566SCraig Topper   BasicBlock *CallSiteBB = CB.getParent();
196373ce7ecSAditya Kumar   // Need 2 predecessors and cannot split an edge from an IndirectBrInst.
197373ce7ecSAditya Kumar   SmallVector<BasicBlock *, 2> Preds(predecessors(CallSiteBB));
198373ce7ecSAditya Kumar   if (Preds.size() != 2 || isa<IndirectBrInst>(Preds[0]->getTerminator()) ||
199373ce7ecSAditya Kumar       isa<IndirectBrInst>(Preds[1]->getTerminator()))
200373ce7ecSAditya Kumar     return false;
201373ce7ecSAditya Kumar 
202de58e936SSanjay Patel   // BasicBlock::canSplitPredecessors is more aggressive, so checking for
203373ce7ecSAditya Kumar   // BasicBlock::isEHPad as well.
204373ce7ecSAditya Kumar   if (!CallSiteBB->canSplitPredecessors() || CallSiteBB->isEHPad())
205373ce7ecSAditya Kumar     return false;
206373ce7ecSAditya Kumar 
207b4e3bad8SFlorian Hahn   // Allow splitting a call-site only when the CodeSize cost of the
208b4e3bad8SFlorian Hahn   // instructions before the call is less then DuplicationThreshold. The
209b4e3bad8SFlorian Hahn   // instructions before the call will be duplicated in the split blocks and
210b4e3bad8SFlorian Hahn   // corresponding uses will be updated.
2119b76160eSDavid Sherwood   InstructionCost Cost = 0;
212b4e3bad8SFlorian Hahn   for (auto &InstBeforeCall :
21324072566SCraig Topper        llvm::make_range(CallSiteBB->begin(), CB.getIterator())) {
214b4e3bad8SFlorian Hahn     Cost += TTI.getInstructionCost(&InstBeforeCall,
215b4e3bad8SFlorian Hahn                                    TargetTransformInfo::TCK_CodeSize);
216b4e3bad8SFlorian Hahn     if (Cost >= DuplicationThreshold)
2170c99007dSJun Bum Lim       return false;
218b4e3bad8SFlorian Hahn   }
2190c99007dSJun Bum Lim 
220373ce7ecSAditya Kumar   return true;
2210c99007dSJun Bum Lim }
2220c99007dSJun Bum Lim 
cloneInstForMustTail(Instruction * I,Instruction * Before,Value * V)223f9e09c1dSFedor Indutny static Instruction *cloneInstForMustTail(Instruction *I, Instruction *Before,
224f9e09c1dSFedor Indutny                                          Value *V) {
225f9e09c1dSFedor Indutny   Instruction *Copy = I->clone();
226f9e09c1dSFedor Indutny   Copy->setName(I->getName());
227f9e09c1dSFedor Indutny   Copy->insertBefore(Before);
228f9e09c1dSFedor Indutny   if (V)
229f9e09c1dSFedor Indutny     Copy->setOperand(0, V);
230f9e09c1dSFedor Indutny   return Copy;
231f9e09c1dSFedor Indutny }
232f9e09c1dSFedor Indutny 
233f9e09c1dSFedor Indutny /// Copy mandatory `musttail` return sequence that follows original `CI`, and
234f9e09c1dSFedor Indutny /// link it up to `NewCI` value instead:
235c6c89bffSFlorian Hahn ///
236f9e09c1dSFedor Indutny ///   * (optional) `bitcast NewCI to ...`
237f9e09c1dSFedor Indutny ///   * `ret bitcast or NewCI`
238f9e09c1dSFedor Indutny ///
239f9e09c1dSFedor Indutny /// Insert this sequence right before `SplitBB`'s terminator, which will be
240f9e09c1dSFedor Indutny /// cleaned up later in `splitCallSite` below.
copyMustTailReturn(BasicBlock * SplitBB,Instruction * CI,Instruction * NewCI)241f9e09c1dSFedor Indutny static void copyMustTailReturn(BasicBlock *SplitBB, Instruction *CI,
242f9e09c1dSFedor Indutny                                Instruction *NewCI) {
243f9e09c1dSFedor Indutny   bool IsVoid = SplitBB->getParent()->getReturnType()->isVoidTy();
244f9e09c1dSFedor Indutny   auto II = std::next(CI->getIterator());
245f9e09c1dSFedor Indutny 
246f9e09c1dSFedor Indutny   BitCastInst* BCI = dyn_cast<BitCastInst>(&*II);
247f9e09c1dSFedor Indutny   if (BCI)
248f9e09c1dSFedor Indutny     ++II;
249f9e09c1dSFedor Indutny 
250f9e09c1dSFedor Indutny   ReturnInst* RI = dyn_cast<ReturnInst>(&*II);
251f9e09c1dSFedor Indutny   assert(RI && "`musttail` call must be followed by `ret` instruction");
252f9e09c1dSFedor Indutny 
253edb12a83SChandler Carruth   Instruction *TI = SplitBB->getTerminator();
254f9e09c1dSFedor Indutny   Value *V = NewCI;
255f9e09c1dSFedor Indutny   if (BCI)
256f9e09c1dSFedor Indutny     V = cloneInstForMustTail(BCI, TI, V);
257f9e09c1dSFedor Indutny   cloneInstForMustTail(RI, TI, IsVoid ? nullptr : V);
258f9e09c1dSFedor Indutny 
259f9e09c1dSFedor Indutny   // FIXME: remove TI here, `DuplicateInstructionsInSplitBetween` has a bug
260f9e09c1dSFedor Indutny   // that prevents doing this now.
261f9e09c1dSFedor Indutny }
262f9e09c1dSFedor Indutny 
263c6c89bffSFlorian Hahn /// For each (predecessor, conditions from predecessors) pair, it will split the
264c6c89bffSFlorian Hahn /// basic block containing the call site, hook it up to the predecessor and
265c6c89bffSFlorian Hahn /// replace the call instruction with new call instructions, which contain
266c6c89bffSFlorian Hahn /// constraints based on the conditions from their predecessors.
2677e932890SFlorian Hahn /// For example, in the IR below with an OR condition, the call-site can
268c6c89bffSFlorian Hahn /// be split. In this case, Preds for Tail is [(Header, a == null),
269c6c89bffSFlorian Hahn /// (TBB, a != null, b == null)]. Tail is replaced by 2 split blocks, containing
270c6c89bffSFlorian Hahn /// CallInst1, which has constraints based on the conditions from Head and
271c6c89bffSFlorian Hahn /// CallInst2, which has constraints based on the conditions coming from TBB.
2720c99007dSJun Bum Lim ///
2737e932890SFlorian Hahn /// From :
2740c99007dSJun Bum Lim ///
2750c99007dSJun Bum Lim ///   Header:
2760c99007dSJun Bum Lim ///     %c = icmp eq i32* %a, null
2770c99007dSJun Bum Lim ///     br i1 %c %Tail, %TBB
2780c99007dSJun Bum Lim ///   TBB:
2790c99007dSJun Bum Lim ///     %c2 = icmp eq i32* %b, null
2800c99007dSJun Bum Lim ///     br i1 %c %Tail, %End
2810c99007dSJun Bum Lim ///   Tail:
2820c99007dSJun Bum Lim ///     %ca = call i1  @callee (i32* %a, i32* %b)
2830c99007dSJun Bum Lim ///
2840c99007dSJun Bum Lim ///  to :
2850c99007dSJun Bum Lim ///
2860c99007dSJun Bum Lim ///   Header:                          // PredBB1 is Header
2870c99007dSJun Bum Lim ///     %c = icmp eq i32* %a, null
2880c99007dSJun Bum Lim ///     br i1 %c %Tail-split1, %TBB
2890c99007dSJun Bum Lim ///   TBB:                             // PredBB2 is TBB
2900c99007dSJun Bum Lim ///     %c2 = icmp eq i32* %b, null
2910c99007dSJun Bum Lim ///     br i1 %c %Tail-split2, %End
2920c99007dSJun Bum Lim ///   Tail-split1:
2930c99007dSJun Bum Lim ///     %ca1 = call @callee (i32* null, i32* %b)         // CallInst1
2940c99007dSJun Bum Lim ///    br %Tail
2950c99007dSJun Bum Lim ///   Tail-split2:
2960c99007dSJun Bum Lim ///     %ca2 = call @callee (i32* nonnull %a, i32* null) // CallInst2
2970c99007dSJun Bum Lim ///    br %Tail
2980c99007dSJun Bum Lim ///   Tail:
2990c99007dSJun Bum Lim ///    %p = phi i1 [%ca1, %Tail-split1],[%ca2, %Tail-split2]
3000c99007dSJun Bum Lim ///
3017e932890SFlorian Hahn /// Note that in case any arguments at the call-site are constrained by its
3027e932890SFlorian Hahn /// predecessors, new call-sites with more constrained arguments will be
3037e932890SFlorian Hahn /// created in createCallSitesOnPredicatedArgument().
splitCallSite(CallBase & CB,ArrayRef<std::pair<BasicBlock *,ConditionsTy>> Preds,DomTreeUpdater & DTU)304*f827ee67SAlexander Shaposhnikov static void splitCallSite(CallBase &CB,
305*f827ee67SAlexander Shaposhnikov                           ArrayRef<std::pair<BasicBlock *, ConditionsTy>> Preds,
306107d0a87SFlorian Hahn                           DomTreeUpdater &DTU) {
30724072566SCraig Topper   BasicBlock *TailBB = CB.getParent();
30824072566SCraig Topper   bool IsMustTailCall = CB.isMustTailCall();
3090c99007dSJun Bum Lim 
310c6c89bffSFlorian Hahn   PHINode *CallPN = nullptr;
311f9e09c1dSFedor Indutny 
312f9e09c1dSFedor Indutny   // `musttail` calls must be followed by optional `bitcast`, and `ret`. The
313f9e09c1dSFedor Indutny   // split blocks will be terminated right after that so there're no users for
314f9e09c1dSFedor Indutny   // this phi in a `TailBB`.
31524072566SCraig Topper   if (!IsMustTailCall && !CB.use_empty()) {
31624072566SCraig Topper     CallPN = PHINode::Create(CB.getType(), Preds.size(), "phi.call");
31724072566SCraig Topper     CallPN->setDebugLoc(CB.getDebugLoc());
3185b7e21a6SFlorian Hahn   }
3190c99007dSJun Bum Lim 
32024072566SCraig Topper   LLVM_DEBUG(dbgs() << "split call-site : " << CB << " into \n");
321b4e3bad8SFlorian Hahn 
322b4e3bad8SFlorian Hahn   assert(Preds.size() == 2 && "The ValueToValueMaps array has size 2.");
323b4e3bad8SFlorian Hahn   // ValueToValueMapTy is neither copy nor moveable, so we use a simple array
324b4e3bad8SFlorian Hahn   // here.
325b4e3bad8SFlorian Hahn   ValueToValueMapTy ValueToValueMaps[2];
326b4e3bad8SFlorian Hahn   for (unsigned i = 0; i < Preds.size(); i++) {
327b4e3bad8SFlorian Hahn     BasicBlock *PredBB = Preds[i].first;
328b4e3bad8SFlorian Hahn     BasicBlock *SplitBlock = DuplicateInstructionsInSplitBetween(
32924072566SCraig Topper         TailBB, PredBB, &*std::next(CB.getIterator()), ValueToValueMaps[i],
330107d0a87SFlorian Hahn         DTU);
331c6c89bffSFlorian Hahn     assert(SplitBlock && "Unexpected new basic block split.");
3320c99007dSJun Bum Lim 
33324072566SCraig Topper     auto *NewCI =
33424072566SCraig Topper         cast<CallBase>(&*std::prev(SplitBlock->getTerminator()->getIterator()));
33524072566SCraig Topper     addConditions(*NewCI, Preds[i].second);
3360c99007dSJun Bum Lim 
3370c99007dSJun Bum Lim     // Handle PHIs used as arguments in the call-site.
338c7fc81e6SBenjamin Kramer     for (PHINode &PN : TailBB->phis()) {
3390c99007dSJun Bum Lim       unsigned ArgNo = 0;
34024072566SCraig Topper       for (auto &CI : CB.args()) {
341c7fc81e6SBenjamin Kramer         if (&*CI == &PN) {
34224072566SCraig Topper           NewCI->setArgOperand(ArgNo, PN.getIncomingValueForBlock(SplitBlock));
3430c99007dSJun Bum Lim         }
3440c99007dSJun Bum Lim         ++ArgNo;
3450c99007dSJun Bum Lim       }
3460c99007dSJun Bum Lim     }
347d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "    " << *NewCI << " in " << SplitBlock->getName()
348c6c89bffSFlorian Hahn                       << "\n");
349c6c89bffSFlorian Hahn     if (CallPN)
350c6c89bffSFlorian Hahn       CallPN->addIncoming(NewCI, SplitBlock);
351f9e09c1dSFedor Indutny 
352f9e09c1dSFedor Indutny     // Clone and place bitcast and return instructions before `TI`
353f9e09c1dSFedor Indutny     if (IsMustTailCall)
35424072566SCraig Topper       copyMustTailReturn(SplitBlock, &CB, NewCI);
355f9e09c1dSFedor Indutny   }
356f9e09c1dSFedor Indutny 
357f9e09c1dSFedor Indutny   NumCallSiteSplit++;
358f9e09c1dSFedor Indutny 
359f9e09c1dSFedor Indutny   // FIXME: remove TI in `copyMustTailReturn`
360f9e09c1dSFedor Indutny   if (IsMustTailCall) {
361f9e09c1dSFedor Indutny     // Remove superfluous `br` terminators from the end of the Split blocks
362364b9c2aSFedor Indutny     // NOTE: Removing terminator removes the SplitBlock from the TailBB's
363364b9c2aSFedor Indutny     // predecessors. Therefore we must get complete list of Splits before
364364b9c2aSFedor Indutny     // attempting removal.
365364b9c2aSFedor Indutny     SmallVector<BasicBlock *, 2> Splits(predecessors((TailBB)));
366364b9c2aSFedor Indutny     assert(Splits.size() == 2 && "Expected exactly 2 splits!");
367926ee459SJoseph Tremoulet     for (unsigned i = 0; i < Splits.size(); i++) {
368364b9c2aSFedor Indutny       Splits[i]->getTerminator()->eraseFromParent();
36970e97163SChijun Sima       DTU.applyUpdatesPermissive({{DominatorTree::Delete, Splits[i], TailBB}});
370926ee459SJoseph Tremoulet     }
371f9e09c1dSFedor Indutny 
372f9e09c1dSFedor Indutny     // Erase the tail block once done with musttail patching
373107d0a87SFlorian Hahn     DTU.deleteBB(TailBB);
374f9e09c1dSFedor Indutny     return;
375c6c89bffSFlorian Hahn   }
3760c99007dSJun Bum Lim 
377b4e3bad8SFlorian Hahn   auto *OriginalBegin = &*TailBB->begin();
3780c99007dSJun Bum Lim   // Replace users of the original call with a PHI mering call-sites split.
379c6c89bffSFlorian Hahn   if (CallPN) {
380b4e3bad8SFlorian Hahn     CallPN->insertBefore(OriginalBegin);
38124072566SCraig Topper     CB.replaceAllUsesWith(CallPN);
3820c99007dSJun Bum Lim   }
383c6c89bffSFlorian Hahn 
384b4e3bad8SFlorian Hahn   // Remove instructions moved to split blocks from TailBB, from the duplicated
385b4e3bad8SFlorian Hahn   // call instruction to the beginning of the basic block. If an instruction
386b4e3bad8SFlorian Hahn   // has any uses, add a new PHI node to combine the values coming from the
387b4e3bad8SFlorian Hahn   // split blocks. The new PHI nodes are placed before the first original
388b4e3bad8SFlorian Hahn   // instruction, so we do not end up deleting them. By using reverse-order, we
389b4e3bad8SFlorian Hahn   // do not introduce unnecessary PHI nodes for def-use chains from the call
390b4e3bad8SFlorian Hahn   // instruction to the beginning of the block.
39124072566SCraig Topper   auto I = CB.getReverseIterator();
392b4e3bad8SFlorian Hahn   while (I != TailBB->rend()) {
393b4e3bad8SFlorian Hahn     Instruction *CurrentI = &*I++;
394b4e3bad8SFlorian Hahn     if (!CurrentI->use_empty()) {
395b4e3bad8SFlorian Hahn       // If an existing PHI has users after the call, there is no need to create
396b4e3bad8SFlorian Hahn       // a new one.
397b4e3bad8SFlorian Hahn       if (isa<PHINode>(CurrentI))
398b4e3bad8SFlorian Hahn         continue;
399b4e3bad8SFlorian Hahn       PHINode *NewPN = PHINode::Create(CurrentI->getType(), Preds.size());
4005b7e21a6SFlorian Hahn       NewPN->setDebugLoc(CurrentI->getDebugLoc());
401b4e3bad8SFlorian Hahn       for (auto &Mapping : ValueToValueMaps)
402b4e3bad8SFlorian Hahn         NewPN->addIncoming(Mapping[CurrentI],
403b4e3bad8SFlorian Hahn                            cast<Instruction>(Mapping[CurrentI])->getParent());
404b4e3bad8SFlorian Hahn       NewPN->insertBefore(&*TailBB->begin());
405b4e3bad8SFlorian Hahn       CurrentI->replaceAllUsesWith(NewPN);
406b4e3bad8SFlorian Hahn     }
407b4e3bad8SFlorian Hahn     CurrentI->eraseFromParent();
408b4e3bad8SFlorian Hahn     // We are done once we handled the first original instruction in TailBB.
409b4e3bad8SFlorian Hahn     if (CurrentI == OriginalBegin)
410b4e3bad8SFlorian Hahn       break;
411b4e3bad8SFlorian Hahn   }
4120c99007dSJun Bum Lim }
4130c99007dSJun Bum Lim 
4140c99007dSJun Bum Lim // Return true if the call-site has an argument which is a PHI with only
4150c99007dSJun Bum Lim // constant incoming values.
isPredicatedOnPHI(CallBase & CB)41624072566SCraig Topper static bool isPredicatedOnPHI(CallBase &CB) {
41724072566SCraig Topper   BasicBlock *Parent = CB.getParent();
41824072566SCraig Topper   if (&CB != Parent->getFirstNonPHIOrDbg())
4190c99007dSJun Bum Lim     return false;
4200c99007dSJun Bum Lim 
421a63b5c9eSFlorian Hahn   for (auto &PN : Parent->phis()) {
42224072566SCraig Topper     for (auto &Arg : CB.args()) {
423a63b5c9eSFlorian Hahn       if (&*Arg != &PN)
4240c99007dSJun Bum Lim         continue;
425a63b5c9eSFlorian Hahn       assert(PN.getNumIncomingValues() == 2 &&
426a63b5c9eSFlorian Hahn              "Unexpected number of incoming values");
427a63b5c9eSFlorian Hahn       if (PN.getIncomingBlock(0) == PN.getIncomingBlock(1))
428a63b5c9eSFlorian Hahn         return false;
429a63b5c9eSFlorian Hahn       if (PN.getIncomingValue(0) == PN.getIncomingValue(1))
430a63b5c9eSFlorian Hahn         continue;
431a63b5c9eSFlorian Hahn       if (isa<Constant>(PN.getIncomingValue(0)) &&
432a63b5c9eSFlorian Hahn           isa<Constant>(PN.getIncomingValue(1)))
4330c99007dSJun Bum Lim         return true;
4340c99007dSJun Bum Lim     }
4350c99007dSJun Bum Lim   }
4360c99007dSJun Bum Lim   return false;
4370c99007dSJun Bum Lim }
4380c99007dSJun Bum Lim 
439107d0a87SFlorian Hahn using PredsWithCondsTy = SmallVector<std::pair<BasicBlock *, ConditionsTy>, 2>;
440107d0a87SFlorian Hahn 
441107d0a87SFlorian Hahn // Check if any of the arguments in CS are predicated on a PHI node and return
442107d0a87SFlorian Hahn // the set of predecessors we should use for splitting.
shouldSplitOnPHIPredicatedArgument(CallBase & CB)44324072566SCraig Topper static PredsWithCondsTy shouldSplitOnPHIPredicatedArgument(CallBase &CB) {
44424072566SCraig Topper   if (!isPredicatedOnPHI(CB))
445107d0a87SFlorian Hahn     return {};
4460c99007dSJun Bum Lim 
44724072566SCraig Topper   auto Preds = getTwoPredecessors(CB.getParent());
448107d0a87SFlorian Hahn   return {{Preds[0], {}}, {Preds[1], {}}};
4492a266a34SFlorian Hahn }
4500c99007dSJun Bum Lim 
451107d0a87SFlorian Hahn // Checks if any of the arguments in CS are predicated in a predecessor and
452107d0a87SFlorian Hahn // returns a list of predecessors with the conditions that hold on their edges
453107d0a87SFlorian Hahn // to CS.
shouldSplitOnPredicatedArgument(CallBase & CB,DomTreeUpdater & DTU)45424072566SCraig Topper static PredsWithCondsTy shouldSplitOnPredicatedArgument(CallBase &CB,
455505091a8SFlorian Hahn                                                         DomTreeUpdater &DTU) {
45624072566SCraig Topper   auto Preds = getTwoPredecessors(CB.getParent());
4577e932890SFlorian Hahn   if (Preds[0] == Preds[1])
458107d0a87SFlorian Hahn     return {};
4592a266a34SFlorian Hahn 
460505091a8SFlorian Hahn   // We can stop recording conditions once we reached the immediate dominator
461505091a8SFlorian Hahn   // for the block containing the call site. Conditions in predecessors of the
462505091a8SFlorian Hahn   // that node will be the same for all paths to the call site and splitting
463505091a8SFlorian Hahn   // is not beneficial.
464505091a8SFlorian Hahn   assert(DTU.hasDomTree() && "We need a DTU with a valid DT!");
46524072566SCraig Topper   auto *CSDTNode = DTU.getDomTree().getNode(CB.getParent());
466505091a8SFlorian Hahn   BasicBlock *StopAt = CSDTNode ? CSDTNode->getIDom()->getBlock() : nullptr;
467505091a8SFlorian Hahn 
468c6c89bffSFlorian Hahn   SmallVector<std::pair<BasicBlock *, ConditionsTy>, 2> PredsCS;
469843d1edaSKazu Hirata   for (auto *Pred : llvm::reverse(Preds)) {
470c6c89bffSFlorian Hahn     ConditionsTy Conditions;
471505091a8SFlorian Hahn     // Record condition on edge BB(CS) <- Pred
47224072566SCraig Topper     recordCondition(CB, Pred, CB.getParent(), Conditions);
473505091a8SFlorian Hahn     // Record conditions following Pred's single predecessors.
47424072566SCraig Topper     recordConditions(CB, Pred, Conditions, StopAt);
475c6c89bffSFlorian Hahn     PredsCS.push_back({Pred, Conditions});
476c6c89bffSFlorian Hahn   }
4772a266a34SFlorian Hahn 
4782e83b2e9SFangrui Song   if (all_of(PredsCS, [](const std::pair<BasicBlock *, ConditionsTy> &P) {
479c6c89bffSFlorian Hahn         return P.second.empty();
480c6c89bffSFlorian Hahn       }))
481107d0a87SFlorian Hahn     return {};
482beda7d51SFlorian Hahn 
483107d0a87SFlorian Hahn   return PredsCS;
4840c99007dSJun Bum Lim }
4850c99007dSJun Bum Lim 
tryToSplitCallSite(CallBase & CB,TargetTransformInfo & TTI,DomTreeUpdater & DTU)48624072566SCraig Topper static bool tryToSplitCallSite(CallBase &CB, TargetTransformInfo &TTI,
487107d0a87SFlorian Hahn                                DomTreeUpdater &DTU) {
488107d0a87SFlorian Hahn   // Check if we can split the call site.
48924072566SCraig Topper   if (!CB.arg_size() || !canSplitCallSite(CB, TTI))
4900c99007dSJun Bum Lim     return false;
491107d0a87SFlorian Hahn 
49224072566SCraig Topper   auto PredsWithConds = shouldSplitOnPredicatedArgument(CB, DTU);
493107d0a87SFlorian Hahn   if (PredsWithConds.empty())
49424072566SCraig Topper     PredsWithConds = shouldSplitOnPHIPredicatedArgument(CB);
495107d0a87SFlorian Hahn   if (PredsWithConds.empty())
496107d0a87SFlorian Hahn     return false;
497107d0a87SFlorian Hahn 
49824072566SCraig Topper   splitCallSite(CB, PredsWithConds, DTU);
499107d0a87SFlorian Hahn   return true;
5000c99007dSJun Bum Lim }
5010c99007dSJun Bum Lim 
doCallSiteSplitting(Function & F,TargetLibraryInfo & TLI,TargetTransformInfo & TTI,DominatorTree & DT)502b4e3bad8SFlorian Hahn static bool doCallSiteSplitting(Function &F, TargetLibraryInfo &TLI,
503505091a8SFlorian Hahn                                 TargetTransformInfo &TTI, DominatorTree &DT) {
504107d0a87SFlorian Hahn 
505505091a8SFlorian Hahn   DomTreeUpdater DTU(&DT, DomTreeUpdater::UpdateStrategy::Lazy);
5060c99007dSJun Bum Lim   bool Changed = false;
5078e86c0e4SKazu Hirata   for (BasicBlock &BB : llvm::make_early_inc_range(F)) {
508517dc51cSFlorian Hahn     auto II = BB.getFirstNonPHIOrDbg()->getIterator();
509517dc51cSFlorian Hahn     auto IE = BB.getTerminator()->getIterator();
510517dc51cSFlorian Hahn     // Iterate until we reach the terminator instruction. tryToSplitCallSite
511517dc51cSFlorian Hahn     // can replace BB's terminator in case BB is a successor of itself. In that
512517dc51cSFlorian Hahn     // case, IE will be invalidated and we also have to check the current
513517dc51cSFlorian Hahn     // terminator.
514517dc51cSFlorian Hahn     while (II != IE && &*II != BB.getTerminator()) {
51524072566SCraig Topper       CallBase *CB = dyn_cast<CallBase>(&*II++);
51624072566SCraig Topper       if (!CB || isa<IntrinsicInst>(CB) || isInstructionTriviallyDead(CB, &TLI))
5170c99007dSJun Bum Lim         continue;
5180c99007dSJun Bum Lim 
51924072566SCraig Topper       Function *Callee = CB->getCalledFunction();
5200c99007dSJun Bum Lim       if (!Callee || Callee->isDeclaration())
5210c99007dSJun Bum Lim         continue;
522f9e09c1dSFedor Indutny 
523f9e09c1dSFedor Indutny       // Successful musttail call-site splits result in erased CI and erased BB.
524f9e09c1dSFedor Indutny       // Check if such path is possible before attempting the splitting.
52524072566SCraig Topper       bool IsMustTail = CB->isMustTailCall();
526f9e09c1dSFedor Indutny 
52724072566SCraig Topper       Changed |= tryToSplitCallSite(*CB, TTI, DTU);
528f9e09c1dSFedor Indutny 
529f9e09c1dSFedor Indutny       // There're no interesting instructions after this. The call site
530f9e09c1dSFedor Indutny       // itself might have been erased on splitting.
531f9e09c1dSFedor Indutny       if (IsMustTail)
532f9e09c1dSFedor Indutny         break;
5330c99007dSJun Bum Lim     }
5340c99007dSJun Bum Lim   }
5350c99007dSJun Bum Lim   return Changed;
5360c99007dSJun Bum Lim }
5370c99007dSJun Bum Lim 
5380c99007dSJun Bum Lim namespace {
5390c99007dSJun Bum Lim struct CallSiteSplittingLegacyPass : public FunctionPass {
5400c99007dSJun Bum Lim   static char ID;
CallSiteSplittingLegacyPass__anonfebdf5120211::CallSiteSplittingLegacyPass5410c99007dSJun Bum Lim   CallSiteSplittingLegacyPass() : FunctionPass(ID) {
5420c99007dSJun Bum Lim     initializeCallSiteSplittingLegacyPassPass(*PassRegistry::getPassRegistry());
5430c99007dSJun Bum Lim   }
5440c99007dSJun Bum Lim 
getAnalysisUsage__anonfebdf5120211::CallSiteSplittingLegacyPass5450c99007dSJun Bum Lim   void getAnalysisUsage(AnalysisUsage &AU) const override {
5460c99007dSJun Bum Lim     AU.addRequired<TargetLibraryInfoWrapperPass>();
547b4e3bad8SFlorian Hahn     AU.addRequired<TargetTransformInfoWrapperPass>();
548505091a8SFlorian Hahn     AU.addRequired<DominatorTreeWrapperPass>();
5499bc0bc4bSFlorian Hahn     AU.addPreserved<DominatorTreeWrapperPass>();
5500c99007dSJun Bum Lim     FunctionPass::getAnalysisUsage(AU);
5510c99007dSJun Bum Lim   }
5520c99007dSJun Bum Lim 
runOnFunction__anonfebdf5120211::CallSiteSplittingLegacyPass5530c99007dSJun Bum Lim   bool runOnFunction(Function &F) override {
5540c99007dSJun Bum Lim     if (skipFunction(F))
5550c99007dSJun Bum Lim       return false;
5560c99007dSJun Bum Lim 
5579c27b59cSTeresa Johnson     auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
558b4e3bad8SFlorian Hahn     auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
559505091a8SFlorian Hahn     auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
560505091a8SFlorian Hahn     return doCallSiteSplitting(F, TLI, TTI, DT);
5610c99007dSJun Bum Lim   }
5620c99007dSJun Bum Lim };
5630c99007dSJun Bum Lim } // namespace
5640c99007dSJun Bum Lim 
5650c99007dSJun Bum Lim char CallSiteSplittingLegacyPass::ID = 0;
5660c99007dSJun Bum Lim INITIALIZE_PASS_BEGIN(CallSiteSplittingLegacyPass, "callsite-splitting",
5670c99007dSJun Bum Lim                       "Call-site splitting", false, false)
INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)5680c99007dSJun Bum Lim INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
569b4e3bad8SFlorian Hahn INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
570505091a8SFlorian Hahn INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
5710c99007dSJun Bum Lim INITIALIZE_PASS_END(CallSiteSplittingLegacyPass, "callsite-splitting",
5720c99007dSJun Bum Lim                     "Call-site splitting", false, false)
5730c99007dSJun Bum Lim FunctionPass *llvm::createCallSiteSplittingPass() {
5740c99007dSJun Bum Lim   return new CallSiteSplittingLegacyPass();
5750c99007dSJun Bum Lim }
5760c99007dSJun Bum Lim 
run(Function & F,FunctionAnalysisManager & AM)5770c99007dSJun Bum Lim PreservedAnalyses CallSiteSplittingPass::run(Function &F,
5780c99007dSJun Bum Lim                                              FunctionAnalysisManager &AM) {
5790c99007dSJun Bum Lim   auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
580b4e3bad8SFlorian Hahn   auto &TTI = AM.getResult<TargetIRAnalysis>(F);
581505091a8SFlorian Hahn   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
5820c99007dSJun Bum Lim 
5839bc0bc4bSFlorian Hahn   if (!doCallSiteSplitting(F, TLI, TTI, DT))
5840c99007dSJun Bum Lim     return PreservedAnalyses::all();
5850c99007dSJun Bum Lim   PreservedAnalyses PA;
5869bc0bc4bSFlorian Hahn   PA.preserve<DominatorTreeAnalysis>();
5870c99007dSJun Bum Lim   return PA;
5880c99007dSJun Bum Lim }
589