blob: 5ebfbf8a879b77c4649d8b286c1b163804694bb4 [file] [log] [blame]
Jun Bum Lim0c990072017-11-03 20:41:16 +00001//===- CallSiteSplitting.cpp ----------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
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 :
15//
Florian Hahn7e932892017-12-23 20:02:26 +000016// 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.
Jun Bum Lim0c990072017-11-03 20:41:16 +000021//
22// Split from :
23// if (!ptr || c)
24// callee(ptr);
25// to :
26// if (!ptr)
27// callee(null) // set the known constant value
28// else if (c)
29// callee(nonnull ptr) // set non-null attribute in the argument
30//
31// 2) We can also split a call-site based on constant incoming values of a PHI
32// For example,
33// from :
34// Header:
35// %c = icmp eq i32 %i1, %i2
36// br i1 %c, label %Tail, label %TBB
37// TBB:
38// br label Tail%
39// Tail:
40// %p = phi i32 [ 0, %Header], [ 1, %TBB]
41// call void @bar(i32 %p)
42// to
43// Header:
44// %c = icmp eq i32 %i1, %i2
45// br i1 %c, label %Tail-split0, label %TBB
46// TBB:
47// br label %Tail-split1
48// Tail-split0:
49// call void @bar(i32 0)
50// br label %Tail
51// Tail-split1:
52// call void @bar(i32 1)
53// br label %Tail
54// Tail:
55// %p = phi i32 [ 0, %Tail-split0 ], [ 1, %Tail-split1 ]
56//
57//===----------------------------------------------------------------------===//
58
59#include "llvm/Transforms/Scalar/CallSiteSplitting.h"
60#include "llvm/ADT/Statistic.h"
61#include "llvm/Analysis/TargetLibraryInfo.h"
Florian Hahnb4e3bad2018-02-14 13:59:12 +000062#include "llvm/Analysis/TargetTransformInfo.h"
David Blaikie31b98d22018-06-04 21:23:21 +000063#include "llvm/Transforms/Utils/Local.h"
Jun Bum Lim0c990072017-11-03 20:41:16 +000064#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"
Florian Hahnb4e3bad2018-02-14 13:59:12 +000069#include "llvm/Transforms/Utils/Cloning.h"
Jun Bum Lim0c990072017-11-03 20:41:16 +000070
71using namespace llvm;
72using namespace PatternMatch;
73
74#define DEBUG_TYPE "callsite-splitting"
75
76STATISTIC(NumCallSiteSplit, "Number of call-site split");
77
Florian Hahnb4e3bad2018-02-14 13:59:12 +000078/// Only allow instructions before a call, if their CodeSize cost is below
79/// DuplicationThreshold. Those instructions need to be duplicated in all
80/// split blocks.
81static 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"),
85 cl::init(5));
86
Florian Hahnc6c89bf2018-01-16 22:13:15 +000087static void addNonNullAttribute(CallSite CS, Value *Op) {
Jun Bum Lim0c990072017-11-03 20:41:16 +000088 unsigned ArgNo = 0;
89 for (auto &I : CS.args()) {
90 if (&*I == Op)
91 CS.addParamAttr(ArgNo, Attribute::NonNull);
92 ++ArgNo;
93 }
94}
95
Florian Hahnc6c89bf2018-01-16 22:13:15 +000096static void setConstantInArgument(CallSite CS, Value *Op,
97 Constant *ConstValue) {
Jun Bum Lim0c990072017-11-03 20:41:16 +000098 unsigned ArgNo = 0;
99 for (auto &I : CS.args()) {
Xin Tong8edff272018-04-23 20:09:08 +0000100 if (&*I == Op) {
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);
Jun Bum Lim0c990072017-11-03 20:41:16 +0000104 CS.setArgument(ArgNo, ConstValue);
Xin Tong8edff272018-04-23 20:09:08 +0000105 }
Jun Bum Lim0c990072017-11-03 20:41:16 +0000106 ++ArgNo;
107 }
108}
109
Florian Hahn2a266a32017-11-18 18:14:13 +0000110static bool isCondRelevantToAnyCallArgument(ICmpInst *Cmp, CallSite CS) {
111 assert(isa<Constant>(Cmp->getOperand(1)) && "Expected a constant operand.");
112 Value *Op0 = Cmp->getOperand(0);
113 unsigned ArgNo = 0;
114 for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); I != E;
115 ++I, ++ArgNo) {
116 // Don't consider constant or arguments that are already known non-null.
117 if (isa<Constant>(*I) || CS.paramHasAttr(ArgNo, Attribute::NonNull))
118 continue;
119
120 if (*I == Op0)
121 return true;
122 }
123 return false;
124}
125
Florian Hahnc6c89bf2018-01-16 22:13:15 +0000126typedef std::pair<ICmpInst *, unsigned> ConditionTy;
127typedef SmallVector<ConditionTy, 2> ConditionsTy;
128
Florian Hahnbeda7d52017-12-13 03:05:20 +0000129/// If From has a conditional jump to To, add the condition to Conditions,
130/// if it is relevant to any argument at CS.
Florian Hahnc6c89bf2018-01-16 22:13:15 +0000131static void recordCondition(CallSite CS, BasicBlock *From, BasicBlock *To,
132 ConditionsTy &Conditions) {
Florian Hahnbeda7d52017-12-13 03:05:20 +0000133 auto *BI = dyn_cast<BranchInst>(From->getTerminator());
134 if (!BI || !BI->isConditional())
135 return;
Florian Hahn2a266a32017-11-18 18:14:13 +0000136
Florian Hahnbeda7d52017-12-13 03:05:20 +0000137 CmpInst::Predicate Pred;
138 Value *Cond = BI->getCondition();
139 if (!match(Cond, m_ICmp(Pred, m_Value(), m_Constant())))
140 return;
141
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
146 ? Pred
147 : Cmp->getInversePredicate()});
Florian Hahn2a266a32017-11-18 18:14:13 +0000148}
149
Florian Hahnbeda7d52017-12-13 03:05:20 +0000150/// Record ICmp conditions relevant to any argument in CS following Pred's
Xin Tongd83c8832018-04-13 04:35:38 +0000151/// single predecessors. If there are conflicting conditions along a path, like
Florian Hahnbeda7d52017-12-13 03:05:20 +0000152/// x == 1 and x == 0, the first condition will be used.
Florian Hahnc6c89bf2018-01-16 22:13:15 +0000153static void recordConditions(CallSite CS, BasicBlock *Pred,
154 ConditionsTy &Conditions) {
Florian Hahnbeda7d52017-12-13 03:05:20 +0000155 recordCondition(CS, Pred, CS.getInstruction()->getParent(), Conditions);
156 BasicBlock *From = Pred;
157 BasicBlock *To = Pred;
Florian Hahn212afb92018-01-26 10:36:50 +0000158 SmallPtrSet<BasicBlock *, 4> Visited;
Florian Hahnbeda7d52017-12-13 03:05:20 +0000159 while (!Visited.count(From->getSinglePredecessor()) &&
160 (From = From->getSinglePredecessor())) {
161 recordCondition(CS, From, To, Conditions);
Florian Hahn212afb92018-01-26 10:36:50 +0000162 Visited.insert(From);
Florian Hahnbeda7d52017-12-13 03:05:20 +0000163 To = From;
164 }
165}
Jun Bum Lim0c990072017-11-03 20:41:16 +0000166
Florian Hahnc6c89bf2018-01-16 22:13:15 +0000167static void addConditions(CallSite CS, const ConditionsTy &Conditions) {
Florian Hahnbeda7d52017-12-13 03:05:20 +0000168 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)
Florian Hahnc6c89bf2018-01-16 22:13:15 +0000172 setConstantInArgument(CS, Arg, ConstVal);
Florian Hahnbeda7d52017-12-13 03:05:20 +0000173 else if (ConstVal->getType()->isPointerTy() && ConstVal->isNullValue()) {
174 assert(Cond.second == ICmpInst::ICMP_NE);
Florian Hahnc6c89bf2018-01-16 22:13:15 +0000175 addNonNullAttribute(CS, Arg);
Jun Bum Lim0c990072017-11-03 20:41:16 +0000176 }
177 }
Florian Hahnbeda7d52017-12-13 03:05:20 +0000178}
179
180static SmallVector<BasicBlock *, 2> getTwoPredecessors(BasicBlock *BB) {
181 SmallVector<BasicBlock *, 2> Preds(predecessors((BB)));
182 assert(Preds.size() == 2 && "Expected exactly 2 predecessors!");
183 return Preds;
Jun Bum Lim0c990072017-11-03 20:41:16 +0000184}
185
Florian Hahnb4e3bad2018-02-14 13:59:12 +0000186static bool canSplitCallSite(CallSite CS, TargetTransformInfo &TTI) {
Jun Bum Lim0c990072017-11-03 20:41:16 +0000187 // 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))
191 return false;
192
Jun Bum Lim0c990072017-11-03 20:41:16 +0000193 BasicBlock *CallSiteBB = Instr->getParent();
Aditya Kumar373ce7e2018-07-21 14:13:44 +0000194 // 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()))
198 return false;
199
200 // BasicBlock::canSplitPredecessors is more agressive, so checking for
201 // BasicBlock::isEHPad as well.
202 if (!CallSiteBB->canSplitPredecessors() || CallSiteBB->isEHPad())
203 return false;
204
Florian Hahnb4e3bad2018-02-14 13:59:12 +0000205 // 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.
209 unsigned Cost = 0;
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)
215 return false;
216 }
Jun Bum Lim0c990072017-11-03 20:41:16 +0000217
Aditya Kumar373ce7e2018-07-21 14:13:44 +0000218 return true;
Jun Bum Lim0c990072017-11-03 20:41:16 +0000219}
220
Fedor Indutnyf9e09c12018-03-03 21:40:14 +0000221static Instruction *cloneInstForMustTail(Instruction *I, Instruction *Before,
222 Value *V) {
223 Instruction *Copy = I->clone();
224 Copy->setName(I->getName());
225 Copy->insertBefore(Before);
226 if (V)
227 Copy->setOperand(0, V);
228 return Copy;
229}
230
231/// Copy mandatory `musttail` return sequence that follows original `CI`, and
232/// link it up to `NewCI` value instead:
Florian Hahnc6c89bf2018-01-16 22:13:15 +0000233///
Fedor Indutnyf9e09c12018-03-03 21:40:14 +0000234/// * (optional) `bitcast NewCI to ...`
235/// * `ret bitcast or NewCI`
236///
237/// Insert this sequence right before `SplitBB`'s terminator, which will be
238/// cleaned up later in `splitCallSite` below.
239static void copyMustTailReturn(BasicBlock *SplitBB, Instruction *CI,
240 Instruction *NewCI) {
241 bool IsVoid = SplitBB->getParent()->getReturnType()->isVoidTy();
242 auto II = std::next(CI->getIterator());
243
244 BitCastInst* BCI = dyn_cast<BitCastInst>(&*II);
245 if (BCI)
246 ++II;
247
248 ReturnInst* RI = dyn_cast<ReturnInst>(&*II);
249 assert(RI && "`musttail` call must be followed by `ret` instruction");
250
251 TerminatorInst *TI = SplitBB->getTerminator();
252 Value *V = NewCI;
253 if (BCI)
254 V = cloneInstForMustTail(BCI, TI, V);
255 cloneInstForMustTail(RI, TI, IsVoid ? nullptr : V);
256
257 // FIXME: remove TI here, `DuplicateInstructionsInSplitBetween` has a bug
258 // that prevents doing this now.
259}
260
Florian Hahnc6c89bf2018-01-16 22:13:15 +0000261/// 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.
Florian Hahn7e932892017-12-23 20:02:26 +0000265/// For example, in the IR below with an OR condition, the call-site can
Florian Hahnc6c89bf2018-01-16 22:13:15 +0000266/// 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.
Jun Bum Lim0c990072017-11-03 20:41:16 +0000270///
Florian Hahn7e932892017-12-23 20:02:26 +0000271/// From :
Jun Bum Lim0c990072017-11-03 20:41:16 +0000272///
273/// Header:
274/// %c = icmp eq i32* %a, null
275/// br i1 %c %Tail, %TBB
276/// TBB:
277/// %c2 = icmp eq i32* %b, null
278/// br i1 %c %Tail, %End
279/// Tail:
280/// %ca = call i1 @callee (i32* %a, i32* %b)
281///
282/// to :
283///
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
290/// Tail-split1:
291/// %ca1 = call @callee (i32* null, i32* %b) // CallInst1
292/// br %Tail
293/// Tail-split2:
294/// %ca2 = call @callee (i32* nonnull %a, i32* null) // CallInst2
295/// br %Tail
296/// Tail:
297/// %p = phi i1 [%ca1, %Tail-split1],[%ca2, %Tail-split2]
298///
Florian Hahn7e932892017-12-23 20:02:26 +0000299/// 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().
Florian Hahnc6c89bf2018-01-16 22:13:15 +0000302static void splitCallSite(
303 CallSite CS,
Florian Hahn9bc0bc42018-03-22 15:23:33 +0000304 const SmallVectorImpl<std::pair<BasicBlock *, ConditionsTy>> &Preds,
305 DominatorTree *DT) {
Jun Bum Lim0c990072017-11-03 20:41:16 +0000306 Instruction *Instr = CS.getInstruction();
307 BasicBlock *TailBB = Instr->getParent();
Fedor Indutnyf9e09c12018-03-03 21:40:14 +0000308 bool IsMustTailCall = CS.isMustTailCall();
Jun Bum Lim0c990072017-11-03 20:41:16 +0000309
Florian Hahnc6c89bf2018-01-16 22:13:15 +0000310 PHINode *CallPN = nullptr;
Fedor Indutnyf9e09c12018-03-03 21:40:14 +0000311
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`.
Craig Topper3b4ad9c2018-03-12 18:40:59 +0000315 if (!IsMustTailCall && !Instr->use_empty())
Florian Hahnc6c89bf2018-01-16 22:13:15 +0000316 CallPN = PHINode::Create(Instr->getType(), Preds.size(), "phi.call");
Jun Bum Lim0c990072017-11-03 20:41:16 +0000317
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000318 LLVM_DEBUG(dbgs() << "split call-site : " << *Instr << " into \n");
Florian Hahnb4e3bad2018-02-14 13:59:12 +0000319
320 assert(Preds.size() == 2 && "The ValueToValueMaps array has size 2.");
321 // ValueToValueMapTy is neither copy nor moveable, so we use a simple array
322 // here.
323 ValueToValueMapTy ValueToValueMaps[2];
324 for (unsigned i = 0; i < Preds.size(); i++) {
325 BasicBlock *PredBB = Preds[i].first;
326 BasicBlock *SplitBlock = DuplicateInstructionsInSplitBetween(
Florian Hahn9bc0bc42018-03-22 15:23:33 +0000327 TailBB, PredBB, &*std::next(Instr->getIterator()), ValueToValueMaps[i],
328 DT);
Florian Hahnc6c89bf2018-01-16 22:13:15 +0000329 assert(SplitBlock && "Unexpected new basic block split.");
Jun Bum Lim0c990072017-11-03 20:41:16 +0000330
Florian Hahnb4e3bad2018-02-14 13:59:12 +0000331 Instruction *NewCI =
332 &*std::prev(SplitBlock->getTerminator()->getIterator());
Florian Hahnc6c89bf2018-01-16 22:13:15 +0000333 CallSite NewCS(NewCI);
Florian Hahnb4e3bad2018-02-14 13:59:12 +0000334 addConditions(NewCS, Preds[i].second);
Jun Bum Lim0c990072017-11-03 20:41:16 +0000335
Florian Hahnc6c89bf2018-01-16 22:13:15 +0000336 // Handle PHIs used as arguments in the call-site.
337 for (PHINode &PN : TailBB->phis()) {
338 unsigned ArgNo = 0;
339 for (auto &CI : CS.args()) {
340 if (&*CI == &PN) {
341 NewCS.setArgument(ArgNo, PN.getIncomingValueForBlock(SplitBlock));
342 }
343 ++ArgNo;
Jun Bum Lim0c990072017-11-03 20:41:16 +0000344 }
Jun Bum Lim0c990072017-11-03 20:41:16 +0000345 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000346 LLVM_DEBUG(dbgs() << " " << *NewCI << " in " << SplitBlock->getName()
347 << "\n");
Florian Hahnc6c89bf2018-01-16 22:13:15 +0000348 if (CallPN)
349 CallPN->addIncoming(NewCI, SplitBlock);
Fedor Indutnyf9e09c12018-03-03 21:40:14 +0000350
351 // Clone and place bitcast and return instructions before `TI`
352 if (IsMustTailCall)
353 copyMustTailReturn(SplitBlock, Instr, NewCI);
354 }
355
356 NumCallSiteSplit++;
357
358 // FIXME: remove TI in `copyMustTailReturn`
359 if (IsMustTailCall) {
360 // Remove superfluous `br` terminators from the end of the Split blocks
Fedor Indutny364b9c22018-03-03 22:34:38 +0000361 // NOTE: Removing terminator removes the SplitBlock from the TailBB's
362 // predecessors. Therefore we must get complete list of Splits before
363 // attempting removal.
364 SmallVector<BasicBlock *, 2> Splits(predecessors((TailBB)));
365 assert(Splits.size() == 2 && "Expected exactly 2 splits!");
366 for (unsigned i = 0; i < Splits.size(); i++)
367 Splits[i]->getTerminator()->eraseFromParent();
Fedor Indutnyf9e09c12018-03-03 21:40:14 +0000368
369 // Erase the tail block once done with musttail patching
370 TailBB->eraseFromParent();
371 return;
Jun Bum Lim0c990072017-11-03 20:41:16 +0000372 }
373
Florian Hahnb4e3bad2018-02-14 13:59:12 +0000374 auto *OriginalBegin = &*TailBB->begin();
Jun Bum Lim0c990072017-11-03 20:41:16 +0000375 // Replace users of the original call with a PHI mering call-sites split.
Florian Hahnc6c89bf2018-01-16 22:13:15 +0000376 if (CallPN) {
Florian Hahnb4e3bad2018-02-14 13:59:12 +0000377 CallPN->insertBefore(OriginalBegin);
Florian Hahnc6c89bf2018-01-16 22:13:15 +0000378 Instr->replaceAllUsesWith(CallPN);
Jun Bum Lim0c990072017-11-03 20:41:16 +0000379 }
Florian Hahnc6c89bf2018-01-16 22:13:15 +0000380
Florian Hahnb4e3bad2018-02-14 13:59:12 +0000381 // Remove instructions moved to split blocks from TailBB, from the duplicated
382 // call instruction to the beginning of the basic block. If an instruction
383 // has any uses, add a new PHI node to combine the values coming from the
384 // split blocks. The new PHI nodes are placed before the first original
385 // instruction, so we do not end up deleting them. By using reverse-order, we
386 // do not introduce unnecessary PHI nodes for def-use chains from the call
387 // instruction to the beginning of the block.
388 auto I = Instr->getReverseIterator();
389 while (I != TailBB->rend()) {
390 Instruction *CurrentI = &*I++;
391 if (!CurrentI->use_empty()) {
392 // If an existing PHI has users after the call, there is no need to create
393 // a new one.
394 if (isa<PHINode>(CurrentI))
395 continue;
396 PHINode *NewPN = PHINode::Create(CurrentI->getType(), Preds.size());
397 for (auto &Mapping : ValueToValueMaps)
398 NewPN->addIncoming(Mapping[CurrentI],
399 cast<Instruction>(Mapping[CurrentI])->getParent());
400 NewPN->insertBefore(&*TailBB->begin());
401 CurrentI->replaceAllUsesWith(NewPN);
402 }
403 CurrentI->eraseFromParent();
404 // We are done once we handled the first original instruction in TailBB.
405 if (CurrentI == OriginalBegin)
406 break;
407 }
Jun Bum Lim0c990072017-11-03 20:41:16 +0000408}
409
Jun Bum Lim0c990072017-11-03 20:41:16 +0000410// Return true if the call-site has an argument which is a PHI with only
411// constant incoming values.
412static bool isPredicatedOnPHI(CallSite CS) {
413 Instruction *Instr = CS.getInstruction();
414 BasicBlock *Parent = Instr->getParent();
Mikael Holmen66cf3832017-12-12 07:29:57 +0000415 if (Instr != Parent->getFirstNonPHIOrDbg())
Jun Bum Lim0c990072017-11-03 20:41:16 +0000416 return false;
417
418 for (auto &BI : *Parent) {
419 if (PHINode *PN = dyn_cast<PHINode>(&BI)) {
420 for (auto &I : CS.args())
421 if (&*I == PN) {
422 assert(PN->getNumIncomingValues() == 2 &&
423 "Unexpected number of incoming values");
424 if (PN->getIncomingBlock(0) == PN->getIncomingBlock(1))
425 return false;
426 if (PN->getIncomingValue(0) == PN->getIncomingValue(1))
427 continue;
428 if (isa<Constant>(PN->getIncomingValue(0)) &&
429 isa<Constant>(PN->getIncomingValue(1)))
430 return true;
431 }
432 }
433 break;
434 }
435 return false;
436}
437
Florian Hahn9bc0bc42018-03-22 15:23:33 +0000438static bool tryToSplitOnPHIPredicatedArgument(CallSite CS, DominatorTree *DT) {
Florian Hahn2a266a32017-11-18 18:14:13 +0000439 if (!isPredicatedOnPHI(CS))
Jun Bum Lim0c990072017-11-03 20:41:16 +0000440 return false;
441
Florian Hahn2a266a32017-11-18 18:14:13 +0000442 auto Preds = getTwoPredecessors(CS.getInstruction()->getParent());
Florian Hahnc6c89bf2018-01-16 22:13:15 +0000443 SmallVector<std::pair<BasicBlock *, ConditionsTy>, 2> PredsCS = {
444 {Preds[0], {}}, {Preds[1], {}}};
Florian Hahn9bc0bc42018-03-22 15:23:33 +0000445 splitCallSite(CS, PredsCS, DT);
Florian Hahn2a266a32017-11-18 18:14:13 +0000446 return true;
447}
Jun Bum Lim0c990072017-11-03 20:41:16 +0000448
Florian Hahn9bc0bc42018-03-22 15:23:33 +0000449static bool tryToSplitOnPredicatedArgument(CallSite CS, DominatorTree *DT) {
Florian Hahn2a266a32017-11-18 18:14:13 +0000450 auto Preds = getTwoPredecessors(CS.getInstruction()->getParent());
Florian Hahn7e932892017-12-23 20:02:26 +0000451 if (Preds[0] == Preds[1])
Florian Hahn2a266a32017-11-18 18:14:13 +0000452 return false;
453
Florian Hahnc6c89bf2018-01-16 22:13:15 +0000454 SmallVector<std::pair<BasicBlock *, ConditionsTy>, 2> PredsCS;
455 for (auto *Pred : make_range(Preds.rbegin(), Preds.rend())) {
456 ConditionsTy Conditions;
457 recordConditions(CS, Pred, Conditions);
458 PredsCS.push_back({Pred, Conditions});
459 }
Florian Hahn2a266a32017-11-18 18:14:13 +0000460
Florian Hahnc6c89bf2018-01-16 22:13:15 +0000461 if (std::all_of(PredsCS.begin(), PredsCS.end(),
462 [](const std::pair<BasicBlock *, ConditionsTy> &P) {
463 return P.second.empty();
464 }))
Florian Hahnbeda7d52017-12-13 03:05:20 +0000465 return false;
466
Florian Hahn9bc0bc42018-03-22 15:23:33 +0000467 splitCallSite(CS, PredsCS, DT);
Jun Bum Lim0c990072017-11-03 20:41:16 +0000468 return true;
469}
470
Florian Hahn9bc0bc42018-03-22 15:23:33 +0000471static bool tryToSplitCallSite(CallSite CS, TargetTransformInfo &TTI,
472 DominatorTree *DT) {
Florian Hahnb4e3bad2018-02-14 13:59:12 +0000473 if (!CS.arg_size() || !canSplitCallSite(CS, TTI))
Jun Bum Lim0c990072017-11-03 20:41:16 +0000474 return false;
Florian Hahn9bc0bc42018-03-22 15:23:33 +0000475 return tryToSplitOnPredicatedArgument(CS, DT) ||
476 tryToSplitOnPHIPredicatedArgument(CS, DT);
Jun Bum Lim0c990072017-11-03 20:41:16 +0000477}
478
Florian Hahnb4e3bad2018-02-14 13:59:12 +0000479static bool doCallSiteSplitting(Function &F, TargetLibraryInfo &TLI,
Florian Hahn9bc0bc42018-03-22 15:23:33 +0000480 TargetTransformInfo &TTI, DominatorTree *DT) {
Jun Bum Lim0c990072017-11-03 20:41:16 +0000481 bool Changed = false;
482 for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE;) {
483 BasicBlock &BB = *BI++;
Florian Hahn517dc512018-03-06 14:00:58 +0000484 auto II = BB.getFirstNonPHIOrDbg()->getIterator();
485 auto IE = BB.getTerminator()->getIterator();
486 // Iterate until we reach the terminator instruction. tryToSplitCallSite
487 // can replace BB's terminator in case BB is a successor of itself. In that
488 // case, IE will be invalidated and we also have to check the current
489 // terminator.
490 while (II != IE && &*II != BB.getTerminator()) {
Jun Bum Lim0c990072017-11-03 20:41:16 +0000491 Instruction *I = &*II++;
492 CallSite CS(cast<Value>(I));
493 if (!CS || isa<IntrinsicInst>(I) || isInstructionTriviallyDead(I, &TLI))
494 continue;
495
496 Function *Callee = CS.getCalledFunction();
497 if (!Callee || Callee->isDeclaration())
498 continue;
Fedor Indutnyf9e09c12018-03-03 21:40:14 +0000499
500 // Successful musttail call-site splits result in erased CI and erased BB.
501 // Check if such path is possible before attempting the splitting.
502 bool IsMustTail = CS.isMustTailCall();
503
Florian Hahn9bc0bc42018-03-22 15:23:33 +0000504 Changed |= tryToSplitCallSite(CS, TTI, DT);
Fedor Indutnyf9e09c12018-03-03 21:40:14 +0000505
506 // There're no interesting instructions after this. The call site
507 // itself might have been erased on splitting.
508 if (IsMustTail)
509 break;
Jun Bum Lim0c990072017-11-03 20:41:16 +0000510 }
511 }
512 return Changed;
513}
514
515namespace {
516struct CallSiteSplittingLegacyPass : public FunctionPass {
517 static char ID;
518 CallSiteSplittingLegacyPass() : FunctionPass(ID) {
519 initializeCallSiteSplittingLegacyPassPass(*PassRegistry::getPassRegistry());
520 }
521
522 void getAnalysisUsage(AnalysisUsage &AU) const override {
523 AU.addRequired<TargetLibraryInfoWrapperPass>();
Florian Hahnb4e3bad2018-02-14 13:59:12 +0000524 AU.addRequired<TargetTransformInfoWrapperPass>();
Florian Hahn9bc0bc42018-03-22 15:23:33 +0000525 AU.addPreserved<DominatorTreeWrapperPass>();
Jun Bum Lim0c990072017-11-03 20:41:16 +0000526 FunctionPass::getAnalysisUsage(AU);
527 }
528
529 bool runOnFunction(Function &F) override {
530 if (skipFunction(F))
531 return false;
532
533 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Florian Hahnb4e3bad2018-02-14 13:59:12 +0000534 auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Florian Hahn9bc0bc42018-03-22 15:23:33 +0000535 auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
536 return doCallSiteSplitting(F, TLI, TTI,
537 DTWP ? &DTWP->getDomTree() : nullptr);
Jun Bum Lim0c990072017-11-03 20:41:16 +0000538 }
539};
540} // namespace
541
542char CallSiteSplittingLegacyPass::ID = 0;
543INITIALIZE_PASS_BEGIN(CallSiteSplittingLegacyPass, "callsite-splitting",
544 "Call-site splitting", false, false)
545INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Florian Hahnb4e3bad2018-02-14 13:59:12 +0000546INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Jun Bum Lim0c990072017-11-03 20:41:16 +0000547INITIALIZE_PASS_END(CallSiteSplittingLegacyPass, "callsite-splitting",
548 "Call-site splitting", false, false)
549FunctionPass *llvm::createCallSiteSplittingPass() {
550 return new CallSiteSplittingLegacyPass();
551}
552
553PreservedAnalyses CallSiteSplittingPass::run(Function &F,
554 FunctionAnalysisManager &AM) {
555 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
Florian Hahnb4e3bad2018-02-14 13:59:12 +0000556 auto &TTI = AM.getResult<TargetIRAnalysis>(F);
Florian Hahn9bc0bc42018-03-22 15:23:33 +0000557 auto *DT = AM.getCachedResult<DominatorTreeAnalysis>(F);
Jun Bum Lim0c990072017-11-03 20:41:16 +0000558
Florian Hahn9bc0bc42018-03-22 15:23:33 +0000559 if (!doCallSiteSplitting(F, TLI, TTI, DT))
Jun Bum Lim0c990072017-11-03 20:41:16 +0000560 return PreservedAnalyses::all();
561 PreservedAnalyses PA;
Florian Hahn9bc0bc42018-03-22 15:23:33 +0000562 PA.preserve<DominatorTreeAnalysis>();
Jun Bum Lim0c990072017-11-03 20:41:16 +0000563 return PA;
564}