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