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