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