1 //===- IROutliner.cpp -- Outline Similar Regions ----------------*- C++ -*-===//
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 /// \file
10 // Implementation for the IROutliner which is used by the IROutliner Pass.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Transforms/IPO/IROutliner.h"
15 #include "llvm/Analysis/IRSimilarityIdentifier.h"
16 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
17 #include "llvm/Analysis/TargetTransformInfo.h"
18 #include "llvm/IR/Attributes.h"
19 #include "llvm/IR/DebugInfoMetadata.h"
20 #include "llvm/IR/DIBuilder.h"
21 #include "llvm/IR/Dominators.h"
22 #include "llvm/IR/Mangler.h"
23 #include "llvm/IR/PassManager.h"
24 #include "llvm/InitializePasses.h"
25 #include "llvm/Pass.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Transforms/IPO.h"
28 #include <map>
29 #include <set>
30 #include <vector>
31 
32 #define DEBUG_TYPE "iroutliner"
33 
34 using namespace llvm;
35 using namespace IRSimilarity;
36 
37 // A command flag to be used for debugging to exclude branches from similarity
38 // matching and outlining.
39 extern cl::opt<bool> DisableBranches;
40 
41 // Set to true if the user wants the ir outliner to run on linkonceodr linkage
42 // functions. This is false by default because the linker can dedupe linkonceodr
43 // functions. Since the outliner is confined to a single module (modulo LTO),
44 // this is off by default. It should, however, be the default behavior in
45 // LTO.
46 static cl::opt<bool> EnableLinkOnceODRIROutlining(
47     "enable-linkonceodr-ir-outlining", cl::Hidden,
48     cl::desc("Enable the IR outliner on linkonceodr functions"),
49     cl::init(false));
50 
51 // This is a debug option to test small pieces of code to ensure that outlining
52 // works correctly.
53 static cl::opt<bool> NoCostModel(
54     "ir-outlining-no-cost", cl::init(false), cl::ReallyHidden,
55     cl::desc("Debug option to outline greedily, without restriction that "
56              "calculated benefit outweighs cost"));
57 
58 /// The OutlinableGroup holds all the overarching information for outlining
59 /// a set of regions that are structurally similar to one another, such as the
60 /// types of the overall function, the output blocks, the sets of stores needed
61 /// and a list of the different regions. This information is used in the
62 /// deduplication of extracted regions with the same structure.
63 struct OutlinableGroup {
64   /// The sections that could be outlined
65   std::vector<OutlinableRegion *> Regions;
66 
67   /// The argument types for the function created as the overall function to
68   /// replace the extracted function for each region.
69   std::vector<Type *> ArgumentTypes;
70   /// The FunctionType for the overall function.
71   FunctionType *OutlinedFunctionType = nullptr;
72   /// The Function for the collective overall function.
73   Function *OutlinedFunction = nullptr;
74 
75   /// Flag for whether we should not consider this group of OutlinableRegions
76   /// for extraction.
77   bool IgnoreGroup = false;
78 
79   /// The return blocks for the overall function.
80   DenseMap<Value *, BasicBlock *> EndBBs;
81 
82   /// The PHIBlocks with their corresponding return block based on the return
83   /// value as the key.
84   DenseMap<Value *, BasicBlock *> PHIBlocks;
85 
86   /// A set containing the different GVN store sets needed. Each array contains
87   /// a sorted list of the different values that need to be stored into output
88   /// registers.
89   DenseSet<ArrayRef<unsigned>> OutputGVNCombinations;
90 
91   /// Flag for whether the \ref ArgumentTypes have been defined after the
92   /// extraction of the first region.
93   bool InputTypesSet = false;
94 
95   /// The number of input values in \ref ArgumentTypes.  Anything after this
96   /// index in ArgumentTypes is an output argument.
97   unsigned NumAggregateInputs = 0;
98 
99   /// The mapping of the canonical numbering of the values in outlined sections
100   /// to specific arguments.
101   DenseMap<unsigned, unsigned> CanonicalNumberToAggArg;
102 
103   /// The number of branches in the region target a basic block that is outside
104   /// of the region.
105   unsigned BranchesToOutside = 0;
106 
107   /// The number of instructions that will be outlined by extracting \ref
108   /// Regions.
109   InstructionCost Benefit = 0;
110   /// The number of added instructions needed for the outlining of the \ref
111   /// Regions.
112   InstructionCost Cost = 0;
113 
114   /// The argument that needs to be marked with the swifterr attribute.  If not
115   /// needed, there is no value.
116   Optional<unsigned> SwiftErrorArgument;
117 
118   /// For the \ref Regions, we look at every Value.  If it is a constant,
119   /// we check whether it is the same in Region.
120   ///
121   /// \param [in,out] NotSame contains the global value numbers where the
122   /// constant is not always the same, and must be passed in as an argument.
123   void findSameConstants(DenseSet<unsigned> &NotSame);
124 
125   /// For the regions, look at each set of GVN stores needed and account for
126   /// each combination.  Add an argument to the argument types if there is
127   /// more than one combination.
128   ///
129   /// \param [in] M - The module we are outlining from.
130   void collectGVNStoreSets(Module &M);
131 };
132 
133 /// Move the contents of \p SourceBB to before the last instruction of \p
134 /// TargetBB.
135 /// \param SourceBB - the BasicBlock to pull Instructions from.
136 /// \param TargetBB - the BasicBlock to put Instruction into.
137 static void moveBBContents(BasicBlock &SourceBB, BasicBlock &TargetBB) {
138   BasicBlock::iterator BBCurr, BBEnd, BBNext;
139   for (BBCurr = SourceBB.begin(), BBEnd = SourceBB.end(); BBCurr != BBEnd;
140        BBCurr = BBNext) {
141     BBNext = std::next(BBCurr);
142     BBCurr->moveBefore(TargetBB, TargetBB.end());
143   }
144 }
145 
146 /// A function to sort the keys of \p Map, which must be a mapping of constant
147 /// values to basic blocks and return it in \p SortedKeys
148 ///
149 /// \param SortedKeys - The vector the keys will be return in and sorted.
150 /// \param Map - The DenseMap containing keys to sort.
151 static void getSortedConstantKeys(std::vector<Value *> &SortedKeys,
152                                   DenseMap<Value *, BasicBlock *> &Map) {
153   for (auto &VtoBB : Map)
154     SortedKeys.push_back(VtoBB.first);
155 
156   stable_sort(SortedKeys, [](const Value *LHS, const Value *RHS) {
157     const ConstantInt *LHSC = dyn_cast<ConstantInt>(LHS);
158     const ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS);
159     assert(RHSC && "Not a constant integer in return value?");
160     assert(LHSC && "Not a constant integer in return value?");
161 
162     return LHSC->getLimitedValue() < RHSC->getLimitedValue();
163   });
164 }
165 
166 Value *OutlinableRegion::findCorrespondingValueIn(const OutlinableRegion &Other,
167                                                   Value *V) {
168   Optional<unsigned> GVN = Candidate->getGVN(V);
169   assert(GVN.hasValue() && "No GVN for incoming value");
170   Optional<unsigned> CanonNum = Candidate->getCanonicalNum(*GVN);
171   Optional<unsigned> FirstGVN = Other.Candidate->fromCanonicalNum(*CanonNum);
172   Optional<Value *> FoundValueOpt = Other.Candidate->fromGVN(*FirstGVN);
173   return FoundValueOpt.getValueOr(nullptr);
174 }
175 
176 void OutlinableRegion::splitCandidate() {
177   assert(!CandidateSplit && "Candidate already split!");
178 
179   Instruction *BackInst = Candidate->backInstruction();
180 
181   Instruction *EndInst = nullptr;
182   // Check whether the last instruction is a terminator, if it is, we do
183   // not split on the following instruction. We leave the block as it is.  We
184   // also check that this is not the last instruction in the Module, otherwise
185   // the check for whether the current following instruction matches the
186   // previously recorded instruction will be incorrect.
187   if (!BackInst->isTerminator() ||
188       BackInst->getParent() != &BackInst->getFunction()->back()) {
189     EndInst = Candidate->end()->Inst;
190     assert(EndInst && "Expected an end instruction?");
191   }
192 
193   // We check if the current instruction following the last instruction in the
194   // region is the same as the recorded instruction following the last
195   // instruction. If they do not match, there could be problems in rewriting
196   // the program after outlining, so we ignore it.
197   if (!BackInst->isTerminator() &&
198       EndInst != BackInst->getNextNonDebugInstruction())
199     return;
200 
201   Instruction *StartInst = (*Candidate->begin()).Inst;
202   assert(StartInst && "Expected a start instruction?");
203   StartBB = StartInst->getParent();
204   PrevBB = StartBB;
205 
206   // The basic block gets split like so:
207   // block:                 block:
208   //   inst1                  inst1
209   //   inst2                  inst2
210   //   region1               br block_to_outline
211   //   region2              block_to_outline:
212   //   region3          ->    region1
213   //   region4                region2
214   //   inst3                  region3
215   //   inst4                  region4
216   //                          br block_after_outline
217   //                        block_after_outline:
218   //                          inst3
219   //                          inst4
220 
221   std::string OriginalName = PrevBB->getName().str();
222 
223   StartBB = PrevBB->splitBasicBlock(StartInst, OriginalName + "_to_outline");
224   PrevBB->replaceSuccessorsPhiUsesWith(PrevBB, StartBB);
225 
226   CandidateSplit = true;
227   if (!BackInst->isTerminator()) {
228     EndBB = EndInst->getParent();
229     FollowBB = EndBB->splitBasicBlock(EndInst, OriginalName + "_after_outline");
230     EndBB->replaceSuccessorsPhiUsesWith(EndBB, FollowBB);
231     FollowBB->replaceSuccessorsPhiUsesWith(PrevBB, FollowBB);
232     return;
233   }
234 
235   EndBB = BackInst->getParent();
236   EndsInBranch = true;
237   FollowBB = nullptr;
238 }
239 
240 void OutlinableRegion::reattachCandidate() {
241   assert(CandidateSplit && "Candidate is not split!");
242 
243   // The basic block gets reattached like so:
244   // block:                        block:
245   //   inst1                         inst1
246   //   inst2                         inst2
247   //   br block_to_outline           region1
248   // block_to_outline:        ->     region2
249   //   region1                       region3
250   //   region2                       region4
251   //   region3                       inst3
252   //   region4                       inst4
253   //   br block_after_outline
254   // block_after_outline:
255   //   inst3
256   //   inst4
257   assert(StartBB != nullptr && "StartBB for Candidate is not defined!");
258 
259   // StartBB should only have one predecessor since we put an unconditional
260   // branch at the end of PrevBB when we split the BasicBlock.
261   PrevBB = StartBB->getSinglePredecessor();
262   assert(PrevBB != nullptr &&
263          "No Predecessor for the region start basic block!");
264 
265   assert(PrevBB->getTerminator() && "Terminator removed from PrevBB!");
266   PrevBB->getTerminator()->eraseFromParent();
267 
268   moveBBContents(*StartBB, *PrevBB);
269 
270   BasicBlock *PlacementBB = PrevBB;
271   if (StartBB != EndBB)
272     PlacementBB = EndBB;
273   if (!EndsInBranch && PlacementBB->getUniqueSuccessor() != nullptr) {
274     assert(FollowBB != nullptr && "FollowBB for Candidate is not defined!");
275     assert(PlacementBB->getTerminator() && "Terminator removed from EndBB!");
276     PlacementBB->getTerminator()->eraseFromParent();
277     moveBBContents(*FollowBB, *PlacementBB);
278     PlacementBB->replaceSuccessorsPhiUsesWith(FollowBB, PlacementBB);
279     FollowBB->eraseFromParent();
280   }
281 
282   PrevBB->replaceSuccessorsPhiUsesWith(StartBB, PrevBB);
283   StartBB->eraseFromParent();
284 
285   // Make sure to save changes back to the StartBB.
286   StartBB = PrevBB;
287   EndBB = nullptr;
288   PrevBB = nullptr;
289   FollowBB = nullptr;
290 
291   CandidateSplit = false;
292 }
293 
294 /// Find whether \p V matches the Constants previously found for the \p GVN.
295 ///
296 /// \param V - The value to check for consistency.
297 /// \param GVN - The global value number assigned to \p V.
298 /// \param GVNToConstant - The mapping of global value number to Constants.
299 /// \returns true if the Value matches the Constant mapped to by V and false if
300 /// it \p V is a Constant but does not match.
301 /// \returns None if \p V is not a Constant.
302 static Optional<bool>
303 constantMatches(Value *V, unsigned GVN,
304                 DenseMap<unsigned, Constant *> &GVNToConstant) {
305   // See if we have a constants
306   Constant *CST = dyn_cast<Constant>(V);
307   if (!CST)
308     return None;
309 
310   // Holds a mapping from a global value number to a Constant.
311   DenseMap<unsigned, Constant *>::iterator GVNToConstantIt;
312   bool Inserted;
313 
314 
315   // If we have a constant, try to make a new entry in the GVNToConstant.
316   std::tie(GVNToConstantIt, Inserted) =
317       GVNToConstant.insert(std::make_pair(GVN, CST));
318   // If it was found and is not equal, it is not the same. We do not
319   // handle this case yet, and exit early.
320   if (Inserted || (GVNToConstantIt->second == CST))
321     return true;
322 
323   return false;
324 }
325 
326 InstructionCost OutlinableRegion::getBenefit(TargetTransformInfo &TTI) {
327   InstructionCost Benefit = 0;
328 
329   // Estimate the benefit of outlining a specific sections of the program.  We
330   // delegate mostly this task to the TargetTransformInfo so that if the target
331   // has specific changes, we can have a more accurate estimate.
332 
333   // However, getInstructionCost delegates the code size calculation for
334   // arithmetic instructions to getArithmeticInstrCost in
335   // include/Analysis/TargetTransformImpl.h, where it always estimates that the
336   // code size for a division and remainder instruction to be equal to 4, and
337   // everything else to 1.  This is not an accurate representation of the
338   // division instruction for targets that have a native division instruction.
339   // To be overly conservative, we only add 1 to the number of instructions for
340   // each division instruction.
341   for (IRInstructionData &ID : *Candidate) {
342     Instruction *I = ID.Inst;
343     switch (I->getOpcode()) {
344     case Instruction::FDiv:
345     case Instruction::FRem:
346     case Instruction::SDiv:
347     case Instruction::SRem:
348     case Instruction::UDiv:
349     case Instruction::URem:
350       Benefit += 1;
351       break;
352     default:
353       Benefit += TTI.getInstructionCost(I, TargetTransformInfo::TCK_CodeSize);
354       break;
355     }
356   }
357 
358   return Benefit;
359 }
360 
361 /// Find whether \p Region matches the global value numbering to Constant
362 /// mapping found so far.
363 ///
364 /// \param Region - The OutlinableRegion we are checking for constants
365 /// \param GVNToConstant - The mapping of global value number to Constants.
366 /// \param NotSame - The set of global value numbers that do not have the same
367 /// constant in each region.
368 /// \returns true if all Constants are the same in every use of a Constant in \p
369 /// Region and false if not
370 static bool
371 collectRegionsConstants(OutlinableRegion &Region,
372                         DenseMap<unsigned, Constant *> &GVNToConstant,
373                         DenseSet<unsigned> &NotSame) {
374   bool ConstantsTheSame = true;
375 
376   IRSimilarityCandidate &C = *Region.Candidate;
377   for (IRInstructionData &ID : C) {
378 
379     // Iterate over the operands in an instruction. If the global value number,
380     // assigned by the IRSimilarityCandidate, has been seen before, we check if
381     // the the number has been found to be not the same value in each instance.
382     for (Value *V : ID.OperVals) {
383       Optional<unsigned> GVNOpt = C.getGVN(V);
384       assert(GVNOpt.hasValue() && "Expected a GVN for operand?");
385       unsigned GVN = GVNOpt.getValue();
386 
387       // Check if this global value has been found to not be the same already.
388       if (NotSame.contains(GVN)) {
389         if (isa<Constant>(V))
390           ConstantsTheSame = false;
391         continue;
392       }
393 
394       // If it has been the same so far, we check the value for if the
395       // associated Constant value match the previous instances of the same
396       // global value number.  If the global value does not map to a Constant,
397       // it is considered to not be the same value.
398       Optional<bool> ConstantMatches = constantMatches(V, GVN, GVNToConstant);
399       if (ConstantMatches.hasValue()) {
400         if (ConstantMatches.getValue())
401           continue;
402         else
403           ConstantsTheSame = false;
404       }
405 
406       // While this value is a register, it might not have been previously,
407       // make sure we don't already have a constant mapped to this global value
408       // number.
409       if (GVNToConstant.find(GVN) != GVNToConstant.end())
410         ConstantsTheSame = false;
411 
412       NotSame.insert(GVN);
413     }
414   }
415 
416   return ConstantsTheSame;
417 }
418 
419 void OutlinableGroup::findSameConstants(DenseSet<unsigned> &NotSame) {
420   DenseMap<unsigned, Constant *> GVNToConstant;
421 
422   for (OutlinableRegion *Region : Regions)
423     collectRegionsConstants(*Region, GVNToConstant, NotSame);
424 }
425 
426 void OutlinableGroup::collectGVNStoreSets(Module &M) {
427   for (OutlinableRegion *OS : Regions)
428     OutputGVNCombinations.insert(OS->GVNStores);
429 
430   // We are adding an extracted argument to decide between which output path
431   // to use in the basic block.  It is used in a switch statement and only
432   // needs to be an integer.
433   if (OutputGVNCombinations.size() > 1)
434     ArgumentTypes.push_back(Type::getInt32Ty(M.getContext()));
435 }
436 
437 /// Get the subprogram if it exists for one of the outlined regions.
438 ///
439 /// \param [in] Group - The set of regions to find a subprogram for.
440 /// \returns the subprogram if it exists, or nullptr.
441 static DISubprogram *getSubprogramOrNull(OutlinableGroup &Group) {
442   for (OutlinableRegion *OS : Group.Regions)
443     if (Function *F = OS->Call->getFunction())
444       if (DISubprogram *SP = F->getSubprogram())
445         return SP;
446 
447   return nullptr;
448 }
449 
450 Function *IROutliner::createFunction(Module &M, OutlinableGroup &Group,
451                                      unsigned FunctionNameSuffix) {
452   assert(!Group.OutlinedFunction && "Function is already defined!");
453 
454   Type *RetTy = Type::getVoidTy(M.getContext());
455   // All extracted functions _should_ have the same return type at this point
456   // since the similarity identifier ensures that all branches outside of the
457   // region occur in the same place.
458 
459   // NOTE: Should we ever move to the model that uses a switch at every point
460   // needed, meaning that we could branch within the region or out, it is
461   // possible that we will need to switch to using the most general case all of
462   // the time.
463   for (OutlinableRegion *R : Group.Regions) {
464     Type *ExtractedFuncType = R->ExtractedFunction->getReturnType();
465     if ((RetTy->isVoidTy() && !ExtractedFuncType->isVoidTy()) ||
466         (RetTy->isIntegerTy(1) && ExtractedFuncType->isIntegerTy(16)))
467       RetTy = ExtractedFuncType;
468   }
469 
470   Group.OutlinedFunctionType = FunctionType::get(
471       RetTy, Group.ArgumentTypes, false);
472 
473   // These functions will only be called from within the same module, so
474   // we can set an internal linkage.
475   Group.OutlinedFunction = Function::Create(
476       Group.OutlinedFunctionType, GlobalValue::InternalLinkage,
477       "outlined_ir_func_" + std::to_string(FunctionNameSuffix), M);
478 
479   // Transfer the swifterr attribute to the correct function parameter.
480   if (Group.SwiftErrorArgument.hasValue())
481     Group.OutlinedFunction->addParamAttr(Group.SwiftErrorArgument.getValue(),
482                                          Attribute::SwiftError);
483 
484   Group.OutlinedFunction->addFnAttr(Attribute::OptimizeForSize);
485   Group.OutlinedFunction->addFnAttr(Attribute::MinSize);
486 
487   // If there's a DISubprogram associated with this outlined function, then
488   // emit debug info for the outlined function.
489   if (DISubprogram *SP = getSubprogramOrNull(Group)) {
490     Function *F = Group.OutlinedFunction;
491     // We have a DISubprogram. Get its DICompileUnit.
492     DICompileUnit *CU = SP->getUnit();
493     DIBuilder DB(M, true, CU);
494     DIFile *Unit = SP->getFile();
495     Mangler Mg;
496     // Get the mangled name of the function for the linkage name.
497     std::string Dummy;
498     llvm::raw_string_ostream MangledNameStream(Dummy);
499     Mg.getNameWithPrefix(MangledNameStream, F, false);
500 
501     DISubprogram *OutlinedSP = DB.createFunction(
502         Unit /* Context */, F->getName(), MangledNameStream.str(),
503         Unit /* File */,
504         0 /* Line 0 is reserved for compiler-generated code. */,
505         DB.createSubroutineType(DB.getOrCreateTypeArray(None)), /* void type */
506         0, /* Line 0 is reserved for compiler-generated code. */
507         DINode::DIFlags::FlagArtificial /* Compiler-generated code. */,
508         /* Outlined code is optimized code by definition. */
509         DISubprogram::SPFlagDefinition | DISubprogram::SPFlagOptimized);
510 
511     // Don't add any new variables to the subprogram.
512     DB.finalizeSubprogram(OutlinedSP);
513 
514     // Attach subprogram to the function.
515     F->setSubprogram(OutlinedSP);
516     // We're done with the DIBuilder.
517     DB.finalize();
518   }
519 
520   return Group.OutlinedFunction;
521 }
522 
523 /// Move each BasicBlock in \p Old to \p New.
524 ///
525 /// \param [in] Old - The function to move the basic blocks from.
526 /// \param [in] New - The function to move the basic blocks to.
527 /// \param [out] NewEnds - The return blocks of the new overall function.
528 /// \returns the first return block for the function in New.
529 static void moveFunctionData(Function &Old, Function &New,
530                              DenseMap<Value *, BasicBlock *> &NewEnds) {
531   Function::iterator CurrBB, NextBB, FinalBB;
532   for (CurrBB = Old.begin(), FinalBB = Old.end(); CurrBB != FinalBB;
533        CurrBB = NextBB) {
534     NextBB = std::next(CurrBB);
535     CurrBB->removeFromParent();
536     CurrBB->insertInto(&New);
537     Instruction *I = CurrBB->getTerminator();
538 
539     // For each block we find a return instruction is, it is a potential exit
540     // path for the function.  We keep track of each block based on the return
541     // value here.
542     if (ReturnInst *RI = dyn_cast<ReturnInst>(I))
543       NewEnds.insert(std::make_pair(RI->getReturnValue(), &(*CurrBB)));
544 
545     std::vector<Instruction *> DebugInsts;
546 
547     for (Instruction &Val : *CurrBB) {
548       // We must handle the scoping of called functions differently than
549       // other outlined instructions.
550       if (!isa<CallInst>(&Val)) {
551         // Remove the debug information for outlined functions.
552         Val.setDebugLoc(DebugLoc());
553         continue;
554       }
555 
556       // From this point we are only handling call instructions.
557       CallInst *CI = cast<CallInst>(&Val);
558 
559       // We add any debug statements here, to be removed after.  Since the
560       // instructions originate from many different locations in the program,
561       // it will cause incorrect reporting from a debugger if we keep the
562       // same debug instructions.
563       if (isa<DbgInfoIntrinsic>(CI)) {
564         DebugInsts.push_back(&Val);
565         continue;
566       }
567 
568       // Edit the scope of called functions inside of outlined functions.
569       if (DISubprogram *SP = New.getSubprogram()) {
570         DILocation *DI = DILocation::get(New.getContext(), 0, 0, SP);
571         Val.setDebugLoc(DI);
572       }
573     }
574 
575     for (Instruction *I : DebugInsts)
576       I->eraseFromParent();
577   }
578 
579   assert(NewEnds.size() > 0 && "No return instruction for new function?");
580 }
581 
582 /// Find the the constants that will need to be lifted into arguments
583 /// as they are not the same in each instance of the region.
584 ///
585 /// \param [in] C - The IRSimilarityCandidate containing the region we are
586 /// analyzing.
587 /// \param [in] NotSame - The set of global value numbers that do not have a
588 /// single Constant across all OutlinableRegions similar to \p C.
589 /// \param [out] Inputs - The list containing the global value numbers of the
590 /// arguments needed for the region of code.
591 static void findConstants(IRSimilarityCandidate &C, DenseSet<unsigned> &NotSame,
592                           std::vector<unsigned> &Inputs) {
593   DenseSet<unsigned> Seen;
594   // Iterate over the instructions, and find what constants will need to be
595   // extracted into arguments.
596   for (IRInstructionDataList::iterator IDIt = C.begin(), EndIDIt = C.end();
597        IDIt != EndIDIt; IDIt++) {
598     for (Value *V : (*IDIt).OperVals) {
599       // Since these are stored before any outlining, they will be in the
600       // global value numbering.
601       unsigned GVN = C.getGVN(V).getValue();
602       if (isa<Constant>(V))
603         if (NotSame.contains(GVN) && !Seen.contains(GVN)) {
604           Inputs.push_back(GVN);
605           Seen.insert(GVN);
606         }
607     }
608   }
609 }
610 
611 /// Find the GVN for the inputs that have been found by the CodeExtractor.
612 ///
613 /// \param [in] C - The IRSimilarityCandidate containing the region we are
614 /// analyzing.
615 /// \param [in] CurrentInputs - The set of inputs found by the
616 /// CodeExtractor.
617 /// \param [in] OutputMappings - The mapping of values that have been replaced
618 /// by a new output value.
619 /// \param [out] EndInputNumbers - The global value numbers for the extracted
620 /// arguments.
621 static void mapInputsToGVNs(IRSimilarityCandidate &C,
622                             SetVector<Value *> &CurrentInputs,
623                             const DenseMap<Value *, Value *> &OutputMappings,
624                             std::vector<unsigned> &EndInputNumbers) {
625   // Get the Global Value Number for each input.  We check if the Value has been
626   // replaced by a different value at output, and use the original value before
627   // replacement.
628   for (Value *Input : CurrentInputs) {
629     assert(Input && "Have a nullptr as an input");
630     if (OutputMappings.find(Input) != OutputMappings.end())
631       Input = OutputMappings.find(Input)->second;
632     assert(C.getGVN(Input).hasValue() &&
633            "Could not find a numbering for the given input");
634     EndInputNumbers.push_back(C.getGVN(Input).getValue());
635   }
636 }
637 
638 /// Find the original value for the \p ArgInput values if any one of them was
639 /// replaced during a previous extraction.
640 ///
641 /// \param [in] ArgInputs - The inputs to be extracted by the code extractor.
642 /// \param [in] OutputMappings - The mapping of values that have been replaced
643 /// by a new output value.
644 /// \param [out] RemappedArgInputs - The remapped values according to
645 /// \p OutputMappings that will be extracted.
646 static void
647 remapExtractedInputs(const ArrayRef<Value *> ArgInputs,
648                      const DenseMap<Value *, Value *> &OutputMappings,
649                      SetVector<Value *> &RemappedArgInputs) {
650   // Get the global value number for each input that will be extracted as an
651   // argument by the code extractor, remapping if needed for reloaded values.
652   for (Value *Input : ArgInputs) {
653     if (OutputMappings.find(Input) != OutputMappings.end())
654       Input = OutputMappings.find(Input)->second;
655     RemappedArgInputs.insert(Input);
656   }
657 }
658 
659 /// Find the input GVNs and the output values for a region of Instructions.
660 /// Using the code extractor, we collect the inputs to the extracted function.
661 ///
662 /// The \p Region can be identified as needing to be ignored in this function.
663 /// It should be checked whether it should be ignored after a call to this
664 /// function.
665 ///
666 /// \param [in,out] Region - The region of code to be analyzed.
667 /// \param [out] InputGVNs - The global value numbers for the extracted
668 /// arguments.
669 /// \param [in] NotSame - The global value numbers in the region that do not
670 /// have the same constant value in the regions structurally similar to
671 /// \p Region.
672 /// \param [in] OutputMappings - The mapping of values that have been replaced
673 /// by a new output value after extraction.
674 /// \param [out] ArgInputs - The values of the inputs to the extracted function.
675 /// \param [out] Outputs - The set of values extracted by the CodeExtractor
676 /// as outputs.
677 static void getCodeExtractorArguments(
678     OutlinableRegion &Region, std::vector<unsigned> &InputGVNs,
679     DenseSet<unsigned> &NotSame, DenseMap<Value *, Value *> &OutputMappings,
680     SetVector<Value *> &ArgInputs, SetVector<Value *> &Outputs) {
681   IRSimilarityCandidate &C = *Region.Candidate;
682 
683   // OverallInputs are the inputs to the region found by the CodeExtractor,
684   // SinkCands and HoistCands are used by the CodeExtractor to find sunken
685   // allocas of values whose lifetimes are contained completely within the
686   // outlined region. PremappedInputs are the arguments found by the
687   // CodeExtractor, removing conditions such as sunken allocas, but that
688   // may need to be remapped due to the extracted output values replacing
689   // the original values. We use DummyOutputs for this first run of finding
690   // inputs and outputs since the outputs could change during findAllocas,
691   // the correct set of extracted outputs will be in the final Outputs ValueSet.
692   SetVector<Value *> OverallInputs, PremappedInputs, SinkCands, HoistCands,
693       DummyOutputs;
694 
695   // Use the code extractor to get the inputs and outputs, without sunken
696   // allocas or removing llvm.assumes.
697   CodeExtractor *CE = Region.CE;
698   CE->findInputsOutputs(OverallInputs, DummyOutputs, SinkCands);
699   assert(Region.StartBB && "Region must have a start BasicBlock!");
700   Function *OrigF = Region.StartBB->getParent();
701   CodeExtractorAnalysisCache CEAC(*OrigF);
702   BasicBlock *Dummy = nullptr;
703 
704   // The region may be ineligible due to VarArgs in the parent function. In this
705   // case we ignore the region.
706   if (!CE->isEligible()) {
707     Region.IgnoreRegion = true;
708     return;
709   }
710 
711   // Find if any values are going to be sunk into the function when extracted
712   CE->findAllocas(CEAC, SinkCands, HoistCands, Dummy);
713   CE->findInputsOutputs(PremappedInputs, Outputs, SinkCands);
714 
715   // TODO: Support regions with sunken allocas: values whose lifetimes are
716   // contained completely within the outlined region.  These are not guaranteed
717   // to be the same in every region, so we must elevate them all to arguments
718   // when they appear.  If these values are not equal, it means there is some
719   // Input in OverallInputs that was removed for ArgInputs.
720   if (OverallInputs.size() != PremappedInputs.size()) {
721     Region.IgnoreRegion = true;
722     return;
723   }
724 
725   findConstants(C, NotSame, InputGVNs);
726 
727   mapInputsToGVNs(C, OverallInputs, OutputMappings, InputGVNs);
728 
729   remapExtractedInputs(PremappedInputs.getArrayRef(), OutputMappings,
730                        ArgInputs);
731 
732   // Sort the GVNs, since we now have constants included in the \ref InputGVNs
733   // we need to make sure they are in a deterministic order.
734   stable_sort(InputGVNs);
735 }
736 
737 /// Look over the inputs and map each input argument to an argument in the
738 /// overall function for the OutlinableRegions.  This creates a way to replace
739 /// the arguments of the extracted function with the arguments of the new
740 /// overall function.
741 ///
742 /// \param [in,out] Region - The region of code to be analyzed.
743 /// \param [in] InputGVNs - The global value numbering of the input values
744 /// collected.
745 /// \param [in] ArgInputs - The values of the arguments to the extracted
746 /// function.
747 static void
748 findExtractedInputToOverallInputMapping(OutlinableRegion &Region,
749                                         std::vector<unsigned> &InputGVNs,
750                                         SetVector<Value *> &ArgInputs) {
751 
752   IRSimilarityCandidate &C = *Region.Candidate;
753   OutlinableGroup &Group = *Region.Parent;
754 
755   // This counts the argument number in the overall function.
756   unsigned TypeIndex = 0;
757 
758   // This counts the argument number in the extracted function.
759   unsigned OriginalIndex = 0;
760 
761   // Find the mapping of the extracted arguments to the arguments for the
762   // overall function. Since there may be extra arguments in the overall
763   // function to account for the extracted constants, we have two different
764   // counters as we find extracted arguments, and as we come across overall
765   // arguments.
766 
767   // Additionally, in our first pass, for the first extracted function,
768   // we find argument locations for the canonical value numbering.  This
769   // numbering overrides any discovered location for the extracted code.
770   for (unsigned InputVal : InputGVNs) {
771     Optional<unsigned> CanonicalNumberOpt = C.getCanonicalNum(InputVal);
772     assert(CanonicalNumberOpt.hasValue() && "Canonical number not found?");
773     unsigned CanonicalNumber = CanonicalNumberOpt.getValue();
774 
775     Optional<Value *> InputOpt = C.fromGVN(InputVal);
776     assert(InputOpt.hasValue() && "Global value number not found?");
777     Value *Input = InputOpt.getValue();
778 
779     DenseMap<unsigned, unsigned>::iterator AggArgIt =
780         Group.CanonicalNumberToAggArg.find(CanonicalNumber);
781 
782     if (!Group.InputTypesSet) {
783       Group.ArgumentTypes.push_back(Input->getType());
784       // If the input value has a swifterr attribute, make sure to mark the
785       // argument in the overall function.
786       if (Input->isSwiftError()) {
787         assert(
788             !Group.SwiftErrorArgument.hasValue() &&
789             "Argument already marked with swifterr for this OutlinableGroup!");
790         Group.SwiftErrorArgument = TypeIndex;
791       }
792     }
793 
794     // Check if we have a constant. If we do add it to the overall argument
795     // number to Constant map for the region, and continue to the next input.
796     if (Constant *CST = dyn_cast<Constant>(Input)) {
797       if (AggArgIt != Group.CanonicalNumberToAggArg.end())
798         Region.AggArgToConstant.insert(std::make_pair(AggArgIt->second, CST));
799       else {
800         Group.CanonicalNumberToAggArg.insert(
801             std::make_pair(CanonicalNumber, TypeIndex));
802         Region.AggArgToConstant.insert(std::make_pair(TypeIndex, CST));
803       }
804       TypeIndex++;
805       continue;
806     }
807 
808     // It is not a constant, we create the mapping from extracted argument list
809     // to the overall argument list, using the canonical location, if it exists.
810     assert(ArgInputs.count(Input) && "Input cannot be found!");
811 
812     if (AggArgIt != Group.CanonicalNumberToAggArg.end()) {
813       if (OriginalIndex != AggArgIt->second)
814         Region.ChangedArgOrder = true;
815       Region.ExtractedArgToAgg.insert(
816           std::make_pair(OriginalIndex, AggArgIt->second));
817       Region.AggArgToExtracted.insert(
818           std::make_pair(AggArgIt->second, OriginalIndex));
819     } else {
820       Group.CanonicalNumberToAggArg.insert(
821           std::make_pair(CanonicalNumber, TypeIndex));
822       Region.ExtractedArgToAgg.insert(std::make_pair(OriginalIndex, TypeIndex));
823       Region.AggArgToExtracted.insert(std::make_pair(TypeIndex, OriginalIndex));
824     }
825     OriginalIndex++;
826     TypeIndex++;
827   }
828 
829   // If the function type definitions for the OutlinableGroup holding the region
830   // have not been set, set the length of the inputs here.  We should have the
831   // same inputs for all of the different regions contained in the
832   // OutlinableGroup since they are all structurally similar to one another.
833   if (!Group.InputTypesSet) {
834     Group.NumAggregateInputs = TypeIndex;
835     Group.InputTypesSet = true;
836   }
837 
838   Region.NumExtractedInputs = OriginalIndex;
839 }
840 
841 /// Create a mapping of the output arguments for the \p Region to the output
842 /// arguments of the overall outlined function.
843 ///
844 /// \param [in,out] Region - The region of code to be analyzed.
845 /// \param [in] Outputs - The values found by the code extractor.
846 static void
847 findExtractedOutputToOverallOutputMapping(OutlinableRegion &Region,
848                                           SetVector<Value *> &Outputs) {
849   OutlinableGroup &Group = *Region.Parent;
850   IRSimilarityCandidate &C = *Region.Candidate;
851 
852   SmallVector<BasicBlock *> BE;
853   DenseSet<BasicBlock *> BBSet;
854   C.getBasicBlocks(BBSet, BE);
855 
856   // Find the exits to the region.
857   SmallPtrSet<BasicBlock *, 1> Exits;
858   for (BasicBlock *Block : BE)
859     for (BasicBlock *Succ : successors(Block))
860       if (!BBSet.contains(Succ))
861         Exits.insert(Succ);
862 
863   // After determining which blocks exit to PHINodes, we add these PHINodes to
864   // the set of outputs to be processed.  We also check the incoming values of
865   // the PHINodes for whether they should no longer be considered outputs.
866   for (BasicBlock *ExitBB : Exits) {
867     for (PHINode &PN : ExitBB->phis()) {
868       // Find all incoming values from the outlining region.
869       SmallVector<unsigned, 2> IncomingVals;
870       for (unsigned Idx = 0; Idx < PN.getNumIncomingValues(); ++Idx)
871         if (BBSet.contains(PN.getIncomingBlock(Idx)))
872           IncomingVals.push_back(Idx);
873 
874       // Do not process PHI if there is one (or fewer) predecessor from region.
875       if (IncomingVals.size() <= 1)
876         continue;
877 
878       Region.IgnoreRegion = true;
879       return;
880     }
881   }
882 
883   // This counts the argument number in the extracted function.
884   unsigned OriginalIndex = Region.NumExtractedInputs;
885 
886   // This counts the argument number in the overall function.
887   unsigned TypeIndex = Group.NumAggregateInputs;
888   bool TypeFound;
889   DenseSet<unsigned> AggArgsUsed;
890 
891   // Iterate over the output types and identify if there is an aggregate pointer
892   // type whose base type matches the current output type. If there is, we mark
893   // that we will use this output register for this value. If not we add another
894   // type to the overall argument type list. We also store the GVNs used for
895   // stores to identify which values will need to be moved into an special
896   // block that holds the stores to the output registers.
897   for (Value *Output : Outputs) {
898     TypeFound = false;
899     // We can do this since it is a result value, and will have a number
900     // that is necessarily the same. BUT if in the future, the instructions
901     // do not have to be in same order, but are functionally the same, we will
902     // have to use a different scheme, as one-to-one correspondence is not
903     // guaranteed.
904     unsigned GlobalValue = C.getGVN(Output).getValue();
905     unsigned ArgumentSize = Group.ArgumentTypes.size();
906 
907     for (unsigned Jdx = TypeIndex; Jdx < ArgumentSize; Jdx++) {
908       if (Group.ArgumentTypes[Jdx] != PointerType::getUnqual(Output->getType()))
909         continue;
910 
911       if (AggArgsUsed.contains(Jdx))
912         continue;
913 
914       TypeFound = true;
915       AggArgsUsed.insert(Jdx);
916       Region.ExtractedArgToAgg.insert(std::make_pair(OriginalIndex, Jdx));
917       Region.AggArgToExtracted.insert(std::make_pair(Jdx, OriginalIndex));
918       Region.GVNStores.push_back(GlobalValue);
919       break;
920     }
921 
922     // We were unable to find an unused type in the output type set that matches
923     // the output, so we add a pointer type to the argument types of the overall
924     // function to handle this output and create a mapping to it.
925     if (!TypeFound) {
926       Group.ArgumentTypes.push_back(PointerType::getUnqual(Output->getType()));
927       AggArgsUsed.insert(Group.ArgumentTypes.size() - 1);
928       Region.ExtractedArgToAgg.insert(
929           std::make_pair(OriginalIndex, Group.ArgumentTypes.size() - 1));
930       Region.AggArgToExtracted.insert(
931           std::make_pair(Group.ArgumentTypes.size() - 1, OriginalIndex));
932       Region.GVNStores.push_back(GlobalValue);
933     }
934 
935     stable_sort(Region.GVNStores);
936     OriginalIndex++;
937     TypeIndex++;
938   }
939 }
940 
941 void IROutliner::findAddInputsOutputs(Module &M, OutlinableRegion &Region,
942                                       DenseSet<unsigned> &NotSame) {
943   std::vector<unsigned> Inputs;
944   SetVector<Value *> ArgInputs, Outputs;
945 
946   getCodeExtractorArguments(Region, Inputs, NotSame, OutputMappings, ArgInputs,
947                             Outputs);
948 
949   if (Region.IgnoreRegion)
950     return;
951 
952   // Map the inputs found by the CodeExtractor to the arguments found for
953   // the overall function.
954   findExtractedInputToOverallInputMapping(Region, Inputs, ArgInputs);
955 
956   // Map the outputs found by the CodeExtractor to the arguments found for
957   // the overall function.
958   findExtractedOutputToOverallOutputMapping(Region, Outputs);
959 }
960 
961 /// Replace the extracted function in the Region with a call to the overall
962 /// function constructed from the deduplicated similar regions, replacing and
963 /// remapping the values passed to the extracted function as arguments to the
964 /// new arguments of the overall function.
965 ///
966 /// \param [in] M - The module to outline from.
967 /// \param [in] Region - The regions of extracted code to be replaced with a new
968 /// function.
969 /// \returns a call instruction with the replaced function.
970 CallInst *replaceCalledFunction(Module &M, OutlinableRegion &Region) {
971   std::vector<Value *> NewCallArgs;
972   DenseMap<unsigned, unsigned>::iterator ArgPair;
973 
974   OutlinableGroup &Group = *Region.Parent;
975   CallInst *Call = Region.Call;
976   assert(Call && "Call to replace is nullptr?");
977   Function *AggFunc = Group.OutlinedFunction;
978   assert(AggFunc && "Function to replace with is nullptr?");
979 
980   // If the arguments are the same size, there are not values that need to be
981   // made into an argument, the argument ordering has not been change, or
982   // different output registers to handle.  We can simply replace the called
983   // function in this case.
984   if (!Region.ChangedArgOrder && AggFunc->arg_size() == Call->arg_size()) {
985     LLVM_DEBUG(dbgs() << "Replace call to " << *Call << " with call to "
986                       << *AggFunc << " with same number of arguments\n");
987     Call->setCalledFunction(AggFunc);
988     return Call;
989   }
990 
991   // We have a different number of arguments than the new function, so
992   // we need to use our previously mappings off extracted argument to overall
993   // function argument, and constants to overall function argument to create the
994   // new argument list.
995   for (unsigned AggArgIdx = 0; AggArgIdx < AggFunc->arg_size(); AggArgIdx++) {
996 
997     if (AggArgIdx == AggFunc->arg_size() - 1 &&
998         Group.OutputGVNCombinations.size() > 1) {
999       // If we are on the last argument, and we need to differentiate between
1000       // output blocks, add an integer to the argument list to determine
1001       // what block to take
1002       LLVM_DEBUG(dbgs() << "Set switch block argument to "
1003                         << Region.OutputBlockNum << "\n");
1004       NewCallArgs.push_back(ConstantInt::get(Type::getInt32Ty(M.getContext()),
1005                                              Region.OutputBlockNum));
1006       continue;
1007     }
1008 
1009     ArgPair = Region.AggArgToExtracted.find(AggArgIdx);
1010     if (ArgPair != Region.AggArgToExtracted.end()) {
1011       Value *ArgumentValue = Call->getArgOperand(ArgPair->second);
1012       // If we found the mapping from the extracted function to the overall
1013       // function, we simply add it to the argument list.  We use the same
1014       // value, it just needs to honor the new order of arguments.
1015       LLVM_DEBUG(dbgs() << "Setting argument " << AggArgIdx << " to value "
1016                         << *ArgumentValue << "\n");
1017       NewCallArgs.push_back(ArgumentValue);
1018       continue;
1019     }
1020 
1021     // If it is a constant, we simply add it to the argument list as a value.
1022     if (Region.AggArgToConstant.find(AggArgIdx) !=
1023         Region.AggArgToConstant.end()) {
1024       Constant *CST = Region.AggArgToConstant.find(AggArgIdx)->second;
1025       LLVM_DEBUG(dbgs() << "Setting argument " << AggArgIdx << " to value "
1026                         << *CST << "\n");
1027       NewCallArgs.push_back(CST);
1028       continue;
1029     }
1030 
1031     // Add a nullptr value if the argument is not found in the extracted
1032     // function.  If we cannot find a value, it means it is not in use
1033     // for the region, so we should not pass anything to it.
1034     LLVM_DEBUG(dbgs() << "Setting argument " << AggArgIdx << " to nullptr\n");
1035     NewCallArgs.push_back(ConstantPointerNull::get(
1036         static_cast<PointerType *>(AggFunc->getArg(AggArgIdx)->getType())));
1037   }
1038 
1039   LLVM_DEBUG(dbgs() << "Replace call to " << *Call << " with call to "
1040                     << *AggFunc << " with new set of arguments\n");
1041   // Create the new call instruction and erase the old one.
1042   Call = CallInst::Create(AggFunc->getFunctionType(), AggFunc, NewCallArgs, "",
1043                           Call);
1044 
1045   // It is possible that the call to the outlined function is either the first
1046   // instruction is in the new block, the last instruction, or both.  If either
1047   // of these is the case, we need to make sure that we replace the instruction
1048   // in the IRInstructionData struct with the new call.
1049   CallInst *OldCall = Region.Call;
1050   if (Region.NewFront->Inst == OldCall)
1051     Region.NewFront->Inst = Call;
1052   if (Region.NewBack->Inst == OldCall)
1053     Region.NewBack->Inst = Call;
1054 
1055   // Transfer any debug information.
1056   Call->setDebugLoc(Region.Call->getDebugLoc());
1057   // Since our output may determine which branch we go to, we make sure to
1058   // propogate this new call value through the module.
1059   OldCall->replaceAllUsesWith(Call);
1060 
1061   // Remove the old instruction.
1062   OldCall->eraseFromParent();
1063   Region.Call = Call;
1064 
1065   // Make sure that the argument in the new function has the SwiftError
1066   // argument.
1067   if (Group.SwiftErrorArgument.hasValue())
1068     Call->addParamAttr(Group.SwiftErrorArgument.getValue(),
1069                        Attribute::SwiftError);
1070 
1071   return Call;
1072 }
1073 
1074 // Within an extracted function, replace the argument uses of the extracted
1075 // region with the arguments of the function for an OutlinableGroup.
1076 //
1077 /// \param [in] Region - The region of extracted code to be changed.
1078 /// \param [in,out] OutputBB - The BasicBlock for the output stores for this
1079 /// region.
1080 /// \param [in] FirstFunction - A flag to indicate whether we are using this
1081 /// function to define the overall outlined function for all the regions, or
1082 /// if we are operating on one of the following regions.
1083 static void
1084 replaceArgumentUses(OutlinableRegion &Region,
1085                     DenseMap<Value *, BasicBlock *> &OutputBBs,
1086                     bool FirstFunction = false) {
1087   OutlinableGroup &Group = *Region.Parent;
1088   assert(Region.ExtractedFunction && "Region has no extracted function?");
1089 
1090   Function *DominatingFunction = Region.ExtractedFunction;
1091   if (FirstFunction)
1092     DominatingFunction = Group.OutlinedFunction;
1093   DominatorTree DT(*DominatingFunction);
1094 
1095   for (unsigned ArgIdx = 0; ArgIdx < Region.ExtractedFunction->arg_size();
1096        ArgIdx++) {
1097     assert(Region.ExtractedArgToAgg.find(ArgIdx) !=
1098                Region.ExtractedArgToAgg.end() &&
1099            "No mapping from extracted to outlined?");
1100     unsigned AggArgIdx = Region.ExtractedArgToAgg.find(ArgIdx)->second;
1101     Argument *AggArg = Group.OutlinedFunction->getArg(AggArgIdx);
1102     Argument *Arg = Region.ExtractedFunction->getArg(ArgIdx);
1103     // The argument is an input, so we can simply replace it with the overall
1104     // argument value
1105     if (ArgIdx < Region.NumExtractedInputs) {
1106       LLVM_DEBUG(dbgs() << "Replacing uses of input " << *Arg << " in function "
1107                         << *Region.ExtractedFunction << " with " << *AggArg
1108                         << " in function " << *Group.OutlinedFunction << "\n");
1109       Arg->replaceAllUsesWith(AggArg);
1110       continue;
1111     }
1112 
1113     // If we are replacing an output, we place the store value in its own
1114     // block inside the overall function before replacing the use of the output
1115     // in the function.
1116     assert(Arg->hasOneUse() && "Output argument can only have one use");
1117     User *InstAsUser = Arg->user_back();
1118     assert(InstAsUser && "User is nullptr!");
1119 
1120     Instruction *I = cast<Instruction>(InstAsUser);
1121     BasicBlock *BB = I->getParent();
1122     SmallVector<BasicBlock *, 4> Descendants;
1123     DT.getDescendants(BB, Descendants);
1124     bool EdgeAdded = false;
1125     if (Descendants.size() == 0) {
1126       EdgeAdded = true;
1127       DT.insertEdge(&DominatingFunction->getEntryBlock(), BB);
1128       DT.getDescendants(BB, Descendants);
1129     }
1130 
1131     // Iterate over the following blocks, looking for return instructions,
1132     // if we find one, find the corresponding output block for the return value
1133     // and move our store instruction there.
1134     for (BasicBlock *DescendBB : Descendants) {
1135       ReturnInst *RI = dyn_cast<ReturnInst>(DescendBB->getTerminator());
1136       if (!RI)
1137         continue;
1138       Value *RetVal = RI->getReturnValue();
1139       auto VBBIt = OutputBBs.find(RetVal);
1140       assert(VBBIt != OutputBBs.end() && "Could not find output value!");
1141 
1142       // If this is storing a PHINode, we must make sure it is included in the
1143       // overall function.
1144       StoreInst *SI = cast<StoreInst>(I);
1145 
1146       Value *ValueOperand = SI->getValueOperand();
1147 
1148       StoreInst *NewI = cast<StoreInst>(I->clone());
1149       NewI->setDebugLoc(DebugLoc());
1150       BasicBlock *OutputBB = VBBIt->second;
1151       OutputBB->getInstList().push_back(NewI);
1152       LLVM_DEBUG(dbgs() << "Move store for instruction " << *I << " to "
1153                         << *OutputBB << "\n");
1154 
1155       if (FirstFunction)
1156         continue;
1157       Value *CorrVal =
1158           Region.findCorrespondingValueIn(*Group.Regions[0], ValueOperand);
1159       assert(CorrVal && "Value is nullptr?");
1160       NewI->setOperand(0, CorrVal);
1161     }
1162 
1163     // If we added an edge for basic blocks without a predecessor, we remove it
1164     // here.
1165     if (EdgeAdded)
1166       DT.deleteEdge(&DominatingFunction->getEntryBlock(), BB);
1167     I->eraseFromParent();
1168 
1169     LLVM_DEBUG(dbgs() << "Replacing uses of output " << *Arg << " in function "
1170                       << *Region.ExtractedFunction << " with " << *AggArg
1171                       << " in function " << *Group.OutlinedFunction << "\n");
1172     Arg->replaceAllUsesWith(AggArg);
1173   }
1174 }
1175 
1176 /// Within an extracted function, replace the constants that need to be lifted
1177 /// into arguments with the actual argument.
1178 ///
1179 /// \param Region [in] - The region of extracted code to be changed.
1180 void replaceConstants(OutlinableRegion &Region) {
1181   OutlinableGroup &Group = *Region.Parent;
1182   // Iterate over the constants that need to be elevated into arguments
1183   for (std::pair<unsigned, Constant *> &Const : Region.AggArgToConstant) {
1184     unsigned AggArgIdx = Const.first;
1185     Function *OutlinedFunction = Group.OutlinedFunction;
1186     assert(OutlinedFunction && "Overall Function is not defined?");
1187     Constant *CST = Const.second;
1188     Argument *Arg = Group.OutlinedFunction->getArg(AggArgIdx);
1189     // Identify the argument it will be elevated to, and replace instances of
1190     // that constant in the function.
1191 
1192     // TODO: If in the future constants do not have one global value number,
1193     // i.e. a constant 1 could be mapped to several values, this check will
1194     // have to be more strict.  It cannot be using only replaceUsesWithIf.
1195 
1196     LLVM_DEBUG(dbgs() << "Replacing uses of constant " << *CST
1197                       << " in function " << *OutlinedFunction << " with "
1198                       << *Arg << "\n");
1199     CST->replaceUsesWithIf(Arg, [OutlinedFunction](Use &U) {
1200       if (Instruction *I = dyn_cast<Instruction>(U.getUser()))
1201         return I->getFunction() == OutlinedFunction;
1202       return false;
1203     });
1204   }
1205 }
1206 
1207 /// It is possible that there is a basic block that already performs the same
1208 /// stores. This returns a duplicate block, if it exists
1209 ///
1210 /// \param OutputBB [in] the block we are looking for a duplicate of.
1211 /// \param OutputStoreBBs [in] The existing output blocks.
1212 /// \returns an optional value with the number output block if there is a match.
1213 Optional<unsigned> findDuplicateOutputBlock(
1214     DenseMap<Value *, BasicBlock *> &OutputBBs,
1215     std::vector<DenseMap<Value *, BasicBlock *>> &OutputStoreBBs) {
1216 
1217   bool Mismatch = false;
1218   unsigned MatchingNum = 0;
1219   // We compare the new set output blocks to the other sets of output blocks.
1220   // If they are the same number, and have identical instructions, they are
1221   // considered to be the same.
1222   for (DenseMap<Value *, BasicBlock *> &CompBBs : OutputStoreBBs) {
1223     Mismatch = false;
1224     for (std::pair<Value *, BasicBlock *> &VToB : CompBBs) {
1225       DenseMap<Value *, BasicBlock *>::iterator OutputBBIt =
1226           OutputBBs.find(VToB.first);
1227       if (OutputBBIt == OutputBBs.end()) {
1228         Mismatch = true;
1229         break;
1230       }
1231 
1232       BasicBlock *CompBB = VToB.second;
1233       BasicBlock *OutputBB = OutputBBIt->second;
1234       if (CompBB->size() - 1 != OutputBB->size()) {
1235         Mismatch = true;
1236         break;
1237       }
1238 
1239       BasicBlock::iterator NIt = OutputBB->begin();
1240       for (Instruction &I : *CompBB) {
1241         if (isa<BranchInst>(&I))
1242           continue;
1243 
1244         if (!I.isIdenticalTo(&(*NIt))) {
1245           Mismatch = true;
1246           break;
1247         }
1248 
1249         NIt++;
1250       }
1251     }
1252 
1253     if (!Mismatch)
1254       return MatchingNum;
1255 
1256     MatchingNum++;
1257   }
1258 
1259   return None;
1260 }
1261 
1262 /// Remove empty output blocks from the outlined region.
1263 ///
1264 /// \param BlocksToPrune - Mapping of return values output blocks for the \p
1265 /// Region.
1266 /// \param Region - The OutlinableRegion we are analyzing.
1267 static bool
1268 analyzeAndPruneOutputBlocks(DenseMap<Value *, BasicBlock *> &BlocksToPrune,
1269                             OutlinableRegion &Region) {
1270   bool AllRemoved = true;
1271   Value *RetValueForBB;
1272   BasicBlock *NewBB;
1273   SmallVector<Value *, 4> ToRemove;
1274   // Iterate over the output blocks created in the outlined section.
1275   for (std::pair<Value *, BasicBlock *> &VtoBB : BlocksToPrune) {
1276     RetValueForBB = VtoBB.first;
1277     NewBB = VtoBB.second;
1278 
1279     // If there are no instructions, we remove it from the module, and also
1280     // mark the value for removal from the return value to output block mapping.
1281     if (NewBB->size() == 0) {
1282       NewBB->eraseFromParent();
1283       ToRemove.push_back(RetValueForBB);
1284       continue;
1285     }
1286 
1287     // Mark that we could not remove all the blocks since they were not all
1288     // empty.
1289     AllRemoved = false;
1290   }
1291 
1292   // Remove the return value from the mapping.
1293   for (Value *V : ToRemove)
1294     BlocksToPrune.erase(V);
1295 
1296   // Mark the region as having the no output scheme.
1297   if (AllRemoved)
1298     Region.OutputBlockNum = -1;
1299 
1300   return AllRemoved;
1301 }
1302 
1303 /// For the outlined section, move needed the StoreInsts for the output
1304 /// registers into their own block. Then, determine if there is a duplicate
1305 /// output block already created.
1306 ///
1307 /// \param [in] OG - The OutlinableGroup of regions to be outlined.
1308 /// \param [in] Region - The OutlinableRegion that is being analyzed.
1309 /// \param [in,out] OutputBB - the block that stores for this region will be
1310 /// placed in.
1311 /// \param [in] EndBB - the final block of the extracted function.
1312 /// \param [in] OutputMappings - OutputMappings the mapping of values that have
1313 /// been replaced by a new output value.
1314 /// \param [in,out] OutputStoreBBs - The existing output blocks.
1315 static void alignOutputBlockWithAggFunc(
1316     OutlinableGroup &OG, OutlinableRegion &Region,
1317     DenseMap<Value *, BasicBlock *> &OutputBBs,
1318     DenseMap<Value *, BasicBlock *> &EndBBs,
1319     const DenseMap<Value *, Value *> &OutputMappings,
1320     std::vector<DenseMap<Value *, BasicBlock *>> &OutputStoreBBs) {
1321   // If none of the output blocks have any instructions, this means that we do
1322   // not have to determine if it matches any of the other output schemes, and we
1323   // don't have to do anything else.
1324   if (analyzeAndPruneOutputBlocks(OutputBBs, Region))
1325     return;
1326 
1327   // Determine is there is a duplicate set of blocks.
1328   Optional<unsigned> MatchingBB =
1329       findDuplicateOutputBlock(OutputBBs, OutputStoreBBs);
1330 
1331   // If there is, we remove the new output blocks.  If it does not,
1332   // we add it to our list of sets of output blocks.
1333   if (MatchingBB.hasValue()) {
1334     LLVM_DEBUG(dbgs() << "Set output block for region in function"
1335                       << Region.ExtractedFunction << " to "
1336                       << MatchingBB.getValue());
1337 
1338     Region.OutputBlockNum = MatchingBB.getValue();
1339     for (std::pair<Value *, BasicBlock *> &VtoBB : OutputBBs)
1340       VtoBB.second->eraseFromParent();
1341     return;
1342   }
1343 
1344   Region.OutputBlockNum = OutputStoreBBs.size();
1345 
1346   Value *RetValueForBB;
1347   BasicBlock *NewBB;
1348   OutputStoreBBs.push_back(DenseMap<Value *, BasicBlock *>());
1349   for (std::pair<Value *, BasicBlock *> &VtoBB : OutputBBs) {
1350     RetValueForBB = VtoBB.first;
1351     NewBB = VtoBB.second;
1352     DenseMap<Value *, BasicBlock *>::iterator VBBIt =
1353         EndBBs.find(RetValueForBB);
1354     LLVM_DEBUG(dbgs() << "Create output block for region in"
1355                       << Region.ExtractedFunction << " to "
1356                       << *NewBB);
1357     BranchInst::Create(VBBIt->second, NewBB);
1358     OutputStoreBBs.back().insert(std::make_pair(RetValueForBB, NewBB));
1359   }
1360 }
1361 
1362 /// Takes in a mapping, \p OldMap of ConstantValues to BasicBlocks, sorts keys,
1363 /// before creating a basic block for each \p NewMap, and inserting into the new
1364 /// block. Each BasicBlock is named with the scheme "<basename>_<key_idx>".
1365 ///
1366 /// \param OldMap [in] - The mapping to base the new mapping off of.
1367 /// \param NewMap [out] - The output mapping using the keys of \p OldMap.
1368 /// \param ParentFunc [in] - The function to put the new basic block in.
1369 /// \param BaseName [in] - The start of the BasicBlock names to be appended to
1370 /// by an index value.
1371 static void createAndInsertBasicBlocks(DenseMap<Value *, BasicBlock *> &OldMap,
1372                                        DenseMap<Value *, BasicBlock *> &NewMap,
1373                                        Function *ParentFunc, Twine BaseName) {
1374   unsigned Idx = 0;
1375   std::vector<Value *> SortedKeys;
1376 
1377   getSortedConstantKeys(SortedKeys, OldMap);
1378 
1379   for (Value *RetVal : SortedKeys) {
1380     BasicBlock *NewBB = BasicBlock::Create(
1381         ParentFunc->getContext(),
1382         Twine(BaseName) + Twine("_") + Twine(static_cast<unsigned>(Idx++)),
1383         ParentFunc);
1384     NewMap.insert(std::make_pair(RetVal, NewBB));
1385   }
1386 }
1387 
1388 /// Create the switch statement for outlined function to differentiate between
1389 /// all the output blocks.
1390 ///
1391 /// For the outlined section, determine if an outlined block already exists that
1392 /// matches the needed stores for the extracted section.
1393 /// \param [in] M - The module we are outlining from.
1394 /// \param [in] OG - The group of regions to be outlined.
1395 /// \param [in] EndBB - The final block of the extracted function.
1396 /// \param [in,out] OutputStoreBBs - The existing output blocks.
1397 void createSwitchStatement(
1398     Module &M, OutlinableGroup &OG, DenseMap<Value *, BasicBlock *> &EndBBs,
1399     std::vector<DenseMap<Value *, BasicBlock *>> &OutputStoreBBs) {
1400   // We only need the switch statement if there is more than one store
1401   // combination.
1402   if (OG.OutputGVNCombinations.size() > 1) {
1403     Function *AggFunc = OG.OutlinedFunction;
1404     // Create a final block for each different return block.
1405     DenseMap<Value *, BasicBlock *> ReturnBBs;
1406     createAndInsertBasicBlocks(OG.EndBBs, ReturnBBs, AggFunc, "final_block");
1407 
1408     for (std::pair<Value *, BasicBlock *> &RetBlockPair : ReturnBBs) {
1409       std::pair<Value *, BasicBlock *> &OutputBlock =
1410           *OG.EndBBs.find(RetBlockPair.first);
1411       BasicBlock *ReturnBlock = RetBlockPair.second;
1412       BasicBlock *EndBB = OutputBlock.second;
1413       Instruction *Term = EndBB->getTerminator();
1414       // Move the return value to the final block instead of the original exit
1415       // stub.
1416       Term->moveBefore(*ReturnBlock, ReturnBlock->end());
1417       // Put the switch statement in the old end basic block for the function
1418       // with a fall through to the new return block.
1419       LLVM_DEBUG(dbgs() << "Create switch statement in " << *AggFunc << " for "
1420                         << OutputStoreBBs.size() << "\n");
1421       SwitchInst *SwitchI =
1422           SwitchInst::Create(AggFunc->getArg(AggFunc->arg_size() - 1),
1423                              ReturnBlock, OutputStoreBBs.size(), EndBB);
1424 
1425       unsigned Idx = 0;
1426       for (DenseMap<Value *, BasicBlock *> &OutputStoreBB : OutputStoreBBs) {
1427         DenseMap<Value *, BasicBlock *>::iterator OSBBIt =
1428             OutputStoreBB.find(OutputBlock.first);
1429 
1430         if (OSBBIt == OutputStoreBB.end())
1431           continue;
1432 
1433         BasicBlock *BB = OSBBIt->second;
1434         SwitchI->addCase(
1435             ConstantInt::get(Type::getInt32Ty(M.getContext()), Idx), BB);
1436         Term = BB->getTerminator();
1437         Term->setSuccessor(0, ReturnBlock);
1438         Idx++;
1439       }
1440     }
1441     return;
1442   }
1443 
1444   // If there needs to be stores, move them from the output blocks to their
1445   // corresponding ending block.
1446   if (OutputStoreBBs.size() == 1) {
1447     LLVM_DEBUG(dbgs() << "Move store instructions to the end block in "
1448                       << *OG.OutlinedFunction << "\n");
1449     DenseMap<Value *, BasicBlock *> OutputBlocks = OutputStoreBBs[0];
1450     for (std::pair<Value *, BasicBlock *> &VBPair : OutputBlocks) {
1451       DenseMap<Value *, BasicBlock *>::iterator EndBBIt =
1452           EndBBs.find(VBPair.first);
1453       assert(EndBBIt != EndBBs.end() && "Could not find end block");
1454       BasicBlock *EndBB = EndBBIt->second;
1455       BasicBlock *OutputBB = VBPair.second;
1456       Instruction *Term = OutputBB->getTerminator();
1457       Term->eraseFromParent();
1458       Term = EndBB->getTerminator();
1459       moveBBContents(*OutputBB, *EndBB);
1460       Term->moveBefore(*EndBB, EndBB->end());
1461       OutputBB->eraseFromParent();
1462     }
1463   }
1464 }
1465 
1466 /// Fill the new function that will serve as the replacement function for all of
1467 /// the extracted regions of a certain structure from the first region in the
1468 /// list of regions.  Replace this first region's extracted function with the
1469 /// new overall function.
1470 ///
1471 /// \param [in] M - The module we are outlining from.
1472 /// \param [in] CurrentGroup - The group of regions to be outlined.
1473 /// \param [in,out] OutputStoreBBs - The output blocks for each different
1474 /// set of stores needed for the different functions.
1475 /// \param [in,out] FuncsToRemove - Extracted functions to erase from module
1476 /// once outlining is complete.
1477 static void fillOverallFunction(
1478     Module &M, OutlinableGroup &CurrentGroup,
1479     std::vector<DenseMap<Value *, BasicBlock *>> &OutputStoreBBs,
1480     std::vector<Function *> &FuncsToRemove) {
1481   OutlinableRegion *CurrentOS = CurrentGroup.Regions[0];
1482 
1483   // Move first extracted function's instructions into new function.
1484   LLVM_DEBUG(dbgs() << "Move instructions from "
1485                     << *CurrentOS->ExtractedFunction << " to instruction "
1486                     << *CurrentGroup.OutlinedFunction << "\n");
1487   moveFunctionData(*CurrentOS->ExtractedFunction,
1488                    *CurrentGroup.OutlinedFunction, CurrentGroup.EndBBs);
1489 
1490   // Transfer the attributes from the function to the new function.
1491   for (Attribute A : CurrentOS->ExtractedFunction->getAttributes().getFnAttrs())
1492     CurrentGroup.OutlinedFunction->addFnAttr(A);
1493 
1494   // Create a new set of output blocks for the first extracted function.
1495   DenseMap<Value *, BasicBlock *> NewBBs;
1496   createAndInsertBasicBlocks(CurrentGroup.EndBBs, NewBBs,
1497                              CurrentGroup.OutlinedFunction, "output_block_0");
1498   CurrentOS->OutputBlockNum = 0;
1499 
1500   replaceArgumentUses(*CurrentOS, NewBBs, true);
1501   replaceConstants(*CurrentOS);
1502 
1503   // We first identify if any output blocks are empty, if they are we remove
1504   // them. We then create a branch instruction to the basic block to the return
1505   // block for the function for each non empty output block.
1506   if (!analyzeAndPruneOutputBlocks(NewBBs, *CurrentOS)) {
1507     OutputStoreBBs.push_back(DenseMap<Value *, BasicBlock *>());
1508     for (std::pair<Value *, BasicBlock *> &VToBB : NewBBs) {
1509       DenseMap<Value *, BasicBlock *>::iterator VBBIt =
1510           CurrentGroup.EndBBs.find(VToBB.first);
1511       BasicBlock *EndBB = VBBIt->second;
1512       BranchInst::Create(EndBB, VToBB.second);
1513       OutputStoreBBs.back().insert(VToBB);
1514     }
1515   }
1516 
1517   // Replace the call to the extracted function with the outlined function.
1518   CurrentOS->Call = replaceCalledFunction(M, *CurrentOS);
1519 
1520   // We only delete the extracted functions at the end since we may need to
1521   // reference instructions contained in them for mapping purposes.
1522   FuncsToRemove.push_back(CurrentOS->ExtractedFunction);
1523 }
1524 
1525 void IROutliner::deduplicateExtractedSections(
1526     Module &M, OutlinableGroup &CurrentGroup,
1527     std::vector<Function *> &FuncsToRemove, unsigned &OutlinedFunctionNum) {
1528   createFunction(M, CurrentGroup, OutlinedFunctionNum);
1529 
1530   std::vector<DenseMap<Value *, BasicBlock *>> OutputStoreBBs;
1531 
1532   OutlinableRegion *CurrentOS;
1533 
1534   fillOverallFunction(M, CurrentGroup, OutputStoreBBs, FuncsToRemove);
1535 
1536   std::vector<Value *> SortedKeys;
1537   for (unsigned Idx = 1; Idx < CurrentGroup.Regions.size(); Idx++) {
1538     CurrentOS = CurrentGroup.Regions[Idx];
1539     AttributeFuncs::mergeAttributesForOutlining(*CurrentGroup.OutlinedFunction,
1540                                                *CurrentOS->ExtractedFunction);
1541 
1542     // Create a set of BasicBlocks, one for each return block, to hold the
1543     // needed store instructions.
1544     DenseMap<Value *, BasicBlock *> NewBBs;
1545     createAndInsertBasicBlocks(
1546         CurrentGroup.EndBBs, NewBBs, CurrentGroup.OutlinedFunction,
1547         "output_block_" + Twine(static_cast<unsigned>(Idx)));
1548 
1549     replaceArgumentUses(*CurrentOS, NewBBs);
1550     alignOutputBlockWithAggFunc(CurrentGroup, *CurrentOS, NewBBs,
1551                                 CurrentGroup.EndBBs, OutputMappings,
1552                                 OutputStoreBBs);
1553 
1554     CurrentOS->Call = replaceCalledFunction(M, *CurrentOS);
1555     FuncsToRemove.push_back(CurrentOS->ExtractedFunction);
1556   }
1557 
1558   // Create a switch statement to handle the different output schemes.
1559   createSwitchStatement(M, CurrentGroup, CurrentGroup.EndBBs, OutputStoreBBs);
1560 
1561   OutlinedFunctionNum++;
1562 }
1563 
1564 /// Checks that the next instruction in the InstructionDataList matches the
1565 /// next instruction in the module.  If they do not, there could be the
1566 /// possibility that extra code has been inserted, and we must ignore it.
1567 ///
1568 /// \param ID - The IRInstructionData to check the next instruction of.
1569 /// \returns true if the InstructionDataList and actual instruction match.
1570 static bool nextIRInstructionDataMatchesNextInst(IRInstructionData &ID) {
1571   // We check if there is a discrepancy between the InstructionDataList
1572   // and the actual next instruction in the module.  If there is, it means
1573   // that an extra instruction was added, likely by the CodeExtractor.
1574 
1575   // Since we do not have any similarity data about this particular
1576   // instruction, we cannot confidently outline it, and must discard this
1577   // candidate.
1578   IRInstructionDataList::iterator NextIDIt = std::next(ID.getIterator());
1579   Instruction *NextIDLInst = NextIDIt->Inst;
1580   Instruction *NextModuleInst = nullptr;
1581   if (!ID.Inst->isTerminator())
1582     NextModuleInst = ID.Inst->getNextNonDebugInstruction();
1583   else if (NextIDLInst != nullptr)
1584     NextModuleInst =
1585         &*NextIDIt->Inst->getParent()->instructionsWithoutDebug().begin();
1586 
1587   if (NextIDLInst && NextIDLInst != NextModuleInst)
1588     return false;
1589 
1590   return true;
1591 }
1592 
1593 bool IROutliner::isCompatibleWithAlreadyOutlinedCode(
1594     const OutlinableRegion &Region) {
1595   IRSimilarityCandidate *IRSC = Region.Candidate;
1596   unsigned StartIdx = IRSC->getStartIdx();
1597   unsigned EndIdx = IRSC->getEndIdx();
1598 
1599   // A check to make sure that we are not about to attempt to outline something
1600   // that has already been outlined.
1601   for (unsigned Idx = StartIdx; Idx <= EndIdx; Idx++)
1602     if (Outlined.contains(Idx))
1603       return false;
1604 
1605   // We check if the recorded instruction matches the actual next instruction,
1606   // if it does not, we fix it in the InstructionDataList.
1607   if (!Region.Candidate->backInstruction()->isTerminator()) {
1608     Instruction *NewEndInst =
1609         Region.Candidate->backInstruction()->getNextNonDebugInstruction();
1610     assert(NewEndInst && "Next instruction is a nullptr?");
1611     if (Region.Candidate->end()->Inst != NewEndInst) {
1612       IRInstructionDataList *IDL = Region.Candidate->front()->IDL;
1613       IRInstructionData *NewEndIRID = new (InstDataAllocator.Allocate())
1614           IRInstructionData(*NewEndInst,
1615                             InstructionClassifier.visit(*NewEndInst), *IDL);
1616 
1617       // Insert the first IRInstructionData of the new region after the
1618       // last IRInstructionData of the IRSimilarityCandidate.
1619       IDL->insert(Region.Candidate->end(), *NewEndIRID);
1620     }
1621   }
1622 
1623   return none_of(*IRSC, [this](IRInstructionData &ID) {
1624     if (!nextIRInstructionDataMatchesNextInst(ID))
1625       return true;
1626 
1627     return !this->InstructionClassifier.visit(ID.Inst);
1628   });
1629 }
1630 
1631 void IROutliner::pruneIncompatibleRegions(
1632     std::vector<IRSimilarityCandidate> &CandidateVec,
1633     OutlinableGroup &CurrentGroup) {
1634   bool PreviouslyOutlined;
1635 
1636   // Sort from beginning to end, so the IRSimilarityCandidates are in order.
1637   stable_sort(CandidateVec, [](const IRSimilarityCandidate &LHS,
1638                                const IRSimilarityCandidate &RHS) {
1639     return LHS.getStartIdx() < RHS.getStartIdx();
1640   });
1641 
1642   IRSimilarityCandidate &FirstCandidate = CandidateVec[0];
1643   // Since outlining a call and a branch instruction will be the same as only
1644   // outlinining a call instruction, we ignore it as a space saving.
1645   if (FirstCandidate.getLength() == 2) {
1646     if (isa<CallInst>(FirstCandidate.front()->Inst) &&
1647         isa<BranchInst>(FirstCandidate.back()->Inst))
1648         return;
1649   }
1650 
1651   unsigned CurrentEndIdx = 0;
1652   for (IRSimilarityCandidate &IRSC : CandidateVec) {
1653     PreviouslyOutlined = false;
1654     unsigned StartIdx = IRSC.getStartIdx();
1655     unsigned EndIdx = IRSC.getEndIdx();
1656 
1657     for (unsigned Idx = StartIdx; Idx <= EndIdx; Idx++)
1658       if (Outlined.contains(Idx)) {
1659         PreviouslyOutlined = true;
1660         break;
1661       }
1662 
1663     if (PreviouslyOutlined)
1664       continue;
1665 
1666     // Check over the instructions, and if the basic block has its address
1667     // taken for use somewhere else, we do not outline that block.
1668     bool BBHasAddressTaken = any_of(IRSC, [](IRInstructionData &ID){
1669       return ID.Inst->getParent()->hasAddressTaken();
1670     });
1671 
1672     if (BBHasAddressTaken)
1673       continue;
1674 
1675     if (IRSC.front()->Inst->getFunction()->hasLinkOnceODRLinkage() &&
1676         !OutlineFromLinkODRs)
1677       continue;
1678 
1679     // Greedily prune out any regions that will overlap with already chosen
1680     // regions.
1681     if (CurrentEndIdx != 0 && StartIdx <= CurrentEndIdx)
1682       continue;
1683 
1684     bool BadInst = any_of(IRSC, [this](IRInstructionData &ID) {
1685       if (!nextIRInstructionDataMatchesNextInst(ID))
1686         return true;
1687 
1688       return !this->InstructionClassifier.visit(ID.Inst);
1689     });
1690 
1691     if (BadInst)
1692       continue;
1693 
1694     OutlinableRegion *OS = new (RegionAllocator.Allocate())
1695         OutlinableRegion(IRSC, CurrentGroup);
1696     CurrentGroup.Regions.push_back(OS);
1697 
1698     CurrentEndIdx = EndIdx;
1699   }
1700 }
1701 
1702 InstructionCost
1703 IROutliner::findBenefitFromAllRegions(OutlinableGroup &CurrentGroup) {
1704   InstructionCost RegionBenefit = 0;
1705   for (OutlinableRegion *Region : CurrentGroup.Regions) {
1706     TargetTransformInfo &TTI = getTTI(*Region->StartBB->getParent());
1707     // We add the number of instructions in the region to the benefit as an
1708     // estimate as to how much will be removed.
1709     RegionBenefit += Region->getBenefit(TTI);
1710     LLVM_DEBUG(dbgs() << "Adding: " << RegionBenefit
1711                       << " saved instructions to overfall benefit.\n");
1712   }
1713 
1714   return RegionBenefit;
1715 }
1716 
1717 InstructionCost
1718 IROutliner::findCostOutputReloads(OutlinableGroup &CurrentGroup) {
1719   InstructionCost OverallCost = 0;
1720   for (OutlinableRegion *Region : CurrentGroup.Regions) {
1721     TargetTransformInfo &TTI = getTTI(*Region->StartBB->getParent());
1722 
1723     // Each output incurs a load after the call, so we add that to the cost.
1724     for (unsigned OutputGVN : Region->GVNStores) {
1725       Optional<Value *> OV = Region->Candidate->fromGVN(OutputGVN);
1726       assert(OV.hasValue() && "Could not find value for GVN?");
1727       Value *V = OV.getValue();
1728       InstructionCost LoadCost =
1729           TTI.getMemoryOpCost(Instruction::Load, V->getType(), Align(1), 0,
1730                               TargetTransformInfo::TCK_CodeSize);
1731 
1732       LLVM_DEBUG(dbgs() << "Adding: " << LoadCost
1733                         << " instructions to cost for output of type "
1734                         << *V->getType() << "\n");
1735       OverallCost += LoadCost;
1736     }
1737   }
1738 
1739   return OverallCost;
1740 }
1741 
1742 /// Find the extra instructions needed to handle any output values for the
1743 /// region.
1744 ///
1745 /// \param [in] M - The Module to outline from.
1746 /// \param [in] CurrentGroup - The collection of OutlinableRegions to analyze.
1747 /// \param [in] TTI - The TargetTransformInfo used to collect information for
1748 /// new instruction costs.
1749 /// \returns the additional cost to handle the outputs.
1750 static InstructionCost findCostForOutputBlocks(Module &M,
1751                                                OutlinableGroup &CurrentGroup,
1752                                                TargetTransformInfo &TTI) {
1753   InstructionCost OutputCost = 0;
1754   unsigned NumOutputBranches = 0;
1755 
1756   IRSimilarityCandidate &Candidate = *CurrentGroup.Regions[0]->Candidate;
1757   DenseSet<BasicBlock *> CandidateBlocks;
1758   Candidate.getBasicBlocks(CandidateBlocks);
1759 
1760   // Count the number of different output branches that point to blocks outside
1761   // of the region.
1762   DenseSet<BasicBlock *> FoundBlocks;
1763   for (IRInstructionData &ID : Candidate) {
1764     if (!isa<BranchInst>(ID.Inst))
1765       continue;
1766 
1767     for (Value *V : ID.OperVals) {
1768       BasicBlock *BB = static_cast<BasicBlock *>(V);
1769       DenseSet<BasicBlock *>::iterator CBIt = CandidateBlocks.find(BB);
1770       if (CBIt != CandidateBlocks.end() || FoundBlocks.contains(BB))
1771         continue;
1772       FoundBlocks.insert(BB);
1773       NumOutputBranches++;
1774     }
1775   }
1776 
1777   CurrentGroup.BranchesToOutside = NumOutputBranches;
1778 
1779   for (const ArrayRef<unsigned> &OutputUse :
1780        CurrentGroup.OutputGVNCombinations) {
1781     for (unsigned GVN : OutputUse) {
1782       Optional<Value *> OV = Candidate.fromGVN(GVN);
1783       assert(OV.hasValue() && "Could not find value for GVN?");
1784       Value *V = OV.getValue();
1785       InstructionCost StoreCost =
1786           TTI.getMemoryOpCost(Instruction::Load, V->getType(), Align(1), 0,
1787                               TargetTransformInfo::TCK_CodeSize);
1788 
1789       // An instruction cost is added for each store set that needs to occur for
1790       // various output combinations inside the function, plus a branch to
1791       // return to the exit block.
1792       LLVM_DEBUG(dbgs() << "Adding: " << StoreCost
1793                         << " instructions to cost for output of type "
1794                         << *V->getType() << "\n");
1795       OutputCost += StoreCost * NumOutputBranches;
1796     }
1797 
1798     InstructionCost BranchCost =
1799         TTI.getCFInstrCost(Instruction::Br, TargetTransformInfo::TCK_CodeSize);
1800     LLVM_DEBUG(dbgs() << "Adding " << BranchCost << " to the current cost for"
1801                       << " a branch instruction\n");
1802     OutputCost += BranchCost * NumOutputBranches;
1803   }
1804 
1805   // If there is more than one output scheme, we must have a comparison and
1806   // branch for each different item in the switch statement.
1807   if (CurrentGroup.OutputGVNCombinations.size() > 1) {
1808     InstructionCost ComparisonCost = TTI.getCmpSelInstrCost(
1809         Instruction::ICmp, Type::getInt32Ty(M.getContext()),
1810         Type::getInt32Ty(M.getContext()), CmpInst::BAD_ICMP_PREDICATE,
1811         TargetTransformInfo::TCK_CodeSize);
1812     InstructionCost BranchCost =
1813         TTI.getCFInstrCost(Instruction::Br, TargetTransformInfo::TCK_CodeSize);
1814 
1815     unsigned DifferentBlocks = CurrentGroup.OutputGVNCombinations.size();
1816     InstructionCost TotalCost = ComparisonCost * BranchCost * DifferentBlocks;
1817 
1818     LLVM_DEBUG(dbgs() << "Adding: " << TotalCost
1819                       << " instructions for each switch case for each different"
1820                       << " output path in a function\n");
1821     OutputCost += TotalCost * NumOutputBranches;
1822   }
1823 
1824   return OutputCost;
1825 }
1826 
1827 void IROutliner::findCostBenefit(Module &M, OutlinableGroup &CurrentGroup) {
1828   InstructionCost RegionBenefit = findBenefitFromAllRegions(CurrentGroup);
1829   CurrentGroup.Benefit += RegionBenefit;
1830   LLVM_DEBUG(dbgs() << "Current Benefit: " << CurrentGroup.Benefit << "\n");
1831 
1832   InstructionCost OutputReloadCost = findCostOutputReloads(CurrentGroup);
1833   CurrentGroup.Cost += OutputReloadCost;
1834   LLVM_DEBUG(dbgs() << "Current Cost: " << CurrentGroup.Cost << "\n");
1835 
1836   InstructionCost AverageRegionBenefit =
1837       RegionBenefit / CurrentGroup.Regions.size();
1838   unsigned OverallArgumentNum = CurrentGroup.ArgumentTypes.size();
1839   unsigned NumRegions = CurrentGroup.Regions.size();
1840   TargetTransformInfo &TTI =
1841       getTTI(*CurrentGroup.Regions[0]->Candidate->getFunction());
1842 
1843   // We add one region to the cost once, to account for the instructions added
1844   // inside of the newly created function.
1845   LLVM_DEBUG(dbgs() << "Adding: " << AverageRegionBenefit
1846                     << " instructions to cost for body of new function.\n");
1847   CurrentGroup.Cost += AverageRegionBenefit;
1848   LLVM_DEBUG(dbgs() << "Current Cost: " << CurrentGroup.Cost << "\n");
1849 
1850   // For each argument, we must add an instruction for loading the argument
1851   // out of the register and into a value inside of the newly outlined function.
1852   LLVM_DEBUG(dbgs() << "Adding: " << OverallArgumentNum
1853                     << " instructions to cost for each argument in the new"
1854                     << " function.\n");
1855   CurrentGroup.Cost +=
1856       OverallArgumentNum * TargetTransformInfo::TCC_Basic;
1857   LLVM_DEBUG(dbgs() << "Current Cost: " << CurrentGroup.Cost << "\n");
1858 
1859   // Each argument needs to either be loaded into a register or onto the stack.
1860   // Some arguments will only be loaded into the stack once the argument
1861   // registers are filled.
1862   LLVM_DEBUG(dbgs() << "Adding: " << OverallArgumentNum
1863                     << " instructions to cost for each argument in the new"
1864                     << " function " << NumRegions << " times for the "
1865                     << "needed argument handling at the call site.\n");
1866   CurrentGroup.Cost +=
1867       2 * OverallArgumentNum * TargetTransformInfo::TCC_Basic * NumRegions;
1868   LLVM_DEBUG(dbgs() << "Current Cost: " << CurrentGroup.Cost << "\n");
1869 
1870   CurrentGroup.Cost += findCostForOutputBlocks(M, CurrentGroup, TTI);
1871   LLVM_DEBUG(dbgs() << "Current Cost: " << CurrentGroup.Cost << "\n");
1872 }
1873 
1874 void IROutliner::updateOutputMapping(OutlinableRegion &Region,
1875                                      ArrayRef<Value *> Outputs,
1876                                      LoadInst *LI) {
1877   // For and load instructions following the call
1878   Value *Operand = LI->getPointerOperand();
1879   Optional<unsigned> OutputIdx = None;
1880   // Find if the operand it is an output register.
1881   for (unsigned ArgIdx = Region.NumExtractedInputs;
1882        ArgIdx < Region.Call->arg_size(); ArgIdx++) {
1883     if (Operand == Region.Call->getArgOperand(ArgIdx)) {
1884       OutputIdx = ArgIdx - Region.NumExtractedInputs;
1885       break;
1886     }
1887   }
1888 
1889   // If we found an output register, place a mapping of the new value
1890   // to the original in the mapping.
1891   if (!OutputIdx.hasValue())
1892     return;
1893 
1894   if (OutputMappings.find(Outputs[OutputIdx.getValue()]) ==
1895       OutputMappings.end()) {
1896     LLVM_DEBUG(dbgs() << "Mapping extracted output " << *LI << " to "
1897                       << *Outputs[OutputIdx.getValue()] << "\n");
1898     OutputMappings.insert(std::make_pair(LI, Outputs[OutputIdx.getValue()]));
1899   } else {
1900     Value *Orig = OutputMappings.find(Outputs[OutputIdx.getValue()])->second;
1901     LLVM_DEBUG(dbgs() << "Mapping extracted output " << *Orig << " to "
1902                       << *Outputs[OutputIdx.getValue()] << "\n");
1903     OutputMappings.insert(std::make_pair(LI, Orig));
1904   }
1905 }
1906 
1907 bool IROutliner::extractSection(OutlinableRegion &Region) {
1908   SetVector<Value *> ArgInputs, Outputs, SinkCands;
1909   assert(Region.StartBB && "StartBB for the OutlinableRegion is nullptr!");
1910   BasicBlock *InitialStart = Region.StartBB;
1911   Function *OrigF = Region.StartBB->getParent();
1912   CodeExtractorAnalysisCache CEAC(*OrigF);
1913   Region.ExtractedFunction =
1914       Region.CE->extractCodeRegion(CEAC, ArgInputs, Outputs);
1915 
1916   // If the extraction was successful, find the BasicBlock, and reassign the
1917   // OutlinableRegion blocks
1918   if (!Region.ExtractedFunction) {
1919     LLVM_DEBUG(dbgs() << "CodeExtractor failed to outline " << Region.StartBB
1920                       << "\n");
1921     Region.reattachCandidate();
1922     return false;
1923   }
1924 
1925   // Get the block containing the called branch, and reassign the blocks as
1926   // necessary.  If the original block still exists, it is because we ended on
1927   // a branch instruction, and so we move the contents into the block before
1928   // and assign the previous block correctly.
1929   User *InstAsUser = Region.ExtractedFunction->user_back();
1930   BasicBlock *RewrittenBB = cast<Instruction>(InstAsUser)->getParent();
1931   Region.PrevBB = RewrittenBB->getSinglePredecessor();
1932   assert(Region.PrevBB && "PrevBB is nullptr?");
1933   if (Region.PrevBB == InitialStart) {
1934     BasicBlock *NewPrev = InitialStart->getSinglePredecessor();
1935     Instruction *BI = NewPrev->getTerminator();
1936     BI->eraseFromParent();
1937     moveBBContents(*InitialStart, *NewPrev);
1938     Region.PrevBB = NewPrev;
1939     InitialStart->eraseFromParent();
1940   }
1941 
1942   Region.StartBB = RewrittenBB;
1943   Region.EndBB = RewrittenBB;
1944 
1945   // The sequences of outlinable regions has now changed.  We must fix the
1946   // IRInstructionDataList for consistency.  Although they may not be illegal
1947   // instructions, they should not be compared with anything else as they
1948   // should not be outlined in this round.  So marking these as illegal is
1949   // allowed.
1950   IRInstructionDataList *IDL = Region.Candidate->front()->IDL;
1951   Instruction *BeginRewritten = &*RewrittenBB->begin();
1952   Instruction *EndRewritten = &*RewrittenBB->begin();
1953   Region.NewFront = new (InstDataAllocator.Allocate()) IRInstructionData(
1954       *BeginRewritten, InstructionClassifier.visit(*BeginRewritten), *IDL);
1955   Region.NewBack = new (InstDataAllocator.Allocate()) IRInstructionData(
1956       *EndRewritten, InstructionClassifier.visit(*EndRewritten), *IDL);
1957 
1958   // Insert the first IRInstructionData of the new region in front of the
1959   // first IRInstructionData of the IRSimilarityCandidate.
1960   IDL->insert(Region.Candidate->begin(), *Region.NewFront);
1961   // Insert the first IRInstructionData of the new region after the
1962   // last IRInstructionData of the IRSimilarityCandidate.
1963   IDL->insert(Region.Candidate->end(), *Region.NewBack);
1964   // Remove the IRInstructionData from the IRSimilarityCandidate.
1965   IDL->erase(Region.Candidate->begin(), std::prev(Region.Candidate->end()));
1966 
1967   assert(RewrittenBB != nullptr &&
1968          "Could not find a predecessor after extraction!");
1969 
1970   // Iterate over the new set of instructions to find the new call
1971   // instruction.
1972   for (Instruction &I : *RewrittenBB)
1973     if (CallInst *CI = dyn_cast<CallInst>(&I)) {
1974       if (Region.ExtractedFunction == CI->getCalledFunction())
1975         Region.Call = CI;
1976     } else if (LoadInst *LI = dyn_cast<LoadInst>(&I))
1977       updateOutputMapping(Region, Outputs.getArrayRef(), LI);
1978   Region.reattachCandidate();
1979   return true;
1980 }
1981 
1982 unsigned IROutliner::doOutline(Module &M) {
1983   // Find the possible similarity sections.
1984   InstructionClassifier.EnableBranches = !DisableBranches;
1985   IRSimilarityIdentifier &Identifier = getIRSI(M);
1986   SimilarityGroupList &SimilarityCandidates = *Identifier.getSimilarity();
1987 
1988   // Sort them by size of extracted sections
1989   unsigned OutlinedFunctionNum = 0;
1990   // If we only have one SimilarityGroup in SimilarityCandidates, we do not have
1991   // to sort them by the potential number of instructions to be outlined
1992   if (SimilarityCandidates.size() > 1)
1993     llvm::stable_sort(SimilarityCandidates,
1994                       [](const std::vector<IRSimilarityCandidate> &LHS,
1995                          const std::vector<IRSimilarityCandidate> &RHS) {
1996                         return LHS[0].getLength() * LHS.size() >
1997                                RHS[0].getLength() * RHS.size();
1998                       });
1999   // Creating OutlinableGroups for each SimilarityCandidate to be used in
2000   // each of the following for loops to avoid making an allocator.
2001   std::vector<OutlinableGroup> PotentialGroups(SimilarityCandidates.size());
2002 
2003   DenseSet<unsigned> NotSame;
2004   std::vector<OutlinableGroup *> NegativeCostGroups;
2005   std::vector<OutlinableRegion *> OutlinedRegions;
2006   // Iterate over the possible sets of similarity.
2007   unsigned PotentialGroupIdx = 0;
2008   for (SimilarityGroup &CandidateVec : SimilarityCandidates) {
2009     OutlinableGroup &CurrentGroup = PotentialGroups[PotentialGroupIdx++];
2010 
2011     // Remove entries that were previously outlined
2012     pruneIncompatibleRegions(CandidateVec, CurrentGroup);
2013 
2014     // We pruned the number of regions to 0 to 1, meaning that it's not worth
2015     // trying to outlined since there is no compatible similar instance of this
2016     // code.
2017     if (CurrentGroup.Regions.size() < 2)
2018       continue;
2019 
2020     // Determine if there are any values that are the same constant throughout
2021     // each section in the set.
2022     NotSame.clear();
2023     CurrentGroup.findSameConstants(NotSame);
2024 
2025     if (CurrentGroup.IgnoreGroup)
2026       continue;
2027 
2028     // Create a CodeExtractor for each outlinable region. Identify inputs and
2029     // outputs for each section using the code extractor and create the argument
2030     // types for the Aggregate Outlining Function.
2031     OutlinedRegions.clear();
2032     for (OutlinableRegion *OS : CurrentGroup.Regions) {
2033       // Break the outlinable region out of its parent BasicBlock into its own
2034       // BasicBlocks (see function implementation).
2035       OS->splitCandidate();
2036 
2037       // There's a chance that when the region is split, extra instructions are
2038       // added to the region. This makes the region no longer viable
2039       // to be split, so we ignore it for outlining.
2040       if (!OS->CandidateSplit)
2041         continue;
2042 
2043       SmallVector<BasicBlock *> BE;
2044       DenseSet<BasicBlock *> BBSet;
2045       OS->Candidate->getBasicBlocks(BBSet, BE);
2046       OS->CE = new (ExtractorAllocator.Allocate())
2047           CodeExtractor(BE, nullptr, false, nullptr, nullptr, nullptr, false,
2048                         false, "outlined");
2049       findAddInputsOutputs(M, *OS, NotSame);
2050       if (!OS->IgnoreRegion)
2051         OutlinedRegions.push_back(OS);
2052 
2053       // We recombine the blocks together now that we have gathered all the
2054       // needed information.
2055       OS->reattachCandidate();
2056     }
2057 
2058     CurrentGroup.Regions = std::move(OutlinedRegions);
2059 
2060     if (CurrentGroup.Regions.empty())
2061       continue;
2062 
2063     CurrentGroup.collectGVNStoreSets(M);
2064 
2065     if (CostModel)
2066       findCostBenefit(M, CurrentGroup);
2067 
2068     // If we are adhering to the cost model, skip those groups where the cost
2069     // outweighs the benefits.
2070     if (CurrentGroup.Cost >= CurrentGroup.Benefit && CostModel) {
2071       OptimizationRemarkEmitter &ORE =
2072           getORE(*CurrentGroup.Regions[0]->Candidate->getFunction());
2073       ORE.emit([&]() {
2074         IRSimilarityCandidate *C = CurrentGroup.Regions[0]->Candidate;
2075         OptimizationRemarkMissed R(DEBUG_TYPE, "WouldNotDecreaseSize",
2076                                    C->frontInstruction());
2077         R << "did not outline "
2078           << ore::NV(std::to_string(CurrentGroup.Regions.size()))
2079           << " regions due to estimated increase of "
2080           << ore::NV("InstructionIncrease",
2081                      CurrentGroup.Cost - CurrentGroup.Benefit)
2082           << " instructions at locations ";
2083         interleave(
2084             CurrentGroup.Regions.begin(), CurrentGroup.Regions.end(),
2085             [&R](OutlinableRegion *Region) {
2086               R << ore::NV(
2087                   "DebugLoc",
2088                   Region->Candidate->frontInstruction()->getDebugLoc());
2089             },
2090             [&R]() { R << " "; });
2091         return R;
2092       });
2093       continue;
2094     }
2095 
2096     NegativeCostGroups.push_back(&CurrentGroup);
2097   }
2098 
2099   ExtractorAllocator.DestroyAll();
2100 
2101   if (NegativeCostGroups.size() > 1)
2102     stable_sort(NegativeCostGroups,
2103                 [](const OutlinableGroup *LHS, const OutlinableGroup *RHS) {
2104                   return LHS->Benefit - LHS->Cost > RHS->Benefit - RHS->Cost;
2105                 });
2106 
2107   std::vector<Function *> FuncsToRemove;
2108   for (OutlinableGroup *CG : NegativeCostGroups) {
2109     OutlinableGroup &CurrentGroup = *CG;
2110 
2111     OutlinedRegions.clear();
2112     for (OutlinableRegion *Region : CurrentGroup.Regions) {
2113       // We check whether our region is compatible with what has already been
2114       // outlined, and whether we need to ignore this item.
2115       if (!isCompatibleWithAlreadyOutlinedCode(*Region))
2116         continue;
2117       OutlinedRegions.push_back(Region);
2118     }
2119 
2120     if (OutlinedRegions.size() < 2)
2121       continue;
2122 
2123     // Reestimate the cost and benefit of the OutlinableGroup. Continue only if
2124     // we are still outlining enough regions to make up for the added cost.
2125     CurrentGroup.Regions = std::move(OutlinedRegions);
2126     if (CostModel) {
2127       CurrentGroup.Benefit = 0;
2128       CurrentGroup.Cost = 0;
2129       findCostBenefit(M, CurrentGroup);
2130       if (CurrentGroup.Cost >= CurrentGroup.Benefit)
2131         continue;
2132     }
2133     OutlinedRegions.clear();
2134     for (OutlinableRegion *Region : CurrentGroup.Regions) {
2135       Region->splitCandidate();
2136       if (!Region->CandidateSplit)
2137         continue;
2138       OutlinedRegions.push_back(Region);
2139     }
2140 
2141     CurrentGroup.Regions = std::move(OutlinedRegions);
2142     if (CurrentGroup.Regions.size() < 2) {
2143       for (OutlinableRegion *R : CurrentGroup.Regions)
2144         R->reattachCandidate();
2145       continue;
2146     }
2147 
2148     LLVM_DEBUG(dbgs() << "Outlining regions with cost " << CurrentGroup.Cost
2149                       << " and benefit " << CurrentGroup.Benefit << "\n");
2150 
2151     // Create functions out of all the sections, and mark them as outlined.
2152     OutlinedRegions.clear();
2153     for (OutlinableRegion *OS : CurrentGroup.Regions) {
2154       SmallVector<BasicBlock *> BE;
2155       DenseSet<BasicBlock *> BBSet;
2156       OS->Candidate->getBasicBlocks(BBSet, BE);
2157       OS->CE = new (ExtractorAllocator.Allocate())
2158           CodeExtractor(BE, nullptr, false, nullptr, nullptr, nullptr, false,
2159                         false, "outlined");
2160       bool FunctionOutlined = extractSection(*OS);
2161       if (FunctionOutlined) {
2162         unsigned StartIdx = OS->Candidate->getStartIdx();
2163         unsigned EndIdx = OS->Candidate->getEndIdx();
2164         for (unsigned Idx = StartIdx; Idx <= EndIdx; Idx++)
2165           Outlined.insert(Idx);
2166 
2167         OutlinedRegions.push_back(OS);
2168       }
2169     }
2170 
2171     LLVM_DEBUG(dbgs() << "Outlined " << OutlinedRegions.size()
2172                       << " with benefit " << CurrentGroup.Benefit
2173                       << " and cost " << CurrentGroup.Cost << "\n");
2174 
2175     CurrentGroup.Regions = std::move(OutlinedRegions);
2176 
2177     if (CurrentGroup.Regions.empty())
2178       continue;
2179 
2180     OptimizationRemarkEmitter &ORE =
2181         getORE(*CurrentGroup.Regions[0]->Call->getFunction());
2182     ORE.emit([&]() {
2183       IRSimilarityCandidate *C = CurrentGroup.Regions[0]->Candidate;
2184       OptimizationRemark R(DEBUG_TYPE, "Outlined", C->front()->Inst);
2185       R << "outlined " << ore::NV(std::to_string(CurrentGroup.Regions.size()))
2186         << " regions with decrease of "
2187         << ore::NV("Benefit", CurrentGroup.Benefit - CurrentGroup.Cost)
2188         << " instructions at locations ";
2189       interleave(
2190           CurrentGroup.Regions.begin(), CurrentGroup.Regions.end(),
2191           [&R](OutlinableRegion *Region) {
2192             R << ore::NV("DebugLoc",
2193                          Region->Candidate->frontInstruction()->getDebugLoc());
2194           },
2195           [&R]() { R << " "; });
2196       return R;
2197     });
2198 
2199     deduplicateExtractedSections(M, CurrentGroup, FuncsToRemove,
2200                                  OutlinedFunctionNum);
2201   }
2202 
2203   for (Function *F : FuncsToRemove)
2204     F->eraseFromParent();
2205 
2206   return OutlinedFunctionNum;
2207 }
2208 
2209 bool IROutliner::run(Module &M) {
2210   CostModel = !NoCostModel;
2211   OutlineFromLinkODRs = EnableLinkOnceODRIROutlining;
2212 
2213   return doOutline(M) > 0;
2214 }
2215 
2216 // Pass Manager Boilerplate
2217 class IROutlinerLegacyPass : public ModulePass {
2218 public:
2219   static char ID;
2220   IROutlinerLegacyPass() : ModulePass(ID) {
2221     initializeIROutlinerLegacyPassPass(*PassRegistry::getPassRegistry());
2222   }
2223 
2224   void getAnalysisUsage(AnalysisUsage &AU) const override {
2225     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
2226     AU.addRequired<TargetTransformInfoWrapperPass>();
2227     AU.addRequired<IRSimilarityIdentifierWrapperPass>();
2228   }
2229 
2230   bool runOnModule(Module &M) override;
2231 };
2232 
2233 bool IROutlinerLegacyPass::runOnModule(Module &M) {
2234   if (skipModule(M))
2235     return false;
2236 
2237   std::unique_ptr<OptimizationRemarkEmitter> ORE;
2238   auto GORE = [&ORE](Function &F) -> OptimizationRemarkEmitter & {
2239     ORE.reset(new OptimizationRemarkEmitter(&F));
2240     return *ORE.get();
2241   };
2242 
2243   auto GTTI = [this](Function &F) -> TargetTransformInfo & {
2244     return this->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2245   };
2246 
2247   auto GIRSI = [this](Module &) -> IRSimilarityIdentifier & {
2248     return this->getAnalysis<IRSimilarityIdentifierWrapperPass>().getIRSI();
2249   };
2250 
2251   return IROutliner(GTTI, GIRSI, GORE).run(M);
2252 }
2253 
2254 PreservedAnalyses IROutlinerPass::run(Module &M, ModuleAnalysisManager &AM) {
2255   auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
2256 
2257   std::function<TargetTransformInfo &(Function &)> GTTI =
2258       [&FAM](Function &F) -> TargetTransformInfo & {
2259     return FAM.getResult<TargetIRAnalysis>(F);
2260   };
2261 
2262   std::function<IRSimilarityIdentifier &(Module &)> GIRSI =
2263       [&AM](Module &M) -> IRSimilarityIdentifier & {
2264     return AM.getResult<IRSimilarityAnalysis>(M);
2265   };
2266 
2267   std::unique_ptr<OptimizationRemarkEmitter> ORE;
2268   std::function<OptimizationRemarkEmitter &(Function &)> GORE =
2269       [&ORE](Function &F) -> OptimizationRemarkEmitter & {
2270     ORE.reset(new OptimizationRemarkEmitter(&F));
2271     return *ORE.get();
2272   };
2273 
2274   if (IROutliner(GTTI, GIRSI, GORE).run(M))
2275     return PreservedAnalyses::none();
2276   return PreservedAnalyses::all();
2277 }
2278 
2279 char IROutlinerLegacyPass::ID = 0;
2280 INITIALIZE_PASS_BEGIN(IROutlinerLegacyPass, "iroutliner", "IR Outliner", false,
2281                       false)
2282 INITIALIZE_PASS_DEPENDENCY(IRSimilarityIdentifierWrapperPass)
2283 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
2284 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
2285 INITIALIZE_PASS_END(IROutlinerLegacyPass, "iroutliner", "IR Outliner", false,
2286                     false)
2287 
2288 ModulePass *llvm::createIROutlinerPass() { return new IROutlinerLegacyPass(); }
2289