xref: /freebsd-src/contrib/llvm-project/llvm/lib/Transforms/IPO/IROutliner.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
1e8d8bef9SDimitry Andric //===- IROutliner.cpp -- Outline Similar Regions ----------------*- C++ -*-===//
2e8d8bef9SDimitry Andric //
3e8d8bef9SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e8d8bef9SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e8d8bef9SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6e8d8bef9SDimitry Andric //
7e8d8bef9SDimitry Andric //===----------------------------------------------------------------------===//
8e8d8bef9SDimitry Andric ///
9e8d8bef9SDimitry Andric /// \file
10e8d8bef9SDimitry Andric // Implementation for the IROutliner which is used by the IROutliner Pass.
11e8d8bef9SDimitry Andric //
12e8d8bef9SDimitry Andric //===----------------------------------------------------------------------===//
13e8d8bef9SDimitry Andric 
14e8d8bef9SDimitry Andric #include "llvm/Transforms/IPO/IROutliner.h"
15e8d8bef9SDimitry Andric #include "llvm/Analysis/IRSimilarityIdentifier.h"
16e8d8bef9SDimitry Andric #include "llvm/Analysis/OptimizationRemarkEmitter.h"
17e8d8bef9SDimitry Andric #include "llvm/Analysis/TargetTransformInfo.h"
18e8d8bef9SDimitry Andric #include "llvm/IR/Attributes.h"
19fe6060f1SDimitry Andric #include "llvm/IR/DIBuilder.h"
2081ad6265SDimitry Andric #include "llvm/IR/DebugInfo.h"
2181ad6265SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
22349cc55cSDimitry Andric #include "llvm/IR/Dominators.h"
23fe6060f1SDimitry Andric #include "llvm/IR/Mangler.h"
24e8d8bef9SDimitry Andric #include "llvm/IR/PassManager.h"
25e8d8bef9SDimitry Andric #include "llvm/Support/CommandLine.h"
26e8d8bef9SDimitry Andric #include "llvm/Transforms/IPO.h"
27bdd1243dSDimitry Andric #include <optional>
28e8d8bef9SDimitry Andric #include <vector>
29e8d8bef9SDimitry Andric 
30e8d8bef9SDimitry Andric #define DEBUG_TYPE "iroutliner"
31e8d8bef9SDimitry Andric 
32e8d8bef9SDimitry Andric using namespace llvm;
33e8d8bef9SDimitry Andric using namespace IRSimilarity;
34e8d8bef9SDimitry Andric 
35349cc55cSDimitry Andric // A command flag to be used for debugging to exclude branches from similarity
36349cc55cSDimitry Andric // matching and outlining.
3704eeddc0SDimitry Andric namespace llvm {
38349cc55cSDimitry Andric extern cl::opt<bool> DisableBranches;
39349cc55cSDimitry Andric 
4004eeddc0SDimitry Andric // A command flag to be used for debugging to indirect calls from similarity
4104eeddc0SDimitry Andric // matching and outlining.
4204eeddc0SDimitry Andric extern cl::opt<bool> DisableIndirectCalls;
431fd87a68SDimitry Andric 
441fd87a68SDimitry Andric // A command flag to be used for debugging to exclude intrinsics from similarity
451fd87a68SDimitry Andric // matching and outlining.
461fd87a68SDimitry Andric extern cl::opt<bool> DisableIntrinsics;
471fd87a68SDimitry Andric 
4804eeddc0SDimitry Andric } // namespace llvm
4904eeddc0SDimitry Andric 
50e8d8bef9SDimitry Andric // Set to true if the user wants the ir outliner to run on linkonceodr linkage
51e8d8bef9SDimitry Andric // functions. This is false by default because the linker can dedupe linkonceodr
52e8d8bef9SDimitry Andric // functions. Since the outliner is confined to a single module (modulo LTO),
53e8d8bef9SDimitry Andric // this is off by default. It should, however, be the default behavior in
54e8d8bef9SDimitry Andric // LTO.
55e8d8bef9SDimitry Andric static cl::opt<bool> EnableLinkOnceODRIROutlining(
56e8d8bef9SDimitry Andric     "enable-linkonceodr-ir-outlining", cl::Hidden,
57e8d8bef9SDimitry Andric     cl::desc("Enable the IR outliner on linkonceodr functions"),
58e8d8bef9SDimitry Andric     cl::init(false));
59e8d8bef9SDimitry Andric 
60e8d8bef9SDimitry Andric // This is a debug option to test small pieces of code to ensure that outlining
61e8d8bef9SDimitry Andric // works correctly.
62e8d8bef9SDimitry Andric static cl::opt<bool> NoCostModel(
63e8d8bef9SDimitry Andric     "ir-outlining-no-cost", cl::init(false), cl::ReallyHidden,
64e8d8bef9SDimitry Andric     cl::desc("Debug option to outline greedily, without restriction that "
65e8d8bef9SDimitry Andric              "calculated benefit outweighs cost"));
66e8d8bef9SDimitry Andric 
67e8d8bef9SDimitry Andric /// The OutlinableGroup holds all the overarching information for outlining
68e8d8bef9SDimitry Andric /// a set of regions that are structurally similar to one another, such as the
69e8d8bef9SDimitry Andric /// types of the overall function, the output blocks, the sets of stores needed
70e8d8bef9SDimitry Andric /// and a list of the different regions. This information is used in the
71e8d8bef9SDimitry Andric /// deduplication of extracted regions with the same structure.
72e8d8bef9SDimitry Andric struct OutlinableGroup {
73e8d8bef9SDimitry Andric   /// The sections that could be outlined
74e8d8bef9SDimitry Andric   std::vector<OutlinableRegion *> Regions;
75e8d8bef9SDimitry Andric 
76e8d8bef9SDimitry Andric   /// The argument types for the function created as the overall function to
77e8d8bef9SDimitry Andric   /// replace the extracted function for each region.
78e8d8bef9SDimitry Andric   std::vector<Type *> ArgumentTypes;
79e8d8bef9SDimitry Andric   /// The FunctionType for the overall function.
80e8d8bef9SDimitry Andric   FunctionType *OutlinedFunctionType = nullptr;
81e8d8bef9SDimitry Andric   /// The Function for the collective overall function.
82e8d8bef9SDimitry Andric   Function *OutlinedFunction = nullptr;
83e8d8bef9SDimitry Andric 
84e8d8bef9SDimitry Andric   /// Flag for whether we should not consider this group of OutlinableRegions
85e8d8bef9SDimitry Andric   /// for extraction.
86e8d8bef9SDimitry Andric   bool IgnoreGroup = false;
87e8d8bef9SDimitry Andric 
88349cc55cSDimitry Andric   /// The return blocks for the overall function.
89349cc55cSDimitry Andric   DenseMap<Value *, BasicBlock *> EndBBs;
90349cc55cSDimitry Andric 
91349cc55cSDimitry Andric   /// The PHIBlocks with their corresponding return block based on the return
92349cc55cSDimitry Andric   /// value as the key.
93349cc55cSDimitry Andric   DenseMap<Value *, BasicBlock *> PHIBlocks;
94e8d8bef9SDimitry Andric 
95e8d8bef9SDimitry Andric   /// A set containing the different GVN store sets needed. Each array contains
96e8d8bef9SDimitry Andric   /// a sorted list of the different values that need to be stored into output
97e8d8bef9SDimitry Andric   /// registers.
98e8d8bef9SDimitry Andric   DenseSet<ArrayRef<unsigned>> OutputGVNCombinations;
99e8d8bef9SDimitry Andric 
100e8d8bef9SDimitry Andric   /// Flag for whether the \ref ArgumentTypes have been defined after the
101e8d8bef9SDimitry Andric   /// extraction of the first region.
102e8d8bef9SDimitry Andric   bool InputTypesSet = false;
103e8d8bef9SDimitry Andric 
104e8d8bef9SDimitry Andric   /// The number of input values in \ref ArgumentTypes.  Anything after this
105e8d8bef9SDimitry Andric   /// index in ArgumentTypes is an output argument.
106e8d8bef9SDimitry Andric   unsigned NumAggregateInputs = 0;
107e8d8bef9SDimitry Andric 
108349cc55cSDimitry Andric   /// The mapping of the canonical numbering of the values in outlined sections
109349cc55cSDimitry Andric   /// to specific arguments.
110349cc55cSDimitry Andric   DenseMap<unsigned, unsigned> CanonicalNumberToAggArg;
111349cc55cSDimitry Andric 
112349cc55cSDimitry Andric   /// The number of branches in the region target a basic block that is outside
113349cc55cSDimitry Andric   /// of the region.
114349cc55cSDimitry Andric   unsigned BranchesToOutside = 0;
115349cc55cSDimitry Andric 
11604eeddc0SDimitry Andric   /// Tracker counting backwards from the highest unsigned value possible to
11704eeddc0SDimitry Andric   /// avoid conflicting with the GVNs of assigned values.  We start at -3 since
11804eeddc0SDimitry Andric   /// -2 and -1 are assigned by the DenseMap.
11904eeddc0SDimitry Andric   unsigned PHINodeGVNTracker = -3;
12004eeddc0SDimitry Andric 
12104eeddc0SDimitry Andric   DenseMap<unsigned,
12204eeddc0SDimitry Andric            std::pair<std::pair<unsigned, unsigned>, SmallVector<unsigned, 2>>>
12304eeddc0SDimitry Andric       PHINodeGVNToGVNs;
12404eeddc0SDimitry Andric   DenseMap<hash_code, unsigned> GVNsToPHINodeGVN;
12504eeddc0SDimitry Andric 
126e8d8bef9SDimitry Andric   /// The number of instructions that will be outlined by extracting \ref
127e8d8bef9SDimitry Andric   /// Regions.
128e8d8bef9SDimitry Andric   InstructionCost Benefit = 0;
129e8d8bef9SDimitry Andric   /// The number of added instructions needed for the outlining of the \ref
130e8d8bef9SDimitry Andric   /// Regions.
131e8d8bef9SDimitry Andric   InstructionCost Cost = 0;
132e8d8bef9SDimitry Andric 
133e8d8bef9SDimitry Andric   /// The argument that needs to be marked with the swifterr attribute.  If not
134e8d8bef9SDimitry Andric   /// needed, there is no value.
135bdd1243dSDimitry Andric   std::optional<unsigned> SwiftErrorArgument;
136e8d8bef9SDimitry Andric 
137e8d8bef9SDimitry Andric   /// For the \ref Regions, we look at every Value.  If it is a constant,
138e8d8bef9SDimitry Andric   /// we check whether it is the same in Region.
139e8d8bef9SDimitry Andric   ///
140e8d8bef9SDimitry Andric   /// \param [in,out] NotSame contains the global value numbers where the
141e8d8bef9SDimitry Andric   /// constant is not always the same, and must be passed in as an argument.
142e8d8bef9SDimitry Andric   void findSameConstants(DenseSet<unsigned> &NotSame);
143e8d8bef9SDimitry Andric 
144e8d8bef9SDimitry Andric   /// For the regions, look at each set of GVN stores needed and account for
145e8d8bef9SDimitry Andric   /// each combination.  Add an argument to the argument types if there is
146e8d8bef9SDimitry Andric   /// more than one combination.
147e8d8bef9SDimitry Andric   ///
148e8d8bef9SDimitry Andric   /// \param [in] M - The module we are outlining from.
149e8d8bef9SDimitry Andric   void collectGVNStoreSets(Module &M);
150e8d8bef9SDimitry Andric };
151e8d8bef9SDimitry Andric 
152e8d8bef9SDimitry Andric /// Move the contents of \p SourceBB to before the last instruction of \p
153e8d8bef9SDimitry Andric /// TargetBB.
154e8d8bef9SDimitry Andric /// \param SourceBB - the BasicBlock to pull Instructions from.
155e8d8bef9SDimitry Andric /// \param TargetBB - the BasicBlock to put Instruction into.
156e8d8bef9SDimitry Andric static void moveBBContents(BasicBlock &SourceBB, BasicBlock &TargetBB) {
1577a6dacacSDimitry Andric   TargetBB.splice(TargetBB.end(), &SourceBB);
158e8d8bef9SDimitry Andric }
159349cc55cSDimitry Andric 
160349cc55cSDimitry Andric /// A function to sort the keys of \p Map, which must be a mapping of constant
161349cc55cSDimitry Andric /// values to basic blocks and return it in \p SortedKeys
162349cc55cSDimitry Andric ///
163349cc55cSDimitry Andric /// \param SortedKeys - The vector the keys will be return in and sorted.
164349cc55cSDimitry Andric /// \param Map - The DenseMap containing keys to sort.
165349cc55cSDimitry Andric static void getSortedConstantKeys(std::vector<Value *> &SortedKeys,
166349cc55cSDimitry Andric                                   DenseMap<Value *, BasicBlock *> &Map) {
167349cc55cSDimitry Andric   for (auto &VtoBB : Map)
168349cc55cSDimitry Andric     SortedKeys.push_back(VtoBB.first);
169349cc55cSDimitry Andric 
170bdd1243dSDimitry Andric   // Here we expect to have either 1 value that is void (nullptr) or multiple
171bdd1243dSDimitry Andric   // values that are all constant integers.
172bdd1243dSDimitry Andric   if (SortedKeys.size() == 1) {
173bdd1243dSDimitry Andric     assert(!SortedKeys[0] && "Expected a single void value.");
174bdd1243dSDimitry Andric     return;
175bdd1243dSDimitry Andric   }
176bdd1243dSDimitry Andric 
177349cc55cSDimitry Andric   stable_sort(SortedKeys, [](const Value *LHS, const Value *RHS) {
178bdd1243dSDimitry Andric     assert(LHS && RHS && "Expected non void values.");
17906c3fb27SDimitry Andric     const ConstantInt *LHSC = cast<ConstantInt>(LHS);
18006c3fb27SDimitry Andric     const ConstantInt *RHSC = cast<ConstantInt>(RHS);
181349cc55cSDimitry Andric 
182349cc55cSDimitry Andric     return LHSC->getLimitedValue() < RHSC->getLimitedValue();
183349cc55cSDimitry Andric   });
184349cc55cSDimitry Andric }
185349cc55cSDimitry Andric 
186349cc55cSDimitry Andric Value *OutlinableRegion::findCorrespondingValueIn(const OutlinableRegion &Other,
187349cc55cSDimitry Andric                                                   Value *V) {
188bdd1243dSDimitry Andric   std::optional<unsigned> GVN = Candidate->getGVN(V);
18981ad6265SDimitry Andric   assert(GVN && "No GVN for incoming value");
190bdd1243dSDimitry Andric   std::optional<unsigned> CanonNum = Candidate->getCanonicalNum(*GVN);
191bdd1243dSDimitry Andric   std::optional<unsigned> FirstGVN =
192bdd1243dSDimitry Andric       Other.Candidate->fromCanonicalNum(*CanonNum);
193bdd1243dSDimitry Andric   std::optional<Value *> FoundValueOpt = Other.Candidate->fromGVN(*FirstGVN);
19481ad6265SDimitry Andric   return FoundValueOpt.value_or(nullptr);
19581ad6265SDimitry Andric }
19681ad6265SDimitry Andric 
19781ad6265SDimitry Andric BasicBlock *
19881ad6265SDimitry Andric OutlinableRegion::findCorrespondingBlockIn(const OutlinableRegion &Other,
19981ad6265SDimitry Andric                                            BasicBlock *BB) {
2005f757f3fSDimitry Andric   Instruction *FirstNonPHI = BB->getFirstNonPHIOrDbg();
20181ad6265SDimitry Andric   assert(FirstNonPHI && "block is empty?");
20281ad6265SDimitry Andric   Value *CorrespondingVal = findCorrespondingValueIn(Other, FirstNonPHI);
20381ad6265SDimitry Andric   if (!CorrespondingVal)
20481ad6265SDimitry Andric     return nullptr;
20581ad6265SDimitry Andric   BasicBlock *CorrespondingBlock =
20681ad6265SDimitry Andric       cast<Instruction>(CorrespondingVal)->getParent();
20781ad6265SDimitry Andric   return CorrespondingBlock;
208e8d8bef9SDimitry Andric }
209e8d8bef9SDimitry Andric 
21004eeddc0SDimitry Andric /// Rewrite the BranchInsts in the incoming blocks to \p PHIBlock that are found
21104eeddc0SDimitry Andric /// in \p Included to branch to BasicBlock \p Replace if they currently branch
21204eeddc0SDimitry Andric /// to the BasicBlock \p Find.  This is used to fix up the incoming basic blocks
21304eeddc0SDimitry Andric /// when PHINodes are included in outlined regions.
21404eeddc0SDimitry Andric ///
21504eeddc0SDimitry Andric /// \param PHIBlock - The BasicBlock containing the PHINodes that need to be
21604eeddc0SDimitry Andric /// checked.
21704eeddc0SDimitry Andric /// \param Find - The successor block to be replaced.
21804eeddc0SDimitry Andric /// \param Replace - The new succesor block to branch to.
21904eeddc0SDimitry Andric /// \param Included - The set of blocks about to be outlined.
22004eeddc0SDimitry Andric static void replaceTargetsFromPHINode(BasicBlock *PHIBlock, BasicBlock *Find,
22104eeddc0SDimitry Andric                                       BasicBlock *Replace,
22204eeddc0SDimitry Andric                                       DenseSet<BasicBlock *> &Included) {
22304eeddc0SDimitry Andric   for (PHINode &PN : PHIBlock->phis()) {
22404eeddc0SDimitry Andric     for (unsigned Idx = 0, PNEnd = PN.getNumIncomingValues(); Idx != PNEnd;
22504eeddc0SDimitry Andric          ++Idx) {
22604eeddc0SDimitry Andric       // Check if the incoming block is included in the set of blocks being
22704eeddc0SDimitry Andric       // outlined.
22804eeddc0SDimitry Andric       BasicBlock *Incoming = PN.getIncomingBlock(Idx);
22904eeddc0SDimitry Andric       if (!Included.contains(Incoming))
23004eeddc0SDimitry Andric         continue;
23104eeddc0SDimitry Andric 
23204eeddc0SDimitry Andric       BranchInst *BI = dyn_cast<BranchInst>(Incoming->getTerminator());
23304eeddc0SDimitry Andric       assert(BI && "Not a branch instruction?");
23404eeddc0SDimitry Andric       // Look over the branching instructions into this block to see if we
23504eeddc0SDimitry Andric       // used to branch to Find in this outlined block.
23604eeddc0SDimitry Andric       for (unsigned Succ = 0, End = BI->getNumSuccessors(); Succ != End;
23704eeddc0SDimitry Andric            Succ++) {
23804eeddc0SDimitry Andric         // If we have found the block to replace, we do so here.
23904eeddc0SDimitry Andric         if (BI->getSuccessor(Succ) != Find)
24004eeddc0SDimitry Andric           continue;
24104eeddc0SDimitry Andric         BI->setSuccessor(Succ, Replace);
24204eeddc0SDimitry Andric       }
24304eeddc0SDimitry Andric     }
24404eeddc0SDimitry Andric   }
24504eeddc0SDimitry Andric }
24604eeddc0SDimitry Andric 
24704eeddc0SDimitry Andric 
248e8d8bef9SDimitry Andric void OutlinableRegion::splitCandidate() {
249e8d8bef9SDimitry Andric   assert(!CandidateSplit && "Candidate already split!");
250e8d8bef9SDimitry Andric 
251349cc55cSDimitry Andric   Instruction *BackInst = Candidate->backInstruction();
252349cc55cSDimitry Andric 
253349cc55cSDimitry Andric   Instruction *EndInst = nullptr;
254349cc55cSDimitry Andric   // Check whether the last instruction is a terminator, if it is, we do
255349cc55cSDimitry Andric   // not split on the following instruction. We leave the block as it is.  We
256349cc55cSDimitry Andric   // also check that this is not the last instruction in the Module, otherwise
257349cc55cSDimitry Andric   // the check for whether the current following instruction matches the
258349cc55cSDimitry Andric   // previously recorded instruction will be incorrect.
259349cc55cSDimitry Andric   if (!BackInst->isTerminator() ||
260349cc55cSDimitry Andric       BackInst->getParent() != &BackInst->getFunction()->back()) {
261349cc55cSDimitry Andric     EndInst = Candidate->end()->Inst;
262349cc55cSDimitry Andric     assert(EndInst && "Expected an end instruction?");
263349cc55cSDimitry Andric   }
264349cc55cSDimitry Andric 
265349cc55cSDimitry Andric   // We check if the current instruction following the last instruction in the
266349cc55cSDimitry Andric   // region is the same as the recorded instruction following the last
267349cc55cSDimitry Andric   // instruction. If they do not match, there could be problems in rewriting
268349cc55cSDimitry Andric   // the program after outlining, so we ignore it.
269349cc55cSDimitry Andric   if (!BackInst->isTerminator() &&
270349cc55cSDimitry Andric       EndInst != BackInst->getNextNonDebugInstruction())
271349cc55cSDimitry Andric     return;
272349cc55cSDimitry Andric 
273e8d8bef9SDimitry Andric   Instruction *StartInst = (*Candidate->begin()).Inst;
274349cc55cSDimitry Andric   assert(StartInst && "Expected a start instruction?");
275e8d8bef9SDimitry Andric   StartBB = StartInst->getParent();
276e8d8bef9SDimitry Andric   PrevBB = StartBB;
277e8d8bef9SDimitry Andric 
27804eeddc0SDimitry Andric   DenseSet<BasicBlock *> BBSet;
27904eeddc0SDimitry Andric   Candidate->getBasicBlocks(BBSet);
28004eeddc0SDimitry Andric 
28104eeddc0SDimitry Andric   // We iterate over the instructions in the region, if we find a PHINode, we
28204eeddc0SDimitry Andric   // check if there are predecessors outside of the region, if there are,
28304eeddc0SDimitry Andric   // we ignore this region since we are unable to handle the severing of the
28404eeddc0SDimitry Andric   // phi node right now.
28581ad6265SDimitry Andric 
28681ad6265SDimitry Andric   // TODO: Handle extraneous inputs for PHINodes through variable number of
28781ad6265SDimitry Andric   // inputs, similar to how outputs are handled.
28804eeddc0SDimitry Andric   BasicBlock::iterator It = StartInst->getIterator();
28981ad6265SDimitry Andric   EndBB = BackInst->getParent();
29081ad6265SDimitry Andric   BasicBlock *IBlock;
29181ad6265SDimitry Andric   BasicBlock *PHIPredBlock = nullptr;
29281ad6265SDimitry Andric   bool EndBBTermAndBackInstDifferent = EndBB->getTerminator() != BackInst;
29304eeddc0SDimitry Andric   while (PHINode *PN = dyn_cast<PHINode>(&*It)) {
29404eeddc0SDimitry Andric     unsigned NumPredsOutsideRegion = 0;
29581ad6265SDimitry Andric     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
29681ad6265SDimitry Andric       if (!BBSet.contains(PN->getIncomingBlock(i))) {
29781ad6265SDimitry Andric         PHIPredBlock = PN->getIncomingBlock(i);
29804eeddc0SDimitry Andric         ++NumPredsOutsideRegion;
29981ad6265SDimitry Andric         continue;
30081ad6265SDimitry Andric       }
30181ad6265SDimitry Andric 
30281ad6265SDimitry Andric       // We must consider the case there the incoming block to the PHINode is
30381ad6265SDimitry Andric       // the same as the final block of the OutlinableRegion.  If this is the
30481ad6265SDimitry Andric       // case, the branch from this block must also be outlined to be valid.
30581ad6265SDimitry Andric       IBlock = PN->getIncomingBlock(i);
30681ad6265SDimitry Andric       if (IBlock == EndBB && EndBBTermAndBackInstDifferent) {
30781ad6265SDimitry Andric         PHIPredBlock = PN->getIncomingBlock(i);
30881ad6265SDimitry Andric         ++NumPredsOutsideRegion;
30981ad6265SDimitry Andric       }
31081ad6265SDimitry Andric     }
31104eeddc0SDimitry Andric 
31204eeddc0SDimitry Andric     if (NumPredsOutsideRegion > 1)
31304eeddc0SDimitry Andric       return;
31404eeddc0SDimitry Andric 
31504eeddc0SDimitry Andric     It++;
31604eeddc0SDimitry Andric   }
31704eeddc0SDimitry Andric 
31804eeddc0SDimitry Andric   // If the region starts with a PHINode, but is not the initial instruction of
31904eeddc0SDimitry Andric   // the BasicBlock, we ignore this region for now.
32004eeddc0SDimitry Andric   if (isa<PHINode>(StartInst) && StartInst != &*StartBB->begin())
32104eeddc0SDimitry Andric     return;
32204eeddc0SDimitry Andric 
32304eeddc0SDimitry Andric   // If the region ends with a PHINode, but does not contain all of the phi node
32404eeddc0SDimitry Andric   // instructions of the region, we ignore it for now.
32581ad6265SDimitry Andric   if (isa<PHINode>(BackInst) &&
32681ad6265SDimitry Andric       BackInst != &*std::prev(EndBB->getFirstInsertionPt()))
32704eeddc0SDimitry Andric     return;
32804eeddc0SDimitry Andric 
329e8d8bef9SDimitry Andric   // The basic block gets split like so:
330e8d8bef9SDimitry Andric   // block:                 block:
331e8d8bef9SDimitry Andric   //   inst1                  inst1
332e8d8bef9SDimitry Andric   //   inst2                  inst2
333e8d8bef9SDimitry Andric   //   region1               br block_to_outline
334e8d8bef9SDimitry Andric   //   region2              block_to_outline:
335e8d8bef9SDimitry Andric   //   region3          ->    region1
336e8d8bef9SDimitry Andric   //   region4                region2
337e8d8bef9SDimitry Andric   //   inst3                  region3
338e8d8bef9SDimitry Andric   //   inst4                  region4
339e8d8bef9SDimitry Andric   //                          br block_after_outline
340e8d8bef9SDimitry Andric   //                        block_after_outline:
341e8d8bef9SDimitry Andric   //                          inst3
342e8d8bef9SDimitry Andric   //                          inst4
343e8d8bef9SDimitry Andric 
344e8d8bef9SDimitry Andric   std::string OriginalName = PrevBB->getName().str();
345e8d8bef9SDimitry Andric 
346e8d8bef9SDimitry Andric   StartBB = PrevBB->splitBasicBlock(StartInst, OriginalName + "_to_outline");
347349cc55cSDimitry Andric   PrevBB->replaceSuccessorsPhiUsesWith(PrevBB, StartBB);
34881ad6265SDimitry Andric   // If there was a PHINode with an incoming block outside the region,
34981ad6265SDimitry Andric   // make sure is correctly updated in the newly split block.
35081ad6265SDimitry Andric   if (PHIPredBlock)
35181ad6265SDimitry Andric     PrevBB->replaceSuccessorsPhiUsesWith(PHIPredBlock, PrevBB);
352e8d8bef9SDimitry Andric 
353e8d8bef9SDimitry Andric   CandidateSplit = true;
354349cc55cSDimitry Andric   if (!BackInst->isTerminator()) {
355349cc55cSDimitry Andric     EndBB = EndInst->getParent();
356349cc55cSDimitry Andric     FollowBB = EndBB->splitBasicBlock(EndInst, OriginalName + "_after_outline");
357349cc55cSDimitry Andric     EndBB->replaceSuccessorsPhiUsesWith(EndBB, FollowBB);
358349cc55cSDimitry Andric     FollowBB->replaceSuccessorsPhiUsesWith(PrevBB, FollowBB);
35904eeddc0SDimitry Andric   } else {
360349cc55cSDimitry Andric     EndBB = BackInst->getParent();
361349cc55cSDimitry Andric     EndsInBranch = true;
362349cc55cSDimitry Andric     FollowBB = nullptr;
363e8d8bef9SDimitry Andric   }
364e8d8bef9SDimitry Andric 
36504eeddc0SDimitry Andric   // Refind the basic block set.
36604eeddc0SDimitry Andric   BBSet.clear();
36704eeddc0SDimitry Andric   Candidate->getBasicBlocks(BBSet);
36804eeddc0SDimitry Andric   // For the phi nodes in the new starting basic block of the region, we
36904eeddc0SDimitry Andric   // reassign the targets of the basic blocks branching instructions.
37004eeddc0SDimitry Andric   replaceTargetsFromPHINode(StartBB, PrevBB, StartBB, BBSet);
37104eeddc0SDimitry Andric   if (FollowBB)
37204eeddc0SDimitry Andric     replaceTargetsFromPHINode(FollowBB, EndBB, FollowBB, BBSet);
37304eeddc0SDimitry Andric }
37404eeddc0SDimitry Andric 
375e8d8bef9SDimitry Andric void OutlinableRegion::reattachCandidate() {
376e8d8bef9SDimitry Andric   assert(CandidateSplit && "Candidate is not split!");
377e8d8bef9SDimitry Andric 
378e8d8bef9SDimitry Andric   // The basic block gets reattached like so:
379e8d8bef9SDimitry Andric   // block:                        block:
380e8d8bef9SDimitry Andric   //   inst1                         inst1
381e8d8bef9SDimitry Andric   //   inst2                         inst2
382e8d8bef9SDimitry Andric   //   br block_to_outline           region1
383e8d8bef9SDimitry Andric   // block_to_outline:        ->     region2
384e8d8bef9SDimitry Andric   //   region1                       region3
385e8d8bef9SDimitry Andric   //   region2                       region4
386e8d8bef9SDimitry Andric   //   region3                       inst3
387e8d8bef9SDimitry Andric   //   region4                       inst4
388e8d8bef9SDimitry Andric   //   br block_after_outline
389e8d8bef9SDimitry Andric   // block_after_outline:
390e8d8bef9SDimitry Andric   //   inst3
391e8d8bef9SDimitry Andric   //   inst4
392e8d8bef9SDimitry Andric   assert(StartBB != nullptr && "StartBB for Candidate is not defined!");
393e8d8bef9SDimitry Andric 
394e8d8bef9SDimitry Andric   assert(PrevBB->getTerminator() && "Terminator removed from PrevBB!");
39581ad6265SDimitry Andric   // Make sure PHINode references to the block we are merging into are
39681ad6265SDimitry Andric   // updated to be incoming blocks from the predecessor to the current block.
39781ad6265SDimitry Andric 
39881ad6265SDimitry Andric   // NOTE: If this is updated such that the outlined block can have more than
39981ad6265SDimitry Andric   // one incoming block to a PHINode, this logic will have to updated
40081ad6265SDimitry Andric   // to handle multiple precessors instead.
40181ad6265SDimitry Andric 
40281ad6265SDimitry Andric   // We only need to update this if the outlined section contains a PHINode, if
40381ad6265SDimitry Andric   // it does not, then the incoming block was never changed in the first place.
40481ad6265SDimitry Andric   // On the other hand, if PrevBB has no predecessors, it means that all
40581ad6265SDimitry Andric   // incoming blocks to the first block are contained in the region, and there
40681ad6265SDimitry Andric   // will be nothing to update.
40781ad6265SDimitry Andric   Instruction *StartInst = (*Candidate->begin()).Inst;
40881ad6265SDimitry Andric   if (isa<PHINode>(StartInst) && !PrevBB->hasNPredecessors(0)) {
40981ad6265SDimitry Andric     assert(!PrevBB->hasNPredecessorsOrMore(2) &&
41081ad6265SDimitry Andric          "PrevBB has more than one predecessor. Should be 0 or 1.");
41181ad6265SDimitry Andric     BasicBlock *BeforePrevBB = PrevBB->getSinglePredecessor();
41281ad6265SDimitry Andric     PrevBB->replaceSuccessorsPhiUsesWith(PrevBB, BeforePrevBB);
41381ad6265SDimitry Andric   }
414e8d8bef9SDimitry Andric   PrevBB->getTerminator()->eraseFromParent();
415e8d8bef9SDimitry Andric 
41604eeddc0SDimitry Andric   // If we reattaching after outlining, we iterate over the phi nodes to
41704eeddc0SDimitry Andric   // the initial block, and reassign the branch instructions of the incoming
41804eeddc0SDimitry Andric   // blocks to the block we are remerging into.
41904eeddc0SDimitry Andric   if (!ExtractedFunction) {
42004eeddc0SDimitry Andric     DenseSet<BasicBlock *> BBSet;
42104eeddc0SDimitry Andric     Candidate->getBasicBlocks(BBSet);
42204eeddc0SDimitry Andric 
42304eeddc0SDimitry Andric     replaceTargetsFromPHINode(StartBB, StartBB, PrevBB, BBSet);
42404eeddc0SDimitry Andric     if (!EndsInBranch)
42504eeddc0SDimitry Andric       replaceTargetsFromPHINode(FollowBB, FollowBB, EndBB, BBSet);
42604eeddc0SDimitry Andric   }
42704eeddc0SDimitry Andric 
428e8d8bef9SDimitry Andric   moveBBContents(*StartBB, *PrevBB);
429e8d8bef9SDimitry Andric 
430e8d8bef9SDimitry Andric   BasicBlock *PlacementBB = PrevBB;
431e8d8bef9SDimitry Andric   if (StartBB != EndBB)
432e8d8bef9SDimitry Andric     PlacementBB = EndBB;
433349cc55cSDimitry Andric   if (!EndsInBranch && PlacementBB->getUniqueSuccessor() != nullptr) {
434349cc55cSDimitry Andric     assert(FollowBB != nullptr && "FollowBB for Candidate is not defined!");
435349cc55cSDimitry Andric     assert(PlacementBB->getTerminator() && "Terminator removed from EndBB!");
436349cc55cSDimitry Andric     PlacementBB->getTerminator()->eraseFromParent();
437e8d8bef9SDimitry Andric     moveBBContents(*FollowBB, *PlacementBB);
438349cc55cSDimitry Andric     PlacementBB->replaceSuccessorsPhiUsesWith(FollowBB, PlacementBB);
439349cc55cSDimitry Andric     FollowBB->eraseFromParent();
440349cc55cSDimitry Andric   }
441e8d8bef9SDimitry Andric 
442e8d8bef9SDimitry Andric   PrevBB->replaceSuccessorsPhiUsesWith(StartBB, PrevBB);
443e8d8bef9SDimitry Andric   StartBB->eraseFromParent();
444e8d8bef9SDimitry Andric 
445e8d8bef9SDimitry Andric   // Make sure to save changes back to the StartBB.
446e8d8bef9SDimitry Andric   StartBB = PrevBB;
447e8d8bef9SDimitry Andric   EndBB = nullptr;
448e8d8bef9SDimitry Andric   PrevBB = nullptr;
449e8d8bef9SDimitry Andric   FollowBB = nullptr;
450e8d8bef9SDimitry Andric 
451e8d8bef9SDimitry Andric   CandidateSplit = false;
452e8d8bef9SDimitry Andric }
453e8d8bef9SDimitry Andric 
454e8d8bef9SDimitry Andric /// Find whether \p V matches the Constants previously found for the \p GVN.
455e8d8bef9SDimitry Andric ///
456e8d8bef9SDimitry Andric /// \param V - The value to check for consistency.
457e8d8bef9SDimitry Andric /// \param GVN - The global value number assigned to \p V.
458e8d8bef9SDimitry Andric /// \param GVNToConstant - The mapping of global value number to Constants.
459e8d8bef9SDimitry Andric /// \returns true if the Value matches the Constant mapped to by V and false if
460e8d8bef9SDimitry Andric /// it \p V is a Constant but does not match.
461bdd1243dSDimitry Andric /// \returns std::nullopt if \p V is not a Constant.
462bdd1243dSDimitry Andric static std::optional<bool>
463e8d8bef9SDimitry Andric constantMatches(Value *V, unsigned GVN,
464e8d8bef9SDimitry Andric                 DenseMap<unsigned, Constant *> &GVNToConstant) {
465e8d8bef9SDimitry Andric   // See if we have a constants
466e8d8bef9SDimitry Andric   Constant *CST = dyn_cast<Constant>(V);
467e8d8bef9SDimitry Andric   if (!CST)
468bdd1243dSDimitry Andric     return std::nullopt;
469e8d8bef9SDimitry Andric 
470e8d8bef9SDimitry Andric   // Holds a mapping from a global value number to a Constant.
471e8d8bef9SDimitry Andric   DenseMap<unsigned, Constant *>::iterator GVNToConstantIt;
472e8d8bef9SDimitry Andric   bool Inserted;
473e8d8bef9SDimitry Andric 
474e8d8bef9SDimitry Andric 
475e8d8bef9SDimitry Andric   // If we have a constant, try to make a new entry in the GVNToConstant.
476e8d8bef9SDimitry Andric   std::tie(GVNToConstantIt, Inserted) =
477e8d8bef9SDimitry Andric       GVNToConstant.insert(std::make_pair(GVN, CST));
478e8d8bef9SDimitry Andric   // If it was found and is not equal, it is not the same. We do not
479e8d8bef9SDimitry Andric   // handle this case yet, and exit early.
480e8d8bef9SDimitry Andric   if (Inserted || (GVNToConstantIt->second == CST))
481e8d8bef9SDimitry Andric     return true;
482e8d8bef9SDimitry Andric 
483e8d8bef9SDimitry Andric   return false;
484e8d8bef9SDimitry Andric }
485e8d8bef9SDimitry Andric 
486e8d8bef9SDimitry Andric InstructionCost OutlinableRegion::getBenefit(TargetTransformInfo &TTI) {
487e8d8bef9SDimitry Andric   InstructionCost Benefit = 0;
488e8d8bef9SDimitry Andric 
489e8d8bef9SDimitry Andric   // Estimate the benefit of outlining a specific sections of the program.  We
490e8d8bef9SDimitry Andric   // delegate mostly this task to the TargetTransformInfo so that if the target
491e8d8bef9SDimitry Andric   // has specific changes, we can have a more accurate estimate.
492e8d8bef9SDimitry Andric 
493e8d8bef9SDimitry Andric   // However, getInstructionCost delegates the code size calculation for
494e8d8bef9SDimitry Andric   // arithmetic instructions to getArithmeticInstrCost in
495e8d8bef9SDimitry Andric   // include/Analysis/TargetTransformImpl.h, where it always estimates that the
496e8d8bef9SDimitry Andric   // code size for a division and remainder instruction to be equal to 4, and
497e8d8bef9SDimitry Andric   // everything else to 1.  This is not an accurate representation of the
498e8d8bef9SDimitry Andric   // division instruction for targets that have a native division instruction.
499e8d8bef9SDimitry Andric   // To be overly conservative, we only add 1 to the number of instructions for
500e8d8bef9SDimitry Andric   // each division instruction.
501349cc55cSDimitry Andric   for (IRInstructionData &ID : *Candidate) {
502349cc55cSDimitry Andric     Instruction *I = ID.Inst;
503349cc55cSDimitry Andric     switch (I->getOpcode()) {
504e8d8bef9SDimitry Andric     case Instruction::FDiv:
505e8d8bef9SDimitry Andric     case Instruction::FRem:
506e8d8bef9SDimitry Andric     case Instruction::SDiv:
507e8d8bef9SDimitry Andric     case Instruction::SRem:
508e8d8bef9SDimitry Andric     case Instruction::UDiv:
509e8d8bef9SDimitry Andric     case Instruction::URem:
510e8d8bef9SDimitry Andric       Benefit += 1;
511e8d8bef9SDimitry Andric       break;
512e8d8bef9SDimitry Andric     default:
513349cc55cSDimitry Andric       Benefit += TTI.getInstructionCost(I, TargetTransformInfo::TCK_CodeSize);
514e8d8bef9SDimitry Andric       break;
515e8d8bef9SDimitry Andric     }
516e8d8bef9SDimitry Andric   }
517e8d8bef9SDimitry Andric 
518e8d8bef9SDimitry Andric   return Benefit;
519e8d8bef9SDimitry Andric }
520e8d8bef9SDimitry Andric 
52104eeddc0SDimitry Andric /// Check the \p OutputMappings structure for value \p Input, if it exists
52204eeddc0SDimitry Andric /// it has been used as an output for outlining, and has been renamed, and we
52304eeddc0SDimitry Andric /// return the new value, otherwise, we return the same value.
52404eeddc0SDimitry Andric ///
52504eeddc0SDimitry Andric /// \param OutputMappings [in] - The mapping of values to their renamed value
52604eeddc0SDimitry Andric /// after being used as an output for an outlined region.
52704eeddc0SDimitry Andric /// \param Input [in] - The value to find the remapped value of, if it exists.
52804eeddc0SDimitry Andric /// \return The remapped value if it has been renamed, and the same value if has
52904eeddc0SDimitry Andric /// not.
53004eeddc0SDimitry Andric static Value *findOutputMapping(const DenseMap<Value *, Value *> OutputMappings,
53104eeddc0SDimitry Andric                                 Value *Input) {
53204eeddc0SDimitry Andric   DenseMap<Value *, Value *>::const_iterator OutputMapping =
53304eeddc0SDimitry Andric       OutputMappings.find(Input);
53404eeddc0SDimitry Andric   if (OutputMapping != OutputMappings.end())
53504eeddc0SDimitry Andric     return OutputMapping->second;
53604eeddc0SDimitry Andric   return Input;
53704eeddc0SDimitry Andric }
53804eeddc0SDimitry Andric 
539e8d8bef9SDimitry Andric /// Find whether \p Region matches the global value numbering to Constant
540e8d8bef9SDimitry Andric /// mapping found so far.
541e8d8bef9SDimitry Andric ///
542e8d8bef9SDimitry Andric /// \param Region - The OutlinableRegion we are checking for constants
543e8d8bef9SDimitry Andric /// \param GVNToConstant - The mapping of global value number to Constants.
544e8d8bef9SDimitry Andric /// \param NotSame - The set of global value numbers that do not have the same
545e8d8bef9SDimitry Andric /// constant in each region.
546e8d8bef9SDimitry Andric /// \returns true if all Constants are the same in every use of a Constant in \p
547e8d8bef9SDimitry Andric /// Region and false if not
548e8d8bef9SDimitry Andric static bool
549e8d8bef9SDimitry Andric collectRegionsConstants(OutlinableRegion &Region,
550e8d8bef9SDimitry Andric                         DenseMap<unsigned, Constant *> &GVNToConstant,
551e8d8bef9SDimitry Andric                         DenseSet<unsigned> &NotSame) {
552e8d8bef9SDimitry Andric   bool ConstantsTheSame = true;
553e8d8bef9SDimitry Andric 
554e8d8bef9SDimitry Andric   IRSimilarityCandidate &C = *Region.Candidate;
555e8d8bef9SDimitry Andric   for (IRInstructionData &ID : C) {
556e8d8bef9SDimitry Andric 
557e8d8bef9SDimitry Andric     // Iterate over the operands in an instruction. If the global value number,
558e8d8bef9SDimitry Andric     // assigned by the IRSimilarityCandidate, has been seen before, we check if
5595f757f3fSDimitry Andric     // the number has been found to be not the same value in each instance.
560e8d8bef9SDimitry Andric     for (Value *V : ID.OperVals) {
561bdd1243dSDimitry Andric       std::optional<unsigned> GVNOpt = C.getGVN(V);
56281ad6265SDimitry Andric       assert(GVNOpt && "Expected a GVN for operand?");
563bdd1243dSDimitry Andric       unsigned GVN = *GVNOpt;
564e8d8bef9SDimitry Andric 
565e8d8bef9SDimitry Andric       // Check if this global value has been found to not be the same already.
566e8d8bef9SDimitry Andric       if (NotSame.contains(GVN)) {
567e8d8bef9SDimitry Andric         if (isa<Constant>(V))
568e8d8bef9SDimitry Andric           ConstantsTheSame = false;
569e8d8bef9SDimitry Andric         continue;
570e8d8bef9SDimitry Andric       }
571e8d8bef9SDimitry Andric 
572e8d8bef9SDimitry Andric       // If it has been the same so far, we check the value for if the
573e8d8bef9SDimitry Andric       // associated Constant value match the previous instances of the same
574e8d8bef9SDimitry Andric       // global value number.  If the global value does not map to a Constant,
575e8d8bef9SDimitry Andric       // it is considered to not be the same value.
576bdd1243dSDimitry Andric       std::optional<bool> ConstantMatches =
577bdd1243dSDimitry Andric           constantMatches(V, GVN, GVNToConstant);
57881ad6265SDimitry Andric       if (ConstantMatches) {
579bdd1243dSDimitry Andric         if (*ConstantMatches)
580e8d8bef9SDimitry Andric           continue;
581e8d8bef9SDimitry Andric         else
582e8d8bef9SDimitry Andric           ConstantsTheSame = false;
583e8d8bef9SDimitry Andric       }
584e8d8bef9SDimitry Andric 
585e8d8bef9SDimitry Andric       // While this value is a register, it might not have been previously,
586e8d8bef9SDimitry Andric       // make sure we don't already have a constant mapped to this global value
587e8d8bef9SDimitry Andric       // number.
58806c3fb27SDimitry Andric       if (GVNToConstant.contains(GVN))
589e8d8bef9SDimitry Andric         ConstantsTheSame = false;
590e8d8bef9SDimitry Andric 
591e8d8bef9SDimitry Andric       NotSame.insert(GVN);
592e8d8bef9SDimitry Andric     }
593e8d8bef9SDimitry Andric   }
594e8d8bef9SDimitry Andric 
595e8d8bef9SDimitry Andric   return ConstantsTheSame;
596e8d8bef9SDimitry Andric }
597e8d8bef9SDimitry Andric 
598e8d8bef9SDimitry Andric void OutlinableGroup::findSameConstants(DenseSet<unsigned> &NotSame) {
599e8d8bef9SDimitry Andric   DenseMap<unsigned, Constant *> GVNToConstant;
600e8d8bef9SDimitry Andric 
601e8d8bef9SDimitry Andric   for (OutlinableRegion *Region : Regions)
602e8d8bef9SDimitry Andric     collectRegionsConstants(*Region, GVNToConstant, NotSame);
603e8d8bef9SDimitry Andric }
604e8d8bef9SDimitry Andric 
605e8d8bef9SDimitry Andric void OutlinableGroup::collectGVNStoreSets(Module &M) {
606e8d8bef9SDimitry Andric   for (OutlinableRegion *OS : Regions)
607e8d8bef9SDimitry Andric     OutputGVNCombinations.insert(OS->GVNStores);
608e8d8bef9SDimitry Andric 
609e8d8bef9SDimitry Andric   // We are adding an extracted argument to decide between which output path
610e8d8bef9SDimitry Andric   // to use in the basic block.  It is used in a switch statement and only
611e8d8bef9SDimitry Andric   // needs to be an integer.
612e8d8bef9SDimitry Andric   if (OutputGVNCombinations.size() > 1)
613e8d8bef9SDimitry Andric     ArgumentTypes.push_back(Type::getInt32Ty(M.getContext()));
614e8d8bef9SDimitry Andric }
615e8d8bef9SDimitry Andric 
616fe6060f1SDimitry Andric /// Get the subprogram if it exists for one of the outlined regions.
617fe6060f1SDimitry Andric ///
618fe6060f1SDimitry Andric /// \param [in] Group - The set of regions to find a subprogram for.
619fe6060f1SDimitry Andric /// \returns the subprogram if it exists, or nullptr.
620fe6060f1SDimitry Andric static DISubprogram *getSubprogramOrNull(OutlinableGroup &Group) {
621fe6060f1SDimitry Andric   for (OutlinableRegion *OS : Group.Regions)
622fe6060f1SDimitry Andric     if (Function *F = OS->Call->getFunction())
623fe6060f1SDimitry Andric       if (DISubprogram *SP = F->getSubprogram())
624fe6060f1SDimitry Andric         return SP;
625fe6060f1SDimitry Andric 
626fe6060f1SDimitry Andric   return nullptr;
627fe6060f1SDimitry Andric }
628fe6060f1SDimitry Andric 
629e8d8bef9SDimitry Andric Function *IROutliner::createFunction(Module &M, OutlinableGroup &Group,
630e8d8bef9SDimitry Andric                                      unsigned FunctionNameSuffix) {
631e8d8bef9SDimitry Andric   assert(!Group.OutlinedFunction && "Function is already defined!");
632e8d8bef9SDimitry Andric 
633349cc55cSDimitry Andric   Type *RetTy = Type::getVoidTy(M.getContext());
634349cc55cSDimitry Andric   // All extracted functions _should_ have the same return type at this point
635349cc55cSDimitry Andric   // since the similarity identifier ensures that all branches outside of the
636349cc55cSDimitry Andric   // region occur in the same place.
637349cc55cSDimitry Andric 
638349cc55cSDimitry Andric   // NOTE: Should we ever move to the model that uses a switch at every point
639349cc55cSDimitry Andric   // needed, meaning that we could branch within the region or out, it is
640349cc55cSDimitry Andric   // possible that we will need to switch to using the most general case all of
641349cc55cSDimitry Andric   // the time.
642349cc55cSDimitry Andric   for (OutlinableRegion *R : Group.Regions) {
643349cc55cSDimitry Andric     Type *ExtractedFuncType = R->ExtractedFunction->getReturnType();
644349cc55cSDimitry Andric     if ((RetTy->isVoidTy() && !ExtractedFuncType->isVoidTy()) ||
645349cc55cSDimitry Andric         (RetTy->isIntegerTy(1) && ExtractedFuncType->isIntegerTy(16)))
646349cc55cSDimitry Andric       RetTy = ExtractedFuncType;
647349cc55cSDimitry Andric   }
648349cc55cSDimitry Andric 
649e8d8bef9SDimitry Andric   Group.OutlinedFunctionType = FunctionType::get(
650349cc55cSDimitry Andric       RetTy, Group.ArgumentTypes, false);
651e8d8bef9SDimitry Andric 
652e8d8bef9SDimitry Andric   // These functions will only be called from within the same module, so
653e8d8bef9SDimitry Andric   // we can set an internal linkage.
654e8d8bef9SDimitry Andric   Group.OutlinedFunction = Function::Create(
655e8d8bef9SDimitry Andric       Group.OutlinedFunctionType, GlobalValue::InternalLinkage,
656e8d8bef9SDimitry Andric       "outlined_ir_func_" + std::to_string(FunctionNameSuffix), M);
657e8d8bef9SDimitry Andric 
658e8d8bef9SDimitry Andric   // Transfer the swifterr attribute to the correct function parameter.
65981ad6265SDimitry Andric   if (Group.SwiftErrorArgument)
660bdd1243dSDimitry Andric     Group.OutlinedFunction->addParamAttr(*Group.SwiftErrorArgument,
661e8d8bef9SDimitry Andric                                          Attribute::SwiftError);
662e8d8bef9SDimitry Andric 
663e8d8bef9SDimitry Andric   Group.OutlinedFunction->addFnAttr(Attribute::OptimizeForSize);
664e8d8bef9SDimitry Andric   Group.OutlinedFunction->addFnAttr(Attribute::MinSize);
665e8d8bef9SDimitry Andric 
666fe6060f1SDimitry Andric   // If there's a DISubprogram associated with this outlined function, then
667fe6060f1SDimitry Andric   // emit debug info for the outlined function.
668fe6060f1SDimitry Andric   if (DISubprogram *SP = getSubprogramOrNull(Group)) {
669fe6060f1SDimitry Andric     Function *F = Group.OutlinedFunction;
670fe6060f1SDimitry Andric     // We have a DISubprogram. Get its DICompileUnit.
671fe6060f1SDimitry Andric     DICompileUnit *CU = SP->getUnit();
672fe6060f1SDimitry Andric     DIBuilder DB(M, true, CU);
673fe6060f1SDimitry Andric     DIFile *Unit = SP->getFile();
674fe6060f1SDimitry Andric     Mangler Mg;
675fe6060f1SDimitry Andric     // Get the mangled name of the function for the linkage name.
676fe6060f1SDimitry Andric     std::string Dummy;
677fe6060f1SDimitry Andric     llvm::raw_string_ostream MangledNameStream(Dummy);
678fe6060f1SDimitry Andric     Mg.getNameWithPrefix(MangledNameStream, F, false);
679fe6060f1SDimitry Andric 
680fe6060f1SDimitry Andric     DISubprogram *OutlinedSP = DB.createFunction(
681*0fca6ea1SDimitry Andric         Unit /* Context */, F->getName(), Dummy,
682fe6060f1SDimitry Andric         Unit /* File */,
683fe6060f1SDimitry Andric         0 /* Line 0 is reserved for compiler-generated code. */,
684bdd1243dSDimitry Andric         DB.createSubroutineType(
685bdd1243dSDimitry Andric             DB.getOrCreateTypeArray(std::nullopt)), /* void type */
686fe6060f1SDimitry Andric         0, /* Line 0 is reserved for compiler-generated code. */
687fe6060f1SDimitry Andric         DINode::DIFlags::FlagArtificial /* Compiler-generated code. */,
688fe6060f1SDimitry Andric         /* Outlined code is optimized code by definition. */
689fe6060f1SDimitry Andric         DISubprogram::SPFlagDefinition | DISubprogram::SPFlagOptimized);
690fe6060f1SDimitry Andric 
691fe6060f1SDimitry Andric     // Don't add any new variables to the subprogram.
692fe6060f1SDimitry Andric     DB.finalizeSubprogram(OutlinedSP);
693fe6060f1SDimitry Andric 
694fe6060f1SDimitry Andric     // Attach subprogram to the function.
695fe6060f1SDimitry Andric     F->setSubprogram(OutlinedSP);
696fe6060f1SDimitry Andric     // We're done with the DIBuilder.
697fe6060f1SDimitry Andric     DB.finalize();
698fe6060f1SDimitry Andric   }
699fe6060f1SDimitry Andric 
700e8d8bef9SDimitry Andric   return Group.OutlinedFunction;
701e8d8bef9SDimitry Andric }
702e8d8bef9SDimitry Andric 
703e8d8bef9SDimitry Andric /// Move each BasicBlock in \p Old to \p New.
704e8d8bef9SDimitry Andric ///
705fe6060f1SDimitry Andric /// \param [in] Old - The function to move the basic blocks from.
706e8d8bef9SDimitry Andric /// \param [in] New - The function to move the basic blocks to.
707349cc55cSDimitry Andric /// \param [out] NewEnds - The return blocks of the new overall function.
708349cc55cSDimitry Andric static void moveFunctionData(Function &Old, Function &New,
709349cc55cSDimitry Andric                              DenseMap<Value *, BasicBlock *> &NewEnds) {
710349cc55cSDimitry Andric   for (BasicBlock &CurrBB : llvm::make_early_inc_range(Old)) {
711349cc55cSDimitry Andric     CurrBB.removeFromParent();
712349cc55cSDimitry Andric     CurrBB.insertInto(&New);
713349cc55cSDimitry Andric     Instruction *I = CurrBB.getTerminator();
714fe6060f1SDimitry Andric 
715349cc55cSDimitry Andric     // For each block we find a return instruction is, it is a potential exit
716349cc55cSDimitry Andric     // path for the function.  We keep track of each block based on the return
717349cc55cSDimitry Andric     // value here.
718349cc55cSDimitry Andric     if (ReturnInst *RI = dyn_cast<ReturnInst>(I))
719349cc55cSDimitry Andric       NewEnds.insert(std::make_pair(RI->getReturnValue(), &CurrBB));
720349cc55cSDimitry Andric 
721349cc55cSDimitry Andric     std::vector<Instruction *> DebugInsts;
722349cc55cSDimitry Andric 
723349cc55cSDimitry Andric     for (Instruction &Val : CurrBB) {
724*0fca6ea1SDimitry Andric       // Since debug-info originates from many different locations in the
725*0fca6ea1SDimitry Andric       // program, it will cause incorrect reporting from a debugger if we keep
726*0fca6ea1SDimitry Andric       // the same debug instructions. Drop non-intrinsic DbgVariableRecords
727*0fca6ea1SDimitry Andric       // here, collect intrinsics for removal later.
728*0fca6ea1SDimitry Andric       Val.dropDbgRecords();
729*0fca6ea1SDimitry Andric 
730fe6060f1SDimitry Andric       // We must handle the scoping of called functions differently than
731fe6060f1SDimitry Andric       // other outlined instructions.
732fe6060f1SDimitry Andric       if (!isa<CallInst>(&Val)) {
733fe6060f1SDimitry Andric         // Remove the debug information for outlined functions.
734fe6060f1SDimitry Andric         Val.setDebugLoc(DebugLoc());
73581ad6265SDimitry Andric 
73681ad6265SDimitry Andric         // Loop info metadata may contain line locations. Update them to have no
73781ad6265SDimitry Andric         // value in the new subprogram since the outlined code could be from
73881ad6265SDimitry Andric         // several locations.
73981ad6265SDimitry Andric         auto updateLoopInfoLoc = [&New](Metadata *MD) -> Metadata * {
74081ad6265SDimitry Andric           if (DISubprogram *SP = New.getSubprogram())
74181ad6265SDimitry Andric             if (auto *Loc = dyn_cast_or_null<DILocation>(MD))
74281ad6265SDimitry Andric               return DILocation::get(New.getContext(), Loc->getLine(),
74381ad6265SDimitry Andric                                      Loc->getColumn(), SP, nullptr);
74481ad6265SDimitry Andric           return MD;
74581ad6265SDimitry Andric         };
74681ad6265SDimitry Andric         updateLoopMetadataDebugLocations(Val, updateLoopInfoLoc);
747fe6060f1SDimitry Andric         continue;
748fe6060f1SDimitry Andric       }
749fe6060f1SDimitry Andric 
750fe6060f1SDimitry Andric       // From this point we are only handling call instructions.
751fe6060f1SDimitry Andric       CallInst *CI = cast<CallInst>(&Val);
752fe6060f1SDimitry Andric 
753*0fca6ea1SDimitry Andric       // Collect debug intrinsics for later removal.
754fe6060f1SDimitry Andric       if (isa<DbgInfoIntrinsic>(CI)) {
755fe6060f1SDimitry Andric         DebugInsts.push_back(&Val);
756fe6060f1SDimitry Andric         continue;
757fe6060f1SDimitry Andric       }
758fe6060f1SDimitry Andric 
759fe6060f1SDimitry Andric       // Edit the scope of called functions inside of outlined functions.
760fe6060f1SDimitry Andric       if (DISubprogram *SP = New.getSubprogram()) {
761fe6060f1SDimitry Andric         DILocation *DI = DILocation::get(New.getContext(), 0, 0, SP);
762fe6060f1SDimitry Andric         Val.setDebugLoc(DI);
763fe6060f1SDimitry Andric       }
764fe6060f1SDimitry Andric     }
765fe6060f1SDimitry Andric 
766fe6060f1SDimitry Andric     for (Instruction *I : DebugInsts)
767fe6060f1SDimitry Andric       I->eraseFromParent();
768e8d8bef9SDimitry Andric   }
769e8d8bef9SDimitry Andric }
770e8d8bef9SDimitry Andric 
7715f757f3fSDimitry Andric /// Find the constants that will need to be lifted into arguments
772e8d8bef9SDimitry Andric /// as they are not the same in each instance of the region.
773e8d8bef9SDimitry Andric ///
774e8d8bef9SDimitry Andric /// \param [in] C - The IRSimilarityCandidate containing the region we are
775e8d8bef9SDimitry Andric /// analyzing.
776e8d8bef9SDimitry Andric /// \param [in] NotSame - The set of global value numbers that do not have a
777e8d8bef9SDimitry Andric /// single Constant across all OutlinableRegions similar to \p C.
778e8d8bef9SDimitry Andric /// \param [out] Inputs - The list containing the global value numbers of the
779e8d8bef9SDimitry Andric /// arguments needed for the region of code.
780e8d8bef9SDimitry Andric static void findConstants(IRSimilarityCandidate &C, DenseSet<unsigned> &NotSame,
781e8d8bef9SDimitry Andric                           std::vector<unsigned> &Inputs) {
782e8d8bef9SDimitry Andric   DenseSet<unsigned> Seen;
783e8d8bef9SDimitry Andric   // Iterate over the instructions, and find what constants will need to be
784e8d8bef9SDimitry Andric   // extracted into arguments.
785e8d8bef9SDimitry Andric   for (IRInstructionDataList::iterator IDIt = C.begin(), EndIDIt = C.end();
786e8d8bef9SDimitry Andric        IDIt != EndIDIt; IDIt++) {
787e8d8bef9SDimitry Andric     for (Value *V : (*IDIt).OperVals) {
788e8d8bef9SDimitry Andric       // Since these are stored before any outlining, they will be in the
789e8d8bef9SDimitry Andric       // global value numbering.
79081ad6265SDimitry Andric       unsigned GVN = *C.getGVN(V);
791e8d8bef9SDimitry Andric       if (isa<Constant>(V))
792e8d8bef9SDimitry Andric         if (NotSame.contains(GVN) && !Seen.contains(GVN)) {
793e8d8bef9SDimitry Andric           Inputs.push_back(GVN);
794e8d8bef9SDimitry Andric           Seen.insert(GVN);
795e8d8bef9SDimitry Andric         }
796e8d8bef9SDimitry Andric     }
797e8d8bef9SDimitry Andric   }
798e8d8bef9SDimitry Andric }
799e8d8bef9SDimitry Andric 
800e8d8bef9SDimitry Andric /// Find the GVN for the inputs that have been found by the CodeExtractor.
801e8d8bef9SDimitry Andric ///
802e8d8bef9SDimitry Andric /// \param [in] C - The IRSimilarityCandidate containing the region we are
803e8d8bef9SDimitry Andric /// analyzing.
804e8d8bef9SDimitry Andric /// \param [in] CurrentInputs - The set of inputs found by the
805e8d8bef9SDimitry Andric /// CodeExtractor.
806e8d8bef9SDimitry Andric /// \param [in] OutputMappings - The mapping of values that have been replaced
807e8d8bef9SDimitry Andric /// by a new output value.
808fe6060f1SDimitry Andric /// \param [out] EndInputNumbers - The global value numbers for the extracted
809e8d8bef9SDimitry Andric /// arguments.
810e8d8bef9SDimitry Andric static void mapInputsToGVNs(IRSimilarityCandidate &C,
811e8d8bef9SDimitry Andric                             SetVector<Value *> &CurrentInputs,
812e8d8bef9SDimitry Andric                             const DenseMap<Value *, Value *> &OutputMappings,
813e8d8bef9SDimitry Andric                             std::vector<unsigned> &EndInputNumbers) {
814e8d8bef9SDimitry Andric   // Get the Global Value Number for each input.  We check if the Value has been
815e8d8bef9SDimitry Andric   // replaced by a different value at output, and use the original value before
816e8d8bef9SDimitry Andric   // replacement.
817e8d8bef9SDimitry Andric   for (Value *Input : CurrentInputs) {
818e8d8bef9SDimitry Andric     assert(Input && "Have a nullptr as an input");
81906c3fb27SDimitry Andric     if (OutputMappings.contains(Input))
820e8d8bef9SDimitry Andric       Input = OutputMappings.find(Input)->second;
82181ad6265SDimitry Andric     assert(C.getGVN(Input) && "Could not find a numbering for the given input");
822bdd1243dSDimitry Andric     EndInputNumbers.push_back(*C.getGVN(Input));
823e8d8bef9SDimitry Andric   }
824e8d8bef9SDimitry Andric }
825e8d8bef9SDimitry Andric 
826e8d8bef9SDimitry Andric /// Find the original value for the \p ArgInput values if any one of them was
827e8d8bef9SDimitry Andric /// replaced during a previous extraction.
828e8d8bef9SDimitry Andric ///
829e8d8bef9SDimitry Andric /// \param [in] ArgInputs - The inputs to be extracted by the code extractor.
830e8d8bef9SDimitry Andric /// \param [in] OutputMappings - The mapping of values that have been replaced
831e8d8bef9SDimitry Andric /// by a new output value.
832e8d8bef9SDimitry Andric /// \param [out] RemappedArgInputs - The remapped values according to
833e8d8bef9SDimitry Andric /// \p OutputMappings that will be extracted.
834e8d8bef9SDimitry Andric static void
835e8d8bef9SDimitry Andric remapExtractedInputs(const ArrayRef<Value *> ArgInputs,
836e8d8bef9SDimitry Andric                      const DenseMap<Value *, Value *> &OutputMappings,
837e8d8bef9SDimitry Andric                      SetVector<Value *> &RemappedArgInputs) {
838e8d8bef9SDimitry Andric   // Get the global value number for each input that will be extracted as an
839e8d8bef9SDimitry Andric   // argument by the code extractor, remapping if needed for reloaded values.
840e8d8bef9SDimitry Andric   for (Value *Input : ArgInputs) {
84106c3fb27SDimitry Andric     if (OutputMappings.contains(Input))
842e8d8bef9SDimitry Andric       Input = OutputMappings.find(Input)->second;
843e8d8bef9SDimitry Andric     RemappedArgInputs.insert(Input);
844e8d8bef9SDimitry Andric   }
845e8d8bef9SDimitry Andric }
846e8d8bef9SDimitry Andric 
847e8d8bef9SDimitry Andric /// Find the input GVNs and the output values for a region of Instructions.
848e8d8bef9SDimitry Andric /// Using the code extractor, we collect the inputs to the extracted function.
849e8d8bef9SDimitry Andric ///
850e8d8bef9SDimitry Andric /// The \p Region can be identified as needing to be ignored in this function.
851e8d8bef9SDimitry Andric /// It should be checked whether it should be ignored after a call to this
852e8d8bef9SDimitry Andric /// function.
853e8d8bef9SDimitry Andric ///
854e8d8bef9SDimitry Andric /// \param [in,out] Region - The region of code to be analyzed.
855e8d8bef9SDimitry Andric /// \param [out] InputGVNs - The global value numbers for the extracted
856e8d8bef9SDimitry Andric /// arguments.
857e8d8bef9SDimitry Andric /// \param [in] NotSame - The global value numbers in the region that do not
858e8d8bef9SDimitry Andric /// have the same constant value in the regions structurally similar to
859e8d8bef9SDimitry Andric /// \p Region.
860e8d8bef9SDimitry Andric /// \param [in] OutputMappings - The mapping of values that have been replaced
861e8d8bef9SDimitry Andric /// by a new output value after extraction.
862e8d8bef9SDimitry Andric /// \param [out] ArgInputs - The values of the inputs to the extracted function.
863e8d8bef9SDimitry Andric /// \param [out] Outputs - The set of values extracted by the CodeExtractor
864e8d8bef9SDimitry Andric /// as outputs.
865e8d8bef9SDimitry Andric static void getCodeExtractorArguments(
866e8d8bef9SDimitry Andric     OutlinableRegion &Region, std::vector<unsigned> &InputGVNs,
867e8d8bef9SDimitry Andric     DenseSet<unsigned> &NotSame, DenseMap<Value *, Value *> &OutputMappings,
868e8d8bef9SDimitry Andric     SetVector<Value *> &ArgInputs, SetVector<Value *> &Outputs) {
869e8d8bef9SDimitry Andric   IRSimilarityCandidate &C = *Region.Candidate;
870e8d8bef9SDimitry Andric 
871e8d8bef9SDimitry Andric   // OverallInputs are the inputs to the region found by the CodeExtractor,
872e8d8bef9SDimitry Andric   // SinkCands and HoistCands are used by the CodeExtractor to find sunken
873e8d8bef9SDimitry Andric   // allocas of values whose lifetimes are contained completely within the
874e8d8bef9SDimitry Andric   // outlined region. PremappedInputs are the arguments found by the
875e8d8bef9SDimitry Andric   // CodeExtractor, removing conditions such as sunken allocas, but that
876e8d8bef9SDimitry Andric   // may need to be remapped due to the extracted output values replacing
877e8d8bef9SDimitry Andric   // the original values. We use DummyOutputs for this first run of finding
878e8d8bef9SDimitry Andric   // inputs and outputs since the outputs could change during findAllocas,
879e8d8bef9SDimitry Andric   // the correct set of extracted outputs will be in the final Outputs ValueSet.
880e8d8bef9SDimitry Andric   SetVector<Value *> OverallInputs, PremappedInputs, SinkCands, HoistCands,
881e8d8bef9SDimitry Andric       DummyOutputs;
882e8d8bef9SDimitry Andric 
883e8d8bef9SDimitry Andric   // Use the code extractor to get the inputs and outputs, without sunken
884e8d8bef9SDimitry Andric   // allocas or removing llvm.assumes.
885e8d8bef9SDimitry Andric   CodeExtractor *CE = Region.CE;
886e8d8bef9SDimitry Andric   CE->findInputsOutputs(OverallInputs, DummyOutputs, SinkCands);
887e8d8bef9SDimitry Andric   assert(Region.StartBB && "Region must have a start BasicBlock!");
888e8d8bef9SDimitry Andric   Function *OrigF = Region.StartBB->getParent();
889e8d8bef9SDimitry Andric   CodeExtractorAnalysisCache CEAC(*OrigF);
890e8d8bef9SDimitry Andric   BasicBlock *Dummy = nullptr;
891e8d8bef9SDimitry Andric 
892e8d8bef9SDimitry Andric   // The region may be ineligible due to VarArgs in the parent function. In this
893e8d8bef9SDimitry Andric   // case we ignore the region.
894e8d8bef9SDimitry Andric   if (!CE->isEligible()) {
895e8d8bef9SDimitry Andric     Region.IgnoreRegion = true;
896e8d8bef9SDimitry Andric     return;
897e8d8bef9SDimitry Andric   }
898e8d8bef9SDimitry Andric 
899e8d8bef9SDimitry Andric   // Find if any values are going to be sunk into the function when extracted
900e8d8bef9SDimitry Andric   CE->findAllocas(CEAC, SinkCands, HoistCands, Dummy);
901e8d8bef9SDimitry Andric   CE->findInputsOutputs(PremappedInputs, Outputs, SinkCands);
902e8d8bef9SDimitry Andric 
903e8d8bef9SDimitry Andric   // TODO: Support regions with sunken allocas: values whose lifetimes are
904e8d8bef9SDimitry Andric   // contained completely within the outlined region.  These are not guaranteed
905e8d8bef9SDimitry Andric   // to be the same in every region, so we must elevate them all to arguments
906e8d8bef9SDimitry Andric   // when they appear.  If these values are not equal, it means there is some
907e8d8bef9SDimitry Andric   // Input in OverallInputs that was removed for ArgInputs.
908e8d8bef9SDimitry Andric   if (OverallInputs.size() != PremappedInputs.size()) {
909e8d8bef9SDimitry Andric     Region.IgnoreRegion = true;
910e8d8bef9SDimitry Andric     return;
911e8d8bef9SDimitry Andric   }
912e8d8bef9SDimitry Andric 
913e8d8bef9SDimitry Andric   findConstants(C, NotSame, InputGVNs);
914e8d8bef9SDimitry Andric 
915e8d8bef9SDimitry Andric   mapInputsToGVNs(C, OverallInputs, OutputMappings, InputGVNs);
916e8d8bef9SDimitry Andric 
917e8d8bef9SDimitry Andric   remapExtractedInputs(PremappedInputs.getArrayRef(), OutputMappings,
918e8d8bef9SDimitry Andric                        ArgInputs);
919e8d8bef9SDimitry Andric 
920e8d8bef9SDimitry Andric   // Sort the GVNs, since we now have constants included in the \ref InputGVNs
921e8d8bef9SDimitry Andric   // we need to make sure they are in a deterministic order.
922e8d8bef9SDimitry Andric   stable_sort(InputGVNs);
923e8d8bef9SDimitry Andric }
924e8d8bef9SDimitry Andric 
925e8d8bef9SDimitry Andric /// Look over the inputs and map each input argument to an argument in the
926e8d8bef9SDimitry Andric /// overall function for the OutlinableRegions.  This creates a way to replace
927e8d8bef9SDimitry Andric /// the arguments of the extracted function with the arguments of the new
928e8d8bef9SDimitry Andric /// overall function.
929e8d8bef9SDimitry Andric ///
930e8d8bef9SDimitry Andric /// \param [in,out] Region - The region of code to be analyzed.
931fe6060f1SDimitry Andric /// \param [in] InputGVNs - The global value numbering of the input values
932e8d8bef9SDimitry Andric /// collected.
933e8d8bef9SDimitry Andric /// \param [in] ArgInputs - The values of the arguments to the extracted
934e8d8bef9SDimitry Andric /// function.
935e8d8bef9SDimitry Andric static void
936e8d8bef9SDimitry Andric findExtractedInputToOverallInputMapping(OutlinableRegion &Region,
937e8d8bef9SDimitry Andric                                         std::vector<unsigned> &InputGVNs,
938e8d8bef9SDimitry Andric                                         SetVector<Value *> &ArgInputs) {
939e8d8bef9SDimitry Andric 
940e8d8bef9SDimitry Andric   IRSimilarityCandidate &C = *Region.Candidate;
941e8d8bef9SDimitry Andric   OutlinableGroup &Group = *Region.Parent;
942e8d8bef9SDimitry Andric 
943e8d8bef9SDimitry Andric   // This counts the argument number in the overall function.
944e8d8bef9SDimitry Andric   unsigned TypeIndex = 0;
945e8d8bef9SDimitry Andric 
946e8d8bef9SDimitry Andric   // This counts the argument number in the extracted function.
947e8d8bef9SDimitry Andric   unsigned OriginalIndex = 0;
948e8d8bef9SDimitry Andric 
949e8d8bef9SDimitry Andric   // Find the mapping of the extracted arguments to the arguments for the
950e8d8bef9SDimitry Andric   // overall function. Since there may be extra arguments in the overall
951e8d8bef9SDimitry Andric   // function to account for the extracted constants, we have two different
952e8d8bef9SDimitry Andric   // counters as we find extracted arguments, and as we come across overall
953e8d8bef9SDimitry Andric   // arguments.
954349cc55cSDimitry Andric 
955349cc55cSDimitry Andric   // Additionally, in our first pass, for the first extracted function,
956349cc55cSDimitry Andric   // we find argument locations for the canonical value numbering.  This
957349cc55cSDimitry Andric   // numbering overrides any discovered location for the extracted code.
958e8d8bef9SDimitry Andric   for (unsigned InputVal : InputGVNs) {
959bdd1243dSDimitry Andric     std::optional<unsigned> CanonicalNumberOpt = C.getCanonicalNum(InputVal);
96081ad6265SDimitry Andric     assert(CanonicalNumberOpt && "Canonical number not found?");
961bdd1243dSDimitry Andric     unsigned CanonicalNumber = *CanonicalNumberOpt;
962349cc55cSDimitry Andric 
963bdd1243dSDimitry Andric     std::optional<Value *> InputOpt = C.fromGVN(InputVal);
96481ad6265SDimitry Andric     assert(InputOpt && "Global value number not found?");
965bdd1243dSDimitry Andric     Value *Input = *InputOpt;
966e8d8bef9SDimitry Andric 
967349cc55cSDimitry Andric     DenseMap<unsigned, unsigned>::iterator AggArgIt =
968349cc55cSDimitry Andric         Group.CanonicalNumberToAggArg.find(CanonicalNumber);
969349cc55cSDimitry Andric 
970e8d8bef9SDimitry Andric     if (!Group.InputTypesSet) {
971e8d8bef9SDimitry Andric       Group.ArgumentTypes.push_back(Input->getType());
972e8d8bef9SDimitry Andric       // If the input value has a swifterr attribute, make sure to mark the
973e8d8bef9SDimitry Andric       // argument in the overall function.
974e8d8bef9SDimitry Andric       if (Input->isSwiftError()) {
975e8d8bef9SDimitry Andric         assert(
97681ad6265SDimitry Andric             !Group.SwiftErrorArgument &&
977e8d8bef9SDimitry Andric             "Argument already marked with swifterr for this OutlinableGroup!");
978e8d8bef9SDimitry Andric         Group.SwiftErrorArgument = TypeIndex;
979e8d8bef9SDimitry Andric       }
980e8d8bef9SDimitry Andric     }
981e8d8bef9SDimitry Andric 
982e8d8bef9SDimitry Andric     // Check if we have a constant. If we do add it to the overall argument
983e8d8bef9SDimitry Andric     // number to Constant map for the region, and continue to the next input.
984e8d8bef9SDimitry Andric     if (Constant *CST = dyn_cast<Constant>(Input)) {
985349cc55cSDimitry Andric       if (AggArgIt != Group.CanonicalNumberToAggArg.end())
986349cc55cSDimitry Andric         Region.AggArgToConstant.insert(std::make_pair(AggArgIt->second, CST));
987349cc55cSDimitry Andric       else {
988349cc55cSDimitry Andric         Group.CanonicalNumberToAggArg.insert(
989349cc55cSDimitry Andric             std::make_pair(CanonicalNumber, TypeIndex));
990e8d8bef9SDimitry Andric         Region.AggArgToConstant.insert(std::make_pair(TypeIndex, CST));
991349cc55cSDimitry Andric       }
992e8d8bef9SDimitry Andric       TypeIndex++;
993e8d8bef9SDimitry Andric       continue;
994e8d8bef9SDimitry Andric     }
995e8d8bef9SDimitry Andric 
996e8d8bef9SDimitry Andric     // It is not a constant, we create the mapping from extracted argument list
997349cc55cSDimitry Andric     // to the overall argument list, using the canonical location, if it exists.
998e8d8bef9SDimitry Andric     assert(ArgInputs.count(Input) && "Input cannot be found!");
999e8d8bef9SDimitry Andric 
1000349cc55cSDimitry Andric     if (AggArgIt != Group.CanonicalNumberToAggArg.end()) {
1001349cc55cSDimitry Andric       if (OriginalIndex != AggArgIt->second)
1002349cc55cSDimitry Andric         Region.ChangedArgOrder = true;
1003349cc55cSDimitry Andric       Region.ExtractedArgToAgg.insert(
1004349cc55cSDimitry Andric           std::make_pair(OriginalIndex, AggArgIt->second));
1005349cc55cSDimitry Andric       Region.AggArgToExtracted.insert(
1006349cc55cSDimitry Andric           std::make_pair(AggArgIt->second, OriginalIndex));
1007349cc55cSDimitry Andric     } else {
1008349cc55cSDimitry Andric       Group.CanonicalNumberToAggArg.insert(
1009349cc55cSDimitry Andric           std::make_pair(CanonicalNumber, TypeIndex));
1010e8d8bef9SDimitry Andric       Region.ExtractedArgToAgg.insert(std::make_pair(OriginalIndex, TypeIndex));
1011e8d8bef9SDimitry Andric       Region.AggArgToExtracted.insert(std::make_pair(TypeIndex, OriginalIndex));
1012349cc55cSDimitry Andric     }
1013e8d8bef9SDimitry Andric     OriginalIndex++;
1014e8d8bef9SDimitry Andric     TypeIndex++;
1015e8d8bef9SDimitry Andric   }
1016e8d8bef9SDimitry Andric 
1017e8d8bef9SDimitry Andric   // If the function type definitions for the OutlinableGroup holding the region
1018e8d8bef9SDimitry Andric   // have not been set, set the length of the inputs here.  We should have the
1019e8d8bef9SDimitry Andric   // same inputs for all of the different regions contained in the
1020e8d8bef9SDimitry Andric   // OutlinableGroup since they are all structurally similar to one another.
1021e8d8bef9SDimitry Andric   if (!Group.InputTypesSet) {
1022e8d8bef9SDimitry Andric     Group.NumAggregateInputs = TypeIndex;
1023e8d8bef9SDimitry Andric     Group.InputTypesSet = true;
1024e8d8bef9SDimitry Andric   }
1025e8d8bef9SDimitry Andric 
1026e8d8bef9SDimitry Andric   Region.NumExtractedInputs = OriginalIndex;
1027e8d8bef9SDimitry Andric }
1028e8d8bef9SDimitry Andric 
102904eeddc0SDimitry Andric /// Check if the \p V has any uses outside of the region other than \p PN.
103004eeddc0SDimitry Andric ///
103104eeddc0SDimitry Andric /// \param V [in] - The value to check.
103204eeddc0SDimitry Andric /// \param PHILoc [in] - The location in the PHINode of \p V.
103304eeddc0SDimitry Andric /// \param PN [in] - The PHINode using \p V.
103404eeddc0SDimitry Andric /// \param Exits [in] - The potential blocks we exit to from the outlined
103504eeddc0SDimitry Andric /// region.
103604eeddc0SDimitry Andric /// \param BlocksInRegion [in] - The basic blocks contained in the region.
103704eeddc0SDimitry Andric /// \returns true if \p V has any use soutside its region other than \p PN.
103804eeddc0SDimitry Andric static bool outputHasNonPHI(Value *V, unsigned PHILoc, PHINode &PN,
103904eeddc0SDimitry Andric                             SmallPtrSet<BasicBlock *, 1> &Exits,
104004eeddc0SDimitry Andric                             DenseSet<BasicBlock *> &BlocksInRegion) {
104104eeddc0SDimitry Andric   // We check to see if the value is used by the PHINode from some other
104204eeddc0SDimitry Andric   // predecessor not included in the region.  If it is, we make sure
104304eeddc0SDimitry Andric   // to keep it as an output.
104481ad6265SDimitry Andric   if (any_of(llvm::seq<unsigned>(0, PN.getNumIncomingValues()),
104581ad6265SDimitry Andric              [PHILoc, &PN, V, &BlocksInRegion](unsigned Idx) {
104604eeddc0SDimitry Andric                return (Idx != PHILoc && V == PN.getIncomingValue(Idx) &&
104704eeddc0SDimitry Andric                        !BlocksInRegion.contains(PN.getIncomingBlock(Idx)));
104804eeddc0SDimitry Andric              }))
104904eeddc0SDimitry Andric     return true;
105004eeddc0SDimitry Andric 
105104eeddc0SDimitry Andric   // Check if the value is used by any other instructions outside the region.
105204eeddc0SDimitry Andric   return any_of(V->users(), [&Exits, &BlocksInRegion](User *U) {
105304eeddc0SDimitry Andric     Instruction *I = dyn_cast<Instruction>(U);
105404eeddc0SDimitry Andric     if (!I)
105504eeddc0SDimitry Andric       return false;
105604eeddc0SDimitry Andric 
105704eeddc0SDimitry Andric     // If the use of the item is inside the region, we skip it.  Uses
105804eeddc0SDimitry Andric     // inside the region give us useful information about how the item could be
105904eeddc0SDimitry Andric     // used as an output.
106004eeddc0SDimitry Andric     BasicBlock *Parent = I->getParent();
106104eeddc0SDimitry Andric     if (BlocksInRegion.contains(Parent))
106204eeddc0SDimitry Andric       return false;
106304eeddc0SDimitry Andric 
106404eeddc0SDimitry Andric     // If it's not a PHINode then we definitely know the use matters.  This
106504eeddc0SDimitry Andric     // output value will not completely combined with another item in a PHINode
106604eeddc0SDimitry Andric     // as it is directly reference by another non-phi instruction
106704eeddc0SDimitry Andric     if (!isa<PHINode>(I))
106804eeddc0SDimitry Andric       return true;
106904eeddc0SDimitry Andric 
107004eeddc0SDimitry Andric     // If we have a PHINode outside one of the exit locations, then it
107104eeddc0SDimitry Andric     // can be considered an outside use as well.  If there is a PHINode
107204eeddc0SDimitry Andric     // contained in the Exit where this values use matters, it will be
107304eeddc0SDimitry Andric     // caught when we analyze that PHINode.
107404eeddc0SDimitry Andric     if (!Exits.contains(Parent))
107504eeddc0SDimitry Andric       return true;
107604eeddc0SDimitry Andric 
107704eeddc0SDimitry Andric     return false;
107804eeddc0SDimitry Andric   });
107904eeddc0SDimitry Andric }
108004eeddc0SDimitry Andric 
108104eeddc0SDimitry Andric /// Test whether \p CurrentExitFromRegion contains any PhiNodes that should be
108204eeddc0SDimitry Andric /// considered outputs. A PHINodes is an output when more than one incoming
108304eeddc0SDimitry Andric /// value has been marked by the CodeExtractor as an output.
108404eeddc0SDimitry Andric ///
108504eeddc0SDimitry Andric /// \param CurrentExitFromRegion [in] - The block to analyze.
108604eeddc0SDimitry Andric /// \param PotentialExitsFromRegion [in] - The potential exit blocks from the
108704eeddc0SDimitry Andric /// region.
108804eeddc0SDimitry Andric /// \param RegionBlocks [in] - The basic blocks in the region.
108904eeddc0SDimitry Andric /// \param Outputs [in, out] - The existing outputs for the region, we may add
109004eeddc0SDimitry Andric /// PHINodes to this as we find that they replace output values.
109104eeddc0SDimitry Andric /// \param OutputsReplacedByPHINode [out] - A set containing outputs that are
109204eeddc0SDimitry Andric /// totally replaced  by a PHINode.
109304eeddc0SDimitry Andric /// \param OutputsWithNonPhiUses [out] - A set containing outputs that are used
109404eeddc0SDimitry Andric /// in PHINodes, but have other uses, and should still be considered outputs.
109504eeddc0SDimitry Andric static void analyzeExitPHIsForOutputUses(
109604eeddc0SDimitry Andric     BasicBlock *CurrentExitFromRegion,
109704eeddc0SDimitry Andric     SmallPtrSet<BasicBlock *, 1> &PotentialExitsFromRegion,
109804eeddc0SDimitry Andric     DenseSet<BasicBlock *> &RegionBlocks, SetVector<Value *> &Outputs,
109904eeddc0SDimitry Andric     DenseSet<Value *> &OutputsReplacedByPHINode,
110004eeddc0SDimitry Andric     DenseSet<Value *> &OutputsWithNonPhiUses) {
110104eeddc0SDimitry Andric   for (PHINode &PN : CurrentExitFromRegion->phis()) {
110204eeddc0SDimitry Andric     // Find all incoming values from the outlining region.
110304eeddc0SDimitry Andric     SmallVector<unsigned, 2> IncomingVals;
110404eeddc0SDimitry Andric     for (unsigned I = 0, E = PN.getNumIncomingValues(); I < E; ++I)
110504eeddc0SDimitry Andric       if (RegionBlocks.contains(PN.getIncomingBlock(I)))
110604eeddc0SDimitry Andric         IncomingVals.push_back(I);
110704eeddc0SDimitry Andric 
110804eeddc0SDimitry Andric     // Do not process PHI if there are no predecessors from region.
110904eeddc0SDimitry Andric     unsigned NumIncomingVals = IncomingVals.size();
111004eeddc0SDimitry Andric     if (NumIncomingVals == 0)
111104eeddc0SDimitry Andric       continue;
111204eeddc0SDimitry Andric 
111304eeddc0SDimitry Andric     // If there is one predecessor, we mark it as a value that needs to be kept
111404eeddc0SDimitry Andric     // as an output.
111504eeddc0SDimitry Andric     if (NumIncomingVals == 1) {
111604eeddc0SDimitry Andric       Value *V = PN.getIncomingValue(*IncomingVals.begin());
111704eeddc0SDimitry Andric       OutputsWithNonPhiUses.insert(V);
111804eeddc0SDimitry Andric       OutputsReplacedByPHINode.erase(V);
111904eeddc0SDimitry Andric       continue;
112004eeddc0SDimitry Andric     }
112104eeddc0SDimitry Andric 
112204eeddc0SDimitry Andric     // This PHINode will be used as an output value, so we add it to our list.
112304eeddc0SDimitry Andric     Outputs.insert(&PN);
112404eeddc0SDimitry Andric 
112504eeddc0SDimitry Andric     // Not all of the incoming values should be ignored as other inputs and
112604eeddc0SDimitry Andric     // outputs may have uses in outlined region.  If they have other uses
112704eeddc0SDimitry Andric     // outside of the single PHINode we should not skip over it.
112804eeddc0SDimitry Andric     for (unsigned Idx : IncomingVals) {
112904eeddc0SDimitry Andric       Value *V = PN.getIncomingValue(Idx);
113004eeddc0SDimitry Andric       if (outputHasNonPHI(V, Idx, PN, PotentialExitsFromRegion, RegionBlocks)) {
113104eeddc0SDimitry Andric         OutputsWithNonPhiUses.insert(V);
113204eeddc0SDimitry Andric         OutputsReplacedByPHINode.erase(V);
113304eeddc0SDimitry Andric         continue;
113404eeddc0SDimitry Andric       }
113504eeddc0SDimitry Andric       if (!OutputsWithNonPhiUses.contains(V))
113604eeddc0SDimitry Andric         OutputsReplacedByPHINode.insert(V);
113704eeddc0SDimitry Andric     }
113804eeddc0SDimitry Andric   }
113904eeddc0SDimitry Andric }
114004eeddc0SDimitry Andric 
114104eeddc0SDimitry Andric // Represents the type for the unsigned number denoting the output number for
114204eeddc0SDimitry Andric // phi node, along with the canonical number for the exit block.
114304eeddc0SDimitry Andric using ArgLocWithBBCanon = std::pair<unsigned, unsigned>;
114404eeddc0SDimitry Andric // The list of canonical numbers for the incoming values to a PHINode.
114504eeddc0SDimitry Andric using CanonList = SmallVector<unsigned, 2>;
114604eeddc0SDimitry Andric // The pair type representing the set of canonical values being combined in the
114704eeddc0SDimitry Andric // PHINode, along with the location data for the PHINode.
114804eeddc0SDimitry Andric using PHINodeData = std::pair<ArgLocWithBBCanon, CanonList>;
114904eeddc0SDimitry Andric 
115004eeddc0SDimitry Andric /// Encode \p PND as an integer for easy lookup based on the argument location,
115104eeddc0SDimitry Andric /// the parent BasicBlock canonical numbering, and the canonical numbering of
115204eeddc0SDimitry Andric /// the values stored in the PHINode.
115304eeddc0SDimitry Andric ///
115404eeddc0SDimitry Andric /// \param PND - The data to hash.
115504eeddc0SDimitry Andric /// \returns The hash code of \p PND.
115604eeddc0SDimitry Andric static hash_code encodePHINodeData(PHINodeData &PND) {
115704eeddc0SDimitry Andric   return llvm::hash_combine(
115804eeddc0SDimitry Andric       llvm::hash_value(PND.first.first), llvm::hash_value(PND.first.second),
115904eeddc0SDimitry Andric       llvm::hash_combine_range(PND.second.begin(), PND.second.end()));
116004eeddc0SDimitry Andric }
116104eeddc0SDimitry Andric 
116204eeddc0SDimitry Andric /// Create a special GVN for PHINodes that will be used outside of
116304eeddc0SDimitry Andric /// the region.  We create a hash code based on the Canonical number of the
116404eeddc0SDimitry Andric /// parent BasicBlock, the canonical numbering of the values stored in the
116504eeddc0SDimitry Andric /// PHINode and the aggregate argument location.  This is used to find whether
116604eeddc0SDimitry Andric /// this PHINode type has been given a canonical numbering already.  If not, we
116704eeddc0SDimitry Andric /// assign it a value and store it for later use.  The value is returned to
116804eeddc0SDimitry Andric /// identify different output schemes for the set of regions.
116904eeddc0SDimitry Andric ///
117004eeddc0SDimitry Andric /// \param Region - The region that \p PN is an output for.
117104eeddc0SDimitry Andric /// \param PN - The PHINode we are analyzing.
117281ad6265SDimitry Andric /// \param Blocks - The blocks for the region we are analyzing.
117304eeddc0SDimitry Andric /// \param AggArgIdx - The argument \p PN will be stored into.
1174bdd1243dSDimitry Andric /// \returns An optional holding the assigned canonical number, or std::nullopt
1175bdd1243dSDimitry Andric /// if there is some attribute of the PHINode blocking it from being used.
1176bdd1243dSDimitry Andric static std::optional<unsigned> getGVNForPHINode(OutlinableRegion &Region,
117781ad6265SDimitry Andric                                                 PHINode *PN,
117881ad6265SDimitry Andric                                                 DenseSet<BasicBlock *> &Blocks,
117981ad6265SDimitry Andric                                                 unsigned AggArgIdx) {
118004eeddc0SDimitry Andric   OutlinableGroup &Group = *Region.Parent;
118104eeddc0SDimitry Andric   IRSimilarityCandidate &Cand = *Region.Candidate;
118204eeddc0SDimitry Andric   BasicBlock *PHIBB = PN->getParent();
118304eeddc0SDimitry Andric   CanonList PHIGVNs;
118481ad6265SDimitry Andric   Value *Incoming;
118581ad6265SDimitry Andric   BasicBlock *IncomingBlock;
118681ad6265SDimitry Andric   for (unsigned Idx = 0, EIdx = PN->getNumIncomingValues(); Idx < EIdx; Idx++) {
118781ad6265SDimitry Andric     Incoming = PN->getIncomingValue(Idx);
118881ad6265SDimitry Andric     IncomingBlock = PN->getIncomingBlock(Idx);
118981ad6265SDimitry Andric     // If we cannot find a GVN, and the incoming block is included in the region
119081ad6265SDimitry Andric     // this means that the input to the PHINode is not included in the region we
119181ad6265SDimitry Andric     // are trying to analyze, meaning, that if it was outlined, we would be
119281ad6265SDimitry Andric     // adding an extra input.  We ignore this case for now, and so ignore the
119381ad6265SDimitry Andric     // region.
1194bdd1243dSDimitry Andric     std::optional<unsigned> OGVN = Cand.getGVN(Incoming);
119581ad6265SDimitry Andric     if (!OGVN && Blocks.contains(IncomingBlock)) {
119604eeddc0SDimitry Andric       Region.IgnoreRegion = true;
1197bdd1243dSDimitry Andric       return std::nullopt;
119804eeddc0SDimitry Andric     }
119904eeddc0SDimitry Andric 
120081ad6265SDimitry Andric     // If the incoming block isn't in the region, we don't have to worry about
120181ad6265SDimitry Andric     // this incoming value.
120281ad6265SDimitry Andric     if (!Blocks.contains(IncomingBlock))
120381ad6265SDimitry Andric       continue;
120481ad6265SDimitry Andric 
120504eeddc0SDimitry Andric     // Collect the canonical numbers of the values in the PHINode.
120681ad6265SDimitry Andric     unsigned GVN = *OGVN;
120704eeddc0SDimitry Andric     OGVN = Cand.getCanonicalNum(GVN);
120881ad6265SDimitry Andric     assert(OGVN && "No GVN found for incoming value?");
120981ad6265SDimitry Andric     PHIGVNs.push_back(*OGVN);
121081ad6265SDimitry Andric 
121181ad6265SDimitry Andric     // Find the incoming block and use the canonical numbering as well to define
121281ad6265SDimitry Andric     // the hash for the PHINode.
121381ad6265SDimitry Andric     OGVN = Cand.getGVN(IncomingBlock);
121481ad6265SDimitry Andric 
1215bdd1243dSDimitry Andric     // If there is no number for the incoming block, it is because we have
121681ad6265SDimitry Andric     // split the candidate basic blocks.  So we use the previous block that it
121781ad6265SDimitry Andric     // was split from to find the valid global value numbering for the PHINode.
121881ad6265SDimitry Andric     if (!OGVN) {
121981ad6265SDimitry Andric       assert(Cand.getStartBB() == IncomingBlock &&
122081ad6265SDimitry Andric              "Unknown basic block used in exit path PHINode.");
122181ad6265SDimitry Andric 
122281ad6265SDimitry Andric       BasicBlock *PrevBlock = nullptr;
122381ad6265SDimitry Andric       // Iterate over the predecessors to the incoming block of the
122481ad6265SDimitry Andric       // PHINode, when we find a block that is not contained in the region
122581ad6265SDimitry Andric       // we know that this is the first block that we split from, and should
122681ad6265SDimitry Andric       // have a valid global value numbering.
122781ad6265SDimitry Andric       for (BasicBlock *Pred : predecessors(IncomingBlock))
122881ad6265SDimitry Andric         if (!Blocks.contains(Pred)) {
122981ad6265SDimitry Andric           PrevBlock = Pred;
123081ad6265SDimitry Andric           break;
123181ad6265SDimitry Andric         }
123281ad6265SDimitry Andric       assert(PrevBlock && "Expected a predecessor not in the reigon!");
123381ad6265SDimitry Andric       OGVN = Cand.getGVN(PrevBlock);
123481ad6265SDimitry Andric     }
123581ad6265SDimitry Andric     GVN = *OGVN;
123681ad6265SDimitry Andric     OGVN = Cand.getCanonicalNum(GVN);
123781ad6265SDimitry Andric     assert(OGVN && "No GVN found for incoming block?");
123804eeddc0SDimitry Andric     PHIGVNs.push_back(*OGVN);
123904eeddc0SDimitry Andric   }
124004eeddc0SDimitry Andric 
124104eeddc0SDimitry Andric   // Now that we have the GVNs for the incoming values, we are going to combine
124204eeddc0SDimitry Andric   // them with the GVN of the incoming bock, and the output location of the
124304eeddc0SDimitry Andric   // PHINode to generate a hash value representing this instance of the PHINode.
124404eeddc0SDimitry Andric   DenseMap<hash_code, unsigned>::iterator GVNToPHIIt;
124504eeddc0SDimitry Andric   DenseMap<unsigned, PHINodeData>::iterator PHIToGVNIt;
1246bdd1243dSDimitry Andric   std::optional<unsigned> BBGVN = Cand.getGVN(PHIBB);
124781ad6265SDimitry Andric   assert(BBGVN && "Could not find GVN for the incoming block!");
124804eeddc0SDimitry Andric 
1249bdd1243dSDimitry Andric   BBGVN = Cand.getCanonicalNum(*BBGVN);
125081ad6265SDimitry Andric   assert(BBGVN && "Could not find canonical number for the incoming block!");
125104eeddc0SDimitry Andric   // Create a pair of the exit block canonical value, and the aggregate
125204eeddc0SDimitry Andric   // argument location, connected to the canonical numbers stored in the
125304eeddc0SDimitry Andric   // PHINode.
125404eeddc0SDimitry Andric   PHINodeData TemporaryPair =
1255bdd1243dSDimitry Andric       std::make_pair(std::make_pair(*BBGVN, AggArgIdx), PHIGVNs);
125604eeddc0SDimitry Andric   hash_code PHINodeDataHash = encodePHINodeData(TemporaryPair);
125704eeddc0SDimitry Andric 
125804eeddc0SDimitry Andric   // Look for and create a new entry in our connection between canonical
125904eeddc0SDimitry Andric   // numbers for PHINodes, and the set of objects we just created.
126004eeddc0SDimitry Andric   GVNToPHIIt = Group.GVNsToPHINodeGVN.find(PHINodeDataHash);
126104eeddc0SDimitry Andric   if (GVNToPHIIt == Group.GVNsToPHINodeGVN.end()) {
126204eeddc0SDimitry Andric     bool Inserted = false;
126304eeddc0SDimitry Andric     std::tie(PHIToGVNIt, Inserted) = Group.PHINodeGVNToGVNs.insert(
126404eeddc0SDimitry Andric         std::make_pair(Group.PHINodeGVNTracker, TemporaryPair));
126504eeddc0SDimitry Andric     std::tie(GVNToPHIIt, Inserted) = Group.GVNsToPHINodeGVN.insert(
126604eeddc0SDimitry Andric         std::make_pair(PHINodeDataHash, Group.PHINodeGVNTracker--));
126704eeddc0SDimitry Andric   }
126804eeddc0SDimitry Andric 
126904eeddc0SDimitry Andric   return GVNToPHIIt->second;
127004eeddc0SDimitry Andric }
127104eeddc0SDimitry Andric 
1272e8d8bef9SDimitry Andric /// Create a mapping of the output arguments for the \p Region to the output
1273e8d8bef9SDimitry Andric /// arguments of the overall outlined function.
1274e8d8bef9SDimitry Andric ///
1275e8d8bef9SDimitry Andric /// \param [in,out] Region - The region of code to be analyzed.
1276e8d8bef9SDimitry Andric /// \param [in] Outputs - The values found by the code extractor.
1277e8d8bef9SDimitry Andric static void
1278bdd1243dSDimitry Andric findExtractedOutputToOverallOutputMapping(Module &M, OutlinableRegion &Region,
1279349cc55cSDimitry Andric                                           SetVector<Value *> &Outputs) {
1280e8d8bef9SDimitry Andric   OutlinableGroup &Group = *Region.Parent;
1281e8d8bef9SDimitry Andric   IRSimilarityCandidate &C = *Region.Candidate;
1282e8d8bef9SDimitry Andric 
1283349cc55cSDimitry Andric   SmallVector<BasicBlock *> BE;
128404eeddc0SDimitry Andric   DenseSet<BasicBlock *> BlocksInRegion;
128504eeddc0SDimitry Andric   C.getBasicBlocks(BlocksInRegion, BE);
1286349cc55cSDimitry Andric 
1287349cc55cSDimitry Andric   // Find the exits to the region.
1288349cc55cSDimitry Andric   SmallPtrSet<BasicBlock *, 1> Exits;
1289349cc55cSDimitry Andric   for (BasicBlock *Block : BE)
1290349cc55cSDimitry Andric     for (BasicBlock *Succ : successors(Block))
129104eeddc0SDimitry Andric       if (!BlocksInRegion.contains(Succ))
1292349cc55cSDimitry Andric         Exits.insert(Succ);
1293349cc55cSDimitry Andric 
1294349cc55cSDimitry Andric   // After determining which blocks exit to PHINodes, we add these PHINodes to
1295349cc55cSDimitry Andric   // the set of outputs to be processed.  We also check the incoming values of
1296349cc55cSDimitry Andric   // the PHINodes for whether they should no longer be considered outputs.
129704eeddc0SDimitry Andric   DenseSet<Value *> OutputsReplacedByPHINode;
129804eeddc0SDimitry Andric   DenseSet<Value *> OutputsWithNonPhiUses;
129904eeddc0SDimitry Andric   for (BasicBlock *ExitBB : Exits)
130004eeddc0SDimitry Andric     analyzeExitPHIsForOutputUses(ExitBB, Exits, BlocksInRegion, Outputs,
130104eeddc0SDimitry Andric                                  OutputsReplacedByPHINode,
130204eeddc0SDimitry Andric                                  OutputsWithNonPhiUses);
1303349cc55cSDimitry Andric 
1304e8d8bef9SDimitry Andric   // This counts the argument number in the extracted function.
1305e8d8bef9SDimitry Andric   unsigned OriginalIndex = Region.NumExtractedInputs;
1306e8d8bef9SDimitry Andric 
1307e8d8bef9SDimitry Andric   // This counts the argument number in the overall function.
1308e8d8bef9SDimitry Andric   unsigned TypeIndex = Group.NumAggregateInputs;
1309e8d8bef9SDimitry Andric   bool TypeFound;
1310e8d8bef9SDimitry Andric   DenseSet<unsigned> AggArgsUsed;
1311e8d8bef9SDimitry Andric 
1312e8d8bef9SDimitry Andric   // Iterate over the output types and identify if there is an aggregate pointer
1313e8d8bef9SDimitry Andric   // type whose base type matches the current output type. If there is, we mark
1314e8d8bef9SDimitry Andric   // that we will use this output register for this value. If not we add another
1315e8d8bef9SDimitry Andric   // type to the overall argument type list. We also store the GVNs used for
1316e8d8bef9SDimitry Andric   // stores to identify which values will need to be moved into an special
1317e8d8bef9SDimitry Andric   // block that holds the stores to the output registers.
1318e8d8bef9SDimitry Andric   for (Value *Output : Outputs) {
1319e8d8bef9SDimitry Andric     TypeFound = false;
1320e8d8bef9SDimitry Andric     // We can do this since it is a result value, and will have a number
1321e8d8bef9SDimitry Andric     // that is necessarily the same. BUT if in the future, the instructions
1322e8d8bef9SDimitry Andric     // do not have to be in same order, but are functionally the same, we will
1323e8d8bef9SDimitry Andric     // have to use a different scheme, as one-to-one correspondence is not
1324e8d8bef9SDimitry Andric     // guaranteed.
1325e8d8bef9SDimitry Andric     unsigned ArgumentSize = Group.ArgumentTypes.size();
1326e8d8bef9SDimitry Andric 
132704eeddc0SDimitry Andric     // If the output is combined in a PHINode, we make sure to skip over it.
132804eeddc0SDimitry Andric     if (OutputsReplacedByPHINode.contains(Output))
132904eeddc0SDimitry Andric       continue;
133004eeddc0SDimitry Andric 
133104eeddc0SDimitry Andric     unsigned AggArgIdx = 0;
1332e8d8bef9SDimitry Andric     for (unsigned Jdx = TypeIndex; Jdx < ArgumentSize; Jdx++) {
133306c3fb27SDimitry Andric       if (!isa<PointerType>(Group.ArgumentTypes[Jdx]))
1334e8d8bef9SDimitry Andric         continue;
1335e8d8bef9SDimitry Andric 
1336e8d8bef9SDimitry Andric       if (AggArgsUsed.contains(Jdx))
1337e8d8bef9SDimitry Andric         continue;
1338e8d8bef9SDimitry Andric 
1339e8d8bef9SDimitry Andric       TypeFound = true;
1340e8d8bef9SDimitry Andric       AggArgsUsed.insert(Jdx);
1341e8d8bef9SDimitry Andric       Region.ExtractedArgToAgg.insert(std::make_pair(OriginalIndex, Jdx));
1342e8d8bef9SDimitry Andric       Region.AggArgToExtracted.insert(std::make_pair(Jdx, OriginalIndex));
134304eeddc0SDimitry Andric       AggArgIdx = Jdx;
1344e8d8bef9SDimitry Andric       break;
1345e8d8bef9SDimitry Andric     }
1346e8d8bef9SDimitry Andric 
1347e8d8bef9SDimitry Andric     // We were unable to find an unused type in the output type set that matches
1348e8d8bef9SDimitry Andric     // the output, so we add a pointer type to the argument types of the overall
1349e8d8bef9SDimitry Andric     // function to handle this output and create a mapping to it.
1350e8d8bef9SDimitry Andric     if (!TypeFound) {
13515f757f3fSDimitry Andric       Group.ArgumentTypes.push_back(PointerType::get(Output->getContext(),
1352bdd1243dSDimitry Andric           M.getDataLayout().getAllocaAddrSpace()));
135304eeddc0SDimitry Andric       // Mark the new pointer type as the last value in the aggregate argument
135404eeddc0SDimitry Andric       // list.
135504eeddc0SDimitry Andric       unsigned ArgTypeIdx = Group.ArgumentTypes.size() - 1;
135604eeddc0SDimitry Andric       AggArgsUsed.insert(ArgTypeIdx);
1357e8d8bef9SDimitry Andric       Region.ExtractedArgToAgg.insert(
135804eeddc0SDimitry Andric           std::make_pair(OriginalIndex, ArgTypeIdx));
1359e8d8bef9SDimitry Andric       Region.AggArgToExtracted.insert(
136004eeddc0SDimitry Andric           std::make_pair(ArgTypeIdx, OriginalIndex));
136104eeddc0SDimitry Andric       AggArgIdx = ArgTypeIdx;
1362e8d8bef9SDimitry Andric     }
1363e8d8bef9SDimitry Andric 
136404eeddc0SDimitry Andric     // TODO: Adapt to the extra input from the PHINode.
136504eeddc0SDimitry Andric     PHINode *PN = dyn_cast<PHINode>(Output);
136604eeddc0SDimitry Andric 
1367bdd1243dSDimitry Andric     std::optional<unsigned> GVN;
136804eeddc0SDimitry Andric     if (PN && !BlocksInRegion.contains(PN->getParent())) {
136904eeddc0SDimitry Andric       // Values outside the region can be combined into PHINode when we
137004eeddc0SDimitry Andric       // have multiple exits. We collect both of these into a list to identify
137104eeddc0SDimitry Andric       // which values are being used in the PHINode. Each list identifies a
137204eeddc0SDimitry Andric       // different PHINode, and a different output. We store the PHINode as it's
137304eeddc0SDimitry Andric       // own canonical value.  These canonical values are also dependent on the
137404eeddc0SDimitry Andric       // output argument it is saved to.
137504eeddc0SDimitry Andric 
137604eeddc0SDimitry Andric       // If two PHINodes have the same canonical values, but different aggregate
137704eeddc0SDimitry Andric       // argument locations, then they will have distinct Canonical Values.
137881ad6265SDimitry Andric       GVN = getGVNForPHINode(Region, PN, BlocksInRegion, AggArgIdx);
137981ad6265SDimitry Andric       if (!GVN)
138004eeddc0SDimitry Andric         return;
138104eeddc0SDimitry Andric     } else {
138204eeddc0SDimitry Andric       // If we do not have a PHINode we use the global value numbering for the
138304eeddc0SDimitry Andric       // output value, to find the canonical number to add to the set of stored
138404eeddc0SDimitry Andric       // values.
138504eeddc0SDimitry Andric       GVN = C.getGVN(Output);
138604eeddc0SDimitry Andric       GVN = C.getCanonicalNum(*GVN);
138704eeddc0SDimitry Andric     }
138804eeddc0SDimitry Andric 
138904eeddc0SDimitry Andric     // Each region has a potentially unique set of outputs.  We save which
139004eeddc0SDimitry Andric     // values are output in a list of canonical values so we can differentiate
139104eeddc0SDimitry Andric     // among the different store schemes.
139204eeddc0SDimitry Andric     Region.GVNStores.push_back(*GVN);
139304eeddc0SDimitry Andric 
1394e8d8bef9SDimitry Andric     OriginalIndex++;
1395e8d8bef9SDimitry Andric     TypeIndex++;
1396e8d8bef9SDimitry Andric   }
139704eeddc0SDimitry Andric 
139804eeddc0SDimitry Andric   // We sort the stored values to make sure that we are not affected by analysis
139904eeddc0SDimitry Andric   // order when determining what combination of items were stored.
140004eeddc0SDimitry Andric   stable_sort(Region.GVNStores);
1401e8d8bef9SDimitry Andric }
1402e8d8bef9SDimitry Andric 
1403e8d8bef9SDimitry Andric void IROutliner::findAddInputsOutputs(Module &M, OutlinableRegion &Region,
1404e8d8bef9SDimitry Andric                                       DenseSet<unsigned> &NotSame) {
1405e8d8bef9SDimitry Andric   std::vector<unsigned> Inputs;
1406e8d8bef9SDimitry Andric   SetVector<Value *> ArgInputs, Outputs;
1407e8d8bef9SDimitry Andric 
1408e8d8bef9SDimitry Andric   getCodeExtractorArguments(Region, Inputs, NotSame, OutputMappings, ArgInputs,
1409e8d8bef9SDimitry Andric                             Outputs);
1410e8d8bef9SDimitry Andric 
1411e8d8bef9SDimitry Andric   if (Region.IgnoreRegion)
1412e8d8bef9SDimitry Andric     return;
1413e8d8bef9SDimitry Andric 
1414e8d8bef9SDimitry Andric   // Map the inputs found by the CodeExtractor to the arguments found for
1415e8d8bef9SDimitry Andric   // the overall function.
1416e8d8bef9SDimitry Andric   findExtractedInputToOverallInputMapping(Region, Inputs, ArgInputs);
1417e8d8bef9SDimitry Andric 
1418e8d8bef9SDimitry Andric   // Map the outputs found by the CodeExtractor to the arguments found for
1419e8d8bef9SDimitry Andric   // the overall function.
1420bdd1243dSDimitry Andric   findExtractedOutputToOverallOutputMapping(M, Region, Outputs);
1421e8d8bef9SDimitry Andric }
1422e8d8bef9SDimitry Andric 
1423e8d8bef9SDimitry Andric /// Replace the extracted function in the Region with a call to the overall
1424e8d8bef9SDimitry Andric /// function constructed from the deduplicated similar regions, replacing and
1425e8d8bef9SDimitry Andric /// remapping the values passed to the extracted function as arguments to the
1426e8d8bef9SDimitry Andric /// new arguments of the overall function.
1427e8d8bef9SDimitry Andric ///
1428e8d8bef9SDimitry Andric /// \param [in] M - The module to outline from.
1429e8d8bef9SDimitry Andric /// \param [in] Region - The regions of extracted code to be replaced with a new
1430e8d8bef9SDimitry Andric /// function.
1431e8d8bef9SDimitry Andric /// \returns a call instruction with the replaced function.
1432e8d8bef9SDimitry Andric CallInst *replaceCalledFunction(Module &M, OutlinableRegion &Region) {
1433e8d8bef9SDimitry Andric   std::vector<Value *> NewCallArgs;
1434e8d8bef9SDimitry Andric   DenseMap<unsigned, unsigned>::iterator ArgPair;
1435e8d8bef9SDimitry Andric 
1436e8d8bef9SDimitry Andric   OutlinableGroup &Group = *Region.Parent;
1437e8d8bef9SDimitry Andric   CallInst *Call = Region.Call;
1438e8d8bef9SDimitry Andric   assert(Call && "Call to replace is nullptr?");
1439e8d8bef9SDimitry Andric   Function *AggFunc = Group.OutlinedFunction;
1440e8d8bef9SDimitry Andric   assert(AggFunc && "Function to replace with is nullptr?");
1441e8d8bef9SDimitry Andric 
1442e8d8bef9SDimitry Andric   // If the arguments are the same size, there are not values that need to be
1443349cc55cSDimitry Andric   // made into an argument, the argument ordering has not been change, or
1444349cc55cSDimitry Andric   // different output registers to handle.  We can simply replace the called
1445349cc55cSDimitry Andric   // function in this case.
1446349cc55cSDimitry Andric   if (!Region.ChangedArgOrder && AggFunc->arg_size() == Call->arg_size()) {
1447e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Replace call to " << *Call << " with call to "
1448e8d8bef9SDimitry Andric                       << *AggFunc << " with same number of arguments\n");
1449e8d8bef9SDimitry Andric     Call->setCalledFunction(AggFunc);
1450e8d8bef9SDimitry Andric     return Call;
1451e8d8bef9SDimitry Andric   }
1452e8d8bef9SDimitry Andric 
1453e8d8bef9SDimitry Andric   // We have a different number of arguments than the new function, so
1454e8d8bef9SDimitry Andric   // we need to use our previously mappings off extracted argument to overall
1455e8d8bef9SDimitry Andric   // function argument, and constants to overall function argument to create the
1456e8d8bef9SDimitry Andric   // new argument list.
1457e8d8bef9SDimitry Andric   for (unsigned AggArgIdx = 0; AggArgIdx < AggFunc->arg_size(); AggArgIdx++) {
1458e8d8bef9SDimitry Andric 
1459e8d8bef9SDimitry Andric     if (AggArgIdx == AggFunc->arg_size() - 1 &&
1460e8d8bef9SDimitry Andric         Group.OutputGVNCombinations.size() > 1) {
1461e8d8bef9SDimitry Andric       // If we are on the last argument, and we need to differentiate between
1462e8d8bef9SDimitry Andric       // output blocks, add an integer to the argument list to determine
1463e8d8bef9SDimitry Andric       // what block to take
1464e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "Set switch block argument to "
1465e8d8bef9SDimitry Andric                         << Region.OutputBlockNum << "\n");
1466e8d8bef9SDimitry Andric       NewCallArgs.push_back(ConstantInt::get(Type::getInt32Ty(M.getContext()),
1467e8d8bef9SDimitry Andric                                              Region.OutputBlockNum));
1468e8d8bef9SDimitry Andric       continue;
1469e8d8bef9SDimitry Andric     }
1470e8d8bef9SDimitry Andric 
1471e8d8bef9SDimitry Andric     ArgPair = Region.AggArgToExtracted.find(AggArgIdx);
1472e8d8bef9SDimitry Andric     if (ArgPair != Region.AggArgToExtracted.end()) {
1473e8d8bef9SDimitry Andric       Value *ArgumentValue = Call->getArgOperand(ArgPair->second);
1474e8d8bef9SDimitry Andric       // If we found the mapping from the extracted function to the overall
1475e8d8bef9SDimitry Andric       // function, we simply add it to the argument list.  We use the same
1476e8d8bef9SDimitry Andric       // value, it just needs to honor the new order of arguments.
1477e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "Setting argument " << AggArgIdx << " to value "
1478e8d8bef9SDimitry Andric                         << *ArgumentValue << "\n");
1479e8d8bef9SDimitry Andric       NewCallArgs.push_back(ArgumentValue);
1480e8d8bef9SDimitry Andric       continue;
1481e8d8bef9SDimitry Andric     }
1482e8d8bef9SDimitry Andric 
1483e8d8bef9SDimitry Andric     // If it is a constant, we simply add it to the argument list as a value.
148406c3fb27SDimitry Andric     if (Region.AggArgToConstant.contains(AggArgIdx)) {
1485e8d8bef9SDimitry Andric       Constant *CST = Region.AggArgToConstant.find(AggArgIdx)->second;
1486e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "Setting argument " << AggArgIdx << " to value "
1487e8d8bef9SDimitry Andric                         << *CST << "\n");
1488e8d8bef9SDimitry Andric       NewCallArgs.push_back(CST);
1489e8d8bef9SDimitry Andric       continue;
1490e8d8bef9SDimitry Andric     }
1491e8d8bef9SDimitry Andric 
1492e8d8bef9SDimitry Andric     // Add a nullptr value if the argument is not found in the extracted
1493e8d8bef9SDimitry Andric     // function.  If we cannot find a value, it means it is not in use
1494e8d8bef9SDimitry Andric     // for the region, so we should not pass anything to it.
1495e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Setting argument " << AggArgIdx << " to nullptr\n");
1496e8d8bef9SDimitry Andric     NewCallArgs.push_back(ConstantPointerNull::get(
1497e8d8bef9SDimitry Andric         static_cast<PointerType *>(AggFunc->getArg(AggArgIdx)->getType())));
1498e8d8bef9SDimitry Andric   }
1499e8d8bef9SDimitry Andric 
1500e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "Replace call to " << *Call << " with call to "
1501e8d8bef9SDimitry Andric                     << *AggFunc << " with new set of arguments\n");
1502e8d8bef9SDimitry Andric   // Create the new call instruction and erase the old one.
1503e8d8bef9SDimitry Andric   Call = CallInst::Create(AggFunc->getFunctionType(), AggFunc, NewCallArgs, "",
1504*0fca6ea1SDimitry Andric                           Call->getIterator());
1505e8d8bef9SDimitry Andric 
1506e8d8bef9SDimitry Andric   // It is possible that the call to the outlined function is either the first
1507e8d8bef9SDimitry Andric   // instruction is in the new block, the last instruction, or both.  If either
1508e8d8bef9SDimitry Andric   // of these is the case, we need to make sure that we replace the instruction
1509e8d8bef9SDimitry Andric   // in the IRInstructionData struct with the new call.
1510e8d8bef9SDimitry Andric   CallInst *OldCall = Region.Call;
1511e8d8bef9SDimitry Andric   if (Region.NewFront->Inst == OldCall)
1512e8d8bef9SDimitry Andric     Region.NewFront->Inst = Call;
1513e8d8bef9SDimitry Andric   if (Region.NewBack->Inst == OldCall)
1514e8d8bef9SDimitry Andric     Region.NewBack->Inst = Call;
1515e8d8bef9SDimitry Andric 
1516e8d8bef9SDimitry Andric   // Transfer any debug information.
1517e8d8bef9SDimitry Andric   Call->setDebugLoc(Region.Call->getDebugLoc());
1518349cc55cSDimitry Andric   // Since our output may determine which branch we go to, we make sure to
1519349cc55cSDimitry Andric   // propogate this new call value through the module.
1520349cc55cSDimitry Andric   OldCall->replaceAllUsesWith(Call);
1521e8d8bef9SDimitry Andric 
1522e8d8bef9SDimitry Andric   // Remove the old instruction.
1523e8d8bef9SDimitry Andric   OldCall->eraseFromParent();
1524e8d8bef9SDimitry Andric   Region.Call = Call;
1525e8d8bef9SDimitry Andric 
1526e8d8bef9SDimitry Andric   // Make sure that the argument in the new function has the SwiftError
1527e8d8bef9SDimitry Andric   // argument.
152881ad6265SDimitry Andric   if (Group.SwiftErrorArgument)
1529bdd1243dSDimitry Andric     Call->addParamAttr(*Group.SwiftErrorArgument, Attribute::SwiftError);
1530e8d8bef9SDimitry Andric 
1531e8d8bef9SDimitry Andric   return Call;
1532e8d8bef9SDimitry Andric }
1533e8d8bef9SDimitry Andric 
153404eeddc0SDimitry Andric /// Find or create a BasicBlock in the outlined function containing PhiBlocks
153504eeddc0SDimitry Andric /// for \p RetVal.
153604eeddc0SDimitry Andric ///
153704eeddc0SDimitry Andric /// \param Group - The OutlinableGroup containing the information about the
153804eeddc0SDimitry Andric /// overall outlined function.
153904eeddc0SDimitry Andric /// \param RetVal - The return value or exit option that we are currently
154004eeddc0SDimitry Andric /// evaluating.
154104eeddc0SDimitry Andric /// \returns The found or newly created BasicBlock to contain the needed
154204eeddc0SDimitry Andric /// PHINodes to be used as outputs.
154304eeddc0SDimitry Andric static BasicBlock *findOrCreatePHIBlock(OutlinableGroup &Group, Value *RetVal) {
154404eeddc0SDimitry Andric   DenseMap<Value *, BasicBlock *>::iterator PhiBlockForRetVal,
154504eeddc0SDimitry Andric       ReturnBlockForRetVal;
154604eeddc0SDimitry Andric   PhiBlockForRetVal = Group.PHIBlocks.find(RetVal);
154704eeddc0SDimitry Andric   ReturnBlockForRetVal = Group.EndBBs.find(RetVal);
154804eeddc0SDimitry Andric   assert(ReturnBlockForRetVal != Group.EndBBs.end() &&
154904eeddc0SDimitry Andric          "Could not find output value!");
155004eeddc0SDimitry Andric   BasicBlock *ReturnBB = ReturnBlockForRetVal->second;
155104eeddc0SDimitry Andric 
155204eeddc0SDimitry Andric   // Find if a PHIBlock exists for this return value already.  If it is
155304eeddc0SDimitry Andric   // the first time we are analyzing this, we will not, so we record it.
155404eeddc0SDimitry Andric   PhiBlockForRetVal = Group.PHIBlocks.find(RetVal);
155504eeddc0SDimitry Andric   if (PhiBlockForRetVal != Group.PHIBlocks.end())
155604eeddc0SDimitry Andric     return PhiBlockForRetVal->second;
155704eeddc0SDimitry Andric 
155804eeddc0SDimitry Andric   // If we did not find a block, we create one, and insert it into the
155904eeddc0SDimitry Andric   // overall function and record it.
156004eeddc0SDimitry Andric   bool Inserted = false;
156104eeddc0SDimitry Andric   BasicBlock *PHIBlock = BasicBlock::Create(ReturnBB->getContext(), "phi_block",
156204eeddc0SDimitry Andric                                             ReturnBB->getParent());
156304eeddc0SDimitry Andric   std::tie(PhiBlockForRetVal, Inserted) =
156404eeddc0SDimitry Andric       Group.PHIBlocks.insert(std::make_pair(RetVal, PHIBlock));
156504eeddc0SDimitry Andric 
156604eeddc0SDimitry Andric   // We find the predecessors of the return block in the newly created outlined
156704eeddc0SDimitry Andric   // function in order to point them to the new PHIBlock rather than the already
156804eeddc0SDimitry Andric   // existing return block.
156904eeddc0SDimitry Andric   SmallVector<BranchInst *, 2> BranchesToChange;
157004eeddc0SDimitry Andric   for (BasicBlock *Pred : predecessors(ReturnBB))
157104eeddc0SDimitry Andric     BranchesToChange.push_back(cast<BranchInst>(Pred->getTerminator()));
157204eeddc0SDimitry Andric 
157304eeddc0SDimitry Andric   // Now we mark the branch instructions found, and change the references of the
157404eeddc0SDimitry Andric   // return block to the newly created PHIBlock.
157504eeddc0SDimitry Andric   for (BranchInst *BI : BranchesToChange)
157604eeddc0SDimitry Andric     for (unsigned Succ = 0, End = BI->getNumSuccessors(); Succ < End; Succ++) {
157704eeddc0SDimitry Andric       if (BI->getSuccessor(Succ) != ReturnBB)
157804eeddc0SDimitry Andric         continue;
157904eeddc0SDimitry Andric       BI->setSuccessor(Succ, PHIBlock);
158004eeddc0SDimitry Andric     }
158104eeddc0SDimitry Andric 
158204eeddc0SDimitry Andric   BranchInst::Create(ReturnBB, PHIBlock);
158304eeddc0SDimitry Andric 
158404eeddc0SDimitry Andric   return PhiBlockForRetVal->second;
158504eeddc0SDimitry Andric }
158604eeddc0SDimitry Andric 
158704eeddc0SDimitry Andric /// For the function call now representing the \p Region, find the passed value
158804eeddc0SDimitry Andric /// to that call that represents Argument \p A at the call location if the
158904eeddc0SDimitry Andric /// call has already been replaced with a call to the  overall, aggregate
159004eeddc0SDimitry Andric /// function.
159104eeddc0SDimitry Andric ///
159204eeddc0SDimitry Andric /// \param A - The Argument to get the passed value for.
159304eeddc0SDimitry Andric /// \param Region - The extracted Region corresponding to the outlined function.
159404eeddc0SDimitry Andric /// \returns The Value representing \p A at the call site.
159504eeddc0SDimitry Andric static Value *
159604eeddc0SDimitry Andric getPassedArgumentInAlreadyOutlinedFunction(const Argument *A,
159704eeddc0SDimitry Andric                                            const OutlinableRegion &Region) {
159804eeddc0SDimitry Andric   // If we don't need to adjust the argument number at all (since the call
159904eeddc0SDimitry Andric   // has already been replaced by a call to the overall outlined function)
160004eeddc0SDimitry Andric   // we can just get the specified argument.
160104eeddc0SDimitry Andric   return Region.Call->getArgOperand(A->getArgNo());
160204eeddc0SDimitry Andric }
160304eeddc0SDimitry Andric 
160404eeddc0SDimitry Andric /// For the function call now representing the \p Region, find the passed value
160504eeddc0SDimitry Andric /// to that call that represents Argument \p A at the call location if the
160604eeddc0SDimitry Andric /// call has only been replaced by the call to the aggregate function.
160704eeddc0SDimitry Andric ///
160804eeddc0SDimitry Andric /// \param A - The Argument to get the passed value for.
160904eeddc0SDimitry Andric /// \param Region - The extracted Region corresponding to the outlined function.
161004eeddc0SDimitry Andric /// \returns The Value representing \p A at the call site.
161104eeddc0SDimitry Andric static Value *
161204eeddc0SDimitry Andric getPassedArgumentAndAdjustArgumentLocation(const Argument *A,
161304eeddc0SDimitry Andric                                            const OutlinableRegion &Region) {
161404eeddc0SDimitry Andric   unsigned ArgNum = A->getArgNo();
161504eeddc0SDimitry Andric 
161604eeddc0SDimitry Andric   // If it is a constant, we can look at our mapping from when we created
161704eeddc0SDimitry Andric   // the outputs to figure out what the constant value is.
161804eeddc0SDimitry Andric   if (Region.AggArgToConstant.count(ArgNum))
161904eeddc0SDimitry Andric     return Region.AggArgToConstant.find(ArgNum)->second;
162004eeddc0SDimitry Andric 
162104eeddc0SDimitry Andric   // If it is not a constant, and we are not looking at the overall function, we
162204eeddc0SDimitry Andric   // need to adjust which argument we are looking at.
162304eeddc0SDimitry Andric   ArgNum = Region.AggArgToExtracted.find(ArgNum)->second;
162404eeddc0SDimitry Andric   return Region.Call->getArgOperand(ArgNum);
162504eeddc0SDimitry Andric }
162604eeddc0SDimitry Andric 
162704eeddc0SDimitry Andric /// Find the canonical numbering for the incoming Values into the PHINode \p PN.
162804eeddc0SDimitry Andric ///
162904eeddc0SDimitry Andric /// \param PN [in] - The PHINode that we are finding the canonical numbers for.
163004eeddc0SDimitry Andric /// \param Region [in] - The OutlinableRegion containing \p PN.
163104eeddc0SDimitry Andric /// \param OutputMappings [in] - The mapping of output values from outlined
163204eeddc0SDimitry Andric /// region to their original values.
163304eeddc0SDimitry Andric /// \param CanonNums [out] - The canonical numbering for the incoming values to
163481ad6265SDimitry Andric /// \p PN paired with their incoming block.
163504eeddc0SDimitry Andric /// \param ReplacedWithOutlinedCall - A flag to use the extracted function call
163604eeddc0SDimitry Andric /// of \p Region rather than the overall function's call.
163781ad6265SDimitry Andric static void findCanonNumsForPHI(
163881ad6265SDimitry Andric     PHINode *PN, OutlinableRegion &Region,
163904eeddc0SDimitry Andric     const DenseMap<Value *, Value *> &OutputMappings,
164081ad6265SDimitry Andric     SmallVector<std::pair<unsigned, BasicBlock *>> &CanonNums,
164104eeddc0SDimitry Andric     bool ReplacedWithOutlinedCall = true) {
164204eeddc0SDimitry Andric   // Iterate over the incoming values.
164304eeddc0SDimitry Andric   for (unsigned Idx = 0, EIdx = PN->getNumIncomingValues(); Idx < EIdx; Idx++) {
164404eeddc0SDimitry Andric     Value *IVal = PN->getIncomingValue(Idx);
164581ad6265SDimitry Andric     BasicBlock *IBlock = PN->getIncomingBlock(Idx);
164604eeddc0SDimitry Andric     // If we have an argument as incoming value, we need to grab the passed
164704eeddc0SDimitry Andric     // value from the call itself.
164804eeddc0SDimitry Andric     if (Argument *A = dyn_cast<Argument>(IVal)) {
164904eeddc0SDimitry Andric       if (ReplacedWithOutlinedCall)
165004eeddc0SDimitry Andric         IVal = getPassedArgumentInAlreadyOutlinedFunction(A, Region);
165104eeddc0SDimitry Andric       else
165204eeddc0SDimitry Andric         IVal = getPassedArgumentAndAdjustArgumentLocation(A, Region);
165304eeddc0SDimitry Andric     }
165404eeddc0SDimitry Andric 
165504eeddc0SDimitry Andric     // Get the original value if it has been replaced by an output value.
165604eeddc0SDimitry Andric     IVal = findOutputMapping(OutputMappings, IVal);
165704eeddc0SDimitry Andric 
165804eeddc0SDimitry Andric     // Find and add the canonical number for the incoming value.
1659bdd1243dSDimitry Andric     std::optional<unsigned> GVN = Region.Candidate->getGVN(IVal);
166081ad6265SDimitry Andric     assert(GVN && "No GVN for incoming value");
1661bdd1243dSDimitry Andric     std::optional<unsigned> CanonNum = Region.Candidate->getCanonicalNum(*GVN);
166281ad6265SDimitry Andric     assert(CanonNum && "No Canonical Number for GVN");
166381ad6265SDimitry Andric     CanonNums.push_back(std::make_pair(*CanonNum, IBlock));
166404eeddc0SDimitry Andric   }
166504eeddc0SDimitry Andric }
166604eeddc0SDimitry Andric 
166704eeddc0SDimitry Andric /// Find, or add PHINode \p PN to the combined PHINode Block \p OverallPHIBlock
166804eeddc0SDimitry Andric /// in order to condense the number of instructions added to the outlined
166904eeddc0SDimitry Andric /// function.
167004eeddc0SDimitry Andric ///
167104eeddc0SDimitry Andric /// \param PN [in] - The PHINode that we are finding the canonical numbers for.
167204eeddc0SDimitry Andric /// \param Region [in] - The OutlinableRegion containing \p PN.
167304eeddc0SDimitry Andric /// \param OverallPhiBlock [in] - The overall PHIBlock we are trying to find
167404eeddc0SDimitry Andric /// \p PN in.
167504eeddc0SDimitry Andric /// \param OutputMappings [in] - The mapping of output values from outlined
167604eeddc0SDimitry Andric /// region to their original values.
167781ad6265SDimitry Andric /// \param UsedPHIs [in, out] - The PHINodes in the block that have already been
167881ad6265SDimitry Andric /// matched.
167904eeddc0SDimitry Andric /// \return the newly found or created PHINode in \p OverallPhiBlock.
168004eeddc0SDimitry Andric static PHINode*
168104eeddc0SDimitry Andric findOrCreatePHIInBlock(PHINode &PN, OutlinableRegion &Region,
168204eeddc0SDimitry Andric                        BasicBlock *OverallPhiBlock,
168381ad6265SDimitry Andric                        const DenseMap<Value *, Value *> &OutputMappings,
168481ad6265SDimitry Andric                        DenseSet<PHINode *> &UsedPHIs) {
168504eeddc0SDimitry Andric   OutlinableGroup &Group = *Region.Parent;
168604eeddc0SDimitry Andric 
168781ad6265SDimitry Andric 
168881ad6265SDimitry Andric   // A list of the canonical numbering assigned to each incoming value, paired
168981ad6265SDimitry Andric   // with the incoming block for the PHINode passed into this function.
169081ad6265SDimitry Andric   SmallVector<std::pair<unsigned, BasicBlock *>> PNCanonNums;
169181ad6265SDimitry Andric 
169204eeddc0SDimitry Andric   // We have to use the extracted function since we have merged this region into
169304eeddc0SDimitry Andric   // the overall function yet.  We make sure to reassign the argument numbering
169404eeddc0SDimitry Andric   // since it is possible that the argument ordering is different between the
169504eeddc0SDimitry Andric   // functions.
169604eeddc0SDimitry Andric   findCanonNumsForPHI(&PN, Region, OutputMappings, PNCanonNums,
169704eeddc0SDimitry Andric                       /* ReplacedWithOutlinedCall = */ false);
169804eeddc0SDimitry Andric 
169904eeddc0SDimitry Andric   OutlinableRegion *FirstRegion = Group.Regions[0];
170081ad6265SDimitry Andric 
170181ad6265SDimitry Andric   // A list of the canonical numbering assigned to each incoming value, paired
170281ad6265SDimitry Andric   // with the incoming block for the PHINode that we are currently comparing
170381ad6265SDimitry Andric   // the passed PHINode to.
170481ad6265SDimitry Andric   SmallVector<std::pair<unsigned, BasicBlock *>> CurrentCanonNums;
170581ad6265SDimitry Andric 
170604eeddc0SDimitry Andric   // Find the Canonical Numbering for each PHINode, if it matches, we replace
170704eeddc0SDimitry Andric   // the uses of the PHINode we are searching for, with the found PHINode.
170804eeddc0SDimitry Andric   for (PHINode &CurrPN : OverallPhiBlock->phis()) {
170981ad6265SDimitry Andric     // If this PHINode has already been matched to another PHINode to be merged,
171081ad6265SDimitry Andric     // we skip it.
171181ad6265SDimitry Andric     if (UsedPHIs.contains(&CurrPN))
171281ad6265SDimitry Andric       continue;
171381ad6265SDimitry Andric 
171404eeddc0SDimitry Andric     CurrentCanonNums.clear();
171504eeddc0SDimitry Andric     findCanonNumsForPHI(&CurrPN, *FirstRegion, OutputMappings, CurrentCanonNums,
171604eeddc0SDimitry Andric                         /* ReplacedWithOutlinedCall = */ true);
171704eeddc0SDimitry Andric 
171881ad6265SDimitry Andric     // If the list of incoming values is not the same length, then they cannot
171981ad6265SDimitry Andric     // match since there is not an analogue for each incoming value.
172081ad6265SDimitry Andric     if (PNCanonNums.size() != CurrentCanonNums.size())
172181ad6265SDimitry Andric       continue;
172281ad6265SDimitry Andric 
172381ad6265SDimitry Andric     bool FoundMatch = true;
172481ad6265SDimitry Andric 
172581ad6265SDimitry Andric     // We compare the canonical value for each incoming value in the passed
172681ad6265SDimitry Andric     // in PHINode to one already present in the outlined region.  If the
172781ad6265SDimitry Andric     // incoming values do not match, then the PHINodes do not match.
172881ad6265SDimitry Andric 
172981ad6265SDimitry Andric     // We also check to make sure that the incoming block matches as well by
173081ad6265SDimitry Andric     // finding the corresponding incoming block in the combined outlined region
173181ad6265SDimitry Andric     // for the current outlined region.
173281ad6265SDimitry Andric     for (unsigned Idx = 0, Edx = PNCanonNums.size(); Idx < Edx; ++Idx) {
173381ad6265SDimitry Andric       std::pair<unsigned, BasicBlock *> ToCompareTo = CurrentCanonNums[Idx];
173481ad6265SDimitry Andric       std::pair<unsigned, BasicBlock *> ToAdd = PNCanonNums[Idx];
173581ad6265SDimitry Andric       if (ToCompareTo.first != ToAdd.first) {
173681ad6265SDimitry Andric         FoundMatch = false;
173781ad6265SDimitry Andric         break;
173881ad6265SDimitry Andric       }
173981ad6265SDimitry Andric 
174081ad6265SDimitry Andric       BasicBlock *CorrespondingBlock =
174181ad6265SDimitry Andric           Region.findCorrespondingBlockIn(*FirstRegion, ToAdd.second);
174281ad6265SDimitry Andric       assert(CorrespondingBlock && "Found block is nullptr");
174381ad6265SDimitry Andric       if (CorrespondingBlock != ToCompareTo.second) {
174481ad6265SDimitry Andric         FoundMatch = false;
174581ad6265SDimitry Andric         break;
174681ad6265SDimitry Andric       }
174781ad6265SDimitry Andric     }
174881ad6265SDimitry Andric 
174981ad6265SDimitry Andric     // If all incoming values and branches matched, then we can merge
175081ad6265SDimitry Andric     // into the found PHINode.
175181ad6265SDimitry Andric     if (FoundMatch) {
175281ad6265SDimitry Andric       UsedPHIs.insert(&CurrPN);
175304eeddc0SDimitry Andric       return &CurrPN;
175404eeddc0SDimitry Andric     }
175581ad6265SDimitry Andric   }
175604eeddc0SDimitry Andric 
175704eeddc0SDimitry Andric   // If we've made it here, it means we weren't able to replace the PHINode, so
175804eeddc0SDimitry Andric   // we must insert it ourselves.
175904eeddc0SDimitry Andric   PHINode *NewPN = cast<PHINode>(PN.clone());
176004eeddc0SDimitry Andric   NewPN->insertBefore(&*OverallPhiBlock->begin());
176104eeddc0SDimitry Andric   for (unsigned Idx = 0, Edx = NewPN->getNumIncomingValues(); Idx < Edx;
176204eeddc0SDimitry Andric        Idx++) {
176304eeddc0SDimitry Andric     Value *IncomingVal = NewPN->getIncomingValue(Idx);
176404eeddc0SDimitry Andric     BasicBlock *IncomingBlock = NewPN->getIncomingBlock(Idx);
176504eeddc0SDimitry Andric 
176604eeddc0SDimitry Andric     // Find corresponding basic block in the overall function for the incoming
176704eeddc0SDimitry Andric     // block.
176881ad6265SDimitry Andric     BasicBlock *BlockToUse =
176981ad6265SDimitry Andric         Region.findCorrespondingBlockIn(*FirstRegion, IncomingBlock);
177004eeddc0SDimitry Andric     NewPN->setIncomingBlock(Idx, BlockToUse);
177104eeddc0SDimitry Andric 
177204eeddc0SDimitry Andric     // If we have an argument we make sure we replace using the argument from
177304eeddc0SDimitry Andric     // the correct function.
177404eeddc0SDimitry Andric     if (Argument *A = dyn_cast<Argument>(IncomingVal)) {
177504eeddc0SDimitry Andric       Value *Val = Group.OutlinedFunction->getArg(A->getArgNo());
177604eeddc0SDimitry Andric       NewPN->setIncomingValue(Idx, Val);
177704eeddc0SDimitry Andric       continue;
177804eeddc0SDimitry Andric     }
177904eeddc0SDimitry Andric 
178004eeddc0SDimitry Andric     // Find the corresponding value in the overall function.
178104eeddc0SDimitry Andric     IncomingVal = findOutputMapping(OutputMappings, IncomingVal);
178204eeddc0SDimitry Andric     Value *Val = Region.findCorrespondingValueIn(*FirstRegion, IncomingVal);
178304eeddc0SDimitry Andric     assert(Val && "Value is nullptr?");
178481ad6265SDimitry Andric     DenseMap<Value *, Value *>::iterator RemappedIt =
178581ad6265SDimitry Andric         FirstRegion->RemappedArguments.find(Val);
178681ad6265SDimitry Andric     if (RemappedIt != FirstRegion->RemappedArguments.end())
178781ad6265SDimitry Andric       Val = RemappedIt->second;
178804eeddc0SDimitry Andric     NewPN->setIncomingValue(Idx, Val);
178904eeddc0SDimitry Andric   }
179004eeddc0SDimitry Andric   return NewPN;
179104eeddc0SDimitry Andric }
179204eeddc0SDimitry Andric 
1793e8d8bef9SDimitry Andric // Within an extracted function, replace the argument uses of the extracted
1794e8d8bef9SDimitry Andric // region with the arguments of the function for an OutlinableGroup.
1795e8d8bef9SDimitry Andric //
1796e8d8bef9SDimitry Andric /// \param [in] Region - The region of extracted code to be changed.
1797349cc55cSDimitry Andric /// \param [in,out] OutputBBs - The BasicBlock for the output stores for this
1798e8d8bef9SDimitry Andric /// region.
1799349cc55cSDimitry Andric /// \param [in] FirstFunction - A flag to indicate whether we are using this
1800349cc55cSDimitry Andric /// function to define the overall outlined function for all the regions, or
1801349cc55cSDimitry Andric /// if we are operating on one of the following regions.
1802349cc55cSDimitry Andric static void
1803349cc55cSDimitry Andric replaceArgumentUses(OutlinableRegion &Region,
1804349cc55cSDimitry Andric                     DenseMap<Value *, BasicBlock *> &OutputBBs,
180504eeddc0SDimitry Andric                     const DenseMap<Value *, Value *> &OutputMappings,
1806349cc55cSDimitry Andric                     bool FirstFunction = false) {
1807e8d8bef9SDimitry Andric   OutlinableGroup &Group = *Region.Parent;
1808e8d8bef9SDimitry Andric   assert(Region.ExtractedFunction && "Region has no extracted function?");
1809e8d8bef9SDimitry Andric 
1810349cc55cSDimitry Andric   Function *DominatingFunction = Region.ExtractedFunction;
1811349cc55cSDimitry Andric   if (FirstFunction)
1812349cc55cSDimitry Andric     DominatingFunction = Group.OutlinedFunction;
1813349cc55cSDimitry Andric   DominatorTree DT(*DominatingFunction);
181481ad6265SDimitry Andric   DenseSet<PHINode *> UsedPHIs;
1815349cc55cSDimitry Andric 
1816e8d8bef9SDimitry Andric   for (unsigned ArgIdx = 0; ArgIdx < Region.ExtractedFunction->arg_size();
1817e8d8bef9SDimitry Andric        ArgIdx++) {
181806c3fb27SDimitry Andric     assert(Region.ExtractedArgToAgg.contains(ArgIdx) &&
1819e8d8bef9SDimitry Andric            "No mapping from extracted to outlined?");
1820e8d8bef9SDimitry Andric     unsigned AggArgIdx = Region.ExtractedArgToAgg.find(ArgIdx)->second;
1821e8d8bef9SDimitry Andric     Argument *AggArg = Group.OutlinedFunction->getArg(AggArgIdx);
1822e8d8bef9SDimitry Andric     Argument *Arg = Region.ExtractedFunction->getArg(ArgIdx);
1823e8d8bef9SDimitry Andric     // The argument is an input, so we can simply replace it with the overall
1824e8d8bef9SDimitry Andric     // argument value
1825e8d8bef9SDimitry Andric     if (ArgIdx < Region.NumExtractedInputs) {
1826e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "Replacing uses of input " << *Arg << " in function "
1827e8d8bef9SDimitry Andric                         << *Region.ExtractedFunction << " with " << *AggArg
1828e8d8bef9SDimitry Andric                         << " in function " << *Group.OutlinedFunction << "\n");
1829e8d8bef9SDimitry Andric       Arg->replaceAllUsesWith(AggArg);
183081ad6265SDimitry Andric       Value *V = Region.Call->getArgOperand(ArgIdx);
183181ad6265SDimitry Andric       Region.RemappedArguments.insert(std::make_pair(V, AggArg));
1832e8d8bef9SDimitry Andric       continue;
1833e8d8bef9SDimitry Andric     }
1834e8d8bef9SDimitry Andric 
1835e8d8bef9SDimitry Andric     // If we are replacing an output, we place the store value in its own
1836e8d8bef9SDimitry Andric     // block inside the overall function before replacing the use of the output
1837e8d8bef9SDimitry Andric     // in the function.
1838e8d8bef9SDimitry Andric     assert(Arg->hasOneUse() && "Output argument can only have one use");
1839e8d8bef9SDimitry Andric     User *InstAsUser = Arg->user_back();
1840e8d8bef9SDimitry Andric     assert(InstAsUser && "User is nullptr!");
1841e8d8bef9SDimitry Andric 
1842e8d8bef9SDimitry Andric     Instruction *I = cast<Instruction>(InstAsUser);
1843349cc55cSDimitry Andric     BasicBlock *BB = I->getParent();
1844349cc55cSDimitry Andric     SmallVector<BasicBlock *, 4> Descendants;
1845349cc55cSDimitry Andric     DT.getDescendants(BB, Descendants);
1846349cc55cSDimitry Andric     bool EdgeAdded = false;
1847349cc55cSDimitry Andric     if (Descendants.size() == 0) {
1848349cc55cSDimitry Andric       EdgeAdded = true;
1849349cc55cSDimitry Andric       DT.insertEdge(&DominatingFunction->getEntryBlock(), BB);
1850349cc55cSDimitry Andric       DT.getDescendants(BB, Descendants);
1851349cc55cSDimitry Andric     }
1852349cc55cSDimitry Andric 
1853349cc55cSDimitry Andric     // Iterate over the following blocks, looking for return instructions,
1854349cc55cSDimitry Andric     // if we find one, find the corresponding output block for the return value
1855349cc55cSDimitry Andric     // and move our store instruction there.
1856349cc55cSDimitry Andric     for (BasicBlock *DescendBB : Descendants) {
1857349cc55cSDimitry Andric       ReturnInst *RI = dyn_cast<ReturnInst>(DescendBB->getTerminator());
1858349cc55cSDimitry Andric       if (!RI)
1859349cc55cSDimitry Andric         continue;
1860349cc55cSDimitry Andric       Value *RetVal = RI->getReturnValue();
1861349cc55cSDimitry Andric       auto VBBIt = OutputBBs.find(RetVal);
1862349cc55cSDimitry Andric       assert(VBBIt != OutputBBs.end() && "Could not find output value!");
1863349cc55cSDimitry Andric 
1864349cc55cSDimitry Andric       // If this is storing a PHINode, we must make sure it is included in the
1865349cc55cSDimitry Andric       // overall function.
1866349cc55cSDimitry Andric       StoreInst *SI = cast<StoreInst>(I);
1867349cc55cSDimitry Andric 
1868349cc55cSDimitry Andric       Value *ValueOperand = SI->getValueOperand();
1869349cc55cSDimitry Andric 
1870349cc55cSDimitry Andric       StoreInst *NewI = cast<StoreInst>(I->clone());
1871349cc55cSDimitry Andric       NewI->setDebugLoc(DebugLoc());
1872349cc55cSDimitry Andric       BasicBlock *OutputBB = VBBIt->second;
1873bdd1243dSDimitry Andric       NewI->insertInto(OutputBB, OutputBB->end());
1874e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "Move store for instruction " << *I << " to "
1875e8d8bef9SDimitry Andric                         << *OutputBB << "\n");
1876e8d8bef9SDimitry Andric 
187704eeddc0SDimitry Andric       // If this is storing a PHINode, we must make sure it is included in the
187804eeddc0SDimitry Andric       // overall function.
187904eeddc0SDimitry Andric       if (!isa<PHINode>(ValueOperand) ||
188081ad6265SDimitry Andric           Region.Candidate->getGVN(ValueOperand).has_value()) {
1881349cc55cSDimitry Andric         if (FirstFunction)
1882349cc55cSDimitry Andric           continue;
1883349cc55cSDimitry Andric         Value *CorrVal =
1884349cc55cSDimitry Andric             Region.findCorrespondingValueIn(*Group.Regions[0], ValueOperand);
1885349cc55cSDimitry Andric         assert(CorrVal && "Value is nullptr?");
1886349cc55cSDimitry Andric         NewI->setOperand(0, CorrVal);
188704eeddc0SDimitry Andric         continue;
188804eeddc0SDimitry Andric       }
188904eeddc0SDimitry Andric       PHINode *PN = cast<PHINode>(SI->getValueOperand());
189004eeddc0SDimitry Andric       // If it has a value, it was not split by the code extractor, which
189104eeddc0SDimitry Andric       // is what we are looking for.
189281ad6265SDimitry Andric       if (Region.Candidate->getGVN(PN))
189304eeddc0SDimitry Andric         continue;
189404eeddc0SDimitry Andric 
189504eeddc0SDimitry Andric       // We record the parent block for the PHINode in the Region so that
189604eeddc0SDimitry Andric       // we can exclude it from checks later on.
189704eeddc0SDimitry Andric       Region.PHIBlocks.insert(std::make_pair(RetVal, PN->getParent()));
189804eeddc0SDimitry Andric 
189904eeddc0SDimitry Andric       // If this is the first function, we do not need to worry about mergiing
190004eeddc0SDimitry Andric       // this with any other block in the overall outlined function, so we can
190104eeddc0SDimitry Andric       // just continue.
190204eeddc0SDimitry Andric       if (FirstFunction) {
190304eeddc0SDimitry Andric         BasicBlock *PHIBlock = PN->getParent();
190404eeddc0SDimitry Andric         Group.PHIBlocks.insert(std::make_pair(RetVal, PHIBlock));
190504eeddc0SDimitry Andric         continue;
190604eeddc0SDimitry Andric       }
190704eeddc0SDimitry Andric 
190804eeddc0SDimitry Andric       // We look for the aggregate block that contains the PHINodes leading into
190904eeddc0SDimitry Andric       // this exit path. If we can't find one, we create one.
191004eeddc0SDimitry Andric       BasicBlock *OverallPhiBlock = findOrCreatePHIBlock(Group, RetVal);
191104eeddc0SDimitry Andric 
191204eeddc0SDimitry Andric       // For our PHINode, we find the combined canonical numbering, and
191304eeddc0SDimitry Andric       // attempt to find a matching PHINode in the overall PHIBlock.  If we
191404eeddc0SDimitry Andric       // cannot, we copy the PHINode and move it into this new block.
191581ad6265SDimitry Andric       PHINode *NewPN = findOrCreatePHIInBlock(*PN, Region, OverallPhiBlock,
191681ad6265SDimitry Andric                                               OutputMappings, UsedPHIs);
191704eeddc0SDimitry Andric       NewI->setOperand(0, NewPN);
1918349cc55cSDimitry Andric     }
1919349cc55cSDimitry Andric 
1920349cc55cSDimitry Andric     // If we added an edge for basic blocks without a predecessor, we remove it
1921349cc55cSDimitry Andric     // here.
1922349cc55cSDimitry Andric     if (EdgeAdded)
1923349cc55cSDimitry Andric       DT.deleteEdge(&DominatingFunction->getEntryBlock(), BB);
1924349cc55cSDimitry Andric     I->eraseFromParent();
1925e8d8bef9SDimitry Andric 
1926e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Replacing uses of output " << *Arg << " in function "
1927e8d8bef9SDimitry Andric                       << *Region.ExtractedFunction << " with " << *AggArg
1928e8d8bef9SDimitry Andric                       << " in function " << *Group.OutlinedFunction << "\n");
1929e8d8bef9SDimitry Andric     Arg->replaceAllUsesWith(AggArg);
1930e8d8bef9SDimitry Andric   }
1931e8d8bef9SDimitry Andric }
1932e8d8bef9SDimitry Andric 
1933e8d8bef9SDimitry Andric /// Within an extracted function, replace the constants that need to be lifted
1934e8d8bef9SDimitry Andric /// into arguments with the actual argument.
1935e8d8bef9SDimitry Andric ///
1936e8d8bef9SDimitry Andric /// \param Region [in] - The region of extracted code to be changed.
1937e8d8bef9SDimitry Andric void replaceConstants(OutlinableRegion &Region) {
1938e8d8bef9SDimitry Andric   OutlinableGroup &Group = *Region.Parent;
1939e8d8bef9SDimitry Andric   // Iterate over the constants that need to be elevated into arguments
1940e8d8bef9SDimitry Andric   for (std::pair<unsigned, Constant *> &Const : Region.AggArgToConstant) {
1941e8d8bef9SDimitry Andric     unsigned AggArgIdx = Const.first;
1942e8d8bef9SDimitry Andric     Function *OutlinedFunction = Group.OutlinedFunction;
1943e8d8bef9SDimitry Andric     assert(OutlinedFunction && "Overall Function is not defined?");
1944e8d8bef9SDimitry Andric     Constant *CST = Const.second;
1945e8d8bef9SDimitry Andric     Argument *Arg = Group.OutlinedFunction->getArg(AggArgIdx);
1946e8d8bef9SDimitry Andric     // Identify the argument it will be elevated to, and replace instances of
1947e8d8bef9SDimitry Andric     // that constant in the function.
1948e8d8bef9SDimitry Andric 
1949e8d8bef9SDimitry Andric     // TODO: If in the future constants do not have one global value number,
1950e8d8bef9SDimitry Andric     // i.e. a constant 1 could be mapped to several values, this check will
1951e8d8bef9SDimitry Andric     // have to be more strict.  It cannot be using only replaceUsesWithIf.
1952e8d8bef9SDimitry Andric 
1953e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Replacing uses of constant " << *CST
1954e8d8bef9SDimitry Andric                       << " in function " << *OutlinedFunction << " with "
1955e8d8bef9SDimitry Andric                       << *Arg << "\n");
1956e8d8bef9SDimitry Andric     CST->replaceUsesWithIf(Arg, [OutlinedFunction](Use &U) {
1957e8d8bef9SDimitry Andric       if (Instruction *I = dyn_cast<Instruction>(U.getUser()))
1958e8d8bef9SDimitry Andric         return I->getFunction() == OutlinedFunction;
1959e8d8bef9SDimitry Andric       return false;
1960e8d8bef9SDimitry Andric     });
1961e8d8bef9SDimitry Andric   }
1962e8d8bef9SDimitry Andric }
1963e8d8bef9SDimitry Andric 
1964e8d8bef9SDimitry Andric /// It is possible that there is a basic block that already performs the same
1965e8d8bef9SDimitry Andric /// stores. This returns a duplicate block, if it exists
1966e8d8bef9SDimitry Andric ///
1967349cc55cSDimitry Andric /// \param OutputBBs [in] the blocks we are looking for a duplicate of.
1968e8d8bef9SDimitry Andric /// \param OutputStoreBBs [in] The existing output blocks.
1969e8d8bef9SDimitry Andric /// \returns an optional value with the number output block if there is a match.
1970bdd1243dSDimitry Andric std::optional<unsigned> findDuplicateOutputBlock(
1971349cc55cSDimitry Andric     DenseMap<Value *, BasicBlock *> &OutputBBs,
1972349cc55cSDimitry Andric     std::vector<DenseMap<Value *, BasicBlock *>> &OutputStoreBBs) {
1973e8d8bef9SDimitry Andric 
1974349cc55cSDimitry Andric   bool Mismatch = false;
1975e8d8bef9SDimitry Andric   unsigned MatchingNum = 0;
1976349cc55cSDimitry Andric   // We compare the new set output blocks to the other sets of output blocks.
1977349cc55cSDimitry Andric   // If they are the same number, and have identical instructions, they are
1978349cc55cSDimitry Andric   // considered to be the same.
1979349cc55cSDimitry Andric   for (DenseMap<Value *, BasicBlock *> &CompBBs : OutputStoreBBs) {
1980349cc55cSDimitry Andric     Mismatch = false;
1981349cc55cSDimitry Andric     for (std::pair<Value *, BasicBlock *> &VToB : CompBBs) {
1982349cc55cSDimitry Andric       DenseMap<Value *, BasicBlock *>::iterator OutputBBIt =
1983349cc55cSDimitry Andric           OutputBBs.find(VToB.first);
1984349cc55cSDimitry Andric       if (OutputBBIt == OutputBBs.end()) {
1985349cc55cSDimitry Andric         Mismatch = true;
1986349cc55cSDimitry Andric         break;
1987e8d8bef9SDimitry Andric       }
1988e8d8bef9SDimitry Andric 
1989349cc55cSDimitry Andric       BasicBlock *CompBB = VToB.second;
1990349cc55cSDimitry Andric       BasicBlock *OutputBB = OutputBBIt->second;
1991349cc55cSDimitry Andric       if (CompBB->size() - 1 != OutputBB->size()) {
1992349cc55cSDimitry Andric         Mismatch = true;
1993349cc55cSDimitry Andric         break;
1994349cc55cSDimitry Andric       }
1995349cc55cSDimitry Andric 
1996e8d8bef9SDimitry Andric       BasicBlock::iterator NIt = OutputBB->begin();
1997e8d8bef9SDimitry Andric       for (Instruction &I : *CompBB) {
1998e8d8bef9SDimitry Andric         if (isa<BranchInst>(&I))
1999e8d8bef9SDimitry Andric           continue;
2000e8d8bef9SDimitry Andric 
2001e8d8bef9SDimitry Andric         if (!I.isIdenticalTo(&(*NIt))) {
2002349cc55cSDimitry Andric           Mismatch = true;
2003e8d8bef9SDimitry Andric           break;
2004e8d8bef9SDimitry Andric         }
2005e8d8bef9SDimitry Andric 
2006e8d8bef9SDimitry Andric         NIt++;
2007e8d8bef9SDimitry Andric       }
2008349cc55cSDimitry Andric     }
2009349cc55cSDimitry Andric 
2010349cc55cSDimitry Andric     if (!Mismatch)
2011e8d8bef9SDimitry Andric       return MatchingNum;
2012e8d8bef9SDimitry Andric 
2013e8d8bef9SDimitry Andric     MatchingNum++;
2014e8d8bef9SDimitry Andric   }
2015e8d8bef9SDimitry Andric 
2016bdd1243dSDimitry Andric   return std::nullopt;
2017e8d8bef9SDimitry Andric }
2018e8d8bef9SDimitry Andric 
2019349cc55cSDimitry Andric /// Remove empty output blocks from the outlined region.
2020349cc55cSDimitry Andric ///
2021349cc55cSDimitry Andric /// \param BlocksToPrune - Mapping of return values output blocks for the \p
2022349cc55cSDimitry Andric /// Region.
2023349cc55cSDimitry Andric /// \param Region - The OutlinableRegion we are analyzing.
2024349cc55cSDimitry Andric static bool
2025349cc55cSDimitry Andric analyzeAndPruneOutputBlocks(DenseMap<Value *, BasicBlock *> &BlocksToPrune,
2026349cc55cSDimitry Andric                             OutlinableRegion &Region) {
2027349cc55cSDimitry Andric   bool AllRemoved = true;
2028349cc55cSDimitry Andric   Value *RetValueForBB;
2029349cc55cSDimitry Andric   BasicBlock *NewBB;
2030349cc55cSDimitry Andric   SmallVector<Value *, 4> ToRemove;
2031349cc55cSDimitry Andric   // Iterate over the output blocks created in the outlined section.
2032349cc55cSDimitry Andric   for (std::pair<Value *, BasicBlock *> &VtoBB : BlocksToPrune) {
2033349cc55cSDimitry Andric     RetValueForBB = VtoBB.first;
2034349cc55cSDimitry Andric     NewBB = VtoBB.second;
2035349cc55cSDimitry Andric 
2036349cc55cSDimitry Andric     // If there are no instructions, we remove it from the module, and also
2037349cc55cSDimitry Andric     // mark the value for removal from the return value to output block mapping.
2038349cc55cSDimitry Andric     if (NewBB->size() == 0) {
2039349cc55cSDimitry Andric       NewBB->eraseFromParent();
2040349cc55cSDimitry Andric       ToRemove.push_back(RetValueForBB);
2041349cc55cSDimitry Andric       continue;
2042349cc55cSDimitry Andric     }
2043349cc55cSDimitry Andric 
2044349cc55cSDimitry Andric     // Mark that we could not remove all the blocks since they were not all
2045349cc55cSDimitry Andric     // empty.
2046349cc55cSDimitry Andric     AllRemoved = false;
2047349cc55cSDimitry Andric   }
2048349cc55cSDimitry Andric 
2049349cc55cSDimitry Andric   // Remove the return value from the mapping.
2050349cc55cSDimitry Andric   for (Value *V : ToRemove)
2051349cc55cSDimitry Andric     BlocksToPrune.erase(V);
2052349cc55cSDimitry Andric 
2053349cc55cSDimitry Andric   // Mark the region as having the no output scheme.
2054349cc55cSDimitry Andric   if (AllRemoved)
2055349cc55cSDimitry Andric     Region.OutputBlockNum = -1;
2056349cc55cSDimitry Andric 
2057349cc55cSDimitry Andric   return AllRemoved;
2058349cc55cSDimitry Andric }
2059349cc55cSDimitry Andric 
2060e8d8bef9SDimitry Andric /// For the outlined section, move needed the StoreInsts for the output
2061e8d8bef9SDimitry Andric /// registers into their own block. Then, determine if there is a duplicate
2062e8d8bef9SDimitry Andric /// output block already created.
2063e8d8bef9SDimitry Andric ///
2064e8d8bef9SDimitry Andric /// \param [in] OG - The OutlinableGroup of regions to be outlined.
2065e8d8bef9SDimitry Andric /// \param [in] Region - The OutlinableRegion that is being analyzed.
2066349cc55cSDimitry Andric /// \param [in,out] OutputBBs - the blocks that stores for this region will be
2067e8d8bef9SDimitry Andric /// placed in.
2068349cc55cSDimitry Andric /// \param [in] EndBBs - the final blocks of the extracted function.
2069e8d8bef9SDimitry Andric /// \param [in] OutputMappings - OutputMappings the mapping of values that have
2070e8d8bef9SDimitry Andric /// been replaced by a new output value.
2071e8d8bef9SDimitry Andric /// \param [in,out] OutputStoreBBs - The existing output blocks.
2072349cc55cSDimitry Andric static void alignOutputBlockWithAggFunc(
2073349cc55cSDimitry Andric     OutlinableGroup &OG, OutlinableRegion &Region,
2074349cc55cSDimitry Andric     DenseMap<Value *, BasicBlock *> &OutputBBs,
2075349cc55cSDimitry Andric     DenseMap<Value *, BasicBlock *> &EndBBs,
2076e8d8bef9SDimitry Andric     const DenseMap<Value *, Value *> &OutputMappings,
2077349cc55cSDimitry Andric     std::vector<DenseMap<Value *, BasicBlock *>> &OutputStoreBBs) {
2078349cc55cSDimitry Andric   // If none of the output blocks have any instructions, this means that we do
2079349cc55cSDimitry Andric   // not have to determine if it matches any of the other output schemes, and we
2080349cc55cSDimitry Andric   // don't have to do anything else.
2081349cc55cSDimitry Andric   if (analyzeAndPruneOutputBlocks(OutputBBs, Region))
2082e8d8bef9SDimitry Andric     return;
2083e8d8bef9SDimitry Andric 
2084349cc55cSDimitry Andric   // Determine is there is a duplicate set of blocks.
2085bdd1243dSDimitry Andric   std::optional<unsigned> MatchingBB =
2086349cc55cSDimitry Andric       findDuplicateOutputBlock(OutputBBs, OutputStoreBBs);
2087e8d8bef9SDimitry Andric 
2088349cc55cSDimitry Andric   // If there is, we remove the new output blocks.  If it does not,
2089349cc55cSDimitry Andric   // we add it to our list of sets of output blocks.
209081ad6265SDimitry Andric   if (MatchingBB) {
2091e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Set output block for region in function"
2092bdd1243dSDimitry Andric                       << Region.ExtractedFunction << " to " << *MatchingBB);
2093e8d8bef9SDimitry Andric 
2094bdd1243dSDimitry Andric     Region.OutputBlockNum = *MatchingBB;
2095349cc55cSDimitry Andric     for (std::pair<Value *, BasicBlock *> &VtoBB : OutputBBs)
2096349cc55cSDimitry Andric       VtoBB.second->eraseFromParent();
2097e8d8bef9SDimitry Andric     return;
2098e8d8bef9SDimitry Andric   }
2099e8d8bef9SDimitry Andric 
2100e8d8bef9SDimitry Andric   Region.OutputBlockNum = OutputStoreBBs.size();
2101e8d8bef9SDimitry Andric 
2102349cc55cSDimitry Andric   Value *RetValueForBB;
2103349cc55cSDimitry Andric   BasicBlock *NewBB;
2104349cc55cSDimitry Andric   OutputStoreBBs.push_back(DenseMap<Value *, BasicBlock *>());
2105349cc55cSDimitry Andric   for (std::pair<Value *, BasicBlock *> &VtoBB : OutputBBs) {
2106349cc55cSDimitry Andric     RetValueForBB = VtoBB.first;
2107349cc55cSDimitry Andric     NewBB = VtoBB.second;
2108349cc55cSDimitry Andric     DenseMap<Value *, BasicBlock *>::iterator VBBIt =
2109349cc55cSDimitry Andric         EndBBs.find(RetValueForBB);
2110e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Create output block for region in"
2111e8d8bef9SDimitry Andric                       << Region.ExtractedFunction << " to "
2112349cc55cSDimitry Andric                       << *NewBB);
2113349cc55cSDimitry Andric     BranchInst::Create(VBBIt->second, NewBB);
2114349cc55cSDimitry Andric     OutputStoreBBs.back().insert(std::make_pair(RetValueForBB, NewBB));
2115349cc55cSDimitry Andric   }
2116349cc55cSDimitry Andric }
2117349cc55cSDimitry Andric 
2118349cc55cSDimitry Andric /// Takes in a mapping, \p OldMap of ConstantValues to BasicBlocks, sorts keys,
2119349cc55cSDimitry Andric /// before creating a basic block for each \p NewMap, and inserting into the new
2120349cc55cSDimitry Andric /// block. Each BasicBlock is named with the scheme "<basename>_<key_idx>".
2121349cc55cSDimitry Andric ///
2122349cc55cSDimitry Andric /// \param OldMap [in] - The mapping to base the new mapping off of.
2123349cc55cSDimitry Andric /// \param NewMap [out] - The output mapping using the keys of \p OldMap.
2124349cc55cSDimitry Andric /// \param ParentFunc [in] - The function to put the new basic block in.
2125349cc55cSDimitry Andric /// \param BaseName [in] - The start of the BasicBlock names to be appended to
2126349cc55cSDimitry Andric /// by an index value.
2127349cc55cSDimitry Andric static void createAndInsertBasicBlocks(DenseMap<Value *, BasicBlock *> &OldMap,
2128349cc55cSDimitry Andric                                        DenseMap<Value *, BasicBlock *> &NewMap,
2129349cc55cSDimitry Andric                                        Function *ParentFunc, Twine BaseName) {
2130349cc55cSDimitry Andric   unsigned Idx = 0;
2131349cc55cSDimitry Andric   std::vector<Value *> SortedKeys;
2132349cc55cSDimitry Andric 
2133349cc55cSDimitry Andric   getSortedConstantKeys(SortedKeys, OldMap);
2134349cc55cSDimitry Andric 
2135349cc55cSDimitry Andric   for (Value *RetVal : SortedKeys) {
2136349cc55cSDimitry Andric     BasicBlock *NewBB = BasicBlock::Create(
2137349cc55cSDimitry Andric         ParentFunc->getContext(),
2138349cc55cSDimitry Andric         Twine(BaseName) + Twine("_") + Twine(static_cast<unsigned>(Idx++)),
2139349cc55cSDimitry Andric         ParentFunc);
2140349cc55cSDimitry Andric     NewMap.insert(std::make_pair(RetVal, NewBB));
2141349cc55cSDimitry Andric   }
2142e8d8bef9SDimitry Andric }
2143e8d8bef9SDimitry Andric 
2144e8d8bef9SDimitry Andric /// Create the switch statement for outlined function to differentiate between
2145e8d8bef9SDimitry Andric /// all the output blocks.
2146e8d8bef9SDimitry Andric ///
2147e8d8bef9SDimitry Andric /// For the outlined section, determine if an outlined block already exists that
2148e8d8bef9SDimitry Andric /// matches the needed stores for the extracted section.
2149e8d8bef9SDimitry Andric /// \param [in] M - The module we are outlining from.
2150e8d8bef9SDimitry Andric /// \param [in] OG - The group of regions to be outlined.
2151349cc55cSDimitry Andric /// \param [in] EndBBs - The final blocks of the extracted function.
2152e8d8bef9SDimitry Andric /// \param [in,out] OutputStoreBBs - The existing output blocks.
2153349cc55cSDimitry Andric void createSwitchStatement(
2154349cc55cSDimitry Andric     Module &M, OutlinableGroup &OG, DenseMap<Value *, BasicBlock *> &EndBBs,
2155349cc55cSDimitry Andric     std::vector<DenseMap<Value *, BasicBlock *>> &OutputStoreBBs) {
2156e8d8bef9SDimitry Andric   // We only need the switch statement if there is more than one store
215704eeddc0SDimitry Andric   // combination, or there is more than one set of output blocks.  The first
215804eeddc0SDimitry Andric   // will occur when we store different sets of values for two different
215904eeddc0SDimitry Andric   // regions.  The second will occur when we have two outputs that are combined
216004eeddc0SDimitry Andric   // in a PHINode outside of the region in one outlined instance, and are used
216104eeddc0SDimitry Andric   // seaparately in another. This will create the same set of OutputGVNs, but
216204eeddc0SDimitry Andric   // will generate two different output schemes.
2163e8d8bef9SDimitry Andric   if (OG.OutputGVNCombinations.size() > 1) {
2164e8d8bef9SDimitry Andric     Function *AggFunc = OG.OutlinedFunction;
2165349cc55cSDimitry Andric     // Create a final block for each different return block.
2166349cc55cSDimitry Andric     DenseMap<Value *, BasicBlock *> ReturnBBs;
2167349cc55cSDimitry Andric     createAndInsertBasicBlocks(OG.EndBBs, ReturnBBs, AggFunc, "final_block");
2168349cc55cSDimitry Andric 
2169349cc55cSDimitry Andric     for (std::pair<Value *, BasicBlock *> &RetBlockPair : ReturnBBs) {
2170349cc55cSDimitry Andric       std::pair<Value *, BasicBlock *> &OutputBlock =
2171349cc55cSDimitry Andric           *OG.EndBBs.find(RetBlockPair.first);
2172349cc55cSDimitry Andric       BasicBlock *ReturnBlock = RetBlockPair.second;
2173349cc55cSDimitry Andric       BasicBlock *EndBB = OutputBlock.second;
2174e8d8bef9SDimitry Andric       Instruction *Term = EndBB->getTerminator();
2175349cc55cSDimitry Andric       // Move the return value to the final block instead of the original exit
2176349cc55cSDimitry Andric       // stub.
2177e8d8bef9SDimitry Andric       Term->moveBefore(*ReturnBlock, ReturnBlock->end());
2178349cc55cSDimitry Andric       // Put the switch statement in the old end basic block for the function
2179349cc55cSDimitry Andric       // with a fall through to the new return block.
2180e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "Create switch statement in " << *AggFunc << " for "
2181e8d8bef9SDimitry Andric                         << OutputStoreBBs.size() << "\n");
2182e8d8bef9SDimitry Andric       SwitchInst *SwitchI =
2183e8d8bef9SDimitry Andric           SwitchInst::Create(AggFunc->getArg(AggFunc->arg_size() - 1),
2184e8d8bef9SDimitry Andric                              ReturnBlock, OutputStoreBBs.size(), EndBB);
2185e8d8bef9SDimitry Andric 
2186e8d8bef9SDimitry Andric       unsigned Idx = 0;
2187349cc55cSDimitry Andric       for (DenseMap<Value *, BasicBlock *> &OutputStoreBB : OutputStoreBBs) {
2188349cc55cSDimitry Andric         DenseMap<Value *, BasicBlock *>::iterator OSBBIt =
2189349cc55cSDimitry Andric             OutputStoreBB.find(OutputBlock.first);
2190349cc55cSDimitry Andric 
2191349cc55cSDimitry Andric         if (OSBBIt == OutputStoreBB.end())
2192349cc55cSDimitry Andric           continue;
2193349cc55cSDimitry Andric 
2194349cc55cSDimitry Andric         BasicBlock *BB = OSBBIt->second;
2195349cc55cSDimitry Andric         SwitchI->addCase(
2196349cc55cSDimitry Andric             ConstantInt::get(Type::getInt32Ty(M.getContext()), Idx), BB);
2197e8d8bef9SDimitry Andric         Term = BB->getTerminator();
2198e8d8bef9SDimitry Andric         Term->setSuccessor(0, ReturnBlock);
2199e8d8bef9SDimitry Andric         Idx++;
2200e8d8bef9SDimitry Andric       }
2201349cc55cSDimitry Andric     }
2202e8d8bef9SDimitry Andric     return;
2203e8d8bef9SDimitry Andric   }
2204e8d8bef9SDimitry Andric 
220504eeddc0SDimitry Andric   assert(OutputStoreBBs.size() < 2 && "Different store sets not handled!");
220604eeddc0SDimitry Andric 
2207349cc55cSDimitry Andric   // If there needs to be stores, move them from the output blocks to their
220804eeddc0SDimitry Andric   // corresponding ending block.  We do not check that the OutputGVNCombinations
220904eeddc0SDimitry Andric   // is equal to 1 here since that could just been the case where there are 0
221004eeddc0SDimitry Andric   // outputs. Instead, we check whether there is more than one set of output
221104eeddc0SDimitry Andric   // blocks since this is the only case where we would have to move the
221204eeddc0SDimitry Andric   // stores, and erase the extraneous blocks.
2213e8d8bef9SDimitry Andric   if (OutputStoreBBs.size() == 1) {
2214e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Move store instructions to the end block in "
2215e8d8bef9SDimitry Andric                       << *OG.OutlinedFunction << "\n");
2216349cc55cSDimitry Andric     DenseMap<Value *, BasicBlock *> OutputBlocks = OutputStoreBBs[0];
2217349cc55cSDimitry Andric     for (std::pair<Value *, BasicBlock *> &VBPair : OutputBlocks) {
2218349cc55cSDimitry Andric       DenseMap<Value *, BasicBlock *>::iterator EndBBIt =
2219349cc55cSDimitry Andric           EndBBs.find(VBPair.first);
2220349cc55cSDimitry Andric       assert(EndBBIt != EndBBs.end() && "Could not find end block");
2221349cc55cSDimitry Andric       BasicBlock *EndBB = EndBBIt->second;
2222349cc55cSDimitry Andric       BasicBlock *OutputBB = VBPair.second;
2223349cc55cSDimitry Andric       Instruction *Term = OutputBB->getTerminator();
2224e8d8bef9SDimitry Andric       Term->eraseFromParent();
2225e8d8bef9SDimitry Andric       Term = EndBB->getTerminator();
2226349cc55cSDimitry Andric       moveBBContents(*OutputBB, *EndBB);
2227e8d8bef9SDimitry Andric       Term->moveBefore(*EndBB, EndBB->end());
2228349cc55cSDimitry Andric       OutputBB->eraseFromParent();
2229349cc55cSDimitry Andric     }
2230e8d8bef9SDimitry Andric   }
2231e8d8bef9SDimitry Andric }
2232e8d8bef9SDimitry Andric 
2233e8d8bef9SDimitry Andric /// Fill the new function that will serve as the replacement function for all of
2234e8d8bef9SDimitry Andric /// the extracted regions of a certain structure from the first region in the
2235e8d8bef9SDimitry Andric /// list of regions.  Replace this first region's extracted function with the
2236e8d8bef9SDimitry Andric /// new overall function.
2237e8d8bef9SDimitry Andric ///
2238e8d8bef9SDimitry Andric /// \param [in] M - The module we are outlining from.
2239e8d8bef9SDimitry Andric /// \param [in] CurrentGroup - The group of regions to be outlined.
2240e8d8bef9SDimitry Andric /// \param [in,out] OutputStoreBBs - The output blocks for each different
2241e8d8bef9SDimitry Andric /// set of stores needed for the different functions.
2242e8d8bef9SDimitry Andric /// \param [in,out] FuncsToRemove - Extracted functions to erase from module
2243e8d8bef9SDimitry Andric /// once outlining is complete.
224404eeddc0SDimitry Andric /// \param [in] OutputMappings - Extracted functions to erase from module
224504eeddc0SDimitry Andric /// once outlining is complete.
2246349cc55cSDimitry Andric static void fillOverallFunction(
2247349cc55cSDimitry Andric     Module &M, OutlinableGroup &CurrentGroup,
2248349cc55cSDimitry Andric     std::vector<DenseMap<Value *, BasicBlock *>> &OutputStoreBBs,
224904eeddc0SDimitry Andric     std::vector<Function *> &FuncsToRemove,
225004eeddc0SDimitry Andric     const DenseMap<Value *, Value *> &OutputMappings) {
2251e8d8bef9SDimitry Andric   OutlinableRegion *CurrentOS = CurrentGroup.Regions[0];
2252e8d8bef9SDimitry Andric 
2253e8d8bef9SDimitry Andric   // Move first extracted function's instructions into new function.
2254e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "Move instructions from "
2255e8d8bef9SDimitry Andric                     << *CurrentOS->ExtractedFunction << " to instruction "
2256e8d8bef9SDimitry Andric                     << *CurrentGroup.OutlinedFunction << "\n");
2257349cc55cSDimitry Andric   moveFunctionData(*CurrentOS->ExtractedFunction,
2258349cc55cSDimitry Andric                    *CurrentGroup.OutlinedFunction, CurrentGroup.EndBBs);
2259e8d8bef9SDimitry Andric 
2260e8d8bef9SDimitry Andric   // Transfer the attributes from the function to the new function.
2261349cc55cSDimitry Andric   for (Attribute A : CurrentOS->ExtractedFunction->getAttributes().getFnAttrs())
2262e8d8bef9SDimitry Andric     CurrentGroup.OutlinedFunction->addFnAttr(A);
2263e8d8bef9SDimitry Andric 
2264349cc55cSDimitry Andric   // Create a new set of output blocks for the first extracted function.
2265349cc55cSDimitry Andric   DenseMap<Value *, BasicBlock *> NewBBs;
2266349cc55cSDimitry Andric   createAndInsertBasicBlocks(CurrentGroup.EndBBs, NewBBs,
2267349cc55cSDimitry Andric                              CurrentGroup.OutlinedFunction, "output_block_0");
2268e8d8bef9SDimitry Andric   CurrentOS->OutputBlockNum = 0;
2269e8d8bef9SDimitry Andric 
227004eeddc0SDimitry Andric   replaceArgumentUses(*CurrentOS, NewBBs, OutputMappings, true);
2271e8d8bef9SDimitry Andric   replaceConstants(*CurrentOS);
2272e8d8bef9SDimitry Andric 
2273349cc55cSDimitry Andric   // We first identify if any output blocks are empty, if they are we remove
2274349cc55cSDimitry Andric   // them. We then create a branch instruction to the basic block to the return
2275349cc55cSDimitry Andric   // block for the function for each non empty output block.
2276349cc55cSDimitry Andric   if (!analyzeAndPruneOutputBlocks(NewBBs, *CurrentOS)) {
2277349cc55cSDimitry Andric     OutputStoreBBs.push_back(DenseMap<Value *, BasicBlock *>());
2278349cc55cSDimitry Andric     for (std::pair<Value *, BasicBlock *> &VToBB : NewBBs) {
2279349cc55cSDimitry Andric       DenseMap<Value *, BasicBlock *>::iterator VBBIt =
2280349cc55cSDimitry Andric           CurrentGroup.EndBBs.find(VToBB.first);
2281349cc55cSDimitry Andric       BasicBlock *EndBB = VBBIt->second;
2282349cc55cSDimitry Andric       BranchInst::Create(EndBB, VToBB.second);
2283349cc55cSDimitry Andric       OutputStoreBBs.back().insert(VToBB);
2284349cc55cSDimitry Andric     }
2285e8d8bef9SDimitry Andric   }
2286e8d8bef9SDimitry Andric 
2287e8d8bef9SDimitry Andric   // Replace the call to the extracted function with the outlined function.
2288e8d8bef9SDimitry Andric   CurrentOS->Call = replaceCalledFunction(M, *CurrentOS);
2289e8d8bef9SDimitry Andric 
2290e8d8bef9SDimitry Andric   // We only delete the extracted functions at the end since we may need to
2291e8d8bef9SDimitry Andric   // reference instructions contained in them for mapping purposes.
2292e8d8bef9SDimitry Andric   FuncsToRemove.push_back(CurrentOS->ExtractedFunction);
2293e8d8bef9SDimitry Andric }
2294e8d8bef9SDimitry Andric 
2295e8d8bef9SDimitry Andric void IROutliner::deduplicateExtractedSections(
2296e8d8bef9SDimitry Andric     Module &M, OutlinableGroup &CurrentGroup,
2297e8d8bef9SDimitry Andric     std::vector<Function *> &FuncsToRemove, unsigned &OutlinedFunctionNum) {
2298e8d8bef9SDimitry Andric   createFunction(M, CurrentGroup, OutlinedFunctionNum);
2299e8d8bef9SDimitry Andric 
2300349cc55cSDimitry Andric   std::vector<DenseMap<Value *, BasicBlock *>> OutputStoreBBs;
2301e8d8bef9SDimitry Andric 
2302e8d8bef9SDimitry Andric   OutlinableRegion *CurrentOS;
2303e8d8bef9SDimitry Andric 
230404eeddc0SDimitry Andric   fillOverallFunction(M, CurrentGroup, OutputStoreBBs, FuncsToRemove,
230504eeddc0SDimitry Andric                       OutputMappings);
2306e8d8bef9SDimitry Andric 
2307349cc55cSDimitry Andric   std::vector<Value *> SortedKeys;
2308e8d8bef9SDimitry Andric   for (unsigned Idx = 1; Idx < CurrentGroup.Regions.size(); Idx++) {
2309e8d8bef9SDimitry Andric     CurrentOS = CurrentGroup.Regions[Idx];
2310e8d8bef9SDimitry Andric     AttributeFuncs::mergeAttributesForOutlining(*CurrentGroup.OutlinedFunction,
2311e8d8bef9SDimitry Andric                                                *CurrentOS->ExtractedFunction);
2312e8d8bef9SDimitry Andric 
2313349cc55cSDimitry Andric     // Create a set of BasicBlocks, one for each return block, to hold the
2314349cc55cSDimitry Andric     // needed store instructions.
2315349cc55cSDimitry Andric     DenseMap<Value *, BasicBlock *> NewBBs;
2316349cc55cSDimitry Andric     createAndInsertBasicBlocks(
2317349cc55cSDimitry Andric         CurrentGroup.EndBBs, NewBBs, CurrentGroup.OutlinedFunction,
2318349cc55cSDimitry Andric         "output_block_" + Twine(static_cast<unsigned>(Idx)));
231904eeddc0SDimitry Andric     replaceArgumentUses(*CurrentOS, NewBBs, OutputMappings);
2320349cc55cSDimitry Andric     alignOutputBlockWithAggFunc(CurrentGroup, *CurrentOS, NewBBs,
2321349cc55cSDimitry Andric                                 CurrentGroup.EndBBs, OutputMappings,
2322e8d8bef9SDimitry Andric                                 OutputStoreBBs);
2323e8d8bef9SDimitry Andric 
2324e8d8bef9SDimitry Andric     CurrentOS->Call = replaceCalledFunction(M, *CurrentOS);
2325e8d8bef9SDimitry Andric     FuncsToRemove.push_back(CurrentOS->ExtractedFunction);
2326e8d8bef9SDimitry Andric   }
2327e8d8bef9SDimitry Andric 
2328e8d8bef9SDimitry Andric   // Create a switch statement to handle the different output schemes.
2329349cc55cSDimitry Andric   createSwitchStatement(M, CurrentGroup, CurrentGroup.EndBBs, OutputStoreBBs);
2330e8d8bef9SDimitry Andric 
2331e8d8bef9SDimitry Andric   OutlinedFunctionNum++;
2332e8d8bef9SDimitry Andric }
2333e8d8bef9SDimitry Andric 
2334349cc55cSDimitry Andric /// Checks that the next instruction in the InstructionDataList matches the
2335349cc55cSDimitry Andric /// next instruction in the module.  If they do not, there could be the
2336349cc55cSDimitry Andric /// possibility that extra code has been inserted, and we must ignore it.
2337349cc55cSDimitry Andric ///
2338349cc55cSDimitry Andric /// \param ID - The IRInstructionData to check the next instruction of.
2339349cc55cSDimitry Andric /// \returns true if the InstructionDataList and actual instruction match.
2340349cc55cSDimitry Andric static bool nextIRInstructionDataMatchesNextInst(IRInstructionData &ID) {
2341349cc55cSDimitry Andric   // We check if there is a discrepancy between the InstructionDataList
2342349cc55cSDimitry Andric   // and the actual next instruction in the module.  If there is, it means
2343349cc55cSDimitry Andric   // that an extra instruction was added, likely by the CodeExtractor.
2344349cc55cSDimitry Andric 
2345349cc55cSDimitry Andric   // Since we do not have any similarity data about this particular
2346349cc55cSDimitry Andric   // instruction, we cannot confidently outline it, and must discard this
2347349cc55cSDimitry Andric   // candidate.
2348349cc55cSDimitry Andric   IRInstructionDataList::iterator NextIDIt = std::next(ID.getIterator());
2349349cc55cSDimitry Andric   Instruction *NextIDLInst = NextIDIt->Inst;
2350349cc55cSDimitry Andric   Instruction *NextModuleInst = nullptr;
2351349cc55cSDimitry Andric   if (!ID.Inst->isTerminator())
2352349cc55cSDimitry Andric     NextModuleInst = ID.Inst->getNextNonDebugInstruction();
2353349cc55cSDimitry Andric   else if (NextIDLInst != nullptr)
2354349cc55cSDimitry Andric     NextModuleInst =
2355349cc55cSDimitry Andric         &*NextIDIt->Inst->getParent()->instructionsWithoutDebug().begin();
2356349cc55cSDimitry Andric 
2357349cc55cSDimitry Andric   if (NextIDLInst && NextIDLInst != NextModuleInst)
2358349cc55cSDimitry Andric     return false;
2359349cc55cSDimitry Andric 
2360349cc55cSDimitry Andric   return true;
2361349cc55cSDimitry Andric }
2362349cc55cSDimitry Andric 
2363349cc55cSDimitry Andric bool IROutliner::isCompatibleWithAlreadyOutlinedCode(
2364349cc55cSDimitry Andric     const OutlinableRegion &Region) {
2365349cc55cSDimitry Andric   IRSimilarityCandidate *IRSC = Region.Candidate;
2366349cc55cSDimitry Andric   unsigned StartIdx = IRSC->getStartIdx();
2367349cc55cSDimitry Andric   unsigned EndIdx = IRSC->getEndIdx();
2368349cc55cSDimitry Andric 
2369349cc55cSDimitry Andric   // A check to make sure that we are not about to attempt to outline something
2370349cc55cSDimitry Andric   // that has already been outlined.
2371349cc55cSDimitry Andric   for (unsigned Idx = StartIdx; Idx <= EndIdx; Idx++)
2372349cc55cSDimitry Andric     if (Outlined.contains(Idx))
2373349cc55cSDimitry Andric       return false;
2374349cc55cSDimitry Andric 
2375349cc55cSDimitry Andric   // We check if the recorded instruction matches the actual next instruction,
2376349cc55cSDimitry Andric   // if it does not, we fix it in the InstructionDataList.
2377349cc55cSDimitry Andric   if (!Region.Candidate->backInstruction()->isTerminator()) {
2378349cc55cSDimitry Andric     Instruction *NewEndInst =
2379349cc55cSDimitry Andric         Region.Candidate->backInstruction()->getNextNonDebugInstruction();
2380349cc55cSDimitry Andric     assert(NewEndInst && "Next instruction is a nullptr?");
2381349cc55cSDimitry Andric     if (Region.Candidate->end()->Inst != NewEndInst) {
2382349cc55cSDimitry Andric       IRInstructionDataList *IDL = Region.Candidate->front()->IDL;
2383349cc55cSDimitry Andric       IRInstructionData *NewEndIRID = new (InstDataAllocator.Allocate())
2384349cc55cSDimitry Andric           IRInstructionData(*NewEndInst,
2385349cc55cSDimitry Andric                             InstructionClassifier.visit(*NewEndInst), *IDL);
2386349cc55cSDimitry Andric 
2387349cc55cSDimitry Andric       // Insert the first IRInstructionData of the new region after the
2388349cc55cSDimitry Andric       // last IRInstructionData of the IRSimilarityCandidate.
2389349cc55cSDimitry Andric       IDL->insert(Region.Candidate->end(), *NewEndIRID);
2390349cc55cSDimitry Andric     }
2391349cc55cSDimitry Andric   }
2392349cc55cSDimitry Andric 
2393349cc55cSDimitry Andric   return none_of(*IRSC, [this](IRInstructionData &ID) {
2394349cc55cSDimitry Andric     if (!nextIRInstructionDataMatchesNextInst(ID))
2395349cc55cSDimitry Andric       return true;
2396349cc55cSDimitry Andric 
2397349cc55cSDimitry Andric     return !this->InstructionClassifier.visit(ID.Inst);
2398349cc55cSDimitry Andric   });
2399349cc55cSDimitry Andric }
2400349cc55cSDimitry Andric 
2401e8d8bef9SDimitry Andric void IROutliner::pruneIncompatibleRegions(
2402e8d8bef9SDimitry Andric     std::vector<IRSimilarityCandidate> &CandidateVec,
2403e8d8bef9SDimitry Andric     OutlinableGroup &CurrentGroup) {
2404e8d8bef9SDimitry Andric   bool PreviouslyOutlined;
2405e8d8bef9SDimitry Andric 
2406e8d8bef9SDimitry Andric   // Sort from beginning to end, so the IRSimilarityCandidates are in order.
2407e8d8bef9SDimitry Andric   stable_sort(CandidateVec, [](const IRSimilarityCandidate &LHS,
2408e8d8bef9SDimitry Andric                                const IRSimilarityCandidate &RHS) {
2409e8d8bef9SDimitry Andric     return LHS.getStartIdx() < RHS.getStartIdx();
2410e8d8bef9SDimitry Andric   });
2411e8d8bef9SDimitry Andric 
2412349cc55cSDimitry Andric   IRSimilarityCandidate &FirstCandidate = CandidateVec[0];
2413349cc55cSDimitry Andric   // Since outlining a call and a branch instruction will be the same as only
2414349cc55cSDimitry Andric   // outlinining a call instruction, we ignore it as a space saving.
2415349cc55cSDimitry Andric   if (FirstCandidate.getLength() == 2) {
2416349cc55cSDimitry Andric     if (isa<CallInst>(FirstCandidate.front()->Inst) &&
2417349cc55cSDimitry Andric         isa<BranchInst>(FirstCandidate.back()->Inst))
2418349cc55cSDimitry Andric       return;
2419349cc55cSDimitry Andric   }
2420349cc55cSDimitry Andric 
2421e8d8bef9SDimitry Andric   unsigned CurrentEndIdx = 0;
2422e8d8bef9SDimitry Andric   for (IRSimilarityCandidate &IRSC : CandidateVec) {
2423e8d8bef9SDimitry Andric     PreviouslyOutlined = false;
2424e8d8bef9SDimitry Andric     unsigned StartIdx = IRSC.getStartIdx();
2425e8d8bef9SDimitry Andric     unsigned EndIdx = IRSC.getEndIdx();
2426bdd1243dSDimitry Andric     const Function &FnForCurrCand = *IRSC.getFunction();
2427e8d8bef9SDimitry Andric 
2428e8d8bef9SDimitry Andric     for (unsigned Idx = StartIdx; Idx <= EndIdx; Idx++)
2429e8d8bef9SDimitry Andric       if (Outlined.contains(Idx)) {
2430e8d8bef9SDimitry Andric         PreviouslyOutlined = true;
2431e8d8bef9SDimitry Andric         break;
2432e8d8bef9SDimitry Andric       }
2433e8d8bef9SDimitry Andric 
2434e8d8bef9SDimitry Andric     if (PreviouslyOutlined)
2435e8d8bef9SDimitry Andric       continue;
2436e8d8bef9SDimitry Andric 
2437349cc55cSDimitry Andric     // Check over the instructions, and if the basic block has its address
2438349cc55cSDimitry Andric     // taken for use somewhere else, we do not outline that block.
2439349cc55cSDimitry Andric     bool BBHasAddressTaken = any_of(IRSC, [](IRInstructionData &ID){
2440349cc55cSDimitry Andric       return ID.Inst->getParent()->hasAddressTaken();
2441349cc55cSDimitry Andric     });
2442349cc55cSDimitry Andric 
2443349cc55cSDimitry Andric     if (BBHasAddressTaken)
2444e8d8bef9SDimitry Andric       continue;
2445e8d8bef9SDimitry Andric 
2446bdd1243dSDimitry Andric     if (FnForCurrCand.hasOptNone())
244781ad6265SDimitry Andric       continue;
244881ad6265SDimitry Andric 
2449bdd1243dSDimitry Andric     if (FnForCurrCand.hasFnAttribute("nooutline")) {
2450bdd1243dSDimitry Andric       LLVM_DEBUG({
2451bdd1243dSDimitry Andric         dbgs() << "... Skipping function with nooutline attribute: "
2452bdd1243dSDimitry Andric                << FnForCurrCand.getName() << "\n";
2453bdd1243dSDimitry Andric       });
2454bdd1243dSDimitry Andric       continue;
2455bdd1243dSDimitry Andric     }
2456bdd1243dSDimitry Andric 
2457e8d8bef9SDimitry Andric     if (IRSC.front()->Inst->getFunction()->hasLinkOnceODRLinkage() &&
2458e8d8bef9SDimitry Andric         !OutlineFromLinkODRs)
2459e8d8bef9SDimitry Andric       continue;
2460e8d8bef9SDimitry Andric 
2461e8d8bef9SDimitry Andric     // Greedily prune out any regions that will overlap with already chosen
2462e8d8bef9SDimitry Andric     // regions.
2463e8d8bef9SDimitry Andric     if (CurrentEndIdx != 0 && StartIdx <= CurrentEndIdx)
2464e8d8bef9SDimitry Andric       continue;
2465e8d8bef9SDimitry Andric 
2466e8d8bef9SDimitry Andric     bool BadInst = any_of(IRSC, [this](IRInstructionData &ID) {
2467349cc55cSDimitry Andric       if (!nextIRInstructionDataMatchesNextInst(ID))
2468e8d8bef9SDimitry Andric         return true;
2469349cc55cSDimitry Andric 
2470e8d8bef9SDimitry Andric       return !this->InstructionClassifier.visit(ID.Inst);
2471e8d8bef9SDimitry Andric     });
2472e8d8bef9SDimitry Andric 
2473e8d8bef9SDimitry Andric     if (BadInst)
2474e8d8bef9SDimitry Andric       continue;
2475e8d8bef9SDimitry Andric 
2476e8d8bef9SDimitry Andric     OutlinableRegion *OS = new (RegionAllocator.Allocate())
2477e8d8bef9SDimitry Andric         OutlinableRegion(IRSC, CurrentGroup);
2478e8d8bef9SDimitry Andric     CurrentGroup.Regions.push_back(OS);
2479e8d8bef9SDimitry Andric 
2480e8d8bef9SDimitry Andric     CurrentEndIdx = EndIdx;
2481e8d8bef9SDimitry Andric   }
2482e8d8bef9SDimitry Andric }
2483e8d8bef9SDimitry Andric 
2484e8d8bef9SDimitry Andric InstructionCost
2485e8d8bef9SDimitry Andric IROutliner::findBenefitFromAllRegions(OutlinableGroup &CurrentGroup) {
2486e8d8bef9SDimitry Andric   InstructionCost RegionBenefit = 0;
2487e8d8bef9SDimitry Andric   for (OutlinableRegion *Region : CurrentGroup.Regions) {
2488e8d8bef9SDimitry Andric     TargetTransformInfo &TTI = getTTI(*Region->StartBB->getParent());
2489e8d8bef9SDimitry Andric     // We add the number of instructions in the region to the benefit as an
2490e8d8bef9SDimitry Andric     // estimate as to how much will be removed.
2491e8d8bef9SDimitry Andric     RegionBenefit += Region->getBenefit(TTI);
2492e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Adding: " << RegionBenefit
2493e8d8bef9SDimitry Andric                       << " saved instructions to overfall benefit.\n");
2494e8d8bef9SDimitry Andric   }
2495e8d8bef9SDimitry Andric 
2496e8d8bef9SDimitry Andric   return RegionBenefit;
2497e8d8bef9SDimitry Andric }
2498e8d8bef9SDimitry Andric 
249904eeddc0SDimitry Andric /// For the \p OutputCanon number passed in find the value represented by this
250004eeddc0SDimitry Andric /// canonical number. If it is from a PHINode, we pick the first incoming
250104eeddc0SDimitry Andric /// value and return that Value instead.
250204eeddc0SDimitry Andric ///
250304eeddc0SDimitry Andric /// \param Region - The OutlinableRegion to get the Value from.
250404eeddc0SDimitry Andric /// \param OutputCanon - The canonical number to find the Value from.
250504eeddc0SDimitry Andric /// \returns The Value represented by a canonical number \p OutputCanon in \p
250604eeddc0SDimitry Andric /// Region.
250704eeddc0SDimitry Andric static Value *findOutputValueInRegion(OutlinableRegion &Region,
250804eeddc0SDimitry Andric                                       unsigned OutputCanon) {
250904eeddc0SDimitry Andric   OutlinableGroup &CurrentGroup = *Region.Parent;
251004eeddc0SDimitry Andric   // If the value is greater than the value in the tracker, we have a
251104eeddc0SDimitry Andric   // PHINode and will instead use one of the incoming values to find the
251204eeddc0SDimitry Andric   // type.
251304eeddc0SDimitry Andric   if (OutputCanon > CurrentGroup.PHINodeGVNTracker) {
251404eeddc0SDimitry Andric     auto It = CurrentGroup.PHINodeGVNToGVNs.find(OutputCanon);
251504eeddc0SDimitry Andric     assert(It != CurrentGroup.PHINodeGVNToGVNs.end() &&
251604eeddc0SDimitry Andric            "Could not find GVN set for PHINode number!");
251704eeddc0SDimitry Andric     assert(It->second.second.size() > 0 && "PHINode does not have any values!");
251804eeddc0SDimitry Andric     OutputCanon = *It->second.second.begin();
251904eeddc0SDimitry Andric   }
2520bdd1243dSDimitry Andric   std::optional<unsigned> OGVN =
2521bdd1243dSDimitry Andric       Region.Candidate->fromCanonicalNum(OutputCanon);
252281ad6265SDimitry Andric   assert(OGVN && "Could not find GVN for Canonical Number?");
2523bdd1243dSDimitry Andric   std::optional<Value *> OV = Region.Candidate->fromGVN(*OGVN);
252481ad6265SDimitry Andric   assert(OV && "Could not find value for GVN?");
252504eeddc0SDimitry Andric   return *OV;
252604eeddc0SDimitry Andric }
252704eeddc0SDimitry Andric 
2528e8d8bef9SDimitry Andric InstructionCost
2529e8d8bef9SDimitry Andric IROutliner::findCostOutputReloads(OutlinableGroup &CurrentGroup) {
2530e8d8bef9SDimitry Andric   InstructionCost OverallCost = 0;
2531e8d8bef9SDimitry Andric   for (OutlinableRegion *Region : CurrentGroup.Regions) {
2532e8d8bef9SDimitry Andric     TargetTransformInfo &TTI = getTTI(*Region->StartBB->getParent());
2533e8d8bef9SDimitry Andric 
2534e8d8bef9SDimitry Andric     // Each output incurs a load after the call, so we add that to the cost.
253504eeddc0SDimitry Andric     for (unsigned OutputCanon : Region->GVNStores) {
253604eeddc0SDimitry Andric       Value *V = findOutputValueInRegion(*Region, OutputCanon);
2537e8d8bef9SDimitry Andric       InstructionCost LoadCost =
2538e8d8bef9SDimitry Andric           TTI.getMemoryOpCost(Instruction::Load, V->getType(), Align(1), 0,
2539e8d8bef9SDimitry Andric                               TargetTransformInfo::TCK_CodeSize);
2540e8d8bef9SDimitry Andric 
2541e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "Adding: " << LoadCost
2542e8d8bef9SDimitry Andric                         << " instructions to cost for output of type "
2543e8d8bef9SDimitry Andric                         << *V->getType() << "\n");
2544e8d8bef9SDimitry Andric       OverallCost += LoadCost;
2545e8d8bef9SDimitry Andric     }
2546e8d8bef9SDimitry Andric   }
2547e8d8bef9SDimitry Andric 
2548e8d8bef9SDimitry Andric   return OverallCost;
2549e8d8bef9SDimitry Andric }
2550e8d8bef9SDimitry Andric 
2551e8d8bef9SDimitry Andric /// Find the extra instructions needed to handle any output values for the
2552e8d8bef9SDimitry Andric /// region.
2553e8d8bef9SDimitry Andric ///
2554e8d8bef9SDimitry Andric /// \param [in] M - The Module to outline from.
2555e8d8bef9SDimitry Andric /// \param [in] CurrentGroup - The collection of OutlinableRegions to analyze.
2556e8d8bef9SDimitry Andric /// \param [in] TTI - The TargetTransformInfo used to collect information for
2557e8d8bef9SDimitry Andric /// new instruction costs.
2558e8d8bef9SDimitry Andric /// \returns the additional cost to handle the outputs.
2559e8d8bef9SDimitry Andric static InstructionCost findCostForOutputBlocks(Module &M,
2560e8d8bef9SDimitry Andric                                                OutlinableGroup &CurrentGroup,
2561e8d8bef9SDimitry Andric                                                TargetTransformInfo &TTI) {
2562e8d8bef9SDimitry Andric   InstructionCost OutputCost = 0;
2563349cc55cSDimitry Andric   unsigned NumOutputBranches = 0;
2564349cc55cSDimitry Andric 
256504eeddc0SDimitry Andric   OutlinableRegion &FirstRegion = *CurrentGroup.Regions[0];
2566349cc55cSDimitry Andric   IRSimilarityCandidate &Candidate = *CurrentGroup.Regions[0]->Candidate;
2567349cc55cSDimitry Andric   DenseSet<BasicBlock *> CandidateBlocks;
2568349cc55cSDimitry Andric   Candidate.getBasicBlocks(CandidateBlocks);
2569349cc55cSDimitry Andric 
2570349cc55cSDimitry Andric   // Count the number of different output branches that point to blocks outside
2571349cc55cSDimitry Andric   // of the region.
2572349cc55cSDimitry Andric   DenseSet<BasicBlock *> FoundBlocks;
2573349cc55cSDimitry Andric   for (IRInstructionData &ID : Candidate) {
2574349cc55cSDimitry Andric     if (!isa<BranchInst>(ID.Inst))
2575349cc55cSDimitry Andric       continue;
2576349cc55cSDimitry Andric 
2577349cc55cSDimitry Andric     for (Value *V : ID.OperVals) {
2578349cc55cSDimitry Andric       BasicBlock *BB = static_cast<BasicBlock *>(V);
257981ad6265SDimitry Andric       if (!CandidateBlocks.contains(BB) && FoundBlocks.insert(BB).second)
2580349cc55cSDimitry Andric         NumOutputBranches++;
2581349cc55cSDimitry Andric     }
2582349cc55cSDimitry Andric   }
2583349cc55cSDimitry Andric 
2584349cc55cSDimitry Andric   CurrentGroup.BranchesToOutside = NumOutputBranches;
2585e8d8bef9SDimitry Andric 
2586e8d8bef9SDimitry Andric   for (const ArrayRef<unsigned> &OutputUse :
2587e8d8bef9SDimitry Andric        CurrentGroup.OutputGVNCombinations) {
258804eeddc0SDimitry Andric     for (unsigned OutputCanon : OutputUse) {
258904eeddc0SDimitry Andric       Value *V = findOutputValueInRegion(FirstRegion, OutputCanon);
2590e8d8bef9SDimitry Andric       InstructionCost StoreCost =
2591e8d8bef9SDimitry Andric           TTI.getMemoryOpCost(Instruction::Load, V->getType(), Align(1), 0,
2592e8d8bef9SDimitry Andric                               TargetTransformInfo::TCK_CodeSize);
2593e8d8bef9SDimitry Andric 
2594e8d8bef9SDimitry Andric       // An instruction cost is added for each store set that needs to occur for
2595e8d8bef9SDimitry Andric       // various output combinations inside the function, plus a branch to
2596e8d8bef9SDimitry Andric       // return to the exit block.
2597e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "Adding: " << StoreCost
2598e8d8bef9SDimitry Andric                         << " instructions to cost for output of type "
2599e8d8bef9SDimitry Andric                         << *V->getType() << "\n");
2600349cc55cSDimitry Andric       OutputCost += StoreCost * NumOutputBranches;
2601e8d8bef9SDimitry Andric     }
2602e8d8bef9SDimitry Andric 
2603e8d8bef9SDimitry Andric     InstructionCost BranchCost =
2604e8d8bef9SDimitry Andric         TTI.getCFInstrCost(Instruction::Br, TargetTransformInfo::TCK_CodeSize);
2605e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Adding " << BranchCost << " to the current cost for"
2606e8d8bef9SDimitry Andric                       << " a branch instruction\n");
2607349cc55cSDimitry Andric     OutputCost += BranchCost * NumOutputBranches;
2608e8d8bef9SDimitry Andric   }
2609e8d8bef9SDimitry Andric 
2610e8d8bef9SDimitry Andric   // If there is more than one output scheme, we must have a comparison and
2611e8d8bef9SDimitry Andric   // branch for each different item in the switch statement.
2612e8d8bef9SDimitry Andric   if (CurrentGroup.OutputGVNCombinations.size() > 1) {
2613e8d8bef9SDimitry Andric     InstructionCost ComparisonCost = TTI.getCmpSelInstrCost(
2614e8d8bef9SDimitry Andric         Instruction::ICmp, Type::getInt32Ty(M.getContext()),
2615e8d8bef9SDimitry Andric         Type::getInt32Ty(M.getContext()), CmpInst::BAD_ICMP_PREDICATE,
2616e8d8bef9SDimitry Andric         TargetTransformInfo::TCK_CodeSize);
2617e8d8bef9SDimitry Andric     InstructionCost BranchCost =
2618e8d8bef9SDimitry Andric         TTI.getCFInstrCost(Instruction::Br, TargetTransformInfo::TCK_CodeSize);
2619e8d8bef9SDimitry Andric 
2620e8d8bef9SDimitry Andric     unsigned DifferentBlocks = CurrentGroup.OutputGVNCombinations.size();
2621e8d8bef9SDimitry Andric     InstructionCost TotalCost = ComparisonCost * BranchCost * DifferentBlocks;
2622e8d8bef9SDimitry Andric 
2623e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Adding: " << TotalCost
2624e8d8bef9SDimitry Andric                       << " instructions for each switch case for each different"
2625e8d8bef9SDimitry Andric                       << " output path in a function\n");
2626349cc55cSDimitry Andric     OutputCost += TotalCost * NumOutputBranches;
2627e8d8bef9SDimitry Andric   }
2628e8d8bef9SDimitry Andric 
2629e8d8bef9SDimitry Andric   return OutputCost;
2630e8d8bef9SDimitry Andric }
2631e8d8bef9SDimitry Andric 
2632e8d8bef9SDimitry Andric void IROutliner::findCostBenefit(Module &M, OutlinableGroup &CurrentGroup) {
2633e8d8bef9SDimitry Andric   InstructionCost RegionBenefit = findBenefitFromAllRegions(CurrentGroup);
2634e8d8bef9SDimitry Andric   CurrentGroup.Benefit += RegionBenefit;
2635e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "Current Benefit: " << CurrentGroup.Benefit << "\n");
2636e8d8bef9SDimitry Andric 
2637e8d8bef9SDimitry Andric   InstructionCost OutputReloadCost = findCostOutputReloads(CurrentGroup);
2638e8d8bef9SDimitry Andric   CurrentGroup.Cost += OutputReloadCost;
2639e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "Current Cost: " << CurrentGroup.Cost << "\n");
2640e8d8bef9SDimitry Andric 
2641e8d8bef9SDimitry Andric   InstructionCost AverageRegionBenefit =
2642e8d8bef9SDimitry Andric       RegionBenefit / CurrentGroup.Regions.size();
2643e8d8bef9SDimitry Andric   unsigned OverallArgumentNum = CurrentGroup.ArgumentTypes.size();
2644e8d8bef9SDimitry Andric   unsigned NumRegions = CurrentGroup.Regions.size();
2645e8d8bef9SDimitry Andric   TargetTransformInfo &TTI =
2646e8d8bef9SDimitry Andric       getTTI(*CurrentGroup.Regions[0]->Candidate->getFunction());
2647e8d8bef9SDimitry Andric 
2648e8d8bef9SDimitry Andric   // We add one region to the cost once, to account for the instructions added
2649e8d8bef9SDimitry Andric   // inside of the newly created function.
2650e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "Adding: " << AverageRegionBenefit
2651e8d8bef9SDimitry Andric                     << " instructions to cost for body of new function.\n");
2652e8d8bef9SDimitry Andric   CurrentGroup.Cost += AverageRegionBenefit;
2653e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "Current Cost: " << CurrentGroup.Cost << "\n");
2654e8d8bef9SDimitry Andric 
2655e8d8bef9SDimitry Andric   // For each argument, we must add an instruction for loading the argument
2656e8d8bef9SDimitry Andric   // out of the register and into a value inside of the newly outlined function.
2657e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "Adding: " << OverallArgumentNum
2658e8d8bef9SDimitry Andric                     << " instructions to cost for each argument in the new"
2659e8d8bef9SDimitry Andric                     << " function.\n");
2660e8d8bef9SDimitry Andric   CurrentGroup.Cost +=
2661e8d8bef9SDimitry Andric       OverallArgumentNum * TargetTransformInfo::TCC_Basic;
2662e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "Current Cost: " << CurrentGroup.Cost << "\n");
2663e8d8bef9SDimitry Andric 
2664e8d8bef9SDimitry Andric   // Each argument needs to either be loaded into a register or onto the stack.
2665e8d8bef9SDimitry Andric   // Some arguments will only be loaded into the stack once the argument
2666e8d8bef9SDimitry Andric   // registers are filled.
2667e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "Adding: " << OverallArgumentNum
2668e8d8bef9SDimitry Andric                     << " instructions to cost for each argument in the new"
2669e8d8bef9SDimitry Andric                     << " function " << NumRegions << " times for the "
2670e8d8bef9SDimitry Andric                     << "needed argument handling at the call site.\n");
2671e8d8bef9SDimitry Andric   CurrentGroup.Cost +=
2672e8d8bef9SDimitry Andric       2 * OverallArgumentNum * TargetTransformInfo::TCC_Basic * NumRegions;
2673e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "Current Cost: " << CurrentGroup.Cost << "\n");
2674e8d8bef9SDimitry Andric 
2675e8d8bef9SDimitry Andric   CurrentGroup.Cost += findCostForOutputBlocks(M, CurrentGroup, TTI);
2676e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "Current Cost: " << CurrentGroup.Cost << "\n");
2677e8d8bef9SDimitry Andric }
2678e8d8bef9SDimitry Andric 
2679e8d8bef9SDimitry Andric void IROutliner::updateOutputMapping(OutlinableRegion &Region,
2680e8d8bef9SDimitry Andric                                      ArrayRef<Value *> Outputs,
2681e8d8bef9SDimitry Andric                                      LoadInst *LI) {
2682e8d8bef9SDimitry Andric   // For and load instructions following the call
2683e8d8bef9SDimitry Andric   Value *Operand = LI->getPointerOperand();
2684bdd1243dSDimitry Andric   std::optional<unsigned> OutputIdx;
2685e8d8bef9SDimitry Andric   // Find if the operand it is an output register.
2686e8d8bef9SDimitry Andric   for (unsigned ArgIdx = Region.NumExtractedInputs;
2687e8d8bef9SDimitry Andric        ArgIdx < Region.Call->arg_size(); ArgIdx++) {
2688e8d8bef9SDimitry Andric     if (Operand == Region.Call->getArgOperand(ArgIdx)) {
2689e8d8bef9SDimitry Andric       OutputIdx = ArgIdx - Region.NumExtractedInputs;
2690e8d8bef9SDimitry Andric       break;
2691e8d8bef9SDimitry Andric     }
2692e8d8bef9SDimitry Andric   }
2693e8d8bef9SDimitry Andric 
2694e8d8bef9SDimitry Andric   // If we found an output register, place a mapping of the new value
2695e8d8bef9SDimitry Andric   // to the original in the mapping.
269681ad6265SDimitry Andric   if (!OutputIdx)
2697e8d8bef9SDimitry Andric     return;
2698e8d8bef9SDimitry Andric 
269906c3fb27SDimitry Andric   if (!OutputMappings.contains(Outputs[*OutputIdx])) {
2700e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Mapping extracted output " << *LI << " to "
2701bdd1243dSDimitry Andric                       << *Outputs[*OutputIdx] << "\n");
2702bdd1243dSDimitry Andric     OutputMappings.insert(std::make_pair(LI, Outputs[*OutputIdx]));
2703e8d8bef9SDimitry Andric   } else {
2704bdd1243dSDimitry Andric     Value *Orig = OutputMappings.find(Outputs[*OutputIdx])->second;
2705e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Mapping extracted output " << *Orig << " to "
2706bdd1243dSDimitry Andric                       << *Outputs[*OutputIdx] << "\n");
2707e8d8bef9SDimitry Andric     OutputMappings.insert(std::make_pair(LI, Orig));
2708e8d8bef9SDimitry Andric   }
2709e8d8bef9SDimitry Andric }
2710e8d8bef9SDimitry Andric 
2711e8d8bef9SDimitry Andric bool IROutliner::extractSection(OutlinableRegion &Region) {
2712e8d8bef9SDimitry Andric   SetVector<Value *> ArgInputs, Outputs, SinkCands;
2713e8d8bef9SDimitry Andric   assert(Region.StartBB && "StartBB for the OutlinableRegion is nullptr!");
2714349cc55cSDimitry Andric   BasicBlock *InitialStart = Region.StartBB;
2715e8d8bef9SDimitry Andric   Function *OrigF = Region.StartBB->getParent();
2716e8d8bef9SDimitry Andric   CodeExtractorAnalysisCache CEAC(*OrigF);
2717349cc55cSDimitry Andric   Region.ExtractedFunction =
2718349cc55cSDimitry Andric       Region.CE->extractCodeRegion(CEAC, ArgInputs, Outputs);
2719e8d8bef9SDimitry Andric 
2720e8d8bef9SDimitry Andric   // If the extraction was successful, find the BasicBlock, and reassign the
2721e8d8bef9SDimitry Andric   // OutlinableRegion blocks
2722e8d8bef9SDimitry Andric   if (!Region.ExtractedFunction) {
2723e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "CodeExtractor failed to outline " << Region.StartBB
2724e8d8bef9SDimitry Andric                       << "\n");
2725e8d8bef9SDimitry Andric     Region.reattachCandidate();
2726e8d8bef9SDimitry Andric     return false;
2727e8d8bef9SDimitry Andric   }
2728e8d8bef9SDimitry Andric 
2729349cc55cSDimitry Andric   // Get the block containing the called branch, and reassign the blocks as
2730349cc55cSDimitry Andric   // necessary.  If the original block still exists, it is because we ended on
2731349cc55cSDimitry Andric   // a branch instruction, and so we move the contents into the block before
2732349cc55cSDimitry Andric   // and assign the previous block correctly.
2733349cc55cSDimitry Andric   User *InstAsUser = Region.ExtractedFunction->user_back();
2734349cc55cSDimitry Andric   BasicBlock *RewrittenBB = cast<Instruction>(InstAsUser)->getParent();
2735349cc55cSDimitry Andric   Region.PrevBB = RewrittenBB->getSinglePredecessor();
2736349cc55cSDimitry Andric   assert(Region.PrevBB && "PrevBB is nullptr?");
2737349cc55cSDimitry Andric   if (Region.PrevBB == InitialStart) {
2738349cc55cSDimitry Andric     BasicBlock *NewPrev = InitialStart->getSinglePredecessor();
2739349cc55cSDimitry Andric     Instruction *BI = NewPrev->getTerminator();
2740349cc55cSDimitry Andric     BI->eraseFromParent();
2741349cc55cSDimitry Andric     moveBBContents(*InitialStart, *NewPrev);
2742349cc55cSDimitry Andric     Region.PrevBB = NewPrev;
2743349cc55cSDimitry Andric     InitialStart->eraseFromParent();
2744349cc55cSDimitry Andric   }
2745349cc55cSDimitry Andric 
2746e8d8bef9SDimitry Andric   Region.StartBB = RewrittenBB;
2747e8d8bef9SDimitry Andric   Region.EndBB = RewrittenBB;
2748e8d8bef9SDimitry Andric 
2749e8d8bef9SDimitry Andric   // The sequences of outlinable regions has now changed.  We must fix the
2750e8d8bef9SDimitry Andric   // IRInstructionDataList for consistency.  Although they may not be illegal
2751e8d8bef9SDimitry Andric   // instructions, they should not be compared with anything else as they
2752e8d8bef9SDimitry Andric   // should not be outlined in this round.  So marking these as illegal is
2753e8d8bef9SDimitry Andric   // allowed.
2754e8d8bef9SDimitry Andric   IRInstructionDataList *IDL = Region.Candidate->front()->IDL;
2755e8d8bef9SDimitry Andric   Instruction *BeginRewritten = &*RewrittenBB->begin();
2756e8d8bef9SDimitry Andric   Instruction *EndRewritten = &*RewrittenBB->begin();
2757e8d8bef9SDimitry Andric   Region.NewFront = new (InstDataAllocator.Allocate()) IRInstructionData(
2758e8d8bef9SDimitry Andric       *BeginRewritten, InstructionClassifier.visit(*BeginRewritten), *IDL);
2759e8d8bef9SDimitry Andric   Region.NewBack = new (InstDataAllocator.Allocate()) IRInstructionData(
2760e8d8bef9SDimitry Andric       *EndRewritten, InstructionClassifier.visit(*EndRewritten), *IDL);
2761e8d8bef9SDimitry Andric 
2762e8d8bef9SDimitry Andric   // Insert the first IRInstructionData of the new region in front of the
2763e8d8bef9SDimitry Andric   // first IRInstructionData of the IRSimilarityCandidate.
2764e8d8bef9SDimitry Andric   IDL->insert(Region.Candidate->begin(), *Region.NewFront);
2765e8d8bef9SDimitry Andric   // Insert the first IRInstructionData of the new region after the
2766e8d8bef9SDimitry Andric   // last IRInstructionData of the IRSimilarityCandidate.
2767e8d8bef9SDimitry Andric   IDL->insert(Region.Candidate->end(), *Region.NewBack);
2768e8d8bef9SDimitry Andric   // Remove the IRInstructionData from the IRSimilarityCandidate.
2769e8d8bef9SDimitry Andric   IDL->erase(Region.Candidate->begin(), std::prev(Region.Candidate->end()));
2770e8d8bef9SDimitry Andric 
2771e8d8bef9SDimitry Andric   assert(RewrittenBB != nullptr &&
2772e8d8bef9SDimitry Andric          "Could not find a predecessor after extraction!");
2773e8d8bef9SDimitry Andric 
2774e8d8bef9SDimitry Andric   // Iterate over the new set of instructions to find the new call
2775e8d8bef9SDimitry Andric   // instruction.
2776e8d8bef9SDimitry Andric   for (Instruction &I : *RewrittenBB)
2777e8d8bef9SDimitry Andric     if (CallInst *CI = dyn_cast<CallInst>(&I)) {
2778e8d8bef9SDimitry Andric       if (Region.ExtractedFunction == CI->getCalledFunction())
2779e8d8bef9SDimitry Andric         Region.Call = CI;
2780e8d8bef9SDimitry Andric     } else if (LoadInst *LI = dyn_cast<LoadInst>(&I))
2781e8d8bef9SDimitry Andric       updateOutputMapping(Region, Outputs.getArrayRef(), LI);
2782e8d8bef9SDimitry Andric   Region.reattachCandidate();
2783e8d8bef9SDimitry Andric   return true;
2784e8d8bef9SDimitry Andric }
2785e8d8bef9SDimitry Andric 
2786e8d8bef9SDimitry Andric unsigned IROutliner::doOutline(Module &M) {
2787e8d8bef9SDimitry Andric   // Find the possible similarity sections.
2788349cc55cSDimitry Andric   InstructionClassifier.EnableBranches = !DisableBranches;
278904eeddc0SDimitry Andric   InstructionClassifier.EnableIndirectCalls = !DisableIndirectCalls;
27901fd87a68SDimitry Andric   InstructionClassifier.EnableIntrinsics = !DisableIntrinsics;
27911fd87a68SDimitry Andric 
2792e8d8bef9SDimitry Andric   IRSimilarityIdentifier &Identifier = getIRSI(M);
2793e8d8bef9SDimitry Andric   SimilarityGroupList &SimilarityCandidates = *Identifier.getSimilarity();
2794e8d8bef9SDimitry Andric 
2795e8d8bef9SDimitry Andric   // Sort them by size of extracted sections
2796e8d8bef9SDimitry Andric   unsigned OutlinedFunctionNum = 0;
2797e8d8bef9SDimitry Andric   // If we only have one SimilarityGroup in SimilarityCandidates, we do not have
2798e8d8bef9SDimitry Andric   // to sort them by the potential number of instructions to be outlined
2799e8d8bef9SDimitry Andric   if (SimilarityCandidates.size() > 1)
2800e8d8bef9SDimitry Andric     llvm::stable_sort(SimilarityCandidates,
2801e8d8bef9SDimitry Andric                       [](const std::vector<IRSimilarityCandidate> &LHS,
2802e8d8bef9SDimitry Andric                          const std::vector<IRSimilarityCandidate> &RHS) {
2803e8d8bef9SDimitry Andric                         return LHS[0].getLength() * LHS.size() >
2804e8d8bef9SDimitry Andric                                RHS[0].getLength() * RHS.size();
2805e8d8bef9SDimitry Andric                       });
2806349cc55cSDimitry Andric   // Creating OutlinableGroups for each SimilarityCandidate to be used in
2807349cc55cSDimitry Andric   // each of the following for loops to avoid making an allocator.
2808349cc55cSDimitry Andric   std::vector<OutlinableGroup> PotentialGroups(SimilarityCandidates.size());
2809e8d8bef9SDimitry Andric 
2810e8d8bef9SDimitry Andric   DenseSet<unsigned> NotSame;
2811349cc55cSDimitry Andric   std::vector<OutlinableGroup *> NegativeCostGroups;
2812349cc55cSDimitry Andric   std::vector<OutlinableRegion *> OutlinedRegions;
2813e8d8bef9SDimitry Andric   // Iterate over the possible sets of similarity.
2814349cc55cSDimitry Andric   unsigned PotentialGroupIdx = 0;
2815e8d8bef9SDimitry Andric   for (SimilarityGroup &CandidateVec : SimilarityCandidates) {
2816349cc55cSDimitry Andric     OutlinableGroup &CurrentGroup = PotentialGroups[PotentialGroupIdx++];
2817e8d8bef9SDimitry Andric 
2818e8d8bef9SDimitry Andric     // Remove entries that were previously outlined
2819e8d8bef9SDimitry Andric     pruneIncompatibleRegions(CandidateVec, CurrentGroup);
2820e8d8bef9SDimitry Andric 
2821e8d8bef9SDimitry Andric     // We pruned the number of regions to 0 to 1, meaning that it's not worth
2822e8d8bef9SDimitry Andric     // trying to outlined since there is no compatible similar instance of this
2823e8d8bef9SDimitry Andric     // code.
2824e8d8bef9SDimitry Andric     if (CurrentGroup.Regions.size() < 2)
2825e8d8bef9SDimitry Andric       continue;
2826e8d8bef9SDimitry Andric 
2827e8d8bef9SDimitry Andric     // Determine if there are any values that are the same constant throughout
2828e8d8bef9SDimitry Andric     // each section in the set.
2829e8d8bef9SDimitry Andric     NotSame.clear();
2830e8d8bef9SDimitry Andric     CurrentGroup.findSameConstants(NotSame);
2831e8d8bef9SDimitry Andric 
2832e8d8bef9SDimitry Andric     if (CurrentGroup.IgnoreGroup)
2833e8d8bef9SDimitry Andric       continue;
2834e8d8bef9SDimitry Andric 
2835e8d8bef9SDimitry Andric     // Create a CodeExtractor for each outlinable region. Identify inputs and
2836e8d8bef9SDimitry Andric     // outputs for each section using the code extractor and create the argument
2837e8d8bef9SDimitry Andric     // types for the Aggregate Outlining Function.
2838349cc55cSDimitry Andric     OutlinedRegions.clear();
2839e8d8bef9SDimitry Andric     for (OutlinableRegion *OS : CurrentGroup.Regions) {
2840e8d8bef9SDimitry Andric       // Break the outlinable region out of its parent BasicBlock into its own
2841e8d8bef9SDimitry Andric       // BasicBlocks (see function implementation).
2842e8d8bef9SDimitry Andric       OS->splitCandidate();
2843349cc55cSDimitry Andric 
2844349cc55cSDimitry Andric       // There's a chance that when the region is split, extra instructions are
2845349cc55cSDimitry Andric       // added to the region. This makes the region no longer viable
2846349cc55cSDimitry Andric       // to be split, so we ignore it for outlining.
2847349cc55cSDimitry Andric       if (!OS->CandidateSplit)
2848349cc55cSDimitry Andric         continue;
2849349cc55cSDimitry Andric 
2850349cc55cSDimitry Andric       SmallVector<BasicBlock *> BE;
285104eeddc0SDimitry Andric       DenseSet<BasicBlock *> BlocksInRegion;
285204eeddc0SDimitry Andric       OS->Candidate->getBasicBlocks(BlocksInRegion, BE);
2853e8d8bef9SDimitry Andric       OS->CE = new (ExtractorAllocator.Allocate())
2854e8d8bef9SDimitry Andric           CodeExtractor(BE, nullptr, false, nullptr, nullptr, nullptr, false,
285581ad6265SDimitry Andric                         false, nullptr, "outlined");
2856e8d8bef9SDimitry Andric       findAddInputsOutputs(M, *OS, NotSame);
2857e8d8bef9SDimitry Andric       if (!OS->IgnoreRegion)
2858e8d8bef9SDimitry Andric         OutlinedRegions.push_back(OS);
2859349cc55cSDimitry Andric 
2860349cc55cSDimitry Andric       // We recombine the blocks together now that we have gathered all the
2861349cc55cSDimitry Andric       // needed information.
2862e8d8bef9SDimitry Andric       OS->reattachCandidate();
2863e8d8bef9SDimitry Andric     }
2864e8d8bef9SDimitry Andric 
2865e8d8bef9SDimitry Andric     CurrentGroup.Regions = std::move(OutlinedRegions);
2866e8d8bef9SDimitry Andric 
2867e8d8bef9SDimitry Andric     if (CurrentGroup.Regions.empty())
2868e8d8bef9SDimitry Andric       continue;
2869e8d8bef9SDimitry Andric 
2870e8d8bef9SDimitry Andric     CurrentGroup.collectGVNStoreSets(M);
2871e8d8bef9SDimitry Andric 
2872e8d8bef9SDimitry Andric     if (CostModel)
2873e8d8bef9SDimitry Andric       findCostBenefit(M, CurrentGroup);
2874e8d8bef9SDimitry Andric 
2875349cc55cSDimitry Andric     // If we are adhering to the cost model, skip those groups where the cost
2876349cc55cSDimitry Andric     // outweighs the benefits.
2877e8d8bef9SDimitry Andric     if (CurrentGroup.Cost >= CurrentGroup.Benefit && CostModel) {
2878349cc55cSDimitry Andric       OptimizationRemarkEmitter &ORE =
2879349cc55cSDimitry Andric           getORE(*CurrentGroup.Regions[0]->Candidate->getFunction());
2880e8d8bef9SDimitry Andric       ORE.emit([&]() {
2881e8d8bef9SDimitry Andric         IRSimilarityCandidate *C = CurrentGroup.Regions[0]->Candidate;
2882e8d8bef9SDimitry Andric         OptimizationRemarkMissed R(DEBUG_TYPE, "WouldNotDecreaseSize",
2883e8d8bef9SDimitry Andric                                    C->frontInstruction());
2884e8d8bef9SDimitry Andric         R << "did not outline "
2885e8d8bef9SDimitry Andric           << ore::NV(std::to_string(CurrentGroup.Regions.size()))
2886e8d8bef9SDimitry Andric           << " regions due to estimated increase of "
2887e8d8bef9SDimitry Andric           << ore::NV("InstructionIncrease",
2888e8d8bef9SDimitry Andric                      CurrentGroup.Cost - CurrentGroup.Benefit)
2889e8d8bef9SDimitry Andric           << " instructions at locations ";
2890e8d8bef9SDimitry Andric         interleave(
2891e8d8bef9SDimitry Andric             CurrentGroup.Regions.begin(), CurrentGroup.Regions.end(),
2892e8d8bef9SDimitry Andric             [&R](OutlinableRegion *Region) {
2893e8d8bef9SDimitry Andric               R << ore::NV(
2894e8d8bef9SDimitry Andric                   "DebugLoc",
2895e8d8bef9SDimitry Andric                   Region->Candidate->frontInstruction()->getDebugLoc());
2896e8d8bef9SDimitry Andric             },
2897e8d8bef9SDimitry Andric             [&R]() { R << " "; });
2898e8d8bef9SDimitry Andric         return R;
2899e8d8bef9SDimitry Andric       });
2900e8d8bef9SDimitry Andric       continue;
2901e8d8bef9SDimitry Andric     }
2902e8d8bef9SDimitry Andric 
2903349cc55cSDimitry Andric     NegativeCostGroups.push_back(&CurrentGroup);
2904349cc55cSDimitry Andric   }
2905349cc55cSDimitry Andric 
2906349cc55cSDimitry Andric   ExtractorAllocator.DestroyAll();
2907349cc55cSDimitry Andric 
2908349cc55cSDimitry Andric   if (NegativeCostGroups.size() > 1)
2909349cc55cSDimitry Andric     stable_sort(NegativeCostGroups,
2910349cc55cSDimitry Andric                 [](const OutlinableGroup *LHS, const OutlinableGroup *RHS) {
2911349cc55cSDimitry Andric                   return LHS->Benefit - LHS->Cost > RHS->Benefit - RHS->Cost;
2912349cc55cSDimitry Andric                 });
2913349cc55cSDimitry Andric 
2914349cc55cSDimitry Andric   std::vector<Function *> FuncsToRemove;
2915349cc55cSDimitry Andric   for (OutlinableGroup *CG : NegativeCostGroups) {
2916349cc55cSDimitry Andric     OutlinableGroup &CurrentGroup = *CG;
2917349cc55cSDimitry Andric 
2918349cc55cSDimitry Andric     OutlinedRegions.clear();
2919349cc55cSDimitry Andric     for (OutlinableRegion *Region : CurrentGroup.Regions) {
2920349cc55cSDimitry Andric       // We check whether our region is compatible with what has already been
2921349cc55cSDimitry Andric       // outlined, and whether we need to ignore this item.
2922349cc55cSDimitry Andric       if (!isCompatibleWithAlreadyOutlinedCode(*Region))
2923349cc55cSDimitry Andric         continue;
2924349cc55cSDimitry Andric       OutlinedRegions.push_back(Region);
2925349cc55cSDimitry Andric     }
2926349cc55cSDimitry Andric 
2927349cc55cSDimitry Andric     if (OutlinedRegions.size() < 2)
2928349cc55cSDimitry Andric       continue;
2929349cc55cSDimitry Andric 
2930349cc55cSDimitry Andric     // Reestimate the cost and benefit of the OutlinableGroup. Continue only if
2931349cc55cSDimitry Andric     // we are still outlining enough regions to make up for the added cost.
2932349cc55cSDimitry Andric     CurrentGroup.Regions = std::move(OutlinedRegions);
2933349cc55cSDimitry Andric     if (CostModel) {
2934349cc55cSDimitry Andric       CurrentGroup.Benefit = 0;
2935349cc55cSDimitry Andric       CurrentGroup.Cost = 0;
2936349cc55cSDimitry Andric       findCostBenefit(M, CurrentGroup);
2937349cc55cSDimitry Andric       if (CurrentGroup.Cost >= CurrentGroup.Benefit)
2938349cc55cSDimitry Andric         continue;
2939349cc55cSDimitry Andric     }
2940349cc55cSDimitry Andric     OutlinedRegions.clear();
2941349cc55cSDimitry Andric     for (OutlinableRegion *Region : CurrentGroup.Regions) {
2942349cc55cSDimitry Andric       Region->splitCandidate();
2943349cc55cSDimitry Andric       if (!Region->CandidateSplit)
2944349cc55cSDimitry Andric         continue;
2945349cc55cSDimitry Andric       OutlinedRegions.push_back(Region);
2946349cc55cSDimitry Andric     }
2947349cc55cSDimitry Andric 
2948349cc55cSDimitry Andric     CurrentGroup.Regions = std::move(OutlinedRegions);
2949349cc55cSDimitry Andric     if (CurrentGroup.Regions.size() < 2) {
2950349cc55cSDimitry Andric       for (OutlinableRegion *R : CurrentGroup.Regions)
2951349cc55cSDimitry Andric         R->reattachCandidate();
2952349cc55cSDimitry Andric       continue;
2953349cc55cSDimitry Andric     }
2954349cc55cSDimitry Andric 
2955e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Outlining regions with cost " << CurrentGroup.Cost
2956e8d8bef9SDimitry Andric                       << " and benefit " << CurrentGroup.Benefit << "\n");
2957e8d8bef9SDimitry Andric 
2958e8d8bef9SDimitry Andric     // Create functions out of all the sections, and mark them as outlined.
2959e8d8bef9SDimitry Andric     OutlinedRegions.clear();
2960e8d8bef9SDimitry Andric     for (OutlinableRegion *OS : CurrentGroup.Regions) {
2961349cc55cSDimitry Andric       SmallVector<BasicBlock *> BE;
296204eeddc0SDimitry Andric       DenseSet<BasicBlock *> BlocksInRegion;
296304eeddc0SDimitry Andric       OS->Candidate->getBasicBlocks(BlocksInRegion, BE);
2964349cc55cSDimitry Andric       OS->CE = new (ExtractorAllocator.Allocate())
2965349cc55cSDimitry Andric           CodeExtractor(BE, nullptr, false, nullptr, nullptr, nullptr, false,
296681ad6265SDimitry Andric                         false, nullptr, "outlined");
2967e8d8bef9SDimitry Andric       bool FunctionOutlined = extractSection(*OS);
2968e8d8bef9SDimitry Andric       if (FunctionOutlined) {
2969e8d8bef9SDimitry Andric         unsigned StartIdx = OS->Candidate->getStartIdx();
2970e8d8bef9SDimitry Andric         unsigned EndIdx = OS->Candidate->getEndIdx();
2971e8d8bef9SDimitry Andric         for (unsigned Idx = StartIdx; Idx <= EndIdx; Idx++)
2972e8d8bef9SDimitry Andric           Outlined.insert(Idx);
2973e8d8bef9SDimitry Andric 
2974e8d8bef9SDimitry Andric         OutlinedRegions.push_back(OS);
2975e8d8bef9SDimitry Andric       }
2976e8d8bef9SDimitry Andric     }
2977e8d8bef9SDimitry Andric 
2978e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Outlined " << OutlinedRegions.size()
2979e8d8bef9SDimitry Andric                       << " with benefit " << CurrentGroup.Benefit
2980e8d8bef9SDimitry Andric                       << " and cost " << CurrentGroup.Cost << "\n");
2981e8d8bef9SDimitry Andric 
2982e8d8bef9SDimitry Andric     CurrentGroup.Regions = std::move(OutlinedRegions);
2983e8d8bef9SDimitry Andric 
2984e8d8bef9SDimitry Andric     if (CurrentGroup.Regions.empty())
2985e8d8bef9SDimitry Andric       continue;
2986e8d8bef9SDimitry Andric 
2987e8d8bef9SDimitry Andric     OptimizationRemarkEmitter &ORE =
2988e8d8bef9SDimitry Andric         getORE(*CurrentGroup.Regions[0]->Call->getFunction());
2989e8d8bef9SDimitry Andric     ORE.emit([&]() {
2990e8d8bef9SDimitry Andric       IRSimilarityCandidate *C = CurrentGroup.Regions[0]->Candidate;
2991e8d8bef9SDimitry Andric       OptimizationRemark R(DEBUG_TYPE, "Outlined", C->front()->Inst);
2992e8d8bef9SDimitry Andric       R << "outlined " << ore::NV(std::to_string(CurrentGroup.Regions.size()))
2993e8d8bef9SDimitry Andric         << " regions with decrease of "
2994e8d8bef9SDimitry Andric         << ore::NV("Benefit", CurrentGroup.Benefit - CurrentGroup.Cost)
2995e8d8bef9SDimitry Andric         << " instructions at locations ";
2996e8d8bef9SDimitry Andric       interleave(
2997e8d8bef9SDimitry Andric           CurrentGroup.Regions.begin(), CurrentGroup.Regions.end(),
2998e8d8bef9SDimitry Andric           [&R](OutlinableRegion *Region) {
2999e8d8bef9SDimitry Andric             R << ore::NV("DebugLoc",
3000e8d8bef9SDimitry Andric                          Region->Candidate->frontInstruction()->getDebugLoc());
3001e8d8bef9SDimitry Andric           },
3002e8d8bef9SDimitry Andric           [&R]() { R << " "; });
3003e8d8bef9SDimitry Andric       return R;
3004e8d8bef9SDimitry Andric     });
3005e8d8bef9SDimitry Andric 
3006e8d8bef9SDimitry Andric     deduplicateExtractedSections(M, CurrentGroup, FuncsToRemove,
3007e8d8bef9SDimitry Andric                                  OutlinedFunctionNum);
3008e8d8bef9SDimitry Andric   }
3009e8d8bef9SDimitry Andric 
3010e8d8bef9SDimitry Andric   for (Function *F : FuncsToRemove)
3011e8d8bef9SDimitry Andric     F->eraseFromParent();
3012e8d8bef9SDimitry Andric 
3013e8d8bef9SDimitry Andric   return OutlinedFunctionNum;
3014e8d8bef9SDimitry Andric }
3015e8d8bef9SDimitry Andric 
3016e8d8bef9SDimitry Andric bool IROutliner::run(Module &M) {
3017e8d8bef9SDimitry Andric   CostModel = !NoCostModel;
3018e8d8bef9SDimitry Andric   OutlineFromLinkODRs = EnableLinkOnceODRIROutlining;
3019e8d8bef9SDimitry Andric 
3020e8d8bef9SDimitry Andric   return doOutline(M) > 0;
3021e8d8bef9SDimitry Andric }
3022e8d8bef9SDimitry Andric 
3023e8d8bef9SDimitry Andric PreservedAnalyses IROutlinerPass::run(Module &M, ModuleAnalysisManager &AM) {
3024e8d8bef9SDimitry Andric   auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
3025e8d8bef9SDimitry Andric 
3026e8d8bef9SDimitry Andric   std::function<TargetTransformInfo &(Function &)> GTTI =
3027e8d8bef9SDimitry Andric       [&FAM](Function &F) -> TargetTransformInfo & {
3028e8d8bef9SDimitry Andric     return FAM.getResult<TargetIRAnalysis>(F);
3029e8d8bef9SDimitry Andric   };
3030e8d8bef9SDimitry Andric 
3031e8d8bef9SDimitry Andric   std::function<IRSimilarityIdentifier &(Module &)> GIRSI =
3032e8d8bef9SDimitry Andric       [&AM](Module &M) -> IRSimilarityIdentifier & {
3033e8d8bef9SDimitry Andric     return AM.getResult<IRSimilarityAnalysis>(M);
3034e8d8bef9SDimitry Andric   };
3035e8d8bef9SDimitry Andric 
3036e8d8bef9SDimitry Andric   std::unique_ptr<OptimizationRemarkEmitter> ORE;
3037e8d8bef9SDimitry Andric   std::function<OptimizationRemarkEmitter &(Function &)> GORE =
3038e8d8bef9SDimitry Andric       [&ORE](Function &F) -> OptimizationRemarkEmitter & {
3039e8d8bef9SDimitry Andric     ORE.reset(new OptimizationRemarkEmitter(&F));
304081ad6265SDimitry Andric     return *ORE;
3041e8d8bef9SDimitry Andric   };
3042e8d8bef9SDimitry Andric 
3043e8d8bef9SDimitry Andric   if (IROutliner(GTTI, GIRSI, GORE).run(M))
3044e8d8bef9SDimitry Andric     return PreservedAnalyses::none();
3045e8d8bef9SDimitry Andric   return PreservedAnalyses::all();
3046e8d8bef9SDimitry Andric }
3047