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