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