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