1 //===- CallSiteSplitting.cpp ----------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements a transformation that tries to split a call-site to pass
11 // more constrained arguments if its argument is predicated in the control flow
12 // so that we can expose better context to the later passes (e.g, inliner, jump
13 // threading, or IPA-CP based function cloning, etc.).
14 // As of now we support two cases :
16 // 1) Try to a split call-site with constrained arguments, if any constraints
17 // on any argument can be found by following the single predecessors of the
18 // all site's predecessors. Currently this pass only handles call-sites with 2
19 // predecessors. For example, in the code below, we try to split the call-site
20 // since we can predicate the argument(ptr) based on the OR condition.
27 // callee(null) // set the known constant value
29 // callee(nonnull ptr) // set non-null attribute in the argument
31 // 2) We can also split a call-site based on constant incoming values of a PHI
35 // %c = icmp eq i32 %i1, %i2
36 // br i1 %c, label %Tail, label %TBB
40 // %p = phi i32 [ 0, %Header], [ 1, %TBB]
41 // call void @bar(i32 %p)
44 // %c = icmp eq i32 %i1, %i2
45 // br i1 %c, label %Tail-split0, label %TBB
47 // br label %Tail-split1
49 // call void @bar(i32 0)
52 // call void @bar(i32 1)
55 // %p = phi i32 [ 0, %Tail-split0 ], [ 1, %Tail-split1 ]
57 //===----------------------------------------------------------------------===//
59 #include "llvm/Transforms/Scalar/CallSiteSplitting.h"
60 #include "llvm/ADT/Statistic.h"
61 #include "llvm/Analysis/TargetLibraryInfo.h"
62 #include "llvm/Analysis/TargetTransformInfo.h"
63 #include "llvm/Transforms/Utils/Local.h"
64 #include "llvm/IR/IntrinsicInst.h"
65 #include "llvm/IR/PatternMatch.h"
66 #include "llvm/Support/Debug.h"
67 #include "llvm/Transforms/Scalar.h"
68 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
69 #include "llvm/Transforms/Utils/Cloning.h"
72 using namespace PatternMatch;
74 #define DEBUG_TYPE "callsite-splitting"
76 STATISTIC(NumCallSiteSplit, "Number of call-site split");
78 /// Only allow instructions before a call, if their CodeSize cost is below
79 /// DuplicationThreshold. Those instructions need to be duplicated in all
81 static cl::opt<unsigned>
82 DuplicationThreshold("callsite-splitting-duplication-threshold", cl::Hidden,
83 cl::desc("Only allow instructions before a call, if "
84 "their cost is below DuplicationThreshold"),
87 static void addNonNullAttribute(CallSite CS, Value *Op) {
89 for (auto &I : CS.args()) {
91 CS.addParamAttr(ArgNo, Attribute::NonNull);
96 static void setConstantInArgument(CallSite CS, Value *Op,
97 Constant *ConstValue) {
99 for (auto &I : CS.args()) {
101 // It is possible we have already added the non-null attribute to the
102 // parameter by using an earlier constraining condition.
103 CS.removeParamAttr(ArgNo, Attribute::NonNull);
104 CS.setArgument(ArgNo, ConstValue);
110 static bool isCondRelevantToAnyCallArgument(ICmpInst *Cmp, CallSite CS) {
111 assert(isa<Constant>(Cmp->getOperand(1)) && "Expected a constant operand.");
112 Value *Op0 = Cmp->getOperand(0);
114 for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); I != E;
116 // Don't consider constant or arguments that are already known non-null.
117 if (isa<Constant>(*I) || CS.paramHasAttr(ArgNo, Attribute::NonNull))
126 typedef std::pair<ICmpInst *, unsigned> ConditionTy;
127 typedef SmallVector<ConditionTy, 2> ConditionsTy;
129 /// If From has a conditional jump to To, add the condition to Conditions,
130 /// if it is relevant to any argument at CS.
131 static void recordCondition(CallSite CS, BasicBlock *From, BasicBlock *To,
132 ConditionsTy &Conditions) {
133 auto *BI = dyn_cast<BranchInst>(From->getTerminator());
134 if (!BI || !BI->isConditional())
137 CmpInst::Predicate Pred;
138 Value *Cond = BI->getCondition();
139 if (!match(Cond, m_ICmp(Pred, m_Value(), m_Constant())))
142 ICmpInst *Cmp = cast<ICmpInst>(Cond);
143 if (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE)
144 if (isCondRelevantToAnyCallArgument(Cmp, CS))
145 Conditions.push_back({Cmp, From->getTerminator()->getSuccessor(0) == To
147 : Cmp->getInversePredicate()});
150 /// Record ICmp conditions relevant to any argument in CS following Pred's
151 /// single predecessors. If there are conflicting conditions along a path, like
152 /// x == 1 and x == 0, the first condition will be used. We stop once we reach
153 /// an edge to StopAt.
154 static void recordConditions(CallSite CS, BasicBlock *Pred,
155 ConditionsTy &Conditions, BasicBlock *StopAt) {
156 BasicBlock *From = Pred;
157 BasicBlock *To = Pred;
158 SmallPtrSet<BasicBlock *, 4> Visited;
159 while (To != StopAt && !Visited.count(From->getSinglePredecessor()) &&
160 (From = From->getSinglePredecessor())) {
161 recordCondition(CS, From, To, Conditions);
162 Visited.insert(From);
167 static void addConditions(CallSite CS, const ConditionsTy &Conditions) {
168 for (auto &Cond : Conditions) {
169 Value *Arg = Cond.first->getOperand(0);
170 Constant *ConstVal = cast<Constant>(Cond.first->getOperand(1));
171 if (Cond.second == ICmpInst::ICMP_EQ)
172 setConstantInArgument(CS, Arg, ConstVal);
173 else if (ConstVal->getType()->isPointerTy() && ConstVal->isNullValue()) {
174 assert(Cond.second == ICmpInst::ICMP_NE);
175 addNonNullAttribute(CS, Arg);
180 static SmallVector<BasicBlock *, 2> getTwoPredecessors(BasicBlock *BB) {
181 SmallVector<BasicBlock *, 2> Preds(predecessors((BB)));
182 assert(Preds.size() == 2 && "Expected exactly 2 predecessors!");
186 static bool canSplitCallSite(CallSite CS, TargetTransformInfo &TTI) {
187 // FIXME: As of now we handle only CallInst. InvokeInst could be handled
188 // without too much effort.
189 Instruction *Instr = CS.getInstruction();
190 if (!isa<CallInst>(Instr))
193 BasicBlock *CallSiteBB = Instr->getParent();
194 // Need 2 predecessors and cannot split an edge from an IndirectBrInst.
195 SmallVector<BasicBlock *, 2> Preds(predecessors(CallSiteBB));
196 if (Preds.size() != 2 || isa<IndirectBrInst>(Preds[0]->getTerminator()) ||
197 isa<IndirectBrInst>(Preds[1]->getTerminator()))
200 // BasicBlock::canSplitPredecessors is more aggressive, so checking for
201 // BasicBlock::isEHPad as well.
202 if (!CallSiteBB->canSplitPredecessors() || CallSiteBB->isEHPad())
205 // Allow splitting a call-site only when the CodeSize cost of the
206 // instructions before the call is less then DuplicationThreshold. The
207 // instructions before the call will be duplicated in the split blocks and
208 // corresponding uses will be updated.
210 for (auto &InstBeforeCall :
211 llvm::make_range(CallSiteBB->begin(), Instr->getIterator())) {
212 Cost += TTI.getInstructionCost(&InstBeforeCall,
213 TargetTransformInfo::TCK_CodeSize);
214 if (Cost >= DuplicationThreshold)
221 static Instruction *cloneInstForMustTail(Instruction *I, Instruction *Before,
223 Instruction *Copy = I->clone();
224 Copy->setName(I->getName());
225 Copy->insertBefore(Before);
227 Copy->setOperand(0, V);
231 /// Copy mandatory `musttail` return sequence that follows original `CI`, and
232 /// link it up to `NewCI` value instead:
234 /// * (optional) `bitcast NewCI to ...`
235 /// * `ret bitcast or NewCI`
237 /// Insert this sequence right before `SplitBB`'s terminator, which will be
238 /// cleaned up later in `splitCallSite` below.
239 static void copyMustTailReturn(BasicBlock *SplitBB, Instruction *CI,
240 Instruction *NewCI) {
241 bool IsVoid = SplitBB->getParent()->getReturnType()->isVoidTy();
242 auto II = std::next(CI->getIterator());
244 BitCastInst* BCI = dyn_cast<BitCastInst>(&*II);
248 ReturnInst* RI = dyn_cast<ReturnInst>(&*II);
249 assert(RI && "`musttail` call must be followed by `ret` instruction");
251 Instruction *TI = SplitBB->getTerminator();
254 V = cloneInstForMustTail(BCI, TI, V);
255 cloneInstForMustTail(RI, TI, IsVoid ? nullptr : V);
257 // FIXME: remove TI here, `DuplicateInstructionsInSplitBetween` has a bug
258 // that prevents doing this now.
261 /// For each (predecessor, conditions from predecessors) pair, it will split the
262 /// basic block containing the call site, hook it up to the predecessor and
263 /// replace the call instruction with new call instructions, which contain
264 /// constraints based on the conditions from their predecessors.
265 /// For example, in the IR below with an OR condition, the call-site can
266 /// be split. In this case, Preds for Tail is [(Header, a == null),
267 /// (TBB, a != null, b == null)]. Tail is replaced by 2 split blocks, containing
268 /// CallInst1, which has constraints based on the conditions from Head and
269 /// CallInst2, which has constraints based on the conditions coming from TBB.
274 /// %c = icmp eq i32* %a, null
275 /// br i1 %c %Tail, %TBB
277 /// %c2 = icmp eq i32* %b, null
278 /// br i1 %c %Tail, %End
280 /// %ca = call i1 @callee (i32* %a, i32* %b)
284 /// Header: // PredBB1 is Header
285 /// %c = icmp eq i32* %a, null
286 /// br i1 %c %Tail-split1, %TBB
287 /// TBB: // PredBB2 is TBB
288 /// %c2 = icmp eq i32* %b, null
289 /// br i1 %c %Tail-split2, %End
291 /// %ca1 = call @callee (i32* null, i32* %b) // CallInst1
294 /// %ca2 = call @callee (i32* nonnull %a, i32* null) // CallInst2
297 /// %p = phi i1 [%ca1, %Tail-split1],[%ca2, %Tail-split2]
299 /// Note that in case any arguments at the call-site are constrained by its
300 /// predecessors, new call-sites with more constrained arguments will be
301 /// created in createCallSitesOnPredicatedArgument().
302 static void splitCallSite(
304 const SmallVectorImpl<std::pair<BasicBlock *, ConditionsTy>> &Preds,
305 DomTreeUpdater &DTU) {
306 Instruction *Instr = CS.getInstruction();
307 BasicBlock *TailBB = Instr->getParent();
308 bool IsMustTailCall = CS.isMustTailCall();
310 PHINode *CallPN = nullptr;
312 // `musttail` calls must be followed by optional `bitcast`, and `ret`. The
313 // split blocks will be terminated right after that so there're no users for
314 // this phi in a `TailBB`.
315 if (!IsMustTailCall && !Instr->use_empty()) {
316 CallPN = PHINode::Create(Instr->getType(), Preds.size(), "phi.call");
317 CallPN->setDebugLoc(Instr->getDebugLoc());
320 LLVM_DEBUG(dbgs() << "split call-site : " << *Instr << " into \n");
322 assert(Preds.size() == 2 && "The ValueToValueMaps array has size 2.");
323 // ValueToValueMapTy is neither copy nor moveable, so we use a simple array
325 ValueToValueMapTy ValueToValueMaps[2];
326 for (unsigned i = 0; i < Preds.size(); i++) {
327 BasicBlock *PredBB = Preds[i].first;
328 BasicBlock *SplitBlock = DuplicateInstructionsInSplitBetween(
329 TailBB, PredBB, &*std::next(Instr->getIterator()), ValueToValueMaps[i],
331 assert(SplitBlock && "Unexpected new basic block split.");
334 &*std::prev(SplitBlock->getTerminator()->getIterator());
335 CallSite NewCS(NewCI);
336 addConditions(NewCS, Preds[i].second);
338 // Handle PHIs used as arguments in the call-site.
339 for (PHINode &PN : TailBB->phis()) {
341 for (auto &CI : CS.args()) {
343 NewCS.setArgument(ArgNo, PN.getIncomingValueForBlock(SplitBlock));
348 LLVM_DEBUG(dbgs() << " " << *NewCI << " in " << SplitBlock->getName()
351 CallPN->addIncoming(NewCI, SplitBlock);
353 // Clone and place bitcast and return instructions before `TI`
355 copyMustTailReturn(SplitBlock, Instr, NewCI);
360 // FIXME: remove TI in `copyMustTailReturn`
361 if (IsMustTailCall) {
362 // Remove superfluous `br` terminators from the end of the Split blocks
363 // NOTE: Removing terminator removes the SplitBlock from the TailBB's
364 // predecessors. Therefore we must get complete list of Splits before
365 // attempting removal.
366 SmallVector<BasicBlock *, 2> Splits(predecessors((TailBB)));
367 assert(Splits.size() == 2 && "Expected exactly 2 splits!");
368 for (unsigned i = 0; i < Splits.size(); i++) {
369 Splits[i]->getTerminator()->eraseFromParent();
370 DTU.deleteEdge(Splits[i], TailBB);
373 // Erase the tail block once done with musttail patching
374 DTU.deleteBB(TailBB);
378 auto *OriginalBegin = &*TailBB->begin();
379 // Replace users of the original call with a PHI mering call-sites split.
381 CallPN->insertBefore(OriginalBegin);
382 Instr->replaceAllUsesWith(CallPN);
385 // Remove instructions moved to split blocks from TailBB, from the duplicated
386 // call instruction to the beginning of the basic block. If an instruction
387 // has any uses, add a new PHI node to combine the values coming from the
388 // split blocks. The new PHI nodes are placed before the first original
389 // instruction, so we do not end up deleting them. By using reverse-order, we
390 // do not introduce unnecessary PHI nodes for def-use chains from the call
391 // instruction to the beginning of the block.
392 auto I = Instr->getReverseIterator();
393 while (I != TailBB->rend()) {
394 Instruction *CurrentI = &*I++;
395 if (!CurrentI->use_empty()) {
396 // If an existing PHI has users after the call, there is no need to create
398 if (isa<PHINode>(CurrentI))
400 PHINode *NewPN = PHINode::Create(CurrentI->getType(), Preds.size());
401 NewPN->setDebugLoc(CurrentI->getDebugLoc());
402 for (auto &Mapping : ValueToValueMaps)
403 NewPN->addIncoming(Mapping[CurrentI],
404 cast<Instruction>(Mapping[CurrentI])->getParent());
405 NewPN->insertBefore(&*TailBB->begin());
406 CurrentI->replaceAllUsesWith(NewPN);
408 CurrentI->eraseFromParent();
409 // We are done once we handled the first original instruction in TailBB.
410 if (CurrentI == OriginalBegin)
415 // Return true if the call-site has an argument which is a PHI with only
416 // constant incoming values.
417 static bool isPredicatedOnPHI(CallSite CS) {
418 Instruction *Instr = CS.getInstruction();
419 BasicBlock *Parent = Instr->getParent();
420 if (Instr != Parent->getFirstNonPHIOrDbg())
423 for (auto &BI : *Parent) {
424 if (PHINode *PN = dyn_cast<PHINode>(&BI)) {
425 for (auto &I : CS.args())
427 assert(PN->getNumIncomingValues() == 2 &&
428 "Unexpected number of incoming values");
429 if (PN->getIncomingBlock(0) == PN->getIncomingBlock(1))
431 if (PN->getIncomingValue(0) == PN->getIncomingValue(1))
433 if (isa<Constant>(PN->getIncomingValue(0)) &&
434 isa<Constant>(PN->getIncomingValue(1)))
443 using PredsWithCondsTy = SmallVector<std::pair<BasicBlock *, ConditionsTy>, 2>;
445 // Check if any of the arguments in CS are predicated on a PHI node and return
446 // the set of predecessors we should use for splitting.
447 static PredsWithCondsTy shouldSplitOnPHIPredicatedArgument(CallSite CS) {
448 if (!isPredicatedOnPHI(CS))
451 auto Preds = getTwoPredecessors(CS.getInstruction()->getParent());
452 return {{Preds[0], {}}, {Preds[1], {}}};
455 // Checks if any of the arguments in CS are predicated in a predecessor and
456 // returns a list of predecessors with the conditions that hold on their edges
458 static PredsWithCondsTy shouldSplitOnPredicatedArgument(CallSite CS,
459 DomTreeUpdater &DTU) {
460 auto Preds = getTwoPredecessors(CS.getInstruction()->getParent());
461 if (Preds[0] == Preds[1])
464 // We can stop recording conditions once we reached the immediate dominator
465 // for the block containing the call site. Conditions in predecessors of the
466 // that node will be the same for all paths to the call site and splitting
467 // is not beneficial.
468 assert(DTU.hasDomTree() && "We need a DTU with a valid DT!");
469 auto *CSDTNode = DTU.getDomTree().getNode(CS.getInstruction()->getParent());
470 BasicBlock *StopAt = CSDTNode ? CSDTNode->getIDom()->getBlock() : nullptr;
472 SmallVector<std::pair<BasicBlock *, ConditionsTy>, 2> PredsCS;
473 for (auto *Pred : make_range(Preds.rbegin(), Preds.rend())) {
474 ConditionsTy Conditions;
475 // Record condition on edge BB(CS) <- Pred
476 recordCondition(CS, Pred, CS.getInstruction()->getParent(), Conditions);
477 // Record conditions following Pred's single predecessors.
478 recordConditions(CS, Pred, Conditions, StopAt);
479 PredsCS.push_back({Pred, Conditions});
482 if (all_of(PredsCS, [](const std::pair<BasicBlock *, ConditionsTy> &P) {
483 return P.second.empty();
490 static bool tryToSplitCallSite(CallSite CS, TargetTransformInfo &TTI,
491 DomTreeUpdater &DTU) {
492 // Check if we can split the call site.
493 if (!CS.arg_size() || !canSplitCallSite(CS, TTI))
496 auto PredsWithConds = shouldSplitOnPredicatedArgument(CS, DTU);
497 if (PredsWithConds.empty())
498 PredsWithConds = shouldSplitOnPHIPredicatedArgument(CS);
499 if (PredsWithConds.empty())
502 splitCallSite(CS, PredsWithConds, DTU);
506 static bool doCallSiteSplitting(Function &F, TargetLibraryInfo &TLI,
507 TargetTransformInfo &TTI, DominatorTree &DT) {
509 DomTreeUpdater DTU(&DT, DomTreeUpdater::UpdateStrategy::Lazy);
510 bool Changed = false;
511 for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE;) {
512 BasicBlock &BB = *BI++;
513 auto II = BB.getFirstNonPHIOrDbg()->getIterator();
514 auto IE = BB.getTerminator()->getIterator();
515 // Iterate until we reach the terminator instruction. tryToSplitCallSite
516 // can replace BB's terminator in case BB is a successor of itself. In that
517 // case, IE will be invalidated and we also have to check the current
519 while (II != IE && &*II != BB.getTerminator()) {
520 Instruction *I = &*II++;
521 CallSite CS(cast<Value>(I));
522 if (!CS || isa<IntrinsicInst>(I) || isInstructionTriviallyDead(I, &TLI))
525 Function *Callee = CS.getCalledFunction();
526 if (!Callee || Callee->isDeclaration())
529 // Successful musttail call-site splits result in erased CI and erased BB.
530 // Check if such path is possible before attempting the splitting.
531 bool IsMustTail = CS.isMustTailCall();
533 Changed |= tryToSplitCallSite(CS, TTI, DTU);
535 // There're no interesting instructions after this. The call site
536 // itself might have been erased on splitting.
545 struct CallSiteSplittingLegacyPass : public FunctionPass {
547 CallSiteSplittingLegacyPass() : FunctionPass(ID) {
548 initializeCallSiteSplittingLegacyPassPass(*PassRegistry::getPassRegistry());
551 void getAnalysisUsage(AnalysisUsage &AU) const override {
552 AU.addRequired<TargetLibraryInfoWrapperPass>();
553 AU.addRequired<TargetTransformInfoWrapperPass>();
554 AU.addRequired<DominatorTreeWrapperPass>();
555 AU.addPreserved<DominatorTreeWrapperPass>();
556 FunctionPass::getAnalysisUsage(AU);
559 bool runOnFunction(Function &F) override {
563 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
564 auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
565 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
566 return doCallSiteSplitting(F, TLI, TTI, DT);
571 char CallSiteSplittingLegacyPass::ID = 0;
572 INITIALIZE_PASS_BEGIN(CallSiteSplittingLegacyPass, "callsite-splitting",
573 "Call-site splitting", false, false)
574 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
575 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
576 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
577 INITIALIZE_PASS_END(CallSiteSplittingLegacyPass, "callsite-splitting",
578 "Call-site splitting", false, false)
579 FunctionPass *llvm::createCallSiteSplittingPass() {
580 return new CallSiteSplittingLegacyPass();
583 PreservedAnalyses CallSiteSplittingPass::run(Function &F,
584 FunctionAnalysisManager &AM) {
585 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
586 auto &TTI = AM.getResult<TargetIRAnalysis>(F);
587 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
589 if (!doCallSiteSplitting(F, TLI, TTI, DT))
590 return PreservedAnalyses::all();
591 PreservedAnalyses PA;
592 PA.preserve<DominatorTreeAnalysis>();