1 //===- PartialInlining.cpp - Inline parts of functions --------------------===//
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 pass performs partial inlining, typically by inlining an if statement
10 // that surrounds the body of the function.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Transforms/IPO/PartialInlining.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/DenseSet.h"
17 #include "llvm/ADT/None.h"
18 #include "llvm/ADT/Optional.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/Analysis/BlockFrequencyInfo.h"
23 #include "llvm/Analysis/BranchProbabilityInfo.h"
24 #include "llvm/Analysis/InlineCost.h"
25 #include "llvm/Analysis/LoopInfo.h"
26 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
27 #include "llvm/Analysis/ProfileSummaryInfo.h"
28 #include "llvm/Analysis/TargetLibraryInfo.h"
29 #include "llvm/Analysis/TargetTransformInfo.h"
30 #include "llvm/IR/Attributes.h"
31 #include "llvm/IR/BasicBlock.h"
32 #include "llvm/IR/CFG.h"
33 #include "llvm/IR/DebugLoc.h"
34 #include "llvm/IR/DiagnosticInfo.h"
35 #include "llvm/IR/Dominators.h"
36 #include "llvm/IR/Function.h"
37 #include "llvm/IR/InstrTypes.h"
38 #include "llvm/IR/Instruction.h"
39 #include "llvm/IR/Instructions.h"
40 #include "llvm/IR/IntrinsicInst.h"
41 #include "llvm/IR/Intrinsics.h"
42 #include "llvm/IR/Module.h"
43 #include "llvm/IR/User.h"
44 #include "llvm/InitializePasses.h"
45 #include "llvm/Pass.h"
46 #include "llvm/Support/BlockFrequency.h"
47 #include "llvm/Support/BranchProbability.h"
48 #include "llvm/Support/Casting.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Transforms/IPO.h"
52 #include "llvm/Transforms/Utils/Cloning.h"
53 #include "llvm/Transforms/Utils/CodeExtractor.h"
54 #include "llvm/Transforms/Utils/ValueMapper.h"
55 #include <algorithm>
56 #include <cassert>
57 #include <cstdint>
58 #include <functional>
59 #include <iterator>
60 #include <memory>
61 #include <tuple>
62 #include <vector>
63 
64 using namespace llvm;
65 
66 #define DEBUG_TYPE "partial-inlining"
67 
68 STATISTIC(NumPartialInlined,
69           "Number of callsites functions partially inlined into.");
70 STATISTIC(NumColdOutlinePartialInlined, "Number of times functions with "
71                                         "cold outlined regions were partially "
72                                         "inlined into its caller(s).");
73 STATISTIC(NumColdRegionsFound,
74            "Number of cold single entry/exit regions found.");
75 STATISTIC(NumColdRegionsOutlined,
76            "Number of cold single entry/exit regions outlined.");
77 
78 // Command line option to disable partial-inlining. The default is false:
79 static cl::opt<bool>
80     DisablePartialInlining("disable-partial-inlining", cl::init(false),
81                            cl::Hidden, cl::desc("Disable partial inlining"));
82 // Command line option to disable multi-region partial-inlining. The default is
83 // false:
84 static cl::opt<bool> DisableMultiRegionPartialInline(
85     "disable-mr-partial-inlining", cl::init(false), cl::Hidden,
86     cl::desc("Disable multi-region partial inlining"));
87 
88 // Command line option to force outlining in regions with live exit variables.
89 // The default is false:
90 static cl::opt<bool>
91     ForceLiveExit("pi-force-live-exit-outline", cl::init(false), cl::Hidden,
92                cl::desc("Force outline regions with live exits"));
93 
94 // Command line option to enable marking outline functions with Cold Calling
95 // Convention. The default is false:
96 static cl::opt<bool>
97     MarkOutlinedColdCC("pi-mark-coldcc", cl::init(false), cl::Hidden,
98                        cl::desc("Mark outline function calls with ColdCC"));
99 
100 #ifndef NDEBUG
101 // Command line option to debug partial-inlining. The default is none:
102 static cl::opt<bool> TracePartialInlining("trace-partial-inlining",
103                                           cl::init(false), cl::Hidden,
104                                           cl::desc("Trace partial inlining."));
105 #endif
106 
107 // This is an option used by testing:
108 static cl::opt<bool> SkipCostAnalysis("skip-partial-inlining-cost-analysis",
109                                       cl::init(false), cl::ZeroOrMore,
110                                       cl::ReallyHidden,
111                                       cl::desc("Skip Cost Analysis"));
112 // Used to determine if a cold region is worth outlining based on
113 // its inlining cost compared to the original function.  Default is set at 10%.
114 // ie. if the cold region reduces the inlining cost of the original function by
115 // at least 10%.
116 static cl::opt<float> MinRegionSizeRatio(
117     "min-region-size-ratio", cl::init(0.1), cl::Hidden,
118     cl::desc("Minimum ratio comparing relative sizes of each "
119              "outline candidate and original function"));
120 // Used to tune the minimum number of execution counts needed in the predecessor
121 // block to the cold edge. ie. confidence interval.
122 static cl::opt<unsigned>
123     MinBlockCounterExecution("min-block-execution", cl::init(100), cl::Hidden,
124                              cl::desc("Minimum block executions to consider "
125                                       "its BranchProbabilityInfo valid"));
126 // Used to determine when an edge is considered cold. Default is set to 10%. ie.
127 // if the branch probability is 10% or less, then it is deemed as 'cold'.
128 static cl::opt<float> ColdBranchRatio(
129     "cold-branch-ratio", cl::init(0.1), cl::Hidden,
130     cl::desc("Minimum BranchProbability to consider a region cold."));
131 
132 static cl::opt<unsigned> MaxNumInlineBlocks(
133     "max-num-inline-blocks", cl::init(5), cl::Hidden,
134     cl::desc("Max number of blocks to be partially inlined"));
135 
136 // Command line option to set the maximum number of partial inlining allowed
137 // for the module. The default value of -1 means no limit.
138 static cl::opt<int> MaxNumPartialInlining(
139     "max-partial-inlining", cl::init(-1), cl::Hidden, cl::ZeroOrMore,
140     cl::desc("Max number of partial inlining. The default is unlimited"));
141 
142 // Used only when PGO or user annotated branch data is absent. It is
143 // the least value that is used to weigh the outline region. If BFI
144 // produces larger value, the BFI value will be used.
145 static cl::opt<int>
146     OutlineRegionFreqPercent("outline-region-freq-percent", cl::init(75),
147                              cl::Hidden, cl::ZeroOrMore,
148                              cl::desc("Relative frequency of outline region to "
149                                       "the entry block"));
150 
151 static cl::opt<unsigned> ExtraOutliningPenalty(
152     "partial-inlining-extra-penalty", cl::init(0), cl::Hidden,
153     cl::desc("A debug option to add additional penalty to the computed one."));
154 
155 namespace {
156 
157 struct FunctionOutliningInfo {
158   FunctionOutliningInfo() = default;
159 
160   // Returns the number of blocks to be inlined including all blocks
161   // in Entries and one return block.
162   unsigned GetNumInlinedBlocks() const { return Entries.size() + 1; }
163 
164   // A set of blocks including the function entry that guard
165   // the region to be outlined.
166   SmallVector<BasicBlock *, 4> Entries;
167 
168   // The return block that is not included in the outlined region.
169   BasicBlock *ReturnBlock = nullptr;
170 
171   // The dominating block of the region to be outlined.
172   BasicBlock *NonReturnBlock = nullptr;
173 
174   // The set of blocks in Entries that that are predecessors to ReturnBlock
175   SmallVector<BasicBlock *, 4> ReturnBlockPreds;
176 };
177 
178 struct FunctionOutliningMultiRegionInfo {
179   FunctionOutliningMultiRegionInfo()
180       : ORI() {}
181 
182   // Container for outline regions
183   struct OutlineRegionInfo {
184     OutlineRegionInfo(ArrayRef<BasicBlock *> Region,
185                       BasicBlock *EntryBlock, BasicBlock *ExitBlock,
186                       BasicBlock *ReturnBlock)
187         : Region(Region.begin(), Region.end()), EntryBlock(EntryBlock),
188           ExitBlock(ExitBlock), ReturnBlock(ReturnBlock) {}
189     SmallVector<BasicBlock *, 8> Region;
190     BasicBlock *EntryBlock;
191     BasicBlock *ExitBlock;
192     BasicBlock *ReturnBlock;
193   };
194 
195   SmallVector<OutlineRegionInfo, 4> ORI;
196 };
197 
198 struct PartialInlinerImpl {
199 
200   PartialInlinerImpl(
201       std::function<AssumptionCache &(Function &)> *GetAC,
202       function_ref<AssumptionCache *(Function &)> LookupAC,
203       std::function<TargetTransformInfo &(Function &)> *GTTI,
204       Optional<function_ref<BlockFrequencyInfo &(Function &)>> GBFI,
205       std::function<const TargetLibraryInfo &(Function &)> *GTLI,
206       ProfileSummaryInfo *ProfSI)
207       : GetAssumptionCache(GetAC), LookupAssumptionCache(LookupAC),
208         GetTTI(GTTI), GetBFI(GBFI), GetTLI(GTLI), PSI(ProfSI) {}
209 
210   bool run(Module &M);
211   // Main part of the transformation that calls helper functions to find
212   // outlining candidates, clone & outline the function, and attempt to
213   // partially inline the resulting function. Returns true if
214   // inlining was successful, false otherwise.  Also returns the outline
215   // function (only if we partially inlined early returns) as there is a
216   // possibility to further "peel" early return statements that were left in the
217   // outline function due to code size.
218   std::pair<bool, Function *> unswitchFunction(Function *F);
219 
220   // This class speculatively clones the function to be partial inlined.
221   // At the end of partial inlining, the remaining callsites to the cloned
222   // function that are not partially inlined will be fixed up to reference
223   // the original function, and the cloned function will be erased.
224   struct FunctionCloner {
225     // Two constructors, one for single region outlining, the other for
226     // multi-region outlining.
227     FunctionCloner(Function *F, FunctionOutliningInfo *OI,
228                    OptimizationRemarkEmitter &ORE,
229                    function_ref<AssumptionCache *(Function &)> LookupAC);
230     FunctionCloner(Function *F, FunctionOutliningMultiRegionInfo *OMRI,
231                    OptimizationRemarkEmitter &ORE,
232                    function_ref<AssumptionCache *(Function &)> LookupAC);
233     ~FunctionCloner();
234 
235     // Prepare for function outlining: making sure there is only
236     // one incoming edge from the extracted/outlined region to
237     // the return block.
238     void NormalizeReturnBlock();
239 
240     // Do function outlining for cold regions.
241     bool doMultiRegionFunctionOutlining();
242     // Do function outlining for region after early return block(s).
243     // NOTE: For vararg functions that do the vararg handling in the outlined
244     //       function, we temporarily generate IR that does not properly
245     //       forward varargs to the outlined function. Calling InlineFunction
246     //       will update calls to the outlined functions to properly forward
247     //       the varargs.
248     Function *doSingleRegionFunctionOutlining();
249 
250     Function *OrigFunc = nullptr;
251     Function *ClonedFunc = nullptr;
252 
253     typedef std::pair<Function *, BasicBlock *> FuncBodyCallerPair;
254     // Keep track of Outlined Functions and the basic block they're called from.
255     SmallVector<FuncBodyCallerPair, 4> OutlinedFunctions;
256 
257     // ClonedFunc is inlined in one of its callers after function
258     // outlining.
259     bool IsFunctionInlined = false;
260     // The cost of the region to be outlined.
261     int OutlinedRegionCost = 0;
262     // ClonedOI is specific to outlining non-early return blocks.
263     std::unique_ptr<FunctionOutliningInfo> ClonedOI = nullptr;
264     // ClonedOMRI is specific to outlining cold regions.
265     std::unique_ptr<FunctionOutliningMultiRegionInfo> ClonedOMRI = nullptr;
266     std::unique_ptr<BlockFrequencyInfo> ClonedFuncBFI = nullptr;
267     OptimizationRemarkEmitter &ORE;
268     function_ref<AssumptionCache *(Function &)> LookupAC;
269   };
270 
271 private:
272   int NumPartialInlining = 0;
273   std::function<AssumptionCache &(Function &)> *GetAssumptionCache;
274   function_ref<AssumptionCache *(Function &)> LookupAssumptionCache;
275   std::function<TargetTransformInfo &(Function &)> *GetTTI;
276   Optional<function_ref<BlockFrequencyInfo &(Function &)>> GetBFI;
277   std::function<const TargetLibraryInfo &(Function &)> *GetTLI;
278   ProfileSummaryInfo *PSI;
279 
280   // Return the frequency of the OutlininingBB relative to F's entry point.
281   // The result is no larger than 1 and is represented using BP.
282   // (Note that the outlined region's 'head' block can only have incoming
283   // edges from the guarding entry blocks).
284   BranchProbability getOutliningCallBBRelativeFreq(FunctionCloner &Cloner);
285 
286   // Return true if the callee of CB should be partially inlined with
287   // profit.
288   bool shouldPartialInline(CallBase &CB, FunctionCloner &Cloner,
289                            BlockFrequency WeightedOutliningRcost,
290                            OptimizationRemarkEmitter &ORE);
291 
292   // Try to inline DuplicateFunction (cloned from F with call to
293   // the OutlinedFunction into its callers. Return true
294   // if there is any successful inlining.
295   bool tryPartialInline(FunctionCloner &Cloner);
296 
297   // Compute the mapping from use site of DuplicationFunction to the enclosing
298   // BB's profile count.
299   void computeCallsiteToProfCountMap(Function *DuplicateFunction,
300                                      DenseMap<User *, uint64_t> &SiteCountMap);
301 
302   bool IsLimitReached() {
303     return (MaxNumPartialInlining != -1 &&
304             NumPartialInlining >= MaxNumPartialInlining);
305   }
306 
307   static CallBase *getSupportedCallBase(User *U) {
308     if (isa<CallInst>(U) || isa<InvokeInst>(U))
309       return cast<CallBase>(U);
310     llvm_unreachable("All uses must be calls");
311     return nullptr;
312   }
313 
314   static CallBase *getOneCallSiteTo(Function *F) {
315     User *User = *F->user_begin();
316     return getSupportedCallBase(User);
317   }
318 
319   std::tuple<DebugLoc, BasicBlock *> getOneDebugLoc(Function *F) {
320     CallBase *CB = getOneCallSiteTo(F);
321     DebugLoc DLoc = CB->getDebugLoc();
322     BasicBlock *Block = CB->getParent();
323     return std::make_tuple(DLoc, Block);
324   }
325 
326   // Returns the costs associated with function outlining:
327   // - The first value is the non-weighted runtime cost for making the call
328   //   to the outlined function, including the addtional  setup cost in the
329   //    outlined function itself;
330   // - The second value is the estimated size of the new call sequence in
331   //   basic block Cloner.OutliningCallBB;
332   std::tuple<int, int> computeOutliningCosts(FunctionCloner &Cloner);
333 
334   // Compute the 'InlineCost' of block BB. InlineCost is a proxy used to
335   // approximate both the size and runtime cost (Note that in the current
336   // inline cost analysis, there is no clear distinction there either).
337   static int computeBBInlineCost(BasicBlock *BB);
338 
339   std::unique_ptr<FunctionOutliningInfo> computeOutliningInfo(Function *F);
340   std::unique_ptr<FunctionOutliningMultiRegionInfo>
341   computeOutliningColdRegionsInfo(Function *F, OptimizationRemarkEmitter &ORE);
342 };
343 
344 struct PartialInlinerLegacyPass : public ModulePass {
345   static char ID; // Pass identification, replacement for typeid
346 
347   PartialInlinerLegacyPass() : ModulePass(ID) {
348     initializePartialInlinerLegacyPassPass(*PassRegistry::getPassRegistry());
349   }
350 
351   void getAnalysisUsage(AnalysisUsage &AU) const override {
352     AU.addRequired<AssumptionCacheTracker>();
353     AU.addRequired<ProfileSummaryInfoWrapperPass>();
354     AU.addRequired<TargetTransformInfoWrapperPass>();
355     AU.addRequired<TargetLibraryInfoWrapperPass>();
356   }
357 
358   bool runOnModule(Module &M) override {
359     if (skipModule(M))
360       return false;
361 
362     AssumptionCacheTracker *ACT = &getAnalysis<AssumptionCacheTracker>();
363     TargetTransformInfoWrapperPass *TTIWP =
364         &getAnalysis<TargetTransformInfoWrapperPass>();
365     ProfileSummaryInfo *PSI =
366         &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
367 
368     std::function<AssumptionCache &(Function &)> GetAssumptionCache =
369         [&ACT](Function &F) -> AssumptionCache & {
370       return ACT->getAssumptionCache(F);
371     };
372 
373     auto LookupAssumptionCache = [ACT](Function &F) -> AssumptionCache * {
374       return ACT->lookupAssumptionCache(F);
375     };
376 
377     std::function<TargetTransformInfo &(Function &)> GetTTI =
378         [&TTIWP](Function &F) -> TargetTransformInfo & {
379       return TTIWP->getTTI(F);
380     };
381 
382     std::function<const TargetLibraryInfo &(Function &)> GetTLI =
383         [this](Function &F) -> TargetLibraryInfo & {
384       return this->getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
385     };
386 
387     return PartialInlinerImpl(&GetAssumptionCache, LookupAssumptionCache,
388                               &GetTTI, NoneType::None, &GetTLI, PSI)
389         .run(M);
390   }
391 };
392 
393 } // end anonymous namespace
394 
395 std::unique_ptr<FunctionOutliningMultiRegionInfo>
396 PartialInlinerImpl::computeOutliningColdRegionsInfo(Function *F,
397                                                     OptimizationRemarkEmitter &ORE) {
398   BasicBlock *EntryBlock = &F->front();
399 
400   DominatorTree DT(*F);
401   LoopInfo LI(DT);
402   BranchProbabilityInfo BPI(*F, LI);
403   std::unique_ptr<BlockFrequencyInfo> ScopedBFI;
404   BlockFrequencyInfo *BFI;
405   if (!GetBFI) {
406     ScopedBFI.reset(new BlockFrequencyInfo(*F, BPI, LI));
407     BFI = ScopedBFI.get();
408   } else
409     BFI = &(*GetBFI)(*F);
410 
411   // Return if we don't have profiling information.
412   if (!PSI->hasInstrumentationProfile())
413     return std::unique_ptr<FunctionOutliningMultiRegionInfo>();
414 
415   std::unique_ptr<FunctionOutliningMultiRegionInfo> OutliningInfo =
416       std::make_unique<FunctionOutliningMultiRegionInfo>();
417 
418   auto IsSingleEntry = [](SmallVectorImpl<BasicBlock *> &BlockList) {
419     BasicBlock *Dom = BlockList.front();
420     return BlockList.size() > 1 && Dom->hasNPredecessors(1);
421   };
422 
423   auto IsSingleExit =
424       [&ORE](SmallVectorImpl<BasicBlock *> &BlockList) -> BasicBlock * {
425     BasicBlock *ExitBlock = nullptr;
426     for (auto *Block : BlockList) {
427       for (auto SI = succ_begin(Block); SI != succ_end(Block); ++SI) {
428         if (!is_contained(BlockList, *SI)) {
429           if (ExitBlock) {
430             ORE.emit([&]() {
431               return OptimizationRemarkMissed(DEBUG_TYPE, "MultiExitRegion",
432                                               &SI->front())
433                      << "Region dominated by "
434                      << ore::NV("Block", BlockList.front()->getName())
435                      << " has more than one region exit edge.";
436             });
437             return nullptr;
438           } else
439             ExitBlock = Block;
440         }
441       }
442     }
443     return ExitBlock;
444   };
445 
446   auto BBProfileCount = [BFI](BasicBlock *BB) {
447     return BFI->getBlockProfileCount(BB)
448                ? BFI->getBlockProfileCount(BB).getValue()
449                : 0;
450   };
451 
452   // Use the same computeBBInlineCost function to compute the cost savings of
453   // the outlining the candidate region.
454   int OverallFunctionCost = 0;
455   for (auto &BB : *F)
456     OverallFunctionCost += computeBBInlineCost(&BB);
457 
458 #ifndef NDEBUG
459   if (TracePartialInlining)
460     dbgs() << "OverallFunctionCost = " << OverallFunctionCost << "\n";
461 #endif
462   int MinOutlineRegionCost =
463       static_cast<int>(OverallFunctionCost * MinRegionSizeRatio);
464   BranchProbability MinBranchProbability(
465       static_cast<int>(ColdBranchRatio * MinBlockCounterExecution),
466       MinBlockCounterExecution);
467   bool ColdCandidateFound = false;
468   BasicBlock *CurrEntry = EntryBlock;
469   std::vector<BasicBlock *> DFS;
470   DenseMap<BasicBlock *, bool> VisitedMap;
471   DFS.push_back(CurrEntry);
472   VisitedMap[CurrEntry] = true;
473   // Use Depth First Search on the basic blocks to find CFG edges that are
474   // considered cold.
475   // Cold regions considered must also have its inline cost compared to the
476   // overall inline cost of the original function.  The region is outlined only
477   // if it reduced the inline cost of the function by 'MinOutlineRegionCost' or
478   // more.
479   while (!DFS.empty()) {
480     auto *thisBB = DFS.back();
481     DFS.pop_back();
482     // Only consider regions with predecessor blocks that are considered
483     // not-cold (default: part of the top 99.99% of all block counters)
484     // AND greater than our minimum block execution count (default: 100).
485     if (PSI->isColdBlock(thisBB, BFI) ||
486         BBProfileCount(thisBB) < MinBlockCounterExecution)
487       continue;
488     for (auto SI = succ_begin(thisBB); SI != succ_end(thisBB); ++SI) {
489       if (VisitedMap[*SI])
490         continue;
491       VisitedMap[*SI] = true;
492       DFS.push_back(*SI);
493       // If branch isn't cold, we skip to the next one.
494       BranchProbability SuccProb = BPI.getEdgeProbability(thisBB, *SI);
495       if (SuccProb > MinBranchProbability)
496         continue;
497 #ifndef NDEBUG
498       if (TracePartialInlining) {
499         dbgs() << "Found cold edge: " << thisBB->getName() << "->"
500                << (*SI)->getName() << "\nBranch Probability = " << SuccProb
501                << "\n";
502       }
503 #endif
504       SmallVector<BasicBlock *, 8> DominateVector;
505       DT.getDescendants(*SI, DominateVector);
506       // We can only outline single entry regions (for now).
507       if (!IsSingleEntry(DominateVector))
508         continue;
509       BasicBlock *ExitBlock = nullptr;
510       // We can only outline single exit regions (for now).
511       if (!(ExitBlock = IsSingleExit(DominateVector)))
512         continue;
513       int OutlineRegionCost = 0;
514       for (auto *BB : DominateVector)
515         OutlineRegionCost += computeBBInlineCost(BB);
516 
517 #ifndef NDEBUG
518       if (TracePartialInlining)
519         dbgs() << "OutlineRegionCost = " << OutlineRegionCost << "\n";
520 #endif
521 
522       if (OutlineRegionCost < MinOutlineRegionCost) {
523         ORE.emit([&]() {
524           return OptimizationRemarkAnalysis(DEBUG_TYPE, "TooCostly",
525                                             &SI->front())
526                  << ore::NV("Callee", F) << " inline cost-savings smaller than "
527                  << ore::NV("Cost", MinOutlineRegionCost);
528         });
529         continue;
530       }
531       // For now, ignore blocks that belong to a SISE region that is a
532       // candidate for outlining.  In the future, we may want to look
533       // at inner regions because the outer region may have live-exit
534       // variables.
535       for (auto *BB : DominateVector)
536         VisitedMap[BB] = true;
537       // ReturnBlock here means the block after the outline call
538       BasicBlock *ReturnBlock = ExitBlock->getSingleSuccessor();
539       // assert(ReturnBlock && "ReturnBlock is NULL somehow!");
540       FunctionOutliningMultiRegionInfo::OutlineRegionInfo RegInfo(
541           DominateVector, DominateVector.front(), ExitBlock, ReturnBlock);
542       OutliningInfo->ORI.push_back(RegInfo);
543 #ifndef NDEBUG
544       if (TracePartialInlining) {
545         dbgs() << "Found Cold Candidate starting at block: "
546                << DominateVector.front()->getName() << "\n";
547       }
548 #endif
549       ColdCandidateFound = true;
550       NumColdRegionsFound++;
551     }
552   }
553   if (ColdCandidateFound)
554     return OutliningInfo;
555   else
556     return std::unique_ptr<FunctionOutliningMultiRegionInfo>();
557 }
558 
559 std::unique_ptr<FunctionOutliningInfo>
560 PartialInlinerImpl::computeOutliningInfo(Function *F) {
561   BasicBlock *EntryBlock = &F->front();
562   BranchInst *BR = dyn_cast<BranchInst>(EntryBlock->getTerminator());
563   if (!BR || BR->isUnconditional())
564     return std::unique_ptr<FunctionOutliningInfo>();
565 
566   // Returns true if Succ is BB's successor
567   auto IsSuccessor = [](BasicBlock *Succ, BasicBlock *BB) {
568     return is_contained(successors(BB), Succ);
569   };
570 
571   auto IsReturnBlock = [](BasicBlock *BB) {
572     Instruction *TI = BB->getTerminator();
573     return isa<ReturnInst>(TI);
574   };
575 
576   auto GetReturnBlock = [&](BasicBlock *Succ1, BasicBlock *Succ2) {
577     if (IsReturnBlock(Succ1))
578       return std::make_tuple(Succ1, Succ2);
579     if (IsReturnBlock(Succ2))
580       return std::make_tuple(Succ2, Succ1);
581 
582     return std::make_tuple<BasicBlock *, BasicBlock *>(nullptr, nullptr);
583   };
584 
585   // Detect a triangular shape:
586   auto GetCommonSucc = [&](BasicBlock *Succ1, BasicBlock *Succ2) {
587     if (IsSuccessor(Succ1, Succ2))
588       return std::make_tuple(Succ1, Succ2);
589     if (IsSuccessor(Succ2, Succ1))
590       return std::make_tuple(Succ2, Succ1);
591 
592     return std::make_tuple<BasicBlock *, BasicBlock *>(nullptr, nullptr);
593   };
594 
595   std::unique_ptr<FunctionOutliningInfo> OutliningInfo =
596       std::make_unique<FunctionOutliningInfo>();
597 
598   BasicBlock *CurrEntry = EntryBlock;
599   bool CandidateFound = false;
600   do {
601     // The number of blocks to be inlined has already reached
602     // the limit. When MaxNumInlineBlocks is set to 0 or 1, this
603     // disables partial inlining for the function.
604     if (OutliningInfo->GetNumInlinedBlocks() >= MaxNumInlineBlocks)
605       break;
606 
607     if (succ_size(CurrEntry) != 2)
608       break;
609 
610     BasicBlock *Succ1 = *succ_begin(CurrEntry);
611     BasicBlock *Succ2 = *(succ_begin(CurrEntry) + 1);
612 
613     BasicBlock *ReturnBlock, *NonReturnBlock;
614     std::tie(ReturnBlock, NonReturnBlock) = GetReturnBlock(Succ1, Succ2);
615 
616     if (ReturnBlock) {
617       OutliningInfo->Entries.push_back(CurrEntry);
618       OutliningInfo->ReturnBlock = ReturnBlock;
619       OutliningInfo->NonReturnBlock = NonReturnBlock;
620       CandidateFound = true;
621       break;
622     }
623 
624     BasicBlock *CommSucc;
625     BasicBlock *OtherSucc;
626     std::tie(CommSucc, OtherSucc) = GetCommonSucc(Succ1, Succ2);
627 
628     if (!CommSucc)
629       break;
630 
631     OutliningInfo->Entries.push_back(CurrEntry);
632     CurrEntry = OtherSucc;
633   } while (true);
634 
635   if (!CandidateFound)
636     return std::unique_ptr<FunctionOutliningInfo>();
637 
638   // Do sanity check of the entries: threre should not
639   // be any successors (not in the entry set) other than
640   // {ReturnBlock, NonReturnBlock}
641   assert(OutliningInfo->Entries[0] == &F->front() &&
642          "Function Entry must be the first in Entries vector");
643   DenseSet<BasicBlock *> Entries;
644   for (BasicBlock *E : OutliningInfo->Entries)
645     Entries.insert(E);
646 
647   // Returns true of BB has Predecessor which is not
648   // in Entries set.
649   auto HasNonEntryPred = [Entries](BasicBlock *BB) {
650     for (auto Pred : predecessors(BB)) {
651       if (!Entries.count(Pred))
652         return true;
653     }
654     return false;
655   };
656   auto CheckAndNormalizeCandidate =
657       [Entries, HasNonEntryPred](FunctionOutliningInfo *OutliningInfo) {
658         for (BasicBlock *E : OutliningInfo->Entries) {
659           for (auto Succ : successors(E)) {
660             if (Entries.count(Succ))
661               continue;
662             if (Succ == OutliningInfo->ReturnBlock)
663               OutliningInfo->ReturnBlockPreds.push_back(E);
664             else if (Succ != OutliningInfo->NonReturnBlock)
665               return false;
666           }
667           // There should not be any outside incoming edges either:
668           if (HasNonEntryPred(E))
669             return false;
670         }
671         return true;
672       };
673 
674   if (!CheckAndNormalizeCandidate(OutliningInfo.get()))
675     return std::unique_ptr<FunctionOutliningInfo>();
676 
677   // Now further growing the candidate's inlining region by
678   // peeling off dominating blocks from the outlining region:
679   while (OutliningInfo->GetNumInlinedBlocks() < MaxNumInlineBlocks) {
680     BasicBlock *Cand = OutliningInfo->NonReturnBlock;
681     if (succ_size(Cand) != 2)
682       break;
683 
684     if (HasNonEntryPred(Cand))
685       break;
686 
687     BasicBlock *Succ1 = *succ_begin(Cand);
688     BasicBlock *Succ2 = *(succ_begin(Cand) + 1);
689 
690     BasicBlock *ReturnBlock, *NonReturnBlock;
691     std::tie(ReturnBlock, NonReturnBlock) = GetReturnBlock(Succ1, Succ2);
692     if (!ReturnBlock || ReturnBlock != OutliningInfo->ReturnBlock)
693       break;
694 
695     if (NonReturnBlock->getSinglePredecessor() != Cand)
696       break;
697 
698     // Now grow and update OutlininigInfo:
699     OutliningInfo->Entries.push_back(Cand);
700     OutliningInfo->NonReturnBlock = NonReturnBlock;
701     OutliningInfo->ReturnBlockPreds.push_back(Cand);
702     Entries.insert(Cand);
703   }
704 
705   return OutliningInfo;
706 }
707 
708 // Check if there is PGO data or user annotated branch data:
709 static bool hasProfileData(Function *F, FunctionOutliningInfo *OI) {
710   if (F->hasProfileData())
711     return true;
712   // Now check if any of the entry block has MD_prof data:
713   for (auto *E : OI->Entries) {
714     BranchInst *BR = dyn_cast<BranchInst>(E->getTerminator());
715     if (!BR || BR->isUnconditional())
716       continue;
717     uint64_t T, F;
718     if (BR->extractProfMetadata(T, F))
719       return true;
720   }
721   return false;
722 }
723 
724 BranchProbability
725 PartialInlinerImpl::getOutliningCallBBRelativeFreq(FunctionCloner &Cloner) {
726   BasicBlock *OutliningCallBB = Cloner.OutlinedFunctions.back().second;
727   auto EntryFreq =
728       Cloner.ClonedFuncBFI->getBlockFreq(&Cloner.ClonedFunc->getEntryBlock());
729   auto OutliningCallFreq =
730       Cloner.ClonedFuncBFI->getBlockFreq(OutliningCallBB);
731   // FIXME Hackery needed because ClonedFuncBFI is based on the function BEFORE
732   // we outlined any regions, so we may encounter situations where the
733   // OutliningCallFreq is *slightly* bigger than the EntryFreq.
734   if (OutliningCallFreq.getFrequency() > EntryFreq.getFrequency()) {
735     OutliningCallFreq = EntryFreq;
736   }
737   auto OutlineRegionRelFreq = BranchProbability::getBranchProbability(
738       OutliningCallFreq.getFrequency(), EntryFreq.getFrequency());
739 
740   if (hasProfileData(Cloner.OrigFunc, Cloner.ClonedOI.get()))
741     return OutlineRegionRelFreq;
742 
743   // When profile data is not available, we need to be conservative in
744   // estimating the overall savings. Static branch prediction can usually
745   // guess the branch direction right (taken/non-taken), but the guessed
746   // branch probability is usually not biased enough. In case when the
747   // outlined region is predicted to be likely, its probability needs
748   // to be made higher (more biased) to not under-estimate the cost of
749   // function outlining. On the other hand, if the outlined region
750   // is predicted to be less likely, the predicted probablity is usually
751   // higher than the actual. For instance, the actual probability of the
752   // less likely target is only 5%, but the guessed probablity can be
753   // 40%. In the latter case, there is no need for further adjustement.
754   // FIXME: add an option for this.
755   if (OutlineRegionRelFreq < BranchProbability(45, 100))
756     return OutlineRegionRelFreq;
757 
758   OutlineRegionRelFreq = std::max(
759       OutlineRegionRelFreq, BranchProbability(OutlineRegionFreqPercent, 100));
760 
761   return OutlineRegionRelFreq;
762 }
763 
764 bool PartialInlinerImpl::shouldPartialInline(
765     CallBase &CB, FunctionCloner &Cloner, BlockFrequency WeightedOutliningRcost,
766     OptimizationRemarkEmitter &ORE) {
767   using namespace ore;
768 
769   Function *Callee = CB.getCalledFunction();
770   assert(Callee == Cloner.ClonedFunc);
771 
772   if (SkipCostAnalysis)
773     return isInlineViable(*Callee).isSuccess();
774 
775   Function *Caller = CB.getCaller();
776   auto &CalleeTTI = (*GetTTI)(*Callee);
777   bool RemarksEnabled =
778       Callee->getContext().getDiagHandlerPtr()->isMissedOptRemarkEnabled(
779           DEBUG_TYPE);
780   InlineCost IC =
781       getInlineCost(CB, getInlineParams(), CalleeTTI, *GetAssumptionCache,
782                     GetBFI, *GetTLI, PSI, RemarksEnabled ? &ORE : nullptr);
783 
784   if (IC.isAlways()) {
785     ORE.emit([&]() {
786       return OptimizationRemarkAnalysis(DEBUG_TYPE, "AlwaysInline", &CB)
787              << NV("Callee", Cloner.OrigFunc)
788              << " should always be fully inlined, not partially";
789     });
790     return false;
791   }
792 
793   if (IC.isNever()) {
794     ORE.emit([&]() {
795       return OptimizationRemarkMissed(DEBUG_TYPE, "NeverInline", &CB)
796              << NV("Callee", Cloner.OrigFunc) << " not partially inlined into "
797              << NV("Caller", Caller)
798              << " because it should never be inlined (cost=never)";
799     });
800     return false;
801   }
802 
803   if (!IC) {
804     ORE.emit([&]() {
805       return OptimizationRemarkAnalysis(DEBUG_TYPE, "TooCostly", &CB)
806              << NV("Callee", Cloner.OrigFunc) << " not partially inlined into "
807              << NV("Caller", Caller) << " because too costly to inline (cost="
808              << NV("Cost", IC.getCost()) << ", threshold="
809              << NV("Threshold", IC.getCostDelta() + IC.getCost()) << ")";
810     });
811     return false;
812   }
813   const DataLayout &DL = Caller->getParent()->getDataLayout();
814 
815   // The savings of eliminating the call:
816   int NonWeightedSavings = getCallsiteCost(CB, DL);
817   BlockFrequency NormWeightedSavings(NonWeightedSavings);
818 
819   // Weighted saving is smaller than weighted cost, return false
820   if (NormWeightedSavings < WeightedOutliningRcost) {
821     ORE.emit([&]() {
822       return OptimizationRemarkAnalysis(DEBUG_TYPE, "OutliningCallcostTooHigh",
823                                         &CB)
824              << NV("Callee", Cloner.OrigFunc) << " not partially inlined into "
825              << NV("Caller", Caller) << " runtime overhead (overhead="
826              << NV("Overhead", (unsigned)WeightedOutliningRcost.getFrequency())
827              << ", savings="
828              << NV("Savings", (unsigned)NormWeightedSavings.getFrequency())
829              << ")"
830              << " of making the outlined call is too high";
831     });
832 
833     return false;
834   }
835 
836   ORE.emit([&]() {
837     return OptimizationRemarkAnalysis(DEBUG_TYPE, "CanBePartiallyInlined", &CB)
838            << NV("Callee", Cloner.OrigFunc) << " can be partially inlined into "
839            << NV("Caller", Caller) << " with cost=" << NV("Cost", IC.getCost())
840            << " (threshold="
841            << NV("Threshold", IC.getCostDelta() + IC.getCost()) << ")";
842   });
843   return true;
844 }
845 
846 // TODO: Ideally  we should share Inliner's InlineCost Analysis code.
847 // For now use a simplified version. The returned 'InlineCost' will be used
848 // to esimate the size cost as well as runtime cost of the BB.
849 int PartialInlinerImpl::computeBBInlineCost(BasicBlock *BB) {
850   int InlineCost = 0;
851   const DataLayout &DL = BB->getParent()->getParent()->getDataLayout();
852   for (Instruction &I : BB->instructionsWithoutDebug()) {
853     // Skip free instructions.
854     switch (I.getOpcode()) {
855     case Instruction::BitCast:
856     case Instruction::PtrToInt:
857     case Instruction::IntToPtr:
858     case Instruction::Alloca:
859     case Instruction::PHI:
860       continue;
861     case Instruction::GetElementPtr:
862       if (cast<GetElementPtrInst>(&I)->hasAllZeroIndices())
863         continue;
864       break;
865     default:
866       break;
867     }
868 
869     if (I.isLifetimeStartOrEnd())
870       continue;
871 
872     if (CallInst *CI = dyn_cast<CallInst>(&I)) {
873       InlineCost += getCallsiteCost(*CI, DL);
874       continue;
875     }
876 
877     if (InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
878       InlineCost += getCallsiteCost(*II, DL);
879       continue;
880     }
881 
882     if (SwitchInst *SI = dyn_cast<SwitchInst>(&I)) {
883       InlineCost += (SI->getNumCases() + 1) * InlineConstants::InstrCost;
884       continue;
885     }
886     InlineCost += InlineConstants::InstrCost;
887   }
888   return InlineCost;
889 }
890 
891 std::tuple<int, int>
892 PartialInlinerImpl::computeOutliningCosts(FunctionCloner &Cloner) {
893   int OutliningFuncCallCost = 0, OutlinedFunctionCost = 0;
894   for (auto FuncBBPair : Cloner.OutlinedFunctions) {
895     Function *OutlinedFunc = FuncBBPair.first;
896     BasicBlock* OutliningCallBB = FuncBBPair.second;
897     // Now compute the cost of the call sequence to the outlined function
898     // 'OutlinedFunction' in BB 'OutliningCallBB':
899     OutliningFuncCallCost += computeBBInlineCost(OutliningCallBB);
900 
901     // Now compute the cost of the extracted/outlined function itself:
902     for (BasicBlock &BB : *OutlinedFunc)
903       OutlinedFunctionCost += computeBBInlineCost(&BB);
904   }
905   assert(OutlinedFunctionCost >= Cloner.OutlinedRegionCost &&
906          "Outlined function cost should be no less than the outlined region");
907 
908   // The code extractor introduces a new root and exit stub blocks with
909   // additional unconditional branches. Those branches will be eliminated
910   // later with bb layout. The cost should be adjusted accordingly:
911   OutlinedFunctionCost -=
912       2 * InlineConstants::InstrCost * Cloner.OutlinedFunctions.size();
913 
914   int OutliningRuntimeOverhead =
915       OutliningFuncCallCost +
916       (OutlinedFunctionCost - Cloner.OutlinedRegionCost) +
917       ExtraOutliningPenalty;
918 
919   return std::make_tuple(OutliningFuncCallCost, OutliningRuntimeOverhead);
920 }
921 
922 // Create the callsite to profile count map which is
923 // used to update the original function's entry count,
924 // after the function is partially inlined into the callsite.
925 void PartialInlinerImpl::computeCallsiteToProfCountMap(
926     Function *DuplicateFunction,
927     DenseMap<User *, uint64_t> &CallSiteToProfCountMap) {
928   std::vector<User *> Users(DuplicateFunction->user_begin(),
929                             DuplicateFunction->user_end());
930   Function *CurrentCaller = nullptr;
931   std::unique_ptr<BlockFrequencyInfo> TempBFI;
932   BlockFrequencyInfo *CurrentCallerBFI = nullptr;
933 
934   auto ComputeCurrBFI = [&,this](Function *Caller) {
935       // For the old pass manager:
936       if (!GetBFI) {
937         DominatorTree DT(*Caller);
938         LoopInfo LI(DT);
939         BranchProbabilityInfo BPI(*Caller, LI);
940         TempBFI.reset(new BlockFrequencyInfo(*Caller, BPI, LI));
941         CurrentCallerBFI = TempBFI.get();
942       } else {
943         // New pass manager:
944         CurrentCallerBFI = &(*GetBFI)(*Caller);
945       }
946   };
947 
948   for (User *User : Users) {
949     CallBase *CB = getSupportedCallBase(User);
950     Function *Caller = CB->getCaller();
951     if (CurrentCaller != Caller) {
952       CurrentCaller = Caller;
953       ComputeCurrBFI(Caller);
954     } else {
955       assert(CurrentCallerBFI && "CallerBFI is not set");
956     }
957     BasicBlock *CallBB = CB->getParent();
958     auto Count = CurrentCallerBFI->getBlockProfileCount(CallBB);
959     if (Count)
960       CallSiteToProfCountMap[User] = *Count;
961     else
962       CallSiteToProfCountMap[User] = 0;
963   }
964 }
965 
966 PartialInlinerImpl::FunctionCloner::FunctionCloner(
967     Function *F, FunctionOutliningInfo *OI, OptimizationRemarkEmitter &ORE,
968     function_ref<AssumptionCache *(Function &)> LookupAC)
969     : OrigFunc(F), ORE(ORE), LookupAC(LookupAC) {
970   ClonedOI = std::make_unique<FunctionOutliningInfo>();
971 
972   // Clone the function, so that we can hack away on it.
973   ValueToValueMapTy VMap;
974   ClonedFunc = CloneFunction(F, VMap);
975 
976   ClonedOI->ReturnBlock = cast<BasicBlock>(VMap[OI->ReturnBlock]);
977   ClonedOI->NonReturnBlock = cast<BasicBlock>(VMap[OI->NonReturnBlock]);
978   for (BasicBlock *BB : OI->Entries) {
979     ClonedOI->Entries.push_back(cast<BasicBlock>(VMap[BB]));
980   }
981   for (BasicBlock *E : OI->ReturnBlockPreds) {
982     BasicBlock *NewE = cast<BasicBlock>(VMap[E]);
983     ClonedOI->ReturnBlockPreds.push_back(NewE);
984   }
985   // Go ahead and update all uses to the duplicate, so that we can just
986   // use the inliner functionality when we're done hacking.
987   F->replaceAllUsesWith(ClonedFunc);
988 }
989 
990 PartialInlinerImpl::FunctionCloner::FunctionCloner(
991     Function *F, FunctionOutliningMultiRegionInfo *OI,
992     OptimizationRemarkEmitter &ORE,
993     function_ref<AssumptionCache *(Function &)> LookupAC)
994     : OrigFunc(F), ORE(ORE), LookupAC(LookupAC) {
995   ClonedOMRI = std::make_unique<FunctionOutliningMultiRegionInfo>();
996 
997   // Clone the function, so that we can hack away on it.
998   ValueToValueMapTy VMap;
999   ClonedFunc = CloneFunction(F, VMap);
1000 
1001   // Go through all Outline Candidate Regions and update all BasicBlock
1002   // information.
1003   for (FunctionOutliningMultiRegionInfo::OutlineRegionInfo RegionInfo :
1004        OI->ORI) {
1005     SmallVector<BasicBlock *, 8> Region;
1006     for (BasicBlock *BB : RegionInfo.Region) {
1007       Region.push_back(cast<BasicBlock>(VMap[BB]));
1008     }
1009     BasicBlock *NewEntryBlock = cast<BasicBlock>(VMap[RegionInfo.EntryBlock]);
1010     BasicBlock *NewExitBlock = cast<BasicBlock>(VMap[RegionInfo.ExitBlock]);
1011     BasicBlock *NewReturnBlock = nullptr;
1012     if (RegionInfo.ReturnBlock)
1013       NewReturnBlock = cast<BasicBlock>(VMap[RegionInfo.ReturnBlock]);
1014     FunctionOutliningMultiRegionInfo::OutlineRegionInfo MappedRegionInfo(
1015         Region, NewEntryBlock, NewExitBlock, NewReturnBlock);
1016     ClonedOMRI->ORI.push_back(MappedRegionInfo);
1017   }
1018   // Go ahead and update all uses to the duplicate, so that we can just
1019   // use the inliner functionality when we're done hacking.
1020   F->replaceAllUsesWith(ClonedFunc);
1021 }
1022 
1023 void PartialInlinerImpl::FunctionCloner::NormalizeReturnBlock() {
1024   auto getFirstPHI = [](BasicBlock *BB) {
1025     BasicBlock::iterator I = BB->begin();
1026     PHINode *FirstPhi = nullptr;
1027     while (I != BB->end()) {
1028       PHINode *Phi = dyn_cast<PHINode>(I);
1029       if (!Phi)
1030         break;
1031       if (!FirstPhi) {
1032         FirstPhi = Phi;
1033         break;
1034       }
1035     }
1036     return FirstPhi;
1037   };
1038 
1039   // Shouldn't need to normalize PHIs if we're not outlining non-early return
1040   // blocks.
1041   if (!ClonedOI)
1042     return;
1043 
1044   // Special hackery is needed with PHI nodes that have inputs from more than
1045   // one extracted block.  For simplicity, just split the PHIs into a two-level
1046   // sequence of PHIs, some of which will go in the extracted region, and some
1047   // of which will go outside.
1048   BasicBlock *PreReturn = ClonedOI->ReturnBlock;
1049   // only split block when necessary:
1050   PHINode *FirstPhi = getFirstPHI(PreReturn);
1051   unsigned NumPredsFromEntries = ClonedOI->ReturnBlockPreds.size();
1052 
1053   if (!FirstPhi || FirstPhi->getNumIncomingValues() <= NumPredsFromEntries + 1)
1054     return;
1055 
1056   auto IsTrivialPhi = [](PHINode *PN) -> Value * {
1057     Value *CommonValue = PN->getIncomingValue(0);
1058     if (all_of(PN->incoming_values(),
1059                [&](Value *V) { return V == CommonValue; }))
1060       return CommonValue;
1061     return nullptr;
1062   };
1063 
1064   ClonedOI->ReturnBlock = ClonedOI->ReturnBlock->splitBasicBlock(
1065       ClonedOI->ReturnBlock->getFirstNonPHI()->getIterator());
1066   BasicBlock::iterator I = PreReturn->begin();
1067   Instruction *Ins = &ClonedOI->ReturnBlock->front();
1068   SmallVector<Instruction *, 4> DeadPhis;
1069   while (I != PreReturn->end()) {
1070     PHINode *OldPhi = dyn_cast<PHINode>(I);
1071     if (!OldPhi)
1072       break;
1073 
1074     PHINode *RetPhi =
1075         PHINode::Create(OldPhi->getType(), NumPredsFromEntries + 1, "", Ins);
1076     OldPhi->replaceAllUsesWith(RetPhi);
1077     Ins = ClonedOI->ReturnBlock->getFirstNonPHI();
1078 
1079     RetPhi->addIncoming(&*I, PreReturn);
1080     for (BasicBlock *E : ClonedOI->ReturnBlockPreds) {
1081       RetPhi->addIncoming(OldPhi->getIncomingValueForBlock(E), E);
1082       OldPhi->removeIncomingValue(E);
1083     }
1084 
1085     // After incoming values splitting, the old phi may become trivial.
1086     // Keeping the trivial phi can introduce definition inside the outline
1087     // region which is live-out, causing necessary overhead (load, store
1088     // arg passing etc).
1089     if (auto *OldPhiVal = IsTrivialPhi(OldPhi)) {
1090       OldPhi->replaceAllUsesWith(OldPhiVal);
1091       DeadPhis.push_back(OldPhi);
1092     }
1093     ++I;
1094   }
1095   for (auto *DP : DeadPhis)
1096     DP->eraseFromParent();
1097 
1098   for (auto E : ClonedOI->ReturnBlockPreds) {
1099     E->getTerminator()->replaceUsesOfWith(PreReturn, ClonedOI->ReturnBlock);
1100   }
1101 }
1102 
1103 bool PartialInlinerImpl::FunctionCloner::doMultiRegionFunctionOutlining() {
1104 
1105   auto ComputeRegionCost = [](SmallVectorImpl<BasicBlock *> &Region) {
1106     int Cost = 0;
1107     for (BasicBlock* BB : Region)
1108       Cost += computeBBInlineCost(BB);
1109     return Cost;
1110   };
1111 
1112   assert(ClonedOMRI && "Expecting OutlineInfo for multi region outline");
1113 
1114   if (ClonedOMRI->ORI.empty())
1115     return false;
1116 
1117   // The CodeExtractor needs a dominator tree.
1118   DominatorTree DT;
1119   DT.recalculate(*ClonedFunc);
1120 
1121   // Manually calculate a BlockFrequencyInfo and BranchProbabilityInfo.
1122   LoopInfo LI(DT);
1123   BranchProbabilityInfo BPI(*ClonedFunc, LI);
1124   ClonedFuncBFI.reset(new BlockFrequencyInfo(*ClonedFunc, BPI, LI));
1125 
1126   // Cache and recycle the CodeExtractor analysis to avoid O(n^2) compile-time.
1127   CodeExtractorAnalysisCache CEAC(*ClonedFunc);
1128 
1129   SetVector<Value *> Inputs, Outputs, Sinks;
1130   for (FunctionOutliningMultiRegionInfo::OutlineRegionInfo RegionInfo :
1131        ClonedOMRI->ORI) {
1132     int CurrentOutlinedRegionCost = ComputeRegionCost(RegionInfo.Region);
1133 
1134     CodeExtractor CE(RegionInfo.Region, &DT, /*AggregateArgs*/ false,
1135                      ClonedFuncBFI.get(), &BPI,
1136                      LookupAC(*RegionInfo.EntryBlock->getParent()),
1137                      /* AllowVarargs */ false);
1138 
1139     CE.findInputsOutputs(Inputs, Outputs, Sinks);
1140 
1141 #ifndef NDEBUG
1142     if (TracePartialInlining) {
1143       dbgs() << "inputs: " << Inputs.size() << "\n";
1144       dbgs() << "outputs: " << Outputs.size() << "\n";
1145       for (Value *value : Inputs)
1146         dbgs() << "value used in func: " << *value << "\n";
1147       for (Value *output : Outputs)
1148         dbgs() << "instr used in func: " << *output << "\n";
1149     }
1150 #endif
1151     // Do not extract regions that have live exit variables.
1152     if (Outputs.size() > 0 && !ForceLiveExit)
1153       continue;
1154 
1155     Function *OutlinedFunc = CE.extractCodeRegion(CEAC);
1156 
1157     if (OutlinedFunc) {
1158       CallBase *OCS = PartialInlinerImpl::getOneCallSiteTo(OutlinedFunc);
1159       BasicBlock *OutliningCallBB = OCS->getParent();
1160       assert(OutliningCallBB->getParent() == ClonedFunc);
1161       OutlinedFunctions.push_back(std::make_pair(OutlinedFunc,OutliningCallBB));
1162       NumColdRegionsOutlined++;
1163       OutlinedRegionCost += CurrentOutlinedRegionCost;
1164 
1165       if (MarkOutlinedColdCC) {
1166         OutlinedFunc->setCallingConv(CallingConv::Cold);
1167         OCS->setCallingConv(CallingConv::Cold);
1168       }
1169     } else
1170       ORE.emit([&]() {
1171         return OptimizationRemarkMissed(DEBUG_TYPE, "ExtractFailed",
1172                                         &RegionInfo.Region.front()->front())
1173                << "Failed to extract region at block "
1174                << ore::NV("Block", RegionInfo.Region.front());
1175       });
1176   }
1177 
1178   return !OutlinedFunctions.empty();
1179 }
1180 
1181 Function *
1182 PartialInlinerImpl::FunctionCloner::doSingleRegionFunctionOutlining() {
1183   // Returns true if the block is to be partial inlined into the caller
1184   // (i.e. not to be extracted to the out of line function)
1185   auto ToBeInlined = [&, this](BasicBlock *BB) {
1186     return BB == ClonedOI->ReturnBlock ||
1187            (std::find(ClonedOI->Entries.begin(), ClonedOI->Entries.end(), BB) !=
1188             ClonedOI->Entries.end());
1189   };
1190 
1191   assert(ClonedOI && "Expecting OutlineInfo for single region outline");
1192   // The CodeExtractor needs a dominator tree.
1193   DominatorTree DT;
1194   DT.recalculate(*ClonedFunc);
1195 
1196   // Manually calculate a BlockFrequencyInfo and BranchProbabilityInfo.
1197   LoopInfo LI(DT);
1198   BranchProbabilityInfo BPI(*ClonedFunc, LI);
1199   ClonedFuncBFI.reset(new BlockFrequencyInfo(*ClonedFunc, BPI, LI));
1200 
1201   // Gather up the blocks that we're going to extract.
1202   std::vector<BasicBlock *> ToExtract;
1203   ToExtract.push_back(ClonedOI->NonReturnBlock);
1204   OutlinedRegionCost +=
1205       PartialInlinerImpl::computeBBInlineCost(ClonedOI->NonReturnBlock);
1206   for (BasicBlock &BB : *ClonedFunc)
1207     if (!ToBeInlined(&BB) && &BB != ClonedOI->NonReturnBlock) {
1208       ToExtract.push_back(&BB);
1209       // FIXME: the code extractor may hoist/sink more code
1210       // into the outlined function which may make the outlining
1211       // overhead (the difference of the outlined function cost
1212       // and OutliningRegionCost) look larger.
1213       OutlinedRegionCost += computeBBInlineCost(&BB);
1214     }
1215 
1216   // Extract the body of the if.
1217   CodeExtractorAnalysisCache CEAC(*ClonedFunc);
1218   Function *OutlinedFunc =
1219       CodeExtractor(ToExtract, &DT, /*AggregateArgs*/ false,
1220                     ClonedFuncBFI.get(), &BPI, LookupAC(*ClonedFunc),
1221                     /* AllowVarargs */ true)
1222           .extractCodeRegion(CEAC);
1223 
1224   if (OutlinedFunc) {
1225     BasicBlock *OutliningCallBB =
1226         PartialInlinerImpl::getOneCallSiteTo(OutlinedFunc)
1227             ->getParent();
1228     assert(OutliningCallBB->getParent() == ClonedFunc);
1229     OutlinedFunctions.push_back(std::make_pair(OutlinedFunc, OutliningCallBB));
1230   } else
1231     ORE.emit([&]() {
1232       return OptimizationRemarkMissed(DEBUG_TYPE, "ExtractFailed",
1233                                       &ToExtract.front()->front())
1234              << "Failed to extract region at block "
1235              << ore::NV("Block", ToExtract.front());
1236     });
1237 
1238   return OutlinedFunc;
1239 }
1240 
1241 PartialInlinerImpl::FunctionCloner::~FunctionCloner() {
1242   // Ditch the duplicate, since we're done with it, and rewrite all remaining
1243   // users (function pointers, etc.) back to the original function.
1244   ClonedFunc->replaceAllUsesWith(OrigFunc);
1245   ClonedFunc->eraseFromParent();
1246   if (!IsFunctionInlined) {
1247     // Remove each function that was speculatively created if there is no
1248     // reference.
1249     for (auto FuncBBPair : OutlinedFunctions) {
1250       Function *Func = FuncBBPair.first;
1251       Func->eraseFromParent();
1252     }
1253   }
1254 }
1255 
1256 std::pair<bool, Function *> PartialInlinerImpl::unswitchFunction(Function *F) {
1257 
1258   if (F->hasAddressTaken())
1259     return {false, nullptr};
1260 
1261   // Let inliner handle it
1262   if (F->hasFnAttribute(Attribute::AlwaysInline))
1263     return {false, nullptr};
1264 
1265   if (F->hasFnAttribute(Attribute::NoInline))
1266     return {false, nullptr};
1267 
1268   if (PSI->isFunctionEntryCold(F))
1269     return {false, nullptr};
1270 
1271   if (F->users().empty())
1272     return {false, nullptr};
1273 
1274   OptimizationRemarkEmitter ORE(F);
1275 
1276   // Only try to outline cold regions if we have a profile summary, which
1277   // implies we have profiling information.
1278   if (PSI->hasProfileSummary() && F->hasProfileData() &&
1279       !DisableMultiRegionPartialInline) {
1280     std::unique_ptr<FunctionOutliningMultiRegionInfo> OMRI =
1281         computeOutliningColdRegionsInfo(F, ORE);
1282     if (OMRI) {
1283       FunctionCloner Cloner(F, OMRI.get(), ORE, LookupAssumptionCache);
1284 
1285 #ifndef NDEBUG
1286       if (TracePartialInlining) {
1287         dbgs() << "HotCountThreshold = " << PSI->getHotCountThreshold() << "\n";
1288         dbgs() << "ColdCountThreshold = " << PSI->getColdCountThreshold()
1289                << "\n";
1290       }
1291 #endif
1292       bool DidOutline = Cloner.doMultiRegionFunctionOutlining();
1293 
1294       if (DidOutline) {
1295 #ifndef NDEBUG
1296         if (TracePartialInlining) {
1297           dbgs() << ">>>>>> Outlined (Cloned) Function >>>>>>\n";
1298           Cloner.ClonedFunc->print(dbgs());
1299           dbgs() << "<<<<<< Outlined (Cloned) Function <<<<<<\n";
1300         }
1301 #endif
1302 
1303         if (tryPartialInline(Cloner))
1304           return {true, nullptr};
1305       }
1306     }
1307   }
1308 
1309   // Fall-thru to regular partial inlining if we:
1310   //    i) can't find any cold regions to outline, or
1311   //   ii) can't inline the outlined function anywhere.
1312   std::unique_ptr<FunctionOutliningInfo> OI = computeOutliningInfo(F);
1313   if (!OI)
1314     return {false, nullptr};
1315 
1316   FunctionCloner Cloner(F, OI.get(), ORE, LookupAssumptionCache);
1317   Cloner.NormalizeReturnBlock();
1318 
1319   Function *OutlinedFunction = Cloner.doSingleRegionFunctionOutlining();
1320 
1321   if (!OutlinedFunction)
1322     return {false, nullptr};
1323 
1324   bool AnyInline = tryPartialInline(Cloner);
1325 
1326   if (AnyInline)
1327     return {true, OutlinedFunction};
1328 
1329   return {false, nullptr};
1330 }
1331 
1332 bool PartialInlinerImpl::tryPartialInline(FunctionCloner &Cloner) {
1333   if (Cloner.OutlinedFunctions.empty())
1334     return false;
1335 
1336   int SizeCost = 0;
1337   BlockFrequency WeightedRcost;
1338   int NonWeightedRcost;
1339   std::tie(SizeCost, NonWeightedRcost) = computeOutliningCosts(Cloner);
1340 
1341   // Only calculate RelativeToEntryFreq when we are doing single region
1342   // outlining.
1343   BranchProbability RelativeToEntryFreq;
1344   if (Cloner.ClonedOI) {
1345     RelativeToEntryFreq = getOutliningCallBBRelativeFreq(Cloner);
1346   } else
1347     // RelativeToEntryFreq doesn't make sense when we have more than one
1348     // outlined call because each call will have a different relative frequency
1349     // to the entry block.  We can consider using the average, but the
1350     // usefulness of that information is questionable. For now, assume we never
1351     // execute the calls to outlined functions.
1352     RelativeToEntryFreq = BranchProbability(0, 1);
1353 
1354   WeightedRcost = BlockFrequency(NonWeightedRcost) * RelativeToEntryFreq;
1355 
1356   // The call sequence(s) to the outlined function(s) are larger than the sum of
1357   // the original outlined region size(s), it does not increase the chances of
1358   // inlining the function with outlining (The inliner uses the size increase to
1359   // model the cost of inlining a callee).
1360   if (!SkipCostAnalysis && Cloner.OutlinedRegionCost < SizeCost) {
1361     OptimizationRemarkEmitter OrigFuncORE(Cloner.OrigFunc);
1362     DebugLoc DLoc;
1363     BasicBlock *Block;
1364     std::tie(DLoc, Block) = getOneDebugLoc(Cloner.ClonedFunc);
1365     OrigFuncORE.emit([&]() {
1366       return OptimizationRemarkAnalysis(DEBUG_TYPE, "OutlineRegionTooSmall",
1367                                         DLoc, Block)
1368              << ore::NV("Function", Cloner.OrigFunc)
1369              << " not partially inlined into callers (Original Size = "
1370              << ore::NV("OutlinedRegionOriginalSize", Cloner.OutlinedRegionCost)
1371              << ", Size of call sequence to outlined function = "
1372              << ore::NV("NewSize", SizeCost) << ")";
1373     });
1374     return false;
1375   }
1376 
1377   assert(Cloner.OrigFunc->users().empty() &&
1378          "F's users should all be replaced!");
1379 
1380   std::vector<User *> Users(Cloner.ClonedFunc->user_begin(),
1381                             Cloner.ClonedFunc->user_end());
1382 
1383   DenseMap<User *, uint64_t> CallSiteToProfCountMap;
1384   auto CalleeEntryCount = Cloner.OrigFunc->getEntryCount();
1385   if (CalleeEntryCount)
1386     computeCallsiteToProfCountMap(Cloner.ClonedFunc, CallSiteToProfCountMap);
1387 
1388   uint64_t CalleeEntryCountV =
1389       (CalleeEntryCount ? CalleeEntryCount.getCount() : 0);
1390 
1391   bool AnyInline = false;
1392   for (User *User : Users) {
1393     CallBase *CB = getSupportedCallBase(User);
1394 
1395     if (IsLimitReached())
1396       continue;
1397 
1398     OptimizationRemarkEmitter CallerORE(CB->getCaller());
1399     if (!shouldPartialInline(*CB, Cloner, WeightedRcost, CallerORE))
1400       continue;
1401 
1402     // Construct remark before doing the inlining, as after successful inlining
1403     // the callsite is removed.
1404     OptimizationRemark OR(DEBUG_TYPE, "PartiallyInlined", CB);
1405     OR << ore::NV("Callee", Cloner.OrigFunc) << " partially inlined into "
1406        << ore::NV("Caller", CB->getCaller());
1407 
1408     InlineFunctionInfo IFI(nullptr, GetAssumptionCache, PSI);
1409     // We can only forward varargs when we outlined a single region, else we
1410     // bail on vararg functions.
1411     if (!InlineFunction(*CB, IFI, nullptr, true,
1412                         (Cloner.ClonedOI ? Cloner.OutlinedFunctions.back().first
1413                                          : nullptr))
1414              .isSuccess())
1415       continue;
1416 
1417     CallerORE.emit(OR);
1418 
1419     // Now update the entry count:
1420     if (CalleeEntryCountV && CallSiteToProfCountMap.count(User)) {
1421       uint64_t CallSiteCount = CallSiteToProfCountMap[User];
1422       CalleeEntryCountV -= std::min(CalleeEntryCountV, CallSiteCount);
1423     }
1424 
1425     AnyInline = true;
1426     NumPartialInlining++;
1427     // Update the stats
1428     if (Cloner.ClonedOI)
1429       NumPartialInlined++;
1430     else
1431       NumColdOutlinePartialInlined++;
1432 
1433   }
1434 
1435   if (AnyInline) {
1436     Cloner.IsFunctionInlined = true;
1437     if (CalleeEntryCount)
1438       Cloner.OrigFunc->setEntryCount(
1439           CalleeEntryCount.setCount(CalleeEntryCountV));
1440     OptimizationRemarkEmitter OrigFuncORE(Cloner.OrigFunc);
1441     OrigFuncORE.emit([&]() {
1442       return OptimizationRemark(DEBUG_TYPE, "PartiallyInlined", Cloner.OrigFunc)
1443              << "Partially inlined into at least one caller";
1444     });
1445 
1446   }
1447 
1448   return AnyInline;
1449 }
1450 
1451 bool PartialInlinerImpl::run(Module &M) {
1452   if (DisablePartialInlining)
1453     return false;
1454 
1455   std::vector<Function *> Worklist;
1456   Worklist.reserve(M.size());
1457   for (Function &F : M)
1458     if (!F.use_empty() && !F.isDeclaration())
1459       Worklist.push_back(&F);
1460 
1461   bool Changed = false;
1462   while (!Worklist.empty()) {
1463     Function *CurrFunc = Worklist.back();
1464     Worklist.pop_back();
1465 
1466     if (CurrFunc->use_empty())
1467       continue;
1468 
1469     bool Recursive = false;
1470     for (User *U : CurrFunc->users())
1471       if (Instruction *I = dyn_cast<Instruction>(U))
1472         if (I->getParent()->getParent() == CurrFunc) {
1473           Recursive = true;
1474           break;
1475         }
1476     if (Recursive)
1477       continue;
1478 
1479     std::pair<bool, Function * > Result = unswitchFunction(CurrFunc);
1480     if (Result.second)
1481       Worklist.push_back(Result.second);
1482     Changed |= Result.first;
1483   }
1484 
1485   return Changed;
1486 }
1487 
1488 char PartialInlinerLegacyPass::ID = 0;
1489 
1490 INITIALIZE_PASS_BEGIN(PartialInlinerLegacyPass, "partial-inliner",
1491                       "Partial Inliner", false, false)
1492 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
1493 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
1494 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
1495 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1496 INITIALIZE_PASS_END(PartialInlinerLegacyPass, "partial-inliner",
1497                     "Partial Inliner", false, false)
1498 
1499 ModulePass *llvm::createPartialInliningPass() {
1500   return new PartialInlinerLegacyPass();
1501 }
1502 
1503 PreservedAnalyses PartialInlinerPass::run(Module &M,
1504                                           ModuleAnalysisManager &AM) {
1505   auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
1506 
1507   std::function<AssumptionCache &(Function &)> GetAssumptionCache =
1508       [&FAM](Function &F) -> AssumptionCache & {
1509     return FAM.getResult<AssumptionAnalysis>(F);
1510   };
1511 
1512   auto LookupAssumptionCache = [&FAM](Function &F) -> AssumptionCache * {
1513     return FAM.getCachedResult<AssumptionAnalysis>(F);
1514   };
1515 
1516   std::function<BlockFrequencyInfo &(Function &)> GetBFI =
1517       [&FAM](Function &F) -> BlockFrequencyInfo & {
1518     return FAM.getResult<BlockFrequencyAnalysis>(F);
1519   };
1520 
1521   std::function<TargetTransformInfo &(Function &)> GetTTI =
1522       [&FAM](Function &F) -> TargetTransformInfo & {
1523     return FAM.getResult<TargetIRAnalysis>(F);
1524   };
1525 
1526   std::function<const TargetLibraryInfo &(Function &)> GetTLI =
1527       [&FAM](Function &F) -> TargetLibraryInfo & {
1528     return FAM.getResult<TargetLibraryAnalysis>(F);
1529   };
1530 
1531   ProfileSummaryInfo *PSI = &AM.getResult<ProfileSummaryAnalysis>(M);
1532 
1533   if (PartialInlinerImpl(&GetAssumptionCache, LookupAssumptionCache, &GetTTI,
1534                          {GetBFI}, &GetTLI, PSI)
1535           .run(M))
1536     return PreservedAnalyses::none();
1537   return PreservedAnalyses::all();
1538 }
1539