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