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