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