173471bf0Spatrick //===- IROutliner.cpp -- Outline Similar Regions ----------------*- C++ -*-===//
273471bf0Spatrick //
373471bf0Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
473471bf0Spatrick // See https://llvm.org/LICENSE.txt for license information.
573471bf0Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
673471bf0Spatrick //
773471bf0Spatrick //===----------------------------------------------------------------------===//
873471bf0Spatrick ///
973471bf0Spatrick /// \file
1073471bf0Spatrick // Implementation for the IROutliner which is used by the IROutliner Pass.
1173471bf0Spatrick //
1273471bf0Spatrick //===----------------------------------------------------------------------===//
1373471bf0Spatrick
1473471bf0Spatrick #include "llvm/Transforms/IPO/IROutliner.h"
1573471bf0Spatrick #include "llvm/Analysis/IRSimilarityIdentifier.h"
1673471bf0Spatrick #include "llvm/Analysis/OptimizationRemarkEmitter.h"
1773471bf0Spatrick #include "llvm/Analysis/TargetTransformInfo.h"
1873471bf0Spatrick #include "llvm/IR/Attributes.h"
1973471bf0Spatrick #include "llvm/IR/DIBuilder.h"
20*d415bd75Srobert #include "llvm/IR/DebugInfo.h"
21*d415bd75Srobert #include "llvm/IR/DebugInfoMetadata.h"
22*d415bd75Srobert #include "llvm/IR/Dominators.h"
2373471bf0Spatrick #include "llvm/IR/Mangler.h"
2473471bf0Spatrick #include "llvm/IR/PassManager.h"
2573471bf0Spatrick #include "llvm/InitializePasses.h"
2673471bf0Spatrick #include "llvm/Pass.h"
2773471bf0Spatrick #include "llvm/Support/CommandLine.h"
2873471bf0Spatrick #include "llvm/Transforms/IPO.h"
29*d415bd75Srobert #include <optional>
3073471bf0Spatrick #include <vector>
3173471bf0Spatrick
3273471bf0Spatrick #define DEBUG_TYPE "iroutliner"
3373471bf0Spatrick
3473471bf0Spatrick using namespace llvm;
3573471bf0Spatrick using namespace IRSimilarity;
3673471bf0Spatrick
37*d415bd75Srobert // A command flag to be used for debugging to exclude branches from similarity
38*d415bd75Srobert // matching and outlining.
39*d415bd75Srobert namespace llvm {
40*d415bd75Srobert extern cl::opt<bool> DisableBranches;
41*d415bd75Srobert
42*d415bd75Srobert // A command flag to be used for debugging to indirect calls from similarity
43*d415bd75Srobert // matching and outlining.
44*d415bd75Srobert extern cl::opt<bool> DisableIndirectCalls;
45*d415bd75Srobert
46*d415bd75Srobert // A command flag to be used for debugging to exclude intrinsics from similarity
47*d415bd75Srobert // matching and outlining.
48*d415bd75Srobert extern cl::opt<bool> DisableIntrinsics;
49*d415bd75Srobert
50*d415bd75Srobert } // namespace llvm
51*d415bd75Srobert
5273471bf0Spatrick // Set to true if the user wants the ir outliner to run on linkonceodr linkage
5373471bf0Spatrick // functions. This is false by default because the linker can dedupe linkonceodr
5473471bf0Spatrick // functions. Since the outliner is confined to a single module (modulo LTO),
5573471bf0Spatrick // this is off by default. It should, however, be the default behavior in
5673471bf0Spatrick // LTO.
5773471bf0Spatrick static cl::opt<bool> EnableLinkOnceODRIROutlining(
5873471bf0Spatrick "enable-linkonceodr-ir-outlining", cl::Hidden,
5973471bf0Spatrick cl::desc("Enable the IR outliner on linkonceodr functions"),
6073471bf0Spatrick cl::init(false));
6173471bf0Spatrick
6273471bf0Spatrick // This is a debug option to test small pieces of code to ensure that outlining
6373471bf0Spatrick // works correctly.
6473471bf0Spatrick static cl::opt<bool> NoCostModel(
6573471bf0Spatrick "ir-outlining-no-cost", cl::init(false), cl::ReallyHidden,
6673471bf0Spatrick cl::desc("Debug option to outline greedily, without restriction that "
6773471bf0Spatrick "calculated benefit outweighs cost"));
6873471bf0Spatrick
6973471bf0Spatrick /// The OutlinableGroup holds all the overarching information for outlining
7073471bf0Spatrick /// a set of regions that are structurally similar to one another, such as the
7173471bf0Spatrick /// types of the overall function, the output blocks, the sets of stores needed
7273471bf0Spatrick /// and a list of the different regions. This information is used in the
7373471bf0Spatrick /// deduplication of extracted regions with the same structure.
7473471bf0Spatrick struct OutlinableGroup {
7573471bf0Spatrick /// The sections that could be outlined
7673471bf0Spatrick std::vector<OutlinableRegion *> Regions;
7773471bf0Spatrick
7873471bf0Spatrick /// The argument types for the function created as the overall function to
7973471bf0Spatrick /// replace the extracted function for each region.
8073471bf0Spatrick std::vector<Type *> ArgumentTypes;
8173471bf0Spatrick /// The FunctionType for the overall function.
8273471bf0Spatrick FunctionType *OutlinedFunctionType = nullptr;
8373471bf0Spatrick /// The Function for the collective overall function.
8473471bf0Spatrick Function *OutlinedFunction = nullptr;
8573471bf0Spatrick
8673471bf0Spatrick /// Flag for whether we should not consider this group of OutlinableRegions
8773471bf0Spatrick /// for extraction.
8873471bf0Spatrick bool IgnoreGroup = false;
8973471bf0Spatrick
90*d415bd75Srobert /// The return blocks for the overall function.
91*d415bd75Srobert DenseMap<Value *, BasicBlock *> EndBBs;
92*d415bd75Srobert
93*d415bd75Srobert /// The PHIBlocks with their corresponding return block based on the return
94*d415bd75Srobert /// value as the key.
95*d415bd75Srobert DenseMap<Value *, BasicBlock *> PHIBlocks;
9673471bf0Spatrick
9773471bf0Spatrick /// A set containing the different GVN store sets needed. Each array contains
9873471bf0Spatrick /// a sorted list of the different values that need to be stored into output
9973471bf0Spatrick /// registers.
10073471bf0Spatrick DenseSet<ArrayRef<unsigned>> OutputGVNCombinations;
10173471bf0Spatrick
10273471bf0Spatrick /// Flag for whether the \ref ArgumentTypes have been defined after the
10373471bf0Spatrick /// extraction of the first region.
10473471bf0Spatrick bool InputTypesSet = false;
10573471bf0Spatrick
10673471bf0Spatrick /// The number of input values in \ref ArgumentTypes. Anything after this
10773471bf0Spatrick /// index in ArgumentTypes is an output argument.
10873471bf0Spatrick unsigned NumAggregateInputs = 0;
10973471bf0Spatrick
110*d415bd75Srobert /// The mapping of the canonical numbering of the values in outlined sections
111*d415bd75Srobert /// to specific arguments.
112*d415bd75Srobert DenseMap<unsigned, unsigned> CanonicalNumberToAggArg;
113*d415bd75Srobert
114*d415bd75Srobert /// The number of branches in the region target a basic block that is outside
115*d415bd75Srobert /// of the region.
116*d415bd75Srobert unsigned BranchesToOutside = 0;
117*d415bd75Srobert
118*d415bd75Srobert /// Tracker counting backwards from the highest unsigned value possible to
119*d415bd75Srobert /// avoid conflicting with the GVNs of assigned values. We start at -3 since
120*d415bd75Srobert /// -2 and -1 are assigned by the DenseMap.
121*d415bd75Srobert unsigned PHINodeGVNTracker = -3;
122*d415bd75Srobert
123*d415bd75Srobert DenseMap<unsigned,
124*d415bd75Srobert std::pair<std::pair<unsigned, unsigned>, SmallVector<unsigned, 2>>>
125*d415bd75Srobert PHINodeGVNToGVNs;
126*d415bd75Srobert DenseMap<hash_code, unsigned> GVNsToPHINodeGVN;
127*d415bd75Srobert
12873471bf0Spatrick /// The number of instructions that will be outlined by extracting \ref
12973471bf0Spatrick /// Regions.
13073471bf0Spatrick InstructionCost Benefit = 0;
13173471bf0Spatrick /// The number of added instructions needed for the outlining of the \ref
13273471bf0Spatrick /// Regions.
13373471bf0Spatrick InstructionCost Cost = 0;
13473471bf0Spatrick
13573471bf0Spatrick /// The argument that needs to be marked with the swifterr attribute. If not
13673471bf0Spatrick /// needed, there is no value.
137*d415bd75Srobert std::optional<unsigned> SwiftErrorArgument;
13873471bf0Spatrick
13973471bf0Spatrick /// For the \ref Regions, we look at every Value. If it is a constant,
14073471bf0Spatrick /// we check whether it is the same in Region.
14173471bf0Spatrick ///
14273471bf0Spatrick /// \param [in,out] NotSame contains the global value numbers where the
14373471bf0Spatrick /// constant is not always the same, and must be passed in as an argument.
14473471bf0Spatrick void findSameConstants(DenseSet<unsigned> &NotSame);
14573471bf0Spatrick
14673471bf0Spatrick /// For the regions, look at each set of GVN stores needed and account for
14773471bf0Spatrick /// each combination. Add an argument to the argument types if there is
14873471bf0Spatrick /// more than one combination.
14973471bf0Spatrick ///
15073471bf0Spatrick /// \param [in] M - The module we are outlining from.
15173471bf0Spatrick void collectGVNStoreSets(Module &M);
15273471bf0Spatrick };
15373471bf0Spatrick
15473471bf0Spatrick /// Move the contents of \p SourceBB to before the last instruction of \p
15573471bf0Spatrick /// TargetBB.
15673471bf0Spatrick /// \param SourceBB - the BasicBlock to pull Instructions from.
15773471bf0Spatrick /// \param TargetBB - the BasicBlock to put Instruction into.
moveBBContents(BasicBlock & SourceBB,BasicBlock & TargetBB)15873471bf0Spatrick static void moveBBContents(BasicBlock &SourceBB, BasicBlock &TargetBB) {
159*d415bd75Srobert for (Instruction &I : llvm::make_early_inc_range(SourceBB))
160*d415bd75Srobert I.moveBefore(TargetBB, TargetBB.end());
161*d415bd75Srobert }
162*d415bd75Srobert
163*d415bd75Srobert /// A function to sort the keys of \p Map, which must be a mapping of constant
164*d415bd75Srobert /// values to basic blocks and return it in \p SortedKeys
165*d415bd75Srobert ///
166*d415bd75Srobert /// \param SortedKeys - The vector the keys will be return in and sorted.
167*d415bd75Srobert /// \param Map - The DenseMap containing keys to sort.
getSortedConstantKeys(std::vector<Value * > & SortedKeys,DenseMap<Value *,BasicBlock * > & Map)168*d415bd75Srobert static void getSortedConstantKeys(std::vector<Value *> &SortedKeys,
169*d415bd75Srobert DenseMap<Value *, BasicBlock *> &Map) {
170*d415bd75Srobert for (auto &VtoBB : Map)
171*d415bd75Srobert SortedKeys.push_back(VtoBB.first);
172*d415bd75Srobert
173*d415bd75Srobert // Here we expect to have either 1 value that is void (nullptr) or multiple
174*d415bd75Srobert // values that are all constant integers.
175*d415bd75Srobert if (SortedKeys.size() == 1) {
176*d415bd75Srobert assert(!SortedKeys[0] && "Expected a single void value.");
177*d415bd75Srobert return;
178*d415bd75Srobert }
179*d415bd75Srobert
180*d415bd75Srobert stable_sort(SortedKeys, [](const Value *LHS, const Value *RHS) {
181*d415bd75Srobert assert(LHS && RHS && "Expected non void values.");
182*d415bd75Srobert const ConstantInt *LHSC = dyn_cast<ConstantInt>(LHS);
183*d415bd75Srobert const ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS);
184*d415bd75Srobert assert(RHSC && "Not a constant integer in return value?");
185*d415bd75Srobert assert(LHSC && "Not a constant integer in return value?");
186*d415bd75Srobert
187*d415bd75Srobert return LHSC->getLimitedValue() < RHSC->getLimitedValue();
188*d415bd75Srobert });
189*d415bd75Srobert }
190*d415bd75Srobert
findCorrespondingValueIn(const OutlinableRegion & Other,Value * V)191*d415bd75Srobert Value *OutlinableRegion::findCorrespondingValueIn(const OutlinableRegion &Other,
192*d415bd75Srobert Value *V) {
193*d415bd75Srobert std::optional<unsigned> GVN = Candidate->getGVN(V);
194*d415bd75Srobert assert(GVN && "No GVN for incoming value");
195*d415bd75Srobert std::optional<unsigned> CanonNum = Candidate->getCanonicalNum(*GVN);
196*d415bd75Srobert std::optional<unsigned> FirstGVN =
197*d415bd75Srobert Other.Candidate->fromCanonicalNum(*CanonNum);
198*d415bd75Srobert std::optional<Value *> FoundValueOpt = Other.Candidate->fromGVN(*FirstGVN);
199*d415bd75Srobert return FoundValueOpt.value_or(nullptr);
200*d415bd75Srobert }
201*d415bd75Srobert
202*d415bd75Srobert BasicBlock *
findCorrespondingBlockIn(const OutlinableRegion & Other,BasicBlock * BB)203*d415bd75Srobert OutlinableRegion::findCorrespondingBlockIn(const OutlinableRegion &Other,
204*d415bd75Srobert BasicBlock *BB) {
205*d415bd75Srobert Instruction *FirstNonPHI = BB->getFirstNonPHI();
206*d415bd75Srobert assert(FirstNonPHI && "block is empty?");
207*d415bd75Srobert Value *CorrespondingVal = findCorrespondingValueIn(Other, FirstNonPHI);
208*d415bd75Srobert if (!CorrespondingVal)
209*d415bd75Srobert return nullptr;
210*d415bd75Srobert BasicBlock *CorrespondingBlock =
211*d415bd75Srobert cast<Instruction>(CorrespondingVal)->getParent();
212*d415bd75Srobert return CorrespondingBlock;
213*d415bd75Srobert }
214*d415bd75Srobert
215*d415bd75Srobert /// Rewrite the BranchInsts in the incoming blocks to \p PHIBlock that are found
216*d415bd75Srobert /// in \p Included to branch to BasicBlock \p Replace if they currently branch
217*d415bd75Srobert /// to the BasicBlock \p Find. This is used to fix up the incoming basic blocks
218*d415bd75Srobert /// when PHINodes are included in outlined regions.
219*d415bd75Srobert ///
220*d415bd75Srobert /// \param PHIBlock - The BasicBlock containing the PHINodes that need to be
221*d415bd75Srobert /// checked.
222*d415bd75Srobert /// \param Find - The successor block to be replaced.
223*d415bd75Srobert /// \param Replace - The new succesor block to branch to.
224*d415bd75Srobert /// \param Included - The set of blocks about to be outlined.
replaceTargetsFromPHINode(BasicBlock * PHIBlock,BasicBlock * Find,BasicBlock * Replace,DenseSet<BasicBlock * > & Included)225*d415bd75Srobert static void replaceTargetsFromPHINode(BasicBlock *PHIBlock, BasicBlock *Find,
226*d415bd75Srobert BasicBlock *Replace,
227*d415bd75Srobert DenseSet<BasicBlock *> &Included) {
228*d415bd75Srobert for (PHINode &PN : PHIBlock->phis()) {
229*d415bd75Srobert for (unsigned Idx = 0, PNEnd = PN.getNumIncomingValues(); Idx != PNEnd;
230*d415bd75Srobert ++Idx) {
231*d415bd75Srobert // Check if the incoming block is included in the set of blocks being
232*d415bd75Srobert // outlined.
233*d415bd75Srobert BasicBlock *Incoming = PN.getIncomingBlock(Idx);
234*d415bd75Srobert if (!Included.contains(Incoming))
235*d415bd75Srobert continue;
236*d415bd75Srobert
237*d415bd75Srobert BranchInst *BI = dyn_cast<BranchInst>(Incoming->getTerminator());
238*d415bd75Srobert assert(BI && "Not a branch instruction?");
239*d415bd75Srobert // Look over the branching instructions into this block to see if we
240*d415bd75Srobert // used to branch to Find in this outlined block.
241*d415bd75Srobert for (unsigned Succ = 0, End = BI->getNumSuccessors(); Succ != End;
242*d415bd75Srobert Succ++) {
243*d415bd75Srobert // If we have found the block to replace, we do so here.
244*d415bd75Srobert if (BI->getSuccessor(Succ) != Find)
245*d415bd75Srobert continue;
246*d415bd75Srobert BI->setSuccessor(Succ, Replace);
24773471bf0Spatrick }
24873471bf0Spatrick }
249*d415bd75Srobert }
250*d415bd75Srobert }
251*d415bd75Srobert
25273471bf0Spatrick
splitCandidate()25373471bf0Spatrick void OutlinableRegion::splitCandidate() {
25473471bf0Spatrick assert(!CandidateSplit && "Candidate already split!");
25573471bf0Spatrick
256*d415bd75Srobert Instruction *BackInst = Candidate->backInstruction();
257*d415bd75Srobert
258*d415bd75Srobert Instruction *EndInst = nullptr;
259*d415bd75Srobert // Check whether the last instruction is a terminator, if it is, we do
260*d415bd75Srobert // not split on the following instruction. We leave the block as it is. We
261*d415bd75Srobert // also check that this is not the last instruction in the Module, otherwise
262*d415bd75Srobert // the check for whether the current following instruction matches the
263*d415bd75Srobert // previously recorded instruction will be incorrect.
264*d415bd75Srobert if (!BackInst->isTerminator() ||
265*d415bd75Srobert BackInst->getParent() != &BackInst->getFunction()->back()) {
266*d415bd75Srobert EndInst = Candidate->end()->Inst;
267*d415bd75Srobert assert(EndInst && "Expected an end instruction?");
268*d415bd75Srobert }
269*d415bd75Srobert
270*d415bd75Srobert // We check if the current instruction following the last instruction in the
271*d415bd75Srobert // region is the same as the recorded instruction following the last
272*d415bd75Srobert // instruction. If they do not match, there could be problems in rewriting
273*d415bd75Srobert // the program after outlining, so we ignore it.
274*d415bd75Srobert if (!BackInst->isTerminator() &&
275*d415bd75Srobert EndInst != BackInst->getNextNonDebugInstruction())
276*d415bd75Srobert return;
277*d415bd75Srobert
27873471bf0Spatrick Instruction *StartInst = (*Candidate->begin()).Inst;
279*d415bd75Srobert assert(StartInst && "Expected a start instruction?");
28073471bf0Spatrick StartBB = StartInst->getParent();
28173471bf0Spatrick PrevBB = StartBB;
28273471bf0Spatrick
283*d415bd75Srobert DenseSet<BasicBlock *> BBSet;
284*d415bd75Srobert Candidate->getBasicBlocks(BBSet);
285*d415bd75Srobert
286*d415bd75Srobert // We iterate over the instructions in the region, if we find a PHINode, we
287*d415bd75Srobert // check if there are predecessors outside of the region, if there are,
288*d415bd75Srobert // we ignore this region since we are unable to handle the severing of the
289*d415bd75Srobert // phi node right now.
290*d415bd75Srobert
291*d415bd75Srobert // TODO: Handle extraneous inputs for PHINodes through variable number of
292*d415bd75Srobert // inputs, similar to how outputs are handled.
293*d415bd75Srobert BasicBlock::iterator It = StartInst->getIterator();
294*d415bd75Srobert EndBB = BackInst->getParent();
295*d415bd75Srobert BasicBlock *IBlock;
296*d415bd75Srobert BasicBlock *PHIPredBlock = nullptr;
297*d415bd75Srobert bool EndBBTermAndBackInstDifferent = EndBB->getTerminator() != BackInst;
298*d415bd75Srobert while (PHINode *PN = dyn_cast<PHINode>(&*It)) {
299*d415bd75Srobert unsigned NumPredsOutsideRegion = 0;
300*d415bd75Srobert for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
301*d415bd75Srobert if (!BBSet.contains(PN->getIncomingBlock(i))) {
302*d415bd75Srobert PHIPredBlock = PN->getIncomingBlock(i);
303*d415bd75Srobert ++NumPredsOutsideRegion;
304*d415bd75Srobert continue;
305*d415bd75Srobert }
306*d415bd75Srobert
307*d415bd75Srobert // We must consider the case there the incoming block to the PHINode is
308*d415bd75Srobert // the same as the final block of the OutlinableRegion. If this is the
309*d415bd75Srobert // case, the branch from this block must also be outlined to be valid.
310*d415bd75Srobert IBlock = PN->getIncomingBlock(i);
311*d415bd75Srobert if (IBlock == EndBB && EndBBTermAndBackInstDifferent) {
312*d415bd75Srobert PHIPredBlock = PN->getIncomingBlock(i);
313*d415bd75Srobert ++NumPredsOutsideRegion;
314*d415bd75Srobert }
315*d415bd75Srobert }
316*d415bd75Srobert
317*d415bd75Srobert if (NumPredsOutsideRegion > 1)
318*d415bd75Srobert return;
319*d415bd75Srobert
320*d415bd75Srobert It++;
321*d415bd75Srobert }
322*d415bd75Srobert
323*d415bd75Srobert // If the region starts with a PHINode, but is not the initial instruction of
324*d415bd75Srobert // the BasicBlock, we ignore this region for now.
325*d415bd75Srobert if (isa<PHINode>(StartInst) && StartInst != &*StartBB->begin())
326*d415bd75Srobert return;
327*d415bd75Srobert
328*d415bd75Srobert // If the region ends with a PHINode, but does not contain all of the phi node
329*d415bd75Srobert // instructions of the region, we ignore it for now.
330*d415bd75Srobert if (isa<PHINode>(BackInst) &&
331*d415bd75Srobert BackInst != &*std::prev(EndBB->getFirstInsertionPt()))
332*d415bd75Srobert return;
333*d415bd75Srobert
33473471bf0Spatrick // The basic block gets split like so:
33573471bf0Spatrick // block: block:
33673471bf0Spatrick // inst1 inst1
33773471bf0Spatrick // inst2 inst2
33873471bf0Spatrick // region1 br block_to_outline
33973471bf0Spatrick // region2 block_to_outline:
34073471bf0Spatrick // region3 -> region1
34173471bf0Spatrick // region4 region2
34273471bf0Spatrick // inst3 region3
34373471bf0Spatrick // inst4 region4
34473471bf0Spatrick // br block_after_outline
34573471bf0Spatrick // block_after_outline:
34673471bf0Spatrick // inst3
34773471bf0Spatrick // inst4
34873471bf0Spatrick
34973471bf0Spatrick std::string OriginalName = PrevBB->getName().str();
35073471bf0Spatrick
35173471bf0Spatrick StartBB = PrevBB->splitBasicBlock(StartInst, OriginalName + "_to_outline");
352*d415bd75Srobert PrevBB->replaceSuccessorsPhiUsesWith(PrevBB, StartBB);
353*d415bd75Srobert // If there was a PHINode with an incoming block outside the region,
354*d415bd75Srobert // make sure is correctly updated in the newly split block.
355*d415bd75Srobert if (PHIPredBlock)
356*d415bd75Srobert PrevBB->replaceSuccessorsPhiUsesWith(PHIPredBlock, PrevBB);
35773471bf0Spatrick
35873471bf0Spatrick CandidateSplit = true;
359*d415bd75Srobert if (!BackInst->isTerminator()) {
360*d415bd75Srobert EndBB = EndInst->getParent();
361*d415bd75Srobert FollowBB = EndBB->splitBasicBlock(EndInst, OriginalName + "_after_outline");
362*d415bd75Srobert EndBB->replaceSuccessorsPhiUsesWith(EndBB, FollowBB);
363*d415bd75Srobert FollowBB->replaceSuccessorsPhiUsesWith(PrevBB, FollowBB);
364*d415bd75Srobert } else {
365*d415bd75Srobert EndBB = BackInst->getParent();
366*d415bd75Srobert EndsInBranch = true;
367*d415bd75Srobert FollowBB = nullptr;
368*d415bd75Srobert }
369*d415bd75Srobert
370*d415bd75Srobert // Refind the basic block set.
371*d415bd75Srobert BBSet.clear();
372*d415bd75Srobert Candidate->getBasicBlocks(BBSet);
373*d415bd75Srobert // For the phi nodes in the new starting basic block of the region, we
374*d415bd75Srobert // reassign the targets of the basic blocks branching instructions.
375*d415bd75Srobert replaceTargetsFromPHINode(StartBB, PrevBB, StartBB, BBSet);
376*d415bd75Srobert if (FollowBB)
377*d415bd75Srobert replaceTargetsFromPHINode(FollowBB, EndBB, FollowBB, BBSet);
37873471bf0Spatrick }
37973471bf0Spatrick
reattachCandidate()38073471bf0Spatrick void OutlinableRegion::reattachCandidate() {
38173471bf0Spatrick assert(CandidateSplit && "Candidate is not split!");
38273471bf0Spatrick
38373471bf0Spatrick // The basic block gets reattached like so:
38473471bf0Spatrick // block: block:
38573471bf0Spatrick // inst1 inst1
38673471bf0Spatrick // inst2 inst2
38773471bf0Spatrick // br block_to_outline region1
38873471bf0Spatrick // block_to_outline: -> region2
38973471bf0Spatrick // region1 region3
39073471bf0Spatrick // region2 region4
39173471bf0Spatrick // region3 inst3
39273471bf0Spatrick // region4 inst4
39373471bf0Spatrick // br block_after_outline
39473471bf0Spatrick // block_after_outline:
39573471bf0Spatrick // inst3
39673471bf0Spatrick // inst4
39773471bf0Spatrick assert(StartBB != nullptr && "StartBB for Candidate is not defined!");
39873471bf0Spatrick
39973471bf0Spatrick assert(PrevBB->getTerminator() && "Terminator removed from PrevBB!");
400*d415bd75Srobert // Make sure PHINode references to the block we are merging into are
401*d415bd75Srobert // updated to be incoming blocks from the predecessor to the current block.
402*d415bd75Srobert
403*d415bd75Srobert // NOTE: If this is updated such that the outlined block can have more than
404*d415bd75Srobert // one incoming block to a PHINode, this logic will have to updated
405*d415bd75Srobert // to handle multiple precessors instead.
406*d415bd75Srobert
407*d415bd75Srobert // We only need to update this if the outlined section contains a PHINode, if
408*d415bd75Srobert // it does not, then the incoming block was never changed in the first place.
409*d415bd75Srobert // On the other hand, if PrevBB has no predecessors, it means that all
410*d415bd75Srobert // incoming blocks to the first block are contained in the region, and there
411*d415bd75Srobert // will be nothing to update.
412*d415bd75Srobert Instruction *StartInst = (*Candidate->begin()).Inst;
413*d415bd75Srobert if (isa<PHINode>(StartInst) && !PrevBB->hasNPredecessors(0)) {
414*d415bd75Srobert assert(!PrevBB->hasNPredecessorsOrMore(2) &&
415*d415bd75Srobert "PrevBB has more than one predecessor. Should be 0 or 1.");
416*d415bd75Srobert BasicBlock *BeforePrevBB = PrevBB->getSinglePredecessor();
417*d415bd75Srobert PrevBB->replaceSuccessorsPhiUsesWith(PrevBB, BeforePrevBB);
418*d415bd75Srobert }
41973471bf0Spatrick PrevBB->getTerminator()->eraseFromParent();
420*d415bd75Srobert
421*d415bd75Srobert // If we reattaching after outlining, we iterate over the phi nodes to
422*d415bd75Srobert // the initial block, and reassign the branch instructions of the incoming
423*d415bd75Srobert // blocks to the block we are remerging into.
424*d415bd75Srobert if (!ExtractedFunction) {
425*d415bd75Srobert DenseSet<BasicBlock *> BBSet;
426*d415bd75Srobert Candidate->getBasicBlocks(BBSet);
427*d415bd75Srobert
428*d415bd75Srobert replaceTargetsFromPHINode(StartBB, StartBB, PrevBB, BBSet);
429*d415bd75Srobert if (!EndsInBranch)
430*d415bd75Srobert replaceTargetsFromPHINode(FollowBB, FollowBB, EndBB, BBSet);
431*d415bd75Srobert }
43273471bf0Spatrick
43373471bf0Spatrick moveBBContents(*StartBB, *PrevBB);
43473471bf0Spatrick
43573471bf0Spatrick BasicBlock *PlacementBB = PrevBB;
43673471bf0Spatrick if (StartBB != EndBB)
43773471bf0Spatrick PlacementBB = EndBB;
438*d415bd75Srobert if (!EndsInBranch && PlacementBB->getUniqueSuccessor() != nullptr) {
439*d415bd75Srobert assert(FollowBB != nullptr && "FollowBB for Candidate is not defined!");
440*d415bd75Srobert assert(PlacementBB->getTerminator() && "Terminator removed from EndBB!");
441*d415bd75Srobert PlacementBB->getTerminator()->eraseFromParent();
44273471bf0Spatrick moveBBContents(*FollowBB, *PlacementBB);
443*d415bd75Srobert PlacementBB->replaceSuccessorsPhiUsesWith(FollowBB, PlacementBB);
444*d415bd75Srobert FollowBB->eraseFromParent();
445*d415bd75Srobert }
44673471bf0Spatrick
44773471bf0Spatrick PrevBB->replaceSuccessorsPhiUsesWith(StartBB, PrevBB);
44873471bf0Spatrick StartBB->eraseFromParent();
44973471bf0Spatrick
45073471bf0Spatrick // Make sure to save changes back to the StartBB.
45173471bf0Spatrick StartBB = PrevBB;
45273471bf0Spatrick EndBB = nullptr;
45373471bf0Spatrick PrevBB = nullptr;
45473471bf0Spatrick FollowBB = nullptr;
45573471bf0Spatrick
45673471bf0Spatrick CandidateSplit = false;
45773471bf0Spatrick }
45873471bf0Spatrick
45973471bf0Spatrick /// Find whether \p V matches the Constants previously found for the \p GVN.
46073471bf0Spatrick ///
46173471bf0Spatrick /// \param V - The value to check for consistency.
46273471bf0Spatrick /// \param GVN - The global value number assigned to \p V.
46373471bf0Spatrick /// \param GVNToConstant - The mapping of global value number to Constants.
46473471bf0Spatrick /// \returns true if the Value matches the Constant mapped to by V and false if
46573471bf0Spatrick /// it \p V is a Constant but does not match.
466*d415bd75Srobert /// \returns std::nullopt if \p V is not a Constant.
467*d415bd75Srobert static std::optional<bool>
constantMatches(Value * V,unsigned GVN,DenseMap<unsigned,Constant * > & GVNToConstant)46873471bf0Spatrick constantMatches(Value *V, unsigned GVN,
46973471bf0Spatrick DenseMap<unsigned, Constant *> &GVNToConstant) {
47073471bf0Spatrick // See if we have a constants
47173471bf0Spatrick Constant *CST = dyn_cast<Constant>(V);
47273471bf0Spatrick if (!CST)
473*d415bd75Srobert return std::nullopt;
47473471bf0Spatrick
47573471bf0Spatrick // Holds a mapping from a global value number to a Constant.
47673471bf0Spatrick DenseMap<unsigned, Constant *>::iterator GVNToConstantIt;
47773471bf0Spatrick bool Inserted;
47873471bf0Spatrick
47973471bf0Spatrick
48073471bf0Spatrick // If we have a constant, try to make a new entry in the GVNToConstant.
48173471bf0Spatrick std::tie(GVNToConstantIt, Inserted) =
48273471bf0Spatrick GVNToConstant.insert(std::make_pair(GVN, CST));
48373471bf0Spatrick // If it was found and is not equal, it is not the same. We do not
48473471bf0Spatrick // handle this case yet, and exit early.
48573471bf0Spatrick if (Inserted || (GVNToConstantIt->second == CST))
48673471bf0Spatrick return true;
48773471bf0Spatrick
48873471bf0Spatrick return false;
48973471bf0Spatrick }
49073471bf0Spatrick
getBenefit(TargetTransformInfo & TTI)49173471bf0Spatrick InstructionCost OutlinableRegion::getBenefit(TargetTransformInfo &TTI) {
49273471bf0Spatrick InstructionCost Benefit = 0;
49373471bf0Spatrick
49473471bf0Spatrick // Estimate the benefit of outlining a specific sections of the program. We
49573471bf0Spatrick // delegate mostly this task to the TargetTransformInfo so that if the target
49673471bf0Spatrick // has specific changes, we can have a more accurate estimate.
49773471bf0Spatrick
49873471bf0Spatrick // However, getInstructionCost delegates the code size calculation for
49973471bf0Spatrick // arithmetic instructions to getArithmeticInstrCost in
50073471bf0Spatrick // include/Analysis/TargetTransformImpl.h, where it always estimates that the
50173471bf0Spatrick // code size for a division and remainder instruction to be equal to 4, and
50273471bf0Spatrick // everything else to 1. This is not an accurate representation of the
50373471bf0Spatrick // division instruction for targets that have a native division instruction.
50473471bf0Spatrick // To be overly conservative, we only add 1 to the number of instructions for
50573471bf0Spatrick // each division instruction.
506*d415bd75Srobert for (IRInstructionData &ID : *Candidate) {
507*d415bd75Srobert Instruction *I = ID.Inst;
508*d415bd75Srobert switch (I->getOpcode()) {
50973471bf0Spatrick case Instruction::FDiv:
51073471bf0Spatrick case Instruction::FRem:
51173471bf0Spatrick case Instruction::SDiv:
51273471bf0Spatrick case Instruction::SRem:
51373471bf0Spatrick case Instruction::UDiv:
51473471bf0Spatrick case Instruction::URem:
51573471bf0Spatrick Benefit += 1;
51673471bf0Spatrick break;
51773471bf0Spatrick default:
518*d415bd75Srobert Benefit += TTI.getInstructionCost(I, TargetTransformInfo::TCK_CodeSize);
51973471bf0Spatrick break;
52073471bf0Spatrick }
52173471bf0Spatrick }
52273471bf0Spatrick
52373471bf0Spatrick return Benefit;
52473471bf0Spatrick }
52573471bf0Spatrick
526*d415bd75Srobert /// Check the \p OutputMappings structure for value \p Input, if it exists
527*d415bd75Srobert /// it has been used as an output for outlining, and has been renamed, and we
528*d415bd75Srobert /// return the new value, otherwise, we return the same value.
529*d415bd75Srobert ///
530*d415bd75Srobert /// \param OutputMappings [in] - The mapping of values to their renamed value
531*d415bd75Srobert /// after being used as an output for an outlined region.
532*d415bd75Srobert /// \param Input [in] - The value to find the remapped value of, if it exists.
533*d415bd75Srobert /// \return The remapped value if it has been renamed, and the same value if has
534*d415bd75Srobert /// not.
findOutputMapping(const DenseMap<Value *,Value * > OutputMappings,Value * Input)535*d415bd75Srobert static Value *findOutputMapping(const DenseMap<Value *, Value *> OutputMappings,
536*d415bd75Srobert Value *Input) {
537*d415bd75Srobert DenseMap<Value *, Value *>::const_iterator OutputMapping =
538*d415bd75Srobert OutputMappings.find(Input);
539*d415bd75Srobert if (OutputMapping != OutputMappings.end())
540*d415bd75Srobert return OutputMapping->second;
541*d415bd75Srobert return Input;
542*d415bd75Srobert }
543*d415bd75Srobert
54473471bf0Spatrick /// Find whether \p Region matches the global value numbering to Constant
54573471bf0Spatrick /// mapping found so far.
54673471bf0Spatrick ///
54773471bf0Spatrick /// \param Region - The OutlinableRegion we are checking for constants
54873471bf0Spatrick /// \param GVNToConstant - The mapping of global value number to Constants.
54973471bf0Spatrick /// \param NotSame - The set of global value numbers that do not have the same
55073471bf0Spatrick /// constant in each region.
55173471bf0Spatrick /// \returns true if all Constants are the same in every use of a Constant in \p
55273471bf0Spatrick /// Region and false if not
55373471bf0Spatrick static bool
collectRegionsConstants(OutlinableRegion & Region,DenseMap<unsigned,Constant * > & GVNToConstant,DenseSet<unsigned> & NotSame)55473471bf0Spatrick collectRegionsConstants(OutlinableRegion &Region,
55573471bf0Spatrick DenseMap<unsigned, Constant *> &GVNToConstant,
55673471bf0Spatrick DenseSet<unsigned> &NotSame) {
55773471bf0Spatrick bool ConstantsTheSame = true;
55873471bf0Spatrick
55973471bf0Spatrick IRSimilarityCandidate &C = *Region.Candidate;
56073471bf0Spatrick for (IRInstructionData &ID : C) {
56173471bf0Spatrick
56273471bf0Spatrick // Iterate over the operands in an instruction. If the global value number,
56373471bf0Spatrick // assigned by the IRSimilarityCandidate, has been seen before, we check if
56473471bf0Spatrick // the the number has been found to be not the same value in each instance.
56573471bf0Spatrick for (Value *V : ID.OperVals) {
566*d415bd75Srobert std::optional<unsigned> GVNOpt = C.getGVN(V);
567*d415bd75Srobert assert(GVNOpt && "Expected a GVN for operand?");
568*d415bd75Srobert unsigned GVN = *GVNOpt;
56973471bf0Spatrick
57073471bf0Spatrick // Check if this global value has been found to not be the same already.
57173471bf0Spatrick if (NotSame.contains(GVN)) {
57273471bf0Spatrick if (isa<Constant>(V))
57373471bf0Spatrick ConstantsTheSame = false;
57473471bf0Spatrick continue;
57573471bf0Spatrick }
57673471bf0Spatrick
57773471bf0Spatrick // If it has been the same so far, we check the value for if the
57873471bf0Spatrick // associated Constant value match the previous instances of the same
57973471bf0Spatrick // global value number. If the global value does not map to a Constant,
58073471bf0Spatrick // it is considered to not be the same value.
581*d415bd75Srobert std::optional<bool> ConstantMatches =
582*d415bd75Srobert constantMatches(V, GVN, GVNToConstant);
583*d415bd75Srobert if (ConstantMatches) {
584*d415bd75Srobert if (*ConstantMatches)
58573471bf0Spatrick continue;
58673471bf0Spatrick else
58773471bf0Spatrick ConstantsTheSame = false;
58873471bf0Spatrick }
58973471bf0Spatrick
59073471bf0Spatrick // While this value is a register, it might not have been previously,
59173471bf0Spatrick // make sure we don't already have a constant mapped to this global value
59273471bf0Spatrick // number.
59373471bf0Spatrick if (GVNToConstant.find(GVN) != GVNToConstant.end())
59473471bf0Spatrick ConstantsTheSame = false;
59573471bf0Spatrick
59673471bf0Spatrick NotSame.insert(GVN);
59773471bf0Spatrick }
59873471bf0Spatrick }
59973471bf0Spatrick
60073471bf0Spatrick return ConstantsTheSame;
60173471bf0Spatrick }
60273471bf0Spatrick
findSameConstants(DenseSet<unsigned> & NotSame)60373471bf0Spatrick void OutlinableGroup::findSameConstants(DenseSet<unsigned> &NotSame) {
60473471bf0Spatrick DenseMap<unsigned, Constant *> GVNToConstant;
60573471bf0Spatrick
60673471bf0Spatrick for (OutlinableRegion *Region : Regions)
60773471bf0Spatrick collectRegionsConstants(*Region, GVNToConstant, NotSame);
60873471bf0Spatrick }
60973471bf0Spatrick
collectGVNStoreSets(Module & M)61073471bf0Spatrick void OutlinableGroup::collectGVNStoreSets(Module &M) {
61173471bf0Spatrick for (OutlinableRegion *OS : Regions)
61273471bf0Spatrick OutputGVNCombinations.insert(OS->GVNStores);
61373471bf0Spatrick
61473471bf0Spatrick // We are adding an extracted argument to decide between which output path
61573471bf0Spatrick // to use in the basic block. It is used in a switch statement and only
61673471bf0Spatrick // needs to be an integer.
61773471bf0Spatrick if (OutputGVNCombinations.size() > 1)
61873471bf0Spatrick ArgumentTypes.push_back(Type::getInt32Ty(M.getContext()));
61973471bf0Spatrick }
62073471bf0Spatrick
62173471bf0Spatrick /// Get the subprogram if it exists for one of the outlined regions.
62273471bf0Spatrick ///
62373471bf0Spatrick /// \param [in] Group - The set of regions to find a subprogram for.
62473471bf0Spatrick /// \returns the subprogram if it exists, or nullptr.
getSubprogramOrNull(OutlinableGroup & Group)62573471bf0Spatrick static DISubprogram *getSubprogramOrNull(OutlinableGroup &Group) {
62673471bf0Spatrick for (OutlinableRegion *OS : Group.Regions)
62773471bf0Spatrick if (Function *F = OS->Call->getFunction())
62873471bf0Spatrick if (DISubprogram *SP = F->getSubprogram())
62973471bf0Spatrick return SP;
63073471bf0Spatrick
63173471bf0Spatrick return nullptr;
63273471bf0Spatrick }
63373471bf0Spatrick
createFunction(Module & M,OutlinableGroup & Group,unsigned FunctionNameSuffix)63473471bf0Spatrick Function *IROutliner::createFunction(Module &M, OutlinableGroup &Group,
63573471bf0Spatrick unsigned FunctionNameSuffix) {
63673471bf0Spatrick assert(!Group.OutlinedFunction && "Function is already defined!");
63773471bf0Spatrick
638*d415bd75Srobert Type *RetTy = Type::getVoidTy(M.getContext());
639*d415bd75Srobert // All extracted functions _should_ have the same return type at this point
640*d415bd75Srobert // since the similarity identifier ensures that all branches outside of the
641*d415bd75Srobert // region occur in the same place.
642*d415bd75Srobert
643*d415bd75Srobert // NOTE: Should we ever move to the model that uses a switch at every point
644*d415bd75Srobert // needed, meaning that we could branch within the region or out, it is
645*d415bd75Srobert // possible that we will need to switch to using the most general case all of
646*d415bd75Srobert // the time.
647*d415bd75Srobert for (OutlinableRegion *R : Group.Regions) {
648*d415bd75Srobert Type *ExtractedFuncType = R->ExtractedFunction->getReturnType();
649*d415bd75Srobert if ((RetTy->isVoidTy() && !ExtractedFuncType->isVoidTy()) ||
650*d415bd75Srobert (RetTy->isIntegerTy(1) && ExtractedFuncType->isIntegerTy(16)))
651*d415bd75Srobert RetTy = ExtractedFuncType;
652*d415bd75Srobert }
653*d415bd75Srobert
65473471bf0Spatrick Group.OutlinedFunctionType = FunctionType::get(
655*d415bd75Srobert RetTy, Group.ArgumentTypes, false);
65673471bf0Spatrick
65773471bf0Spatrick // These functions will only be called from within the same module, so
65873471bf0Spatrick // we can set an internal linkage.
65973471bf0Spatrick Group.OutlinedFunction = Function::Create(
66073471bf0Spatrick Group.OutlinedFunctionType, GlobalValue::InternalLinkage,
66173471bf0Spatrick "outlined_ir_func_" + std::to_string(FunctionNameSuffix), M);
66273471bf0Spatrick
66373471bf0Spatrick // Transfer the swifterr attribute to the correct function parameter.
664*d415bd75Srobert if (Group.SwiftErrorArgument)
665*d415bd75Srobert Group.OutlinedFunction->addParamAttr(*Group.SwiftErrorArgument,
66673471bf0Spatrick Attribute::SwiftError);
66773471bf0Spatrick
66873471bf0Spatrick Group.OutlinedFunction->addFnAttr(Attribute::OptimizeForSize);
66973471bf0Spatrick Group.OutlinedFunction->addFnAttr(Attribute::MinSize);
67073471bf0Spatrick
67173471bf0Spatrick // If there's a DISubprogram associated with this outlined function, then
67273471bf0Spatrick // emit debug info for the outlined function.
67373471bf0Spatrick if (DISubprogram *SP = getSubprogramOrNull(Group)) {
67473471bf0Spatrick Function *F = Group.OutlinedFunction;
67573471bf0Spatrick // We have a DISubprogram. Get its DICompileUnit.
67673471bf0Spatrick DICompileUnit *CU = SP->getUnit();
67773471bf0Spatrick DIBuilder DB(M, true, CU);
67873471bf0Spatrick DIFile *Unit = SP->getFile();
67973471bf0Spatrick Mangler Mg;
68073471bf0Spatrick // Get the mangled name of the function for the linkage name.
68173471bf0Spatrick std::string Dummy;
68273471bf0Spatrick llvm::raw_string_ostream MangledNameStream(Dummy);
68373471bf0Spatrick Mg.getNameWithPrefix(MangledNameStream, F, false);
68473471bf0Spatrick
68573471bf0Spatrick DISubprogram *OutlinedSP = DB.createFunction(
68673471bf0Spatrick Unit /* Context */, F->getName(), MangledNameStream.str(),
68773471bf0Spatrick Unit /* File */,
68873471bf0Spatrick 0 /* Line 0 is reserved for compiler-generated code. */,
689*d415bd75Srobert DB.createSubroutineType(
690*d415bd75Srobert DB.getOrCreateTypeArray(std::nullopt)), /* void type */
69173471bf0Spatrick 0, /* Line 0 is reserved for compiler-generated code. */
69273471bf0Spatrick DINode::DIFlags::FlagArtificial /* Compiler-generated code. */,
69373471bf0Spatrick /* Outlined code is optimized code by definition. */
69473471bf0Spatrick DISubprogram::SPFlagDefinition | DISubprogram::SPFlagOptimized);
69573471bf0Spatrick
69673471bf0Spatrick // Don't add any new variables to the subprogram.
69773471bf0Spatrick DB.finalizeSubprogram(OutlinedSP);
69873471bf0Spatrick
69973471bf0Spatrick // Attach subprogram to the function.
70073471bf0Spatrick F->setSubprogram(OutlinedSP);
70173471bf0Spatrick // We're done with the DIBuilder.
70273471bf0Spatrick DB.finalize();
70373471bf0Spatrick }
70473471bf0Spatrick
70573471bf0Spatrick return Group.OutlinedFunction;
70673471bf0Spatrick }
70773471bf0Spatrick
70873471bf0Spatrick /// Move each BasicBlock in \p Old to \p New.
70973471bf0Spatrick ///
71073471bf0Spatrick /// \param [in] Old - The function to move the basic blocks from.
71173471bf0Spatrick /// \param [in] New - The function to move the basic blocks to.
712*d415bd75Srobert /// \param [out] NewEnds - The return blocks of the new overall function.
moveFunctionData(Function & Old,Function & New,DenseMap<Value *,BasicBlock * > & NewEnds)713*d415bd75Srobert static void moveFunctionData(Function &Old, Function &New,
714*d415bd75Srobert DenseMap<Value *, BasicBlock *> &NewEnds) {
715*d415bd75Srobert for (BasicBlock &CurrBB : llvm::make_early_inc_range(Old)) {
716*d415bd75Srobert CurrBB.removeFromParent();
717*d415bd75Srobert CurrBB.insertInto(&New);
718*d415bd75Srobert Instruction *I = CurrBB.getTerminator();
71973471bf0Spatrick
720*d415bd75Srobert // For each block we find a return instruction is, it is a potential exit
721*d415bd75Srobert // path for the function. We keep track of each block based on the return
722*d415bd75Srobert // value here.
723*d415bd75Srobert if (ReturnInst *RI = dyn_cast<ReturnInst>(I))
724*d415bd75Srobert NewEnds.insert(std::make_pair(RI->getReturnValue(), &CurrBB));
725*d415bd75Srobert
726*d415bd75Srobert std::vector<Instruction *> DebugInsts;
727*d415bd75Srobert
728*d415bd75Srobert for (Instruction &Val : CurrBB) {
72973471bf0Spatrick // We must handle the scoping of called functions differently than
73073471bf0Spatrick // other outlined instructions.
73173471bf0Spatrick if (!isa<CallInst>(&Val)) {
73273471bf0Spatrick // Remove the debug information for outlined functions.
73373471bf0Spatrick Val.setDebugLoc(DebugLoc());
734*d415bd75Srobert
735*d415bd75Srobert // Loop info metadata may contain line locations. Update them to have no
736*d415bd75Srobert // value in the new subprogram since the outlined code could be from
737*d415bd75Srobert // several locations.
738*d415bd75Srobert auto updateLoopInfoLoc = [&New](Metadata *MD) -> Metadata * {
739*d415bd75Srobert if (DISubprogram *SP = New.getSubprogram())
740*d415bd75Srobert if (auto *Loc = dyn_cast_or_null<DILocation>(MD))
741*d415bd75Srobert return DILocation::get(New.getContext(), Loc->getLine(),
742*d415bd75Srobert Loc->getColumn(), SP, nullptr);
743*d415bd75Srobert return MD;
744*d415bd75Srobert };
745*d415bd75Srobert updateLoopMetadataDebugLocations(Val, updateLoopInfoLoc);
74673471bf0Spatrick continue;
74773471bf0Spatrick }
74873471bf0Spatrick
74973471bf0Spatrick // From this point we are only handling call instructions.
75073471bf0Spatrick CallInst *CI = cast<CallInst>(&Val);
75173471bf0Spatrick
75273471bf0Spatrick // We add any debug statements here, to be removed after. Since the
75373471bf0Spatrick // instructions originate from many different locations in the program,
75473471bf0Spatrick // it will cause incorrect reporting from a debugger if we keep the
75573471bf0Spatrick // same debug instructions.
75673471bf0Spatrick if (isa<DbgInfoIntrinsic>(CI)) {
75773471bf0Spatrick DebugInsts.push_back(&Val);
75873471bf0Spatrick continue;
75973471bf0Spatrick }
76073471bf0Spatrick
76173471bf0Spatrick // Edit the scope of called functions inside of outlined functions.
76273471bf0Spatrick if (DISubprogram *SP = New.getSubprogram()) {
76373471bf0Spatrick DILocation *DI = DILocation::get(New.getContext(), 0, 0, SP);
76473471bf0Spatrick Val.setDebugLoc(DI);
76573471bf0Spatrick }
76673471bf0Spatrick }
76773471bf0Spatrick
76873471bf0Spatrick for (Instruction *I : DebugInsts)
76973471bf0Spatrick I->eraseFromParent();
77073471bf0Spatrick }
77173471bf0Spatrick }
77273471bf0Spatrick
77373471bf0Spatrick /// Find the the constants that will need to be lifted into arguments
77473471bf0Spatrick /// as they are not the same in each instance of the region.
77573471bf0Spatrick ///
77673471bf0Spatrick /// \param [in] C - The IRSimilarityCandidate containing the region we are
77773471bf0Spatrick /// analyzing.
77873471bf0Spatrick /// \param [in] NotSame - The set of global value numbers that do not have a
77973471bf0Spatrick /// single Constant across all OutlinableRegions similar to \p C.
78073471bf0Spatrick /// \param [out] Inputs - The list containing the global value numbers of the
78173471bf0Spatrick /// arguments needed for the region of code.
findConstants(IRSimilarityCandidate & C,DenseSet<unsigned> & NotSame,std::vector<unsigned> & Inputs)78273471bf0Spatrick static void findConstants(IRSimilarityCandidate &C, DenseSet<unsigned> &NotSame,
78373471bf0Spatrick std::vector<unsigned> &Inputs) {
78473471bf0Spatrick DenseSet<unsigned> Seen;
78573471bf0Spatrick // Iterate over the instructions, and find what constants will need to be
78673471bf0Spatrick // extracted into arguments.
78773471bf0Spatrick for (IRInstructionDataList::iterator IDIt = C.begin(), EndIDIt = C.end();
78873471bf0Spatrick IDIt != EndIDIt; IDIt++) {
78973471bf0Spatrick for (Value *V : (*IDIt).OperVals) {
79073471bf0Spatrick // Since these are stored before any outlining, they will be in the
79173471bf0Spatrick // global value numbering.
792*d415bd75Srobert unsigned GVN = *C.getGVN(V);
79373471bf0Spatrick if (isa<Constant>(V))
79473471bf0Spatrick if (NotSame.contains(GVN) && !Seen.contains(GVN)) {
79573471bf0Spatrick Inputs.push_back(GVN);
79673471bf0Spatrick Seen.insert(GVN);
79773471bf0Spatrick }
79873471bf0Spatrick }
79973471bf0Spatrick }
80073471bf0Spatrick }
80173471bf0Spatrick
80273471bf0Spatrick /// Find the GVN for the inputs that have been found by the CodeExtractor.
80373471bf0Spatrick ///
80473471bf0Spatrick /// \param [in] C - The IRSimilarityCandidate containing the region we are
80573471bf0Spatrick /// analyzing.
80673471bf0Spatrick /// \param [in] CurrentInputs - The set of inputs found by the
80773471bf0Spatrick /// CodeExtractor.
80873471bf0Spatrick /// \param [in] OutputMappings - The mapping of values that have been replaced
80973471bf0Spatrick /// by a new output value.
81073471bf0Spatrick /// \param [out] EndInputNumbers - The global value numbers for the extracted
81173471bf0Spatrick /// arguments.
mapInputsToGVNs(IRSimilarityCandidate & C,SetVector<Value * > & CurrentInputs,const DenseMap<Value *,Value * > & OutputMappings,std::vector<unsigned> & EndInputNumbers)81273471bf0Spatrick static void mapInputsToGVNs(IRSimilarityCandidate &C,
81373471bf0Spatrick SetVector<Value *> &CurrentInputs,
81473471bf0Spatrick const DenseMap<Value *, Value *> &OutputMappings,
81573471bf0Spatrick std::vector<unsigned> &EndInputNumbers) {
81673471bf0Spatrick // Get the Global Value Number for each input. We check if the Value has been
81773471bf0Spatrick // replaced by a different value at output, and use the original value before
81873471bf0Spatrick // replacement.
81973471bf0Spatrick for (Value *Input : CurrentInputs) {
82073471bf0Spatrick assert(Input && "Have a nullptr as an input");
82173471bf0Spatrick if (OutputMappings.find(Input) != OutputMappings.end())
82273471bf0Spatrick Input = OutputMappings.find(Input)->second;
823*d415bd75Srobert assert(C.getGVN(Input) && "Could not find a numbering for the given input");
824*d415bd75Srobert EndInputNumbers.push_back(*C.getGVN(Input));
82573471bf0Spatrick }
82673471bf0Spatrick }
82773471bf0Spatrick
82873471bf0Spatrick /// Find the original value for the \p ArgInput values if any one of them was
82973471bf0Spatrick /// replaced during a previous extraction.
83073471bf0Spatrick ///
83173471bf0Spatrick /// \param [in] ArgInputs - The inputs to be extracted by the code extractor.
83273471bf0Spatrick /// \param [in] OutputMappings - The mapping of values that have been replaced
83373471bf0Spatrick /// by a new output value.
83473471bf0Spatrick /// \param [out] RemappedArgInputs - The remapped values according to
83573471bf0Spatrick /// \p OutputMappings that will be extracted.
83673471bf0Spatrick static void
remapExtractedInputs(const ArrayRef<Value * > ArgInputs,const DenseMap<Value *,Value * > & OutputMappings,SetVector<Value * > & RemappedArgInputs)83773471bf0Spatrick remapExtractedInputs(const ArrayRef<Value *> ArgInputs,
83873471bf0Spatrick const DenseMap<Value *, Value *> &OutputMappings,
83973471bf0Spatrick SetVector<Value *> &RemappedArgInputs) {
84073471bf0Spatrick // Get the global value number for each input that will be extracted as an
84173471bf0Spatrick // argument by the code extractor, remapping if needed for reloaded values.
84273471bf0Spatrick for (Value *Input : ArgInputs) {
84373471bf0Spatrick if (OutputMappings.find(Input) != OutputMappings.end())
84473471bf0Spatrick Input = OutputMappings.find(Input)->second;
84573471bf0Spatrick RemappedArgInputs.insert(Input);
84673471bf0Spatrick }
84773471bf0Spatrick }
84873471bf0Spatrick
84973471bf0Spatrick /// Find the input GVNs and the output values for a region of Instructions.
85073471bf0Spatrick /// Using the code extractor, we collect the inputs to the extracted function.
85173471bf0Spatrick ///
85273471bf0Spatrick /// The \p Region can be identified as needing to be ignored in this function.
85373471bf0Spatrick /// It should be checked whether it should be ignored after a call to this
85473471bf0Spatrick /// function.
85573471bf0Spatrick ///
85673471bf0Spatrick /// \param [in,out] Region - The region of code to be analyzed.
85773471bf0Spatrick /// \param [out] InputGVNs - The global value numbers for the extracted
85873471bf0Spatrick /// arguments.
85973471bf0Spatrick /// \param [in] NotSame - The global value numbers in the region that do not
86073471bf0Spatrick /// have the same constant value in the regions structurally similar to
86173471bf0Spatrick /// \p Region.
86273471bf0Spatrick /// \param [in] OutputMappings - The mapping of values that have been replaced
86373471bf0Spatrick /// by a new output value after extraction.
86473471bf0Spatrick /// \param [out] ArgInputs - The values of the inputs to the extracted function.
86573471bf0Spatrick /// \param [out] Outputs - The set of values extracted by the CodeExtractor
86673471bf0Spatrick /// as outputs.
getCodeExtractorArguments(OutlinableRegion & Region,std::vector<unsigned> & InputGVNs,DenseSet<unsigned> & NotSame,DenseMap<Value *,Value * > & OutputMappings,SetVector<Value * > & ArgInputs,SetVector<Value * > & Outputs)86773471bf0Spatrick static void getCodeExtractorArguments(
86873471bf0Spatrick OutlinableRegion &Region, std::vector<unsigned> &InputGVNs,
86973471bf0Spatrick DenseSet<unsigned> &NotSame, DenseMap<Value *, Value *> &OutputMappings,
87073471bf0Spatrick SetVector<Value *> &ArgInputs, SetVector<Value *> &Outputs) {
87173471bf0Spatrick IRSimilarityCandidate &C = *Region.Candidate;
87273471bf0Spatrick
87373471bf0Spatrick // OverallInputs are the inputs to the region found by the CodeExtractor,
87473471bf0Spatrick // SinkCands and HoistCands are used by the CodeExtractor to find sunken
87573471bf0Spatrick // allocas of values whose lifetimes are contained completely within the
87673471bf0Spatrick // outlined region. PremappedInputs are the arguments found by the
87773471bf0Spatrick // CodeExtractor, removing conditions such as sunken allocas, but that
87873471bf0Spatrick // may need to be remapped due to the extracted output values replacing
87973471bf0Spatrick // the original values. We use DummyOutputs for this first run of finding
88073471bf0Spatrick // inputs and outputs since the outputs could change during findAllocas,
88173471bf0Spatrick // the correct set of extracted outputs will be in the final Outputs ValueSet.
88273471bf0Spatrick SetVector<Value *> OverallInputs, PremappedInputs, SinkCands, HoistCands,
88373471bf0Spatrick DummyOutputs;
88473471bf0Spatrick
88573471bf0Spatrick // Use the code extractor to get the inputs and outputs, without sunken
88673471bf0Spatrick // allocas or removing llvm.assumes.
88773471bf0Spatrick CodeExtractor *CE = Region.CE;
88873471bf0Spatrick CE->findInputsOutputs(OverallInputs, DummyOutputs, SinkCands);
88973471bf0Spatrick assert(Region.StartBB && "Region must have a start BasicBlock!");
89073471bf0Spatrick Function *OrigF = Region.StartBB->getParent();
89173471bf0Spatrick CodeExtractorAnalysisCache CEAC(*OrigF);
89273471bf0Spatrick BasicBlock *Dummy = nullptr;
89373471bf0Spatrick
89473471bf0Spatrick // The region may be ineligible due to VarArgs in the parent function. In this
89573471bf0Spatrick // case we ignore the region.
89673471bf0Spatrick if (!CE->isEligible()) {
89773471bf0Spatrick Region.IgnoreRegion = true;
89873471bf0Spatrick return;
89973471bf0Spatrick }
90073471bf0Spatrick
90173471bf0Spatrick // Find if any values are going to be sunk into the function when extracted
90273471bf0Spatrick CE->findAllocas(CEAC, SinkCands, HoistCands, Dummy);
90373471bf0Spatrick CE->findInputsOutputs(PremappedInputs, Outputs, SinkCands);
90473471bf0Spatrick
90573471bf0Spatrick // TODO: Support regions with sunken allocas: values whose lifetimes are
90673471bf0Spatrick // contained completely within the outlined region. These are not guaranteed
90773471bf0Spatrick // to be the same in every region, so we must elevate them all to arguments
90873471bf0Spatrick // when they appear. If these values are not equal, it means there is some
90973471bf0Spatrick // Input in OverallInputs that was removed for ArgInputs.
91073471bf0Spatrick if (OverallInputs.size() != PremappedInputs.size()) {
91173471bf0Spatrick Region.IgnoreRegion = true;
91273471bf0Spatrick return;
91373471bf0Spatrick }
91473471bf0Spatrick
91573471bf0Spatrick findConstants(C, NotSame, InputGVNs);
91673471bf0Spatrick
91773471bf0Spatrick mapInputsToGVNs(C, OverallInputs, OutputMappings, InputGVNs);
91873471bf0Spatrick
91973471bf0Spatrick remapExtractedInputs(PremappedInputs.getArrayRef(), OutputMappings,
92073471bf0Spatrick ArgInputs);
92173471bf0Spatrick
92273471bf0Spatrick // Sort the GVNs, since we now have constants included in the \ref InputGVNs
92373471bf0Spatrick // we need to make sure they are in a deterministic order.
92473471bf0Spatrick stable_sort(InputGVNs);
92573471bf0Spatrick }
92673471bf0Spatrick
92773471bf0Spatrick /// Look over the inputs and map each input argument to an argument in the
92873471bf0Spatrick /// overall function for the OutlinableRegions. This creates a way to replace
92973471bf0Spatrick /// the arguments of the extracted function with the arguments of the new
93073471bf0Spatrick /// overall function.
93173471bf0Spatrick ///
93273471bf0Spatrick /// \param [in,out] Region - The region of code to be analyzed.
93373471bf0Spatrick /// \param [in] InputGVNs - The global value numbering of the input values
93473471bf0Spatrick /// collected.
93573471bf0Spatrick /// \param [in] ArgInputs - The values of the arguments to the extracted
93673471bf0Spatrick /// function.
93773471bf0Spatrick static void
findExtractedInputToOverallInputMapping(OutlinableRegion & Region,std::vector<unsigned> & InputGVNs,SetVector<Value * > & ArgInputs)93873471bf0Spatrick findExtractedInputToOverallInputMapping(OutlinableRegion &Region,
93973471bf0Spatrick std::vector<unsigned> &InputGVNs,
94073471bf0Spatrick SetVector<Value *> &ArgInputs) {
94173471bf0Spatrick
94273471bf0Spatrick IRSimilarityCandidate &C = *Region.Candidate;
94373471bf0Spatrick OutlinableGroup &Group = *Region.Parent;
94473471bf0Spatrick
94573471bf0Spatrick // This counts the argument number in the overall function.
94673471bf0Spatrick unsigned TypeIndex = 0;
94773471bf0Spatrick
94873471bf0Spatrick // This counts the argument number in the extracted function.
94973471bf0Spatrick unsigned OriginalIndex = 0;
95073471bf0Spatrick
95173471bf0Spatrick // Find the mapping of the extracted arguments to the arguments for the
95273471bf0Spatrick // overall function. Since there may be extra arguments in the overall
95373471bf0Spatrick // function to account for the extracted constants, we have two different
95473471bf0Spatrick // counters as we find extracted arguments, and as we come across overall
95573471bf0Spatrick // arguments.
956*d415bd75Srobert
957*d415bd75Srobert // Additionally, in our first pass, for the first extracted function,
958*d415bd75Srobert // we find argument locations for the canonical value numbering. This
959*d415bd75Srobert // numbering overrides any discovered location for the extracted code.
96073471bf0Spatrick for (unsigned InputVal : InputGVNs) {
961*d415bd75Srobert std::optional<unsigned> CanonicalNumberOpt = C.getCanonicalNum(InputVal);
962*d415bd75Srobert assert(CanonicalNumberOpt && "Canonical number not found?");
963*d415bd75Srobert unsigned CanonicalNumber = *CanonicalNumberOpt;
964*d415bd75Srobert
965*d415bd75Srobert std::optional<Value *> InputOpt = C.fromGVN(InputVal);
966*d415bd75Srobert assert(InputOpt && "Global value number not found?");
967*d415bd75Srobert Value *Input = *InputOpt;
968*d415bd75Srobert
969*d415bd75Srobert DenseMap<unsigned, unsigned>::iterator AggArgIt =
970*d415bd75Srobert Group.CanonicalNumberToAggArg.find(CanonicalNumber);
97173471bf0Spatrick
97273471bf0Spatrick if (!Group.InputTypesSet) {
97373471bf0Spatrick Group.ArgumentTypes.push_back(Input->getType());
97473471bf0Spatrick // If the input value has a swifterr attribute, make sure to mark the
97573471bf0Spatrick // argument in the overall function.
97673471bf0Spatrick if (Input->isSwiftError()) {
97773471bf0Spatrick assert(
978*d415bd75Srobert !Group.SwiftErrorArgument &&
97973471bf0Spatrick "Argument already marked with swifterr for this OutlinableGroup!");
98073471bf0Spatrick Group.SwiftErrorArgument = TypeIndex;
98173471bf0Spatrick }
98273471bf0Spatrick }
98373471bf0Spatrick
98473471bf0Spatrick // Check if we have a constant. If we do add it to the overall argument
98573471bf0Spatrick // number to Constant map for the region, and continue to the next input.
98673471bf0Spatrick if (Constant *CST = dyn_cast<Constant>(Input)) {
987*d415bd75Srobert if (AggArgIt != Group.CanonicalNumberToAggArg.end())
988*d415bd75Srobert Region.AggArgToConstant.insert(std::make_pair(AggArgIt->second, CST));
989*d415bd75Srobert else {
990*d415bd75Srobert Group.CanonicalNumberToAggArg.insert(
991*d415bd75Srobert std::make_pair(CanonicalNumber, TypeIndex));
99273471bf0Spatrick Region.AggArgToConstant.insert(std::make_pair(TypeIndex, CST));
993*d415bd75Srobert }
99473471bf0Spatrick TypeIndex++;
99573471bf0Spatrick continue;
99673471bf0Spatrick }
99773471bf0Spatrick
99873471bf0Spatrick // It is not a constant, we create the mapping from extracted argument list
999*d415bd75Srobert // to the overall argument list, using the canonical location, if it exists.
100073471bf0Spatrick assert(ArgInputs.count(Input) && "Input cannot be found!");
100173471bf0Spatrick
1002*d415bd75Srobert if (AggArgIt != Group.CanonicalNumberToAggArg.end()) {
1003*d415bd75Srobert if (OriginalIndex != AggArgIt->second)
1004*d415bd75Srobert Region.ChangedArgOrder = true;
1005*d415bd75Srobert Region.ExtractedArgToAgg.insert(
1006*d415bd75Srobert std::make_pair(OriginalIndex, AggArgIt->second));
1007*d415bd75Srobert Region.AggArgToExtracted.insert(
1008*d415bd75Srobert std::make_pair(AggArgIt->second, OriginalIndex));
1009*d415bd75Srobert } else {
1010*d415bd75Srobert Group.CanonicalNumberToAggArg.insert(
1011*d415bd75Srobert std::make_pair(CanonicalNumber, TypeIndex));
101273471bf0Spatrick Region.ExtractedArgToAgg.insert(std::make_pair(OriginalIndex, TypeIndex));
101373471bf0Spatrick Region.AggArgToExtracted.insert(std::make_pair(TypeIndex, OriginalIndex));
1014*d415bd75Srobert }
101573471bf0Spatrick OriginalIndex++;
101673471bf0Spatrick TypeIndex++;
101773471bf0Spatrick }
101873471bf0Spatrick
101973471bf0Spatrick // If the function type definitions for the OutlinableGroup holding the region
102073471bf0Spatrick // have not been set, set the length of the inputs here. We should have the
102173471bf0Spatrick // same inputs for all of the different regions contained in the
102273471bf0Spatrick // OutlinableGroup since they are all structurally similar to one another.
102373471bf0Spatrick if (!Group.InputTypesSet) {
102473471bf0Spatrick Group.NumAggregateInputs = TypeIndex;
102573471bf0Spatrick Group.InputTypesSet = true;
102673471bf0Spatrick }
102773471bf0Spatrick
102873471bf0Spatrick Region.NumExtractedInputs = OriginalIndex;
102973471bf0Spatrick }
103073471bf0Spatrick
1031*d415bd75Srobert /// Check if the \p V has any uses outside of the region other than \p PN.
1032*d415bd75Srobert ///
1033*d415bd75Srobert /// \param V [in] - The value to check.
1034*d415bd75Srobert /// \param PHILoc [in] - The location in the PHINode of \p V.
1035*d415bd75Srobert /// \param PN [in] - The PHINode using \p V.
1036*d415bd75Srobert /// \param Exits [in] - The potential blocks we exit to from the outlined
1037*d415bd75Srobert /// region.
1038*d415bd75Srobert /// \param BlocksInRegion [in] - The basic blocks contained in the region.
1039*d415bd75Srobert /// \returns true if \p V has any use soutside its region other than \p PN.
outputHasNonPHI(Value * V,unsigned PHILoc,PHINode & PN,SmallPtrSet<BasicBlock *,1> & Exits,DenseSet<BasicBlock * > & BlocksInRegion)1040*d415bd75Srobert static bool outputHasNonPHI(Value *V, unsigned PHILoc, PHINode &PN,
1041*d415bd75Srobert SmallPtrSet<BasicBlock *, 1> &Exits,
1042*d415bd75Srobert DenseSet<BasicBlock *> &BlocksInRegion) {
1043*d415bd75Srobert // We check to see if the value is used by the PHINode from some other
1044*d415bd75Srobert // predecessor not included in the region. If it is, we make sure
1045*d415bd75Srobert // to keep it as an output.
1046*d415bd75Srobert if (any_of(llvm::seq<unsigned>(0, PN.getNumIncomingValues()),
1047*d415bd75Srobert [PHILoc, &PN, V, &BlocksInRegion](unsigned Idx) {
1048*d415bd75Srobert return (Idx != PHILoc && V == PN.getIncomingValue(Idx) &&
1049*d415bd75Srobert !BlocksInRegion.contains(PN.getIncomingBlock(Idx)));
1050*d415bd75Srobert }))
1051*d415bd75Srobert return true;
1052*d415bd75Srobert
1053*d415bd75Srobert // Check if the value is used by any other instructions outside the region.
1054*d415bd75Srobert return any_of(V->users(), [&Exits, &BlocksInRegion](User *U) {
1055*d415bd75Srobert Instruction *I = dyn_cast<Instruction>(U);
1056*d415bd75Srobert if (!I)
1057*d415bd75Srobert return false;
1058*d415bd75Srobert
1059*d415bd75Srobert // If the use of the item is inside the region, we skip it. Uses
1060*d415bd75Srobert // inside the region give us useful information about how the item could be
1061*d415bd75Srobert // used as an output.
1062*d415bd75Srobert BasicBlock *Parent = I->getParent();
1063*d415bd75Srobert if (BlocksInRegion.contains(Parent))
1064*d415bd75Srobert return false;
1065*d415bd75Srobert
1066*d415bd75Srobert // If it's not a PHINode then we definitely know the use matters. This
1067*d415bd75Srobert // output value will not completely combined with another item in a PHINode
1068*d415bd75Srobert // as it is directly reference by another non-phi instruction
1069*d415bd75Srobert if (!isa<PHINode>(I))
1070*d415bd75Srobert return true;
1071*d415bd75Srobert
1072*d415bd75Srobert // If we have a PHINode outside one of the exit locations, then it
1073*d415bd75Srobert // can be considered an outside use as well. If there is a PHINode
1074*d415bd75Srobert // contained in the Exit where this values use matters, it will be
1075*d415bd75Srobert // caught when we analyze that PHINode.
1076*d415bd75Srobert if (!Exits.contains(Parent))
1077*d415bd75Srobert return true;
1078*d415bd75Srobert
1079*d415bd75Srobert return false;
1080*d415bd75Srobert });
1081*d415bd75Srobert }
1082*d415bd75Srobert
1083*d415bd75Srobert /// Test whether \p CurrentExitFromRegion contains any PhiNodes that should be
1084*d415bd75Srobert /// considered outputs. A PHINodes is an output when more than one incoming
1085*d415bd75Srobert /// value has been marked by the CodeExtractor as an output.
1086*d415bd75Srobert ///
1087*d415bd75Srobert /// \param CurrentExitFromRegion [in] - The block to analyze.
1088*d415bd75Srobert /// \param PotentialExitsFromRegion [in] - The potential exit blocks from the
1089*d415bd75Srobert /// region.
1090*d415bd75Srobert /// \param RegionBlocks [in] - The basic blocks in the region.
1091*d415bd75Srobert /// \param Outputs [in, out] - The existing outputs for the region, we may add
1092*d415bd75Srobert /// PHINodes to this as we find that they replace output values.
1093*d415bd75Srobert /// \param OutputsReplacedByPHINode [out] - A set containing outputs that are
1094*d415bd75Srobert /// totally replaced by a PHINode.
1095*d415bd75Srobert /// \param OutputsWithNonPhiUses [out] - A set containing outputs that are used
1096*d415bd75Srobert /// in PHINodes, but have other uses, and should still be considered outputs.
analyzeExitPHIsForOutputUses(BasicBlock * CurrentExitFromRegion,SmallPtrSet<BasicBlock *,1> & PotentialExitsFromRegion,DenseSet<BasicBlock * > & RegionBlocks,SetVector<Value * > & Outputs,DenseSet<Value * > & OutputsReplacedByPHINode,DenseSet<Value * > & OutputsWithNonPhiUses)1097*d415bd75Srobert static void analyzeExitPHIsForOutputUses(
1098*d415bd75Srobert BasicBlock *CurrentExitFromRegion,
1099*d415bd75Srobert SmallPtrSet<BasicBlock *, 1> &PotentialExitsFromRegion,
1100*d415bd75Srobert DenseSet<BasicBlock *> &RegionBlocks, SetVector<Value *> &Outputs,
1101*d415bd75Srobert DenseSet<Value *> &OutputsReplacedByPHINode,
1102*d415bd75Srobert DenseSet<Value *> &OutputsWithNonPhiUses) {
1103*d415bd75Srobert for (PHINode &PN : CurrentExitFromRegion->phis()) {
1104*d415bd75Srobert // Find all incoming values from the outlining region.
1105*d415bd75Srobert SmallVector<unsigned, 2> IncomingVals;
1106*d415bd75Srobert for (unsigned I = 0, E = PN.getNumIncomingValues(); I < E; ++I)
1107*d415bd75Srobert if (RegionBlocks.contains(PN.getIncomingBlock(I)))
1108*d415bd75Srobert IncomingVals.push_back(I);
1109*d415bd75Srobert
1110*d415bd75Srobert // Do not process PHI if there are no predecessors from region.
1111*d415bd75Srobert unsigned NumIncomingVals = IncomingVals.size();
1112*d415bd75Srobert if (NumIncomingVals == 0)
1113*d415bd75Srobert continue;
1114*d415bd75Srobert
1115*d415bd75Srobert // If there is one predecessor, we mark it as a value that needs to be kept
1116*d415bd75Srobert // as an output.
1117*d415bd75Srobert if (NumIncomingVals == 1) {
1118*d415bd75Srobert Value *V = PN.getIncomingValue(*IncomingVals.begin());
1119*d415bd75Srobert OutputsWithNonPhiUses.insert(V);
1120*d415bd75Srobert OutputsReplacedByPHINode.erase(V);
1121*d415bd75Srobert continue;
1122*d415bd75Srobert }
1123*d415bd75Srobert
1124*d415bd75Srobert // This PHINode will be used as an output value, so we add it to our list.
1125*d415bd75Srobert Outputs.insert(&PN);
1126*d415bd75Srobert
1127*d415bd75Srobert // Not all of the incoming values should be ignored as other inputs and
1128*d415bd75Srobert // outputs may have uses in outlined region. If they have other uses
1129*d415bd75Srobert // outside of the single PHINode we should not skip over it.
1130*d415bd75Srobert for (unsigned Idx : IncomingVals) {
1131*d415bd75Srobert Value *V = PN.getIncomingValue(Idx);
1132*d415bd75Srobert if (outputHasNonPHI(V, Idx, PN, PotentialExitsFromRegion, RegionBlocks)) {
1133*d415bd75Srobert OutputsWithNonPhiUses.insert(V);
1134*d415bd75Srobert OutputsReplacedByPHINode.erase(V);
1135*d415bd75Srobert continue;
1136*d415bd75Srobert }
1137*d415bd75Srobert if (!OutputsWithNonPhiUses.contains(V))
1138*d415bd75Srobert OutputsReplacedByPHINode.insert(V);
1139*d415bd75Srobert }
1140*d415bd75Srobert }
1141*d415bd75Srobert }
1142*d415bd75Srobert
1143*d415bd75Srobert // Represents the type for the unsigned number denoting the output number for
1144*d415bd75Srobert // phi node, along with the canonical number for the exit block.
1145*d415bd75Srobert using ArgLocWithBBCanon = std::pair<unsigned, unsigned>;
1146*d415bd75Srobert // The list of canonical numbers for the incoming values to a PHINode.
1147*d415bd75Srobert using CanonList = SmallVector<unsigned, 2>;
1148*d415bd75Srobert // The pair type representing the set of canonical values being combined in the
1149*d415bd75Srobert // PHINode, along with the location data for the PHINode.
1150*d415bd75Srobert using PHINodeData = std::pair<ArgLocWithBBCanon, CanonList>;
1151*d415bd75Srobert
1152*d415bd75Srobert /// Encode \p PND as an integer for easy lookup based on the argument location,
1153*d415bd75Srobert /// the parent BasicBlock canonical numbering, and the canonical numbering of
1154*d415bd75Srobert /// the values stored in the PHINode.
1155*d415bd75Srobert ///
1156*d415bd75Srobert /// \param PND - The data to hash.
1157*d415bd75Srobert /// \returns The hash code of \p PND.
encodePHINodeData(PHINodeData & PND)1158*d415bd75Srobert static hash_code encodePHINodeData(PHINodeData &PND) {
1159*d415bd75Srobert return llvm::hash_combine(
1160*d415bd75Srobert llvm::hash_value(PND.first.first), llvm::hash_value(PND.first.second),
1161*d415bd75Srobert llvm::hash_combine_range(PND.second.begin(), PND.second.end()));
1162*d415bd75Srobert }
1163*d415bd75Srobert
1164*d415bd75Srobert /// Create a special GVN for PHINodes that will be used outside of
1165*d415bd75Srobert /// the region. We create a hash code based on the Canonical number of the
1166*d415bd75Srobert /// parent BasicBlock, the canonical numbering of the values stored in the
1167*d415bd75Srobert /// PHINode and the aggregate argument location. This is used to find whether
1168*d415bd75Srobert /// this PHINode type has been given a canonical numbering already. If not, we
1169*d415bd75Srobert /// assign it a value and store it for later use. The value is returned to
1170*d415bd75Srobert /// identify different output schemes for the set of regions.
1171*d415bd75Srobert ///
1172*d415bd75Srobert /// \param Region - The region that \p PN is an output for.
1173*d415bd75Srobert /// \param PN - The PHINode we are analyzing.
1174*d415bd75Srobert /// \param Blocks - The blocks for the region we are analyzing.
1175*d415bd75Srobert /// \param AggArgIdx - The argument \p PN will be stored into.
1176*d415bd75Srobert /// \returns An optional holding the assigned canonical number, or std::nullopt
1177*d415bd75Srobert /// if there is some attribute of the PHINode blocking it from being used.
getGVNForPHINode(OutlinableRegion & Region,PHINode * PN,DenseSet<BasicBlock * > & Blocks,unsigned AggArgIdx)1178*d415bd75Srobert static std::optional<unsigned> getGVNForPHINode(OutlinableRegion &Region,
1179*d415bd75Srobert PHINode *PN,
1180*d415bd75Srobert DenseSet<BasicBlock *> &Blocks,
1181*d415bd75Srobert unsigned AggArgIdx) {
1182*d415bd75Srobert OutlinableGroup &Group = *Region.Parent;
1183*d415bd75Srobert IRSimilarityCandidate &Cand = *Region.Candidate;
1184*d415bd75Srobert BasicBlock *PHIBB = PN->getParent();
1185*d415bd75Srobert CanonList PHIGVNs;
1186*d415bd75Srobert Value *Incoming;
1187*d415bd75Srobert BasicBlock *IncomingBlock;
1188*d415bd75Srobert for (unsigned Idx = 0, EIdx = PN->getNumIncomingValues(); Idx < EIdx; Idx++) {
1189*d415bd75Srobert Incoming = PN->getIncomingValue(Idx);
1190*d415bd75Srobert IncomingBlock = PN->getIncomingBlock(Idx);
1191*d415bd75Srobert // If we cannot find a GVN, and the incoming block is included in the region
1192*d415bd75Srobert // this means that the input to the PHINode is not included in the region we
1193*d415bd75Srobert // are trying to analyze, meaning, that if it was outlined, we would be
1194*d415bd75Srobert // adding an extra input. We ignore this case for now, and so ignore the
1195*d415bd75Srobert // region.
1196*d415bd75Srobert std::optional<unsigned> OGVN = Cand.getGVN(Incoming);
1197*d415bd75Srobert if (!OGVN && Blocks.contains(IncomingBlock)) {
1198*d415bd75Srobert Region.IgnoreRegion = true;
1199*d415bd75Srobert return std::nullopt;
1200*d415bd75Srobert }
1201*d415bd75Srobert
1202*d415bd75Srobert // If the incoming block isn't in the region, we don't have to worry about
1203*d415bd75Srobert // this incoming value.
1204*d415bd75Srobert if (!Blocks.contains(IncomingBlock))
1205*d415bd75Srobert continue;
1206*d415bd75Srobert
1207*d415bd75Srobert // Collect the canonical numbers of the values in the PHINode.
1208*d415bd75Srobert unsigned GVN = *OGVN;
1209*d415bd75Srobert OGVN = Cand.getCanonicalNum(GVN);
1210*d415bd75Srobert assert(OGVN && "No GVN found for incoming value?");
1211*d415bd75Srobert PHIGVNs.push_back(*OGVN);
1212*d415bd75Srobert
1213*d415bd75Srobert // Find the incoming block and use the canonical numbering as well to define
1214*d415bd75Srobert // the hash for the PHINode.
1215*d415bd75Srobert OGVN = Cand.getGVN(IncomingBlock);
1216*d415bd75Srobert
1217*d415bd75Srobert // If there is no number for the incoming block, it is because we have
1218*d415bd75Srobert // split the candidate basic blocks. So we use the previous block that it
1219*d415bd75Srobert // was split from to find the valid global value numbering for the PHINode.
1220*d415bd75Srobert if (!OGVN) {
1221*d415bd75Srobert assert(Cand.getStartBB() == IncomingBlock &&
1222*d415bd75Srobert "Unknown basic block used in exit path PHINode.");
1223*d415bd75Srobert
1224*d415bd75Srobert BasicBlock *PrevBlock = nullptr;
1225*d415bd75Srobert // Iterate over the predecessors to the incoming block of the
1226*d415bd75Srobert // PHINode, when we find a block that is not contained in the region
1227*d415bd75Srobert // we know that this is the first block that we split from, and should
1228*d415bd75Srobert // have a valid global value numbering.
1229*d415bd75Srobert for (BasicBlock *Pred : predecessors(IncomingBlock))
1230*d415bd75Srobert if (!Blocks.contains(Pred)) {
1231*d415bd75Srobert PrevBlock = Pred;
1232*d415bd75Srobert break;
1233*d415bd75Srobert }
1234*d415bd75Srobert assert(PrevBlock && "Expected a predecessor not in the reigon!");
1235*d415bd75Srobert OGVN = Cand.getGVN(PrevBlock);
1236*d415bd75Srobert }
1237*d415bd75Srobert GVN = *OGVN;
1238*d415bd75Srobert OGVN = Cand.getCanonicalNum(GVN);
1239*d415bd75Srobert assert(OGVN && "No GVN found for incoming block?");
1240*d415bd75Srobert PHIGVNs.push_back(*OGVN);
1241*d415bd75Srobert }
1242*d415bd75Srobert
1243*d415bd75Srobert // Now that we have the GVNs for the incoming values, we are going to combine
1244*d415bd75Srobert // them with the GVN of the incoming bock, and the output location of the
1245*d415bd75Srobert // PHINode to generate a hash value representing this instance of the PHINode.
1246*d415bd75Srobert DenseMap<hash_code, unsigned>::iterator GVNToPHIIt;
1247*d415bd75Srobert DenseMap<unsigned, PHINodeData>::iterator PHIToGVNIt;
1248*d415bd75Srobert std::optional<unsigned> BBGVN = Cand.getGVN(PHIBB);
1249*d415bd75Srobert assert(BBGVN && "Could not find GVN for the incoming block!");
1250*d415bd75Srobert
1251*d415bd75Srobert BBGVN = Cand.getCanonicalNum(*BBGVN);
1252*d415bd75Srobert assert(BBGVN && "Could not find canonical number for the incoming block!");
1253*d415bd75Srobert // Create a pair of the exit block canonical value, and the aggregate
1254*d415bd75Srobert // argument location, connected to the canonical numbers stored in the
1255*d415bd75Srobert // PHINode.
1256*d415bd75Srobert PHINodeData TemporaryPair =
1257*d415bd75Srobert std::make_pair(std::make_pair(*BBGVN, AggArgIdx), PHIGVNs);
1258*d415bd75Srobert hash_code PHINodeDataHash = encodePHINodeData(TemporaryPair);
1259*d415bd75Srobert
1260*d415bd75Srobert // Look for and create a new entry in our connection between canonical
1261*d415bd75Srobert // numbers for PHINodes, and the set of objects we just created.
1262*d415bd75Srobert GVNToPHIIt = Group.GVNsToPHINodeGVN.find(PHINodeDataHash);
1263*d415bd75Srobert if (GVNToPHIIt == Group.GVNsToPHINodeGVN.end()) {
1264*d415bd75Srobert bool Inserted = false;
1265*d415bd75Srobert std::tie(PHIToGVNIt, Inserted) = Group.PHINodeGVNToGVNs.insert(
1266*d415bd75Srobert std::make_pair(Group.PHINodeGVNTracker, TemporaryPair));
1267*d415bd75Srobert std::tie(GVNToPHIIt, Inserted) = Group.GVNsToPHINodeGVN.insert(
1268*d415bd75Srobert std::make_pair(PHINodeDataHash, Group.PHINodeGVNTracker--));
1269*d415bd75Srobert }
1270*d415bd75Srobert
1271*d415bd75Srobert return GVNToPHIIt->second;
1272*d415bd75Srobert }
1273*d415bd75Srobert
127473471bf0Spatrick /// Create a mapping of the output arguments for the \p Region to the output
127573471bf0Spatrick /// arguments of the overall outlined function.
127673471bf0Spatrick ///
127773471bf0Spatrick /// \param [in,out] Region - The region of code to be analyzed.
127873471bf0Spatrick /// \param [in] Outputs - The values found by the code extractor.
127973471bf0Spatrick static void
findExtractedOutputToOverallOutputMapping(Module & M,OutlinableRegion & Region,SetVector<Value * > & Outputs)1280*d415bd75Srobert findExtractedOutputToOverallOutputMapping(Module &M, OutlinableRegion &Region,
1281*d415bd75Srobert SetVector<Value *> &Outputs) {
128273471bf0Spatrick OutlinableGroup &Group = *Region.Parent;
128373471bf0Spatrick IRSimilarityCandidate &C = *Region.Candidate;
128473471bf0Spatrick
1285*d415bd75Srobert SmallVector<BasicBlock *> BE;
1286*d415bd75Srobert DenseSet<BasicBlock *> BlocksInRegion;
1287*d415bd75Srobert C.getBasicBlocks(BlocksInRegion, BE);
1288*d415bd75Srobert
1289*d415bd75Srobert // Find the exits to the region.
1290*d415bd75Srobert SmallPtrSet<BasicBlock *, 1> Exits;
1291*d415bd75Srobert for (BasicBlock *Block : BE)
1292*d415bd75Srobert for (BasicBlock *Succ : successors(Block))
1293*d415bd75Srobert if (!BlocksInRegion.contains(Succ))
1294*d415bd75Srobert Exits.insert(Succ);
1295*d415bd75Srobert
1296*d415bd75Srobert // After determining which blocks exit to PHINodes, we add these PHINodes to
1297*d415bd75Srobert // the set of outputs to be processed. We also check the incoming values of
1298*d415bd75Srobert // the PHINodes for whether they should no longer be considered outputs.
1299*d415bd75Srobert DenseSet<Value *> OutputsReplacedByPHINode;
1300*d415bd75Srobert DenseSet<Value *> OutputsWithNonPhiUses;
1301*d415bd75Srobert for (BasicBlock *ExitBB : Exits)
1302*d415bd75Srobert analyzeExitPHIsForOutputUses(ExitBB, Exits, BlocksInRegion, Outputs,
1303*d415bd75Srobert OutputsReplacedByPHINode,
1304*d415bd75Srobert OutputsWithNonPhiUses);
1305*d415bd75Srobert
130673471bf0Spatrick // This counts the argument number in the extracted function.
130773471bf0Spatrick unsigned OriginalIndex = Region.NumExtractedInputs;
130873471bf0Spatrick
130973471bf0Spatrick // This counts the argument number in the overall function.
131073471bf0Spatrick unsigned TypeIndex = Group.NumAggregateInputs;
131173471bf0Spatrick bool TypeFound;
131273471bf0Spatrick DenseSet<unsigned> AggArgsUsed;
131373471bf0Spatrick
131473471bf0Spatrick // Iterate over the output types and identify if there is an aggregate pointer
131573471bf0Spatrick // type whose base type matches the current output type. If there is, we mark
131673471bf0Spatrick // that we will use this output register for this value. If not we add another
131773471bf0Spatrick // type to the overall argument type list. We also store the GVNs used for
131873471bf0Spatrick // stores to identify which values will need to be moved into an special
131973471bf0Spatrick // block that holds the stores to the output registers.
132073471bf0Spatrick for (Value *Output : Outputs) {
132173471bf0Spatrick TypeFound = false;
132273471bf0Spatrick // We can do this since it is a result value, and will have a number
132373471bf0Spatrick // that is necessarily the same. BUT if in the future, the instructions
132473471bf0Spatrick // do not have to be in same order, but are functionally the same, we will
132573471bf0Spatrick // have to use a different scheme, as one-to-one correspondence is not
132673471bf0Spatrick // guaranteed.
132773471bf0Spatrick unsigned ArgumentSize = Group.ArgumentTypes.size();
132873471bf0Spatrick
1329*d415bd75Srobert // If the output is combined in a PHINode, we make sure to skip over it.
1330*d415bd75Srobert if (OutputsReplacedByPHINode.contains(Output))
1331*d415bd75Srobert continue;
1332*d415bd75Srobert
1333*d415bd75Srobert unsigned AggArgIdx = 0;
133473471bf0Spatrick for (unsigned Jdx = TypeIndex; Jdx < ArgumentSize; Jdx++) {
133573471bf0Spatrick if (Group.ArgumentTypes[Jdx] != PointerType::getUnqual(Output->getType()))
133673471bf0Spatrick continue;
133773471bf0Spatrick
133873471bf0Spatrick if (AggArgsUsed.contains(Jdx))
133973471bf0Spatrick continue;
134073471bf0Spatrick
134173471bf0Spatrick TypeFound = true;
134273471bf0Spatrick AggArgsUsed.insert(Jdx);
134373471bf0Spatrick Region.ExtractedArgToAgg.insert(std::make_pair(OriginalIndex, Jdx));
134473471bf0Spatrick Region.AggArgToExtracted.insert(std::make_pair(Jdx, OriginalIndex));
1345*d415bd75Srobert AggArgIdx = Jdx;
134673471bf0Spatrick break;
134773471bf0Spatrick }
134873471bf0Spatrick
134973471bf0Spatrick // We were unable to find an unused type in the output type set that matches
135073471bf0Spatrick // the output, so we add a pointer type to the argument types of the overall
135173471bf0Spatrick // function to handle this output and create a mapping to it.
135273471bf0Spatrick if (!TypeFound) {
1353*d415bd75Srobert Group.ArgumentTypes.push_back(Output->getType()->getPointerTo(
1354*d415bd75Srobert M.getDataLayout().getAllocaAddrSpace()));
1355*d415bd75Srobert // Mark the new pointer type as the last value in the aggregate argument
1356*d415bd75Srobert // list.
1357*d415bd75Srobert unsigned ArgTypeIdx = Group.ArgumentTypes.size() - 1;
1358*d415bd75Srobert AggArgsUsed.insert(ArgTypeIdx);
135973471bf0Spatrick Region.ExtractedArgToAgg.insert(
1360*d415bd75Srobert std::make_pair(OriginalIndex, ArgTypeIdx));
136173471bf0Spatrick Region.AggArgToExtracted.insert(
1362*d415bd75Srobert std::make_pair(ArgTypeIdx, OriginalIndex));
1363*d415bd75Srobert AggArgIdx = ArgTypeIdx;
136473471bf0Spatrick }
136573471bf0Spatrick
1366*d415bd75Srobert // TODO: Adapt to the extra input from the PHINode.
1367*d415bd75Srobert PHINode *PN = dyn_cast<PHINode>(Output);
1368*d415bd75Srobert
1369*d415bd75Srobert std::optional<unsigned> GVN;
1370*d415bd75Srobert if (PN && !BlocksInRegion.contains(PN->getParent())) {
1371*d415bd75Srobert // Values outside the region can be combined into PHINode when we
1372*d415bd75Srobert // have multiple exits. We collect both of these into a list to identify
1373*d415bd75Srobert // which values are being used in the PHINode. Each list identifies a
1374*d415bd75Srobert // different PHINode, and a different output. We store the PHINode as it's
1375*d415bd75Srobert // own canonical value. These canonical values are also dependent on the
1376*d415bd75Srobert // output argument it is saved to.
1377*d415bd75Srobert
1378*d415bd75Srobert // If two PHINodes have the same canonical values, but different aggregate
1379*d415bd75Srobert // argument locations, then they will have distinct Canonical Values.
1380*d415bd75Srobert GVN = getGVNForPHINode(Region, PN, BlocksInRegion, AggArgIdx);
1381*d415bd75Srobert if (!GVN)
1382*d415bd75Srobert return;
1383*d415bd75Srobert } else {
1384*d415bd75Srobert // If we do not have a PHINode we use the global value numbering for the
1385*d415bd75Srobert // output value, to find the canonical number to add to the set of stored
1386*d415bd75Srobert // values.
1387*d415bd75Srobert GVN = C.getGVN(Output);
1388*d415bd75Srobert GVN = C.getCanonicalNum(*GVN);
1389*d415bd75Srobert }
1390*d415bd75Srobert
1391*d415bd75Srobert // Each region has a potentially unique set of outputs. We save which
1392*d415bd75Srobert // values are output in a list of canonical values so we can differentiate
1393*d415bd75Srobert // among the different store schemes.
1394*d415bd75Srobert Region.GVNStores.push_back(*GVN);
1395*d415bd75Srobert
139673471bf0Spatrick OriginalIndex++;
139773471bf0Spatrick TypeIndex++;
139873471bf0Spatrick }
1399*d415bd75Srobert
1400*d415bd75Srobert // We sort the stored values to make sure that we are not affected by analysis
1401*d415bd75Srobert // order when determining what combination of items were stored.
1402*d415bd75Srobert stable_sort(Region.GVNStores);
140373471bf0Spatrick }
140473471bf0Spatrick
findAddInputsOutputs(Module & M,OutlinableRegion & Region,DenseSet<unsigned> & NotSame)140573471bf0Spatrick void IROutliner::findAddInputsOutputs(Module &M, OutlinableRegion &Region,
140673471bf0Spatrick DenseSet<unsigned> &NotSame) {
140773471bf0Spatrick std::vector<unsigned> Inputs;
140873471bf0Spatrick SetVector<Value *> ArgInputs, Outputs;
140973471bf0Spatrick
141073471bf0Spatrick getCodeExtractorArguments(Region, Inputs, NotSame, OutputMappings, ArgInputs,
141173471bf0Spatrick Outputs);
141273471bf0Spatrick
141373471bf0Spatrick if (Region.IgnoreRegion)
141473471bf0Spatrick return;
141573471bf0Spatrick
141673471bf0Spatrick // Map the inputs found by the CodeExtractor to the arguments found for
141773471bf0Spatrick // the overall function.
141873471bf0Spatrick findExtractedInputToOverallInputMapping(Region, Inputs, ArgInputs);
141973471bf0Spatrick
142073471bf0Spatrick // Map the outputs found by the CodeExtractor to the arguments found for
142173471bf0Spatrick // the overall function.
1422*d415bd75Srobert findExtractedOutputToOverallOutputMapping(M, Region, Outputs);
142373471bf0Spatrick }
142473471bf0Spatrick
142573471bf0Spatrick /// Replace the extracted function in the Region with a call to the overall
142673471bf0Spatrick /// function constructed from the deduplicated similar regions, replacing and
142773471bf0Spatrick /// remapping the values passed to the extracted function as arguments to the
142873471bf0Spatrick /// new arguments of the overall function.
142973471bf0Spatrick ///
143073471bf0Spatrick /// \param [in] M - The module to outline from.
143173471bf0Spatrick /// \param [in] Region - The regions of extracted code to be replaced with a new
143273471bf0Spatrick /// function.
143373471bf0Spatrick /// \returns a call instruction with the replaced function.
replaceCalledFunction(Module & M,OutlinableRegion & Region)143473471bf0Spatrick CallInst *replaceCalledFunction(Module &M, OutlinableRegion &Region) {
143573471bf0Spatrick std::vector<Value *> NewCallArgs;
143673471bf0Spatrick DenseMap<unsigned, unsigned>::iterator ArgPair;
143773471bf0Spatrick
143873471bf0Spatrick OutlinableGroup &Group = *Region.Parent;
143973471bf0Spatrick CallInst *Call = Region.Call;
144073471bf0Spatrick assert(Call && "Call to replace is nullptr?");
144173471bf0Spatrick Function *AggFunc = Group.OutlinedFunction;
144273471bf0Spatrick assert(AggFunc && "Function to replace with is nullptr?");
144373471bf0Spatrick
144473471bf0Spatrick // If the arguments are the same size, there are not values that need to be
1445*d415bd75Srobert // made into an argument, the argument ordering has not been change, or
1446*d415bd75Srobert // different output registers to handle. We can simply replace the called
1447*d415bd75Srobert // function in this case.
1448*d415bd75Srobert if (!Region.ChangedArgOrder && AggFunc->arg_size() == Call->arg_size()) {
144973471bf0Spatrick LLVM_DEBUG(dbgs() << "Replace call to " << *Call << " with call to "
145073471bf0Spatrick << *AggFunc << " with same number of arguments\n");
145173471bf0Spatrick Call->setCalledFunction(AggFunc);
145273471bf0Spatrick return Call;
145373471bf0Spatrick }
145473471bf0Spatrick
145573471bf0Spatrick // We have a different number of arguments than the new function, so
145673471bf0Spatrick // we need to use our previously mappings off extracted argument to overall
145773471bf0Spatrick // function argument, and constants to overall function argument to create the
145873471bf0Spatrick // new argument list.
145973471bf0Spatrick for (unsigned AggArgIdx = 0; AggArgIdx < AggFunc->arg_size(); AggArgIdx++) {
146073471bf0Spatrick
146173471bf0Spatrick if (AggArgIdx == AggFunc->arg_size() - 1 &&
146273471bf0Spatrick Group.OutputGVNCombinations.size() > 1) {
146373471bf0Spatrick // If we are on the last argument, and we need to differentiate between
146473471bf0Spatrick // output blocks, add an integer to the argument list to determine
146573471bf0Spatrick // what block to take
146673471bf0Spatrick LLVM_DEBUG(dbgs() << "Set switch block argument to "
146773471bf0Spatrick << Region.OutputBlockNum << "\n");
146873471bf0Spatrick NewCallArgs.push_back(ConstantInt::get(Type::getInt32Ty(M.getContext()),
146973471bf0Spatrick Region.OutputBlockNum));
147073471bf0Spatrick continue;
147173471bf0Spatrick }
147273471bf0Spatrick
147373471bf0Spatrick ArgPair = Region.AggArgToExtracted.find(AggArgIdx);
147473471bf0Spatrick if (ArgPair != Region.AggArgToExtracted.end()) {
147573471bf0Spatrick Value *ArgumentValue = Call->getArgOperand(ArgPair->second);
147673471bf0Spatrick // If we found the mapping from the extracted function to the overall
147773471bf0Spatrick // function, we simply add it to the argument list. We use the same
147873471bf0Spatrick // value, it just needs to honor the new order of arguments.
147973471bf0Spatrick LLVM_DEBUG(dbgs() << "Setting argument " << AggArgIdx << " to value "
148073471bf0Spatrick << *ArgumentValue << "\n");
148173471bf0Spatrick NewCallArgs.push_back(ArgumentValue);
148273471bf0Spatrick continue;
148373471bf0Spatrick }
148473471bf0Spatrick
148573471bf0Spatrick // If it is a constant, we simply add it to the argument list as a value.
148673471bf0Spatrick if (Region.AggArgToConstant.find(AggArgIdx) !=
148773471bf0Spatrick Region.AggArgToConstant.end()) {
148873471bf0Spatrick Constant *CST = Region.AggArgToConstant.find(AggArgIdx)->second;
148973471bf0Spatrick LLVM_DEBUG(dbgs() << "Setting argument " << AggArgIdx << " to value "
149073471bf0Spatrick << *CST << "\n");
149173471bf0Spatrick NewCallArgs.push_back(CST);
149273471bf0Spatrick continue;
149373471bf0Spatrick }
149473471bf0Spatrick
149573471bf0Spatrick // Add a nullptr value if the argument is not found in the extracted
149673471bf0Spatrick // function. If we cannot find a value, it means it is not in use
149773471bf0Spatrick // for the region, so we should not pass anything to it.
149873471bf0Spatrick LLVM_DEBUG(dbgs() << "Setting argument " << AggArgIdx << " to nullptr\n");
149973471bf0Spatrick NewCallArgs.push_back(ConstantPointerNull::get(
150073471bf0Spatrick static_cast<PointerType *>(AggFunc->getArg(AggArgIdx)->getType())));
150173471bf0Spatrick }
150273471bf0Spatrick
150373471bf0Spatrick LLVM_DEBUG(dbgs() << "Replace call to " << *Call << " with call to "
150473471bf0Spatrick << *AggFunc << " with new set of arguments\n");
150573471bf0Spatrick // Create the new call instruction and erase the old one.
150673471bf0Spatrick Call = CallInst::Create(AggFunc->getFunctionType(), AggFunc, NewCallArgs, "",
150773471bf0Spatrick Call);
150873471bf0Spatrick
150973471bf0Spatrick // It is possible that the call to the outlined function is either the first
151073471bf0Spatrick // instruction is in the new block, the last instruction, or both. If either
151173471bf0Spatrick // of these is the case, we need to make sure that we replace the instruction
151273471bf0Spatrick // in the IRInstructionData struct with the new call.
151373471bf0Spatrick CallInst *OldCall = Region.Call;
151473471bf0Spatrick if (Region.NewFront->Inst == OldCall)
151573471bf0Spatrick Region.NewFront->Inst = Call;
151673471bf0Spatrick if (Region.NewBack->Inst == OldCall)
151773471bf0Spatrick Region.NewBack->Inst = Call;
151873471bf0Spatrick
151973471bf0Spatrick // Transfer any debug information.
152073471bf0Spatrick Call->setDebugLoc(Region.Call->getDebugLoc());
1521*d415bd75Srobert // Since our output may determine which branch we go to, we make sure to
1522*d415bd75Srobert // propogate this new call value through the module.
1523*d415bd75Srobert OldCall->replaceAllUsesWith(Call);
152473471bf0Spatrick
152573471bf0Spatrick // Remove the old instruction.
152673471bf0Spatrick OldCall->eraseFromParent();
152773471bf0Spatrick Region.Call = Call;
152873471bf0Spatrick
152973471bf0Spatrick // Make sure that the argument in the new function has the SwiftError
153073471bf0Spatrick // argument.
1531*d415bd75Srobert if (Group.SwiftErrorArgument)
1532*d415bd75Srobert Call->addParamAttr(*Group.SwiftErrorArgument, Attribute::SwiftError);
153373471bf0Spatrick
153473471bf0Spatrick return Call;
153573471bf0Spatrick }
153673471bf0Spatrick
1537*d415bd75Srobert /// Find or create a BasicBlock in the outlined function containing PhiBlocks
1538*d415bd75Srobert /// for \p RetVal.
1539*d415bd75Srobert ///
1540*d415bd75Srobert /// \param Group - The OutlinableGroup containing the information about the
1541*d415bd75Srobert /// overall outlined function.
1542*d415bd75Srobert /// \param RetVal - The return value or exit option that we are currently
1543*d415bd75Srobert /// evaluating.
1544*d415bd75Srobert /// \returns The found or newly created BasicBlock to contain the needed
1545*d415bd75Srobert /// PHINodes to be used as outputs.
findOrCreatePHIBlock(OutlinableGroup & Group,Value * RetVal)1546*d415bd75Srobert static BasicBlock *findOrCreatePHIBlock(OutlinableGroup &Group, Value *RetVal) {
1547*d415bd75Srobert DenseMap<Value *, BasicBlock *>::iterator PhiBlockForRetVal,
1548*d415bd75Srobert ReturnBlockForRetVal;
1549*d415bd75Srobert PhiBlockForRetVal = Group.PHIBlocks.find(RetVal);
1550*d415bd75Srobert ReturnBlockForRetVal = Group.EndBBs.find(RetVal);
1551*d415bd75Srobert assert(ReturnBlockForRetVal != Group.EndBBs.end() &&
1552*d415bd75Srobert "Could not find output value!");
1553*d415bd75Srobert BasicBlock *ReturnBB = ReturnBlockForRetVal->second;
1554*d415bd75Srobert
1555*d415bd75Srobert // Find if a PHIBlock exists for this return value already. If it is
1556*d415bd75Srobert // the first time we are analyzing this, we will not, so we record it.
1557*d415bd75Srobert PhiBlockForRetVal = Group.PHIBlocks.find(RetVal);
1558*d415bd75Srobert if (PhiBlockForRetVal != Group.PHIBlocks.end())
1559*d415bd75Srobert return PhiBlockForRetVal->second;
1560*d415bd75Srobert
1561*d415bd75Srobert // If we did not find a block, we create one, and insert it into the
1562*d415bd75Srobert // overall function and record it.
1563*d415bd75Srobert bool Inserted = false;
1564*d415bd75Srobert BasicBlock *PHIBlock = BasicBlock::Create(ReturnBB->getContext(), "phi_block",
1565*d415bd75Srobert ReturnBB->getParent());
1566*d415bd75Srobert std::tie(PhiBlockForRetVal, Inserted) =
1567*d415bd75Srobert Group.PHIBlocks.insert(std::make_pair(RetVal, PHIBlock));
1568*d415bd75Srobert
1569*d415bd75Srobert // We find the predecessors of the return block in the newly created outlined
1570*d415bd75Srobert // function in order to point them to the new PHIBlock rather than the already
1571*d415bd75Srobert // existing return block.
1572*d415bd75Srobert SmallVector<BranchInst *, 2> BranchesToChange;
1573*d415bd75Srobert for (BasicBlock *Pred : predecessors(ReturnBB))
1574*d415bd75Srobert BranchesToChange.push_back(cast<BranchInst>(Pred->getTerminator()));
1575*d415bd75Srobert
1576*d415bd75Srobert // Now we mark the branch instructions found, and change the references of the
1577*d415bd75Srobert // return block to the newly created PHIBlock.
1578*d415bd75Srobert for (BranchInst *BI : BranchesToChange)
1579*d415bd75Srobert for (unsigned Succ = 0, End = BI->getNumSuccessors(); Succ < End; Succ++) {
1580*d415bd75Srobert if (BI->getSuccessor(Succ) != ReturnBB)
1581*d415bd75Srobert continue;
1582*d415bd75Srobert BI->setSuccessor(Succ, PHIBlock);
1583*d415bd75Srobert }
1584*d415bd75Srobert
1585*d415bd75Srobert BranchInst::Create(ReturnBB, PHIBlock);
1586*d415bd75Srobert
1587*d415bd75Srobert return PhiBlockForRetVal->second;
1588*d415bd75Srobert }
1589*d415bd75Srobert
1590*d415bd75Srobert /// For the function call now representing the \p Region, find the passed value
1591*d415bd75Srobert /// to that call that represents Argument \p A at the call location if the
1592*d415bd75Srobert /// call has already been replaced with a call to the overall, aggregate
1593*d415bd75Srobert /// function.
1594*d415bd75Srobert ///
1595*d415bd75Srobert /// \param A - The Argument to get the passed value for.
1596*d415bd75Srobert /// \param Region - The extracted Region corresponding to the outlined function.
1597*d415bd75Srobert /// \returns The Value representing \p A at the call site.
1598*d415bd75Srobert static Value *
getPassedArgumentInAlreadyOutlinedFunction(const Argument * A,const OutlinableRegion & Region)1599*d415bd75Srobert getPassedArgumentInAlreadyOutlinedFunction(const Argument *A,
1600*d415bd75Srobert const OutlinableRegion &Region) {
1601*d415bd75Srobert // If we don't need to adjust the argument number at all (since the call
1602*d415bd75Srobert // has already been replaced by a call to the overall outlined function)
1603*d415bd75Srobert // we can just get the specified argument.
1604*d415bd75Srobert return Region.Call->getArgOperand(A->getArgNo());
1605*d415bd75Srobert }
1606*d415bd75Srobert
1607*d415bd75Srobert /// For the function call now representing the \p Region, find the passed value
1608*d415bd75Srobert /// to that call that represents Argument \p A at the call location if the
1609*d415bd75Srobert /// call has only been replaced by the call to the aggregate function.
1610*d415bd75Srobert ///
1611*d415bd75Srobert /// \param A - The Argument to get the passed value for.
1612*d415bd75Srobert /// \param Region - The extracted Region corresponding to the outlined function.
1613*d415bd75Srobert /// \returns The Value representing \p A at the call site.
1614*d415bd75Srobert static Value *
getPassedArgumentAndAdjustArgumentLocation(const Argument * A,const OutlinableRegion & Region)1615*d415bd75Srobert getPassedArgumentAndAdjustArgumentLocation(const Argument *A,
1616*d415bd75Srobert const OutlinableRegion &Region) {
1617*d415bd75Srobert unsigned ArgNum = A->getArgNo();
1618*d415bd75Srobert
1619*d415bd75Srobert // If it is a constant, we can look at our mapping from when we created
1620*d415bd75Srobert // the outputs to figure out what the constant value is.
1621*d415bd75Srobert if (Region.AggArgToConstant.count(ArgNum))
1622*d415bd75Srobert return Region.AggArgToConstant.find(ArgNum)->second;
1623*d415bd75Srobert
1624*d415bd75Srobert // If it is not a constant, and we are not looking at the overall function, we
1625*d415bd75Srobert // need to adjust which argument we are looking at.
1626*d415bd75Srobert ArgNum = Region.AggArgToExtracted.find(ArgNum)->second;
1627*d415bd75Srobert return Region.Call->getArgOperand(ArgNum);
1628*d415bd75Srobert }
1629*d415bd75Srobert
1630*d415bd75Srobert /// Find the canonical numbering for the incoming Values into the PHINode \p PN.
1631*d415bd75Srobert ///
1632*d415bd75Srobert /// \param PN [in] - The PHINode that we are finding the canonical numbers for.
1633*d415bd75Srobert /// \param Region [in] - The OutlinableRegion containing \p PN.
1634*d415bd75Srobert /// \param OutputMappings [in] - The mapping of output values from outlined
1635*d415bd75Srobert /// region to their original values.
1636*d415bd75Srobert /// \param CanonNums [out] - The canonical numbering for the incoming values to
1637*d415bd75Srobert /// \p PN paired with their incoming block.
1638*d415bd75Srobert /// \param ReplacedWithOutlinedCall - A flag to use the extracted function call
1639*d415bd75Srobert /// of \p Region rather than the overall function's call.
findCanonNumsForPHI(PHINode * PN,OutlinableRegion & Region,const DenseMap<Value *,Value * > & OutputMappings,SmallVector<std::pair<unsigned,BasicBlock * >> & CanonNums,bool ReplacedWithOutlinedCall=true)1640*d415bd75Srobert static void findCanonNumsForPHI(
1641*d415bd75Srobert PHINode *PN, OutlinableRegion &Region,
1642*d415bd75Srobert const DenseMap<Value *, Value *> &OutputMappings,
1643*d415bd75Srobert SmallVector<std::pair<unsigned, BasicBlock *>> &CanonNums,
1644*d415bd75Srobert bool ReplacedWithOutlinedCall = true) {
1645*d415bd75Srobert // Iterate over the incoming values.
1646*d415bd75Srobert for (unsigned Idx = 0, EIdx = PN->getNumIncomingValues(); Idx < EIdx; Idx++) {
1647*d415bd75Srobert Value *IVal = PN->getIncomingValue(Idx);
1648*d415bd75Srobert BasicBlock *IBlock = PN->getIncomingBlock(Idx);
1649*d415bd75Srobert // If we have an argument as incoming value, we need to grab the passed
1650*d415bd75Srobert // value from the call itself.
1651*d415bd75Srobert if (Argument *A = dyn_cast<Argument>(IVal)) {
1652*d415bd75Srobert if (ReplacedWithOutlinedCall)
1653*d415bd75Srobert IVal = getPassedArgumentInAlreadyOutlinedFunction(A, Region);
1654*d415bd75Srobert else
1655*d415bd75Srobert IVal = getPassedArgumentAndAdjustArgumentLocation(A, Region);
1656*d415bd75Srobert }
1657*d415bd75Srobert
1658*d415bd75Srobert // Get the original value if it has been replaced by an output value.
1659*d415bd75Srobert IVal = findOutputMapping(OutputMappings, IVal);
1660*d415bd75Srobert
1661*d415bd75Srobert // Find and add the canonical number for the incoming value.
1662*d415bd75Srobert std::optional<unsigned> GVN = Region.Candidate->getGVN(IVal);
1663*d415bd75Srobert assert(GVN && "No GVN for incoming value");
1664*d415bd75Srobert std::optional<unsigned> CanonNum = Region.Candidate->getCanonicalNum(*GVN);
1665*d415bd75Srobert assert(CanonNum && "No Canonical Number for GVN");
1666*d415bd75Srobert CanonNums.push_back(std::make_pair(*CanonNum, IBlock));
1667*d415bd75Srobert }
1668*d415bd75Srobert }
1669*d415bd75Srobert
1670*d415bd75Srobert /// Find, or add PHINode \p PN to the combined PHINode Block \p OverallPHIBlock
1671*d415bd75Srobert /// in order to condense the number of instructions added to the outlined
1672*d415bd75Srobert /// function.
1673*d415bd75Srobert ///
1674*d415bd75Srobert /// \param PN [in] - The PHINode that we are finding the canonical numbers for.
1675*d415bd75Srobert /// \param Region [in] - The OutlinableRegion containing \p PN.
1676*d415bd75Srobert /// \param OverallPhiBlock [in] - The overall PHIBlock we are trying to find
1677*d415bd75Srobert /// \p PN in.
1678*d415bd75Srobert /// \param OutputMappings [in] - The mapping of output values from outlined
1679*d415bd75Srobert /// region to their original values.
1680*d415bd75Srobert /// \param UsedPHIs [in, out] - The PHINodes in the block that have already been
1681*d415bd75Srobert /// matched.
1682*d415bd75Srobert /// \return the newly found or created PHINode in \p OverallPhiBlock.
1683*d415bd75Srobert static PHINode*
findOrCreatePHIInBlock(PHINode & PN,OutlinableRegion & Region,BasicBlock * OverallPhiBlock,const DenseMap<Value *,Value * > & OutputMappings,DenseSet<PHINode * > & UsedPHIs)1684*d415bd75Srobert findOrCreatePHIInBlock(PHINode &PN, OutlinableRegion &Region,
1685*d415bd75Srobert BasicBlock *OverallPhiBlock,
1686*d415bd75Srobert const DenseMap<Value *, Value *> &OutputMappings,
1687*d415bd75Srobert DenseSet<PHINode *> &UsedPHIs) {
1688*d415bd75Srobert OutlinableGroup &Group = *Region.Parent;
1689*d415bd75Srobert
1690*d415bd75Srobert
1691*d415bd75Srobert // A list of the canonical numbering assigned to each incoming value, paired
1692*d415bd75Srobert // with the incoming block for the PHINode passed into this function.
1693*d415bd75Srobert SmallVector<std::pair<unsigned, BasicBlock *>> PNCanonNums;
1694*d415bd75Srobert
1695*d415bd75Srobert // We have to use the extracted function since we have merged this region into
1696*d415bd75Srobert // the overall function yet. We make sure to reassign the argument numbering
1697*d415bd75Srobert // since it is possible that the argument ordering is different between the
1698*d415bd75Srobert // functions.
1699*d415bd75Srobert findCanonNumsForPHI(&PN, Region, OutputMappings, PNCanonNums,
1700*d415bd75Srobert /* ReplacedWithOutlinedCall = */ false);
1701*d415bd75Srobert
1702*d415bd75Srobert OutlinableRegion *FirstRegion = Group.Regions[0];
1703*d415bd75Srobert
1704*d415bd75Srobert // A list of the canonical numbering assigned to each incoming value, paired
1705*d415bd75Srobert // with the incoming block for the PHINode that we are currently comparing
1706*d415bd75Srobert // the passed PHINode to.
1707*d415bd75Srobert SmallVector<std::pair<unsigned, BasicBlock *>> CurrentCanonNums;
1708*d415bd75Srobert
1709*d415bd75Srobert // Find the Canonical Numbering for each PHINode, if it matches, we replace
1710*d415bd75Srobert // the uses of the PHINode we are searching for, with the found PHINode.
1711*d415bd75Srobert for (PHINode &CurrPN : OverallPhiBlock->phis()) {
1712*d415bd75Srobert // If this PHINode has already been matched to another PHINode to be merged,
1713*d415bd75Srobert // we skip it.
1714*d415bd75Srobert if (UsedPHIs.contains(&CurrPN))
1715*d415bd75Srobert continue;
1716*d415bd75Srobert
1717*d415bd75Srobert CurrentCanonNums.clear();
1718*d415bd75Srobert findCanonNumsForPHI(&CurrPN, *FirstRegion, OutputMappings, CurrentCanonNums,
1719*d415bd75Srobert /* ReplacedWithOutlinedCall = */ true);
1720*d415bd75Srobert
1721*d415bd75Srobert // If the list of incoming values is not the same length, then they cannot
1722*d415bd75Srobert // match since there is not an analogue for each incoming value.
1723*d415bd75Srobert if (PNCanonNums.size() != CurrentCanonNums.size())
1724*d415bd75Srobert continue;
1725*d415bd75Srobert
1726*d415bd75Srobert bool FoundMatch = true;
1727*d415bd75Srobert
1728*d415bd75Srobert // We compare the canonical value for each incoming value in the passed
1729*d415bd75Srobert // in PHINode to one already present in the outlined region. If the
1730*d415bd75Srobert // incoming values do not match, then the PHINodes do not match.
1731*d415bd75Srobert
1732*d415bd75Srobert // We also check to make sure that the incoming block matches as well by
1733*d415bd75Srobert // finding the corresponding incoming block in the combined outlined region
1734*d415bd75Srobert // for the current outlined region.
1735*d415bd75Srobert for (unsigned Idx = 0, Edx = PNCanonNums.size(); Idx < Edx; ++Idx) {
1736*d415bd75Srobert std::pair<unsigned, BasicBlock *> ToCompareTo = CurrentCanonNums[Idx];
1737*d415bd75Srobert std::pair<unsigned, BasicBlock *> ToAdd = PNCanonNums[Idx];
1738*d415bd75Srobert if (ToCompareTo.first != ToAdd.first) {
1739*d415bd75Srobert FoundMatch = false;
1740*d415bd75Srobert break;
1741*d415bd75Srobert }
1742*d415bd75Srobert
1743*d415bd75Srobert BasicBlock *CorrespondingBlock =
1744*d415bd75Srobert Region.findCorrespondingBlockIn(*FirstRegion, ToAdd.second);
1745*d415bd75Srobert assert(CorrespondingBlock && "Found block is nullptr");
1746*d415bd75Srobert if (CorrespondingBlock != ToCompareTo.second) {
1747*d415bd75Srobert FoundMatch = false;
1748*d415bd75Srobert break;
1749*d415bd75Srobert }
1750*d415bd75Srobert }
1751*d415bd75Srobert
1752*d415bd75Srobert // If all incoming values and branches matched, then we can merge
1753*d415bd75Srobert // into the found PHINode.
1754*d415bd75Srobert if (FoundMatch) {
1755*d415bd75Srobert UsedPHIs.insert(&CurrPN);
1756*d415bd75Srobert return &CurrPN;
1757*d415bd75Srobert }
1758*d415bd75Srobert }
1759*d415bd75Srobert
1760*d415bd75Srobert // If we've made it here, it means we weren't able to replace the PHINode, so
1761*d415bd75Srobert // we must insert it ourselves.
1762*d415bd75Srobert PHINode *NewPN = cast<PHINode>(PN.clone());
1763*d415bd75Srobert NewPN->insertBefore(&*OverallPhiBlock->begin());
1764*d415bd75Srobert for (unsigned Idx = 0, Edx = NewPN->getNumIncomingValues(); Idx < Edx;
1765*d415bd75Srobert Idx++) {
1766*d415bd75Srobert Value *IncomingVal = NewPN->getIncomingValue(Idx);
1767*d415bd75Srobert BasicBlock *IncomingBlock = NewPN->getIncomingBlock(Idx);
1768*d415bd75Srobert
1769*d415bd75Srobert // Find corresponding basic block in the overall function for the incoming
1770*d415bd75Srobert // block.
1771*d415bd75Srobert BasicBlock *BlockToUse =
1772*d415bd75Srobert Region.findCorrespondingBlockIn(*FirstRegion, IncomingBlock);
1773*d415bd75Srobert NewPN->setIncomingBlock(Idx, BlockToUse);
1774*d415bd75Srobert
1775*d415bd75Srobert // If we have an argument we make sure we replace using the argument from
1776*d415bd75Srobert // the correct function.
1777*d415bd75Srobert if (Argument *A = dyn_cast<Argument>(IncomingVal)) {
1778*d415bd75Srobert Value *Val = Group.OutlinedFunction->getArg(A->getArgNo());
1779*d415bd75Srobert NewPN->setIncomingValue(Idx, Val);
1780*d415bd75Srobert continue;
1781*d415bd75Srobert }
1782*d415bd75Srobert
1783*d415bd75Srobert // Find the corresponding value in the overall function.
1784*d415bd75Srobert IncomingVal = findOutputMapping(OutputMappings, IncomingVal);
1785*d415bd75Srobert Value *Val = Region.findCorrespondingValueIn(*FirstRegion, IncomingVal);
1786*d415bd75Srobert assert(Val && "Value is nullptr?");
1787*d415bd75Srobert DenseMap<Value *, Value *>::iterator RemappedIt =
1788*d415bd75Srobert FirstRegion->RemappedArguments.find(Val);
1789*d415bd75Srobert if (RemappedIt != FirstRegion->RemappedArguments.end())
1790*d415bd75Srobert Val = RemappedIt->second;
1791*d415bd75Srobert NewPN->setIncomingValue(Idx, Val);
1792*d415bd75Srobert }
1793*d415bd75Srobert return NewPN;
1794*d415bd75Srobert }
1795*d415bd75Srobert
179673471bf0Spatrick // Within an extracted function, replace the argument uses of the extracted
179773471bf0Spatrick // region with the arguments of the function for an OutlinableGroup.
179873471bf0Spatrick //
179973471bf0Spatrick /// \param [in] Region - The region of extracted code to be changed.
1800*d415bd75Srobert /// \param [in,out] OutputBBs - The BasicBlock for the output stores for this
180173471bf0Spatrick /// region.
1802*d415bd75Srobert /// \param [in] FirstFunction - A flag to indicate whether we are using this
1803*d415bd75Srobert /// function to define the overall outlined function for all the regions, or
1804*d415bd75Srobert /// if we are operating on one of the following regions.
1805*d415bd75Srobert static void
replaceArgumentUses(OutlinableRegion & Region,DenseMap<Value *,BasicBlock * > & OutputBBs,const DenseMap<Value *,Value * > & OutputMappings,bool FirstFunction=false)1806*d415bd75Srobert replaceArgumentUses(OutlinableRegion &Region,
1807*d415bd75Srobert DenseMap<Value *, BasicBlock *> &OutputBBs,
1808*d415bd75Srobert const DenseMap<Value *, Value *> &OutputMappings,
1809*d415bd75Srobert bool FirstFunction = false) {
181073471bf0Spatrick OutlinableGroup &Group = *Region.Parent;
181173471bf0Spatrick assert(Region.ExtractedFunction && "Region has no extracted function?");
181273471bf0Spatrick
1813*d415bd75Srobert Function *DominatingFunction = Region.ExtractedFunction;
1814*d415bd75Srobert if (FirstFunction)
1815*d415bd75Srobert DominatingFunction = Group.OutlinedFunction;
1816*d415bd75Srobert DominatorTree DT(*DominatingFunction);
1817*d415bd75Srobert DenseSet<PHINode *> UsedPHIs;
1818*d415bd75Srobert
181973471bf0Spatrick for (unsigned ArgIdx = 0; ArgIdx < Region.ExtractedFunction->arg_size();
182073471bf0Spatrick ArgIdx++) {
182173471bf0Spatrick assert(Region.ExtractedArgToAgg.find(ArgIdx) !=
182273471bf0Spatrick Region.ExtractedArgToAgg.end() &&
182373471bf0Spatrick "No mapping from extracted to outlined?");
182473471bf0Spatrick unsigned AggArgIdx = Region.ExtractedArgToAgg.find(ArgIdx)->second;
182573471bf0Spatrick Argument *AggArg = Group.OutlinedFunction->getArg(AggArgIdx);
182673471bf0Spatrick Argument *Arg = Region.ExtractedFunction->getArg(ArgIdx);
182773471bf0Spatrick // The argument is an input, so we can simply replace it with the overall
182873471bf0Spatrick // argument value
182973471bf0Spatrick if (ArgIdx < Region.NumExtractedInputs) {
183073471bf0Spatrick LLVM_DEBUG(dbgs() << "Replacing uses of input " << *Arg << " in function "
183173471bf0Spatrick << *Region.ExtractedFunction << " with " << *AggArg
183273471bf0Spatrick << " in function " << *Group.OutlinedFunction << "\n");
183373471bf0Spatrick Arg->replaceAllUsesWith(AggArg);
1834*d415bd75Srobert Value *V = Region.Call->getArgOperand(ArgIdx);
1835*d415bd75Srobert Region.RemappedArguments.insert(std::make_pair(V, AggArg));
183673471bf0Spatrick continue;
183773471bf0Spatrick }
183873471bf0Spatrick
183973471bf0Spatrick // If we are replacing an output, we place the store value in its own
184073471bf0Spatrick // block inside the overall function before replacing the use of the output
184173471bf0Spatrick // in the function.
184273471bf0Spatrick assert(Arg->hasOneUse() && "Output argument can only have one use");
184373471bf0Spatrick User *InstAsUser = Arg->user_back();
184473471bf0Spatrick assert(InstAsUser && "User is nullptr!");
184573471bf0Spatrick
184673471bf0Spatrick Instruction *I = cast<Instruction>(InstAsUser);
1847*d415bd75Srobert BasicBlock *BB = I->getParent();
1848*d415bd75Srobert SmallVector<BasicBlock *, 4> Descendants;
1849*d415bd75Srobert DT.getDescendants(BB, Descendants);
1850*d415bd75Srobert bool EdgeAdded = false;
1851*d415bd75Srobert if (Descendants.size() == 0) {
1852*d415bd75Srobert EdgeAdded = true;
1853*d415bd75Srobert DT.insertEdge(&DominatingFunction->getEntryBlock(), BB);
1854*d415bd75Srobert DT.getDescendants(BB, Descendants);
1855*d415bd75Srobert }
1856*d415bd75Srobert
1857*d415bd75Srobert // Iterate over the following blocks, looking for return instructions,
1858*d415bd75Srobert // if we find one, find the corresponding output block for the return value
1859*d415bd75Srobert // and move our store instruction there.
1860*d415bd75Srobert for (BasicBlock *DescendBB : Descendants) {
1861*d415bd75Srobert ReturnInst *RI = dyn_cast<ReturnInst>(DescendBB->getTerminator());
1862*d415bd75Srobert if (!RI)
1863*d415bd75Srobert continue;
1864*d415bd75Srobert Value *RetVal = RI->getReturnValue();
1865*d415bd75Srobert auto VBBIt = OutputBBs.find(RetVal);
1866*d415bd75Srobert assert(VBBIt != OutputBBs.end() && "Could not find output value!");
1867*d415bd75Srobert
1868*d415bd75Srobert // If this is storing a PHINode, we must make sure it is included in the
1869*d415bd75Srobert // overall function.
1870*d415bd75Srobert StoreInst *SI = cast<StoreInst>(I);
1871*d415bd75Srobert
1872*d415bd75Srobert Value *ValueOperand = SI->getValueOperand();
1873*d415bd75Srobert
1874*d415bd75Srobert StoreInst *NewI = cast<StoreInst>(I->clone());
1875*d415bd75Srobert NewI->setDebugLoc(DebugLoc());
1876*d415bd75Srobert BasicBlock *OutputBB = VBBIt->second;
1877*d415bd75Srobert NewI->insertInto(OutputBB, OutputBB->end());
187873471bf0Spatrick LLVM_DEBUG(dbgs() << "Move store for instruction " << *I << " to "
187973471bf0Spatrick << *OutputBB << "\n");
188073471bf0Spatrick
1881*d415bd75Srobert // If this is storing a PHINode, we must make sure it is included in the
1882*d415bd75Srobert // overall function.
1883*d415bd75Srobert if (!isa<PHINode>(ValueOperand) ||
1884*d415bd75Srobert Region.Candidate->getGVN(ValueOperand).has_value()) {
1885*d415bd75Srobert if (FirstFunction)
1886*d415bd75Srobert continue;
1887*d415bd75Srobert Value *CorrVal =
1888*d415bd75Srobert Region.findCorrespondingValueIn(*Group.Regions[0], ValueOperand);
1889*d415bd75Srobert assert(CorrVal && "Value is nullptr?");
1890*d415bd75Srobert NewI->setOperand(0, CorrVal);
1891*d415bd75Srobert continue;
1892*d415bd75Srobert }
1893*d415bd75Srobert PHINode *PN = cast<PHINode>(SI->getValueOperand());
1894*d415bd75Srobert // If it has a value, it was not split by the code extractor, which
1895*d415bd75Srobert // is what we are looking for.
1896*d415bd75Srobert if (Region.Candidate->getGVN(PN))
1897*d415bd75Srobert continue;
1898*d415bd75Srobert
1899*d415bd75Srobert // We record the parent block for the PHINode in the Region so that
1900*d415bd75Srobert // we can exclude it from checks later on.
1901*d415bd75Srobert Region.PHIBlocks.insert(std::make_pair(RetVal, PN->getParent()));
1902*d415bd75Srobert
1903*d415bd75Srobert // If this is the first function, we do not need to worry about mergiing
1904*d415bd75Srobert // this with any other block in the overall outlined function, so we can
1905*d415bd75Srobert // just continue.
1906*d415bd75Srobert if (FirstFunction) {
1907*d415bd75Srobert BasicBlock *PHIBlock = PN->getParent();
1908*d415bd75Srobert Group.PHIBlocks.insert(std::make_pair(RetVal, PHIBlock));
1909*d415bd75Srobert continue;
1910*d415bd75Srobert }
1911*d415bd75Srobert
1912*d415bd75Srobert // We look for the aggregate block that contains the PHINodes leading into
1913*d415bd75Srobert // this exit path. If we can't find one, we create one.
1914*d415bd75Srobert BasicBlock *OverallPhiBlock = findOrCreatePHIBlock(Group, RetVal);
1915*d415bd75Srobert
1916*d415bd75Srobert // For our PHINode, we find the combined canonical numbering, and
1917*d415bd75Srobert // attempt to find a matching PHINode in the overall PHIBlock. If we
1918*d415bd75Srobert // cannot, we copy the PHINode and move it into this new block.
1919*d415bd75Srobert PHINode *NewPN = findOrCreatePHIInBlock(*PN, Region, OverallPhiBlock,
1920*d415bd75Srobert OutputMappings, UsedPHIs);
1921*d415bd75Srobert NewI->setOperand(0, NewPN);
1922*d415bd75Srobert }
1923*d415bd75Srobert
1924*d415bd75Srobert // If we added an edge for basic blocks without a predecessor, we remove it
1925*d415bd75Srobert // here.
1926*d415bd75Srobert if (EdgeAdded)
1927*d415bd75Srobert DT.deleteEdge(&DominatingFunction->getEntryBlock(), BB);
1928*d415bd75Srobert I->eraseFromParent();
192973471bf0Spatrick
193073471bf0Spatrick LLVM_DEBUG(dbgs() << "Replacing uses of output " << *Arg << " in function "
193173471bf0Spatrick << *Region.ExtractedFunction << " with " << *AggArg
193273471bf0Spatrick << " in function " << *Group.OutlinedFunction << "\n");
193373471bf0Spatrick Arg->replaceAllUsesWith(AggArg);
193473471bf0Spatrick }
193573471bf0Spatrick }
193673471bf0Spatrick
193773471bf0Spatrick /// Within an extracted function, replace the constants that need to be lifted
193873471bf0Spatrick /// into arguments with the actual argument.
193973471bf0Spatrick ///
194073471bf0Spatrick /// \param Region [in] - The region of extracted code to be changed.
replaceConstants(OutlinableRegion & Region)194173471bf0Spatrick void replaceConstants(OutlinableRegion &Region) {
194273471bf0Spatrick OutlinableGroup &Group = *Region.Parent;
194373471bf0Spatrick // Iterate over the constants that need to be elevated into arguments
194473471bf0Spatrick for (std::pair<unsigned, Constant *> &Const : Region.AggArgToConstant) {
194573471bf0Spatrick unsigned AggArgIdx = Const.first;
194673471bf0Spatrick Function *OutlinedFunction = Group.OutlinedFunction;
194773471bf0Spatrick assert(OutlinedFunction && "Overall Function is not defined?");
194873471bf0Spatrick Constant *CST = Const.second;
194973471bf0Spatrick Argument *Arg = Group.OutlinedFunction->getArg(AggArgIdx);
195073471bf0Spatrick // Identify the argument it will be elevated to, and replace instances of
195173471bf0Spatrick // that constant in the function.
195273471bf0Spatrick
195373471bf0Spatrick // TODO: If in the future constants do not have one global value number,
195473471bf0Spatrick // i.e. a constant 1 could be mapped to several values, this check will
195573471bf0Spatrick // have to be more strict. It cannot be using only replaceUsesWithIf.
195673471bf0Spatrick
195773471bf0Spatrick LLVM_DEBUG(dbgs() << "Replacing uses of constant " << *CST
195873471bf0Spatrick << " in function " << *OutlinedFunction << " with "
195973471bf0Spatrick << *Arg << "\n");
196073471bf0Spatrick CST->replaceUsesWithIf(Arg, [OutlinedFunction](Use &U) {
196173471bf0Spatrick if (Instruction *I = dyn_cast<Instruction>(U.getUser()))
196273471bf0Spatrick return I->getFunction() == OutlinedFunction;
196373471bf0Spatrick return false;
196473471bf0Spatrick });
196573471bf0Spatrick }
196673471bf0Spatrick }
196773471bf0Spatrick
196873471bf0Spatrick /// It is possible that there is a basic block that already performs the same
196973471bf0Spatrick /// stores. This returns a duplicate block, if it exists
197073471bf0Spatrick ///
1971*d415bd75Srobert /// \param OutputBBs [in] the blocks we are looking for a duplicate of.
197273471bf0Spatrick /// \param OutputStoreBBs [in] The existing output blocks.
197373471bf0Spatrick /// \returns an optional value with the number output block if there is a match.
findDuplicateOutputBlock(DenseMap<Value *,BasicBlock * > & OutputBBs,std::vector<DenseMap<Value *,BasicBlock * >> & OutputStoreBBs)1974*d415bd75Srobert std::optional<unsigned> findDuplicateOutputBlock(
1975*d415bd75Srobert DenseMap<Value *, BasicBlock *> &OutputBBs,
1976*d415bd75Srobert std::vector<DenseMap<Value *, BasicBlock *>> &OutputStoreBBs) {
197773471bf0Spatrick
1978*d415bd75Srobert bool Mismatch = false;
197973471bf0Spatrick unsigned MatchingNum = 0;
1980*d415bd75Srobert // We compare the new set output blocks to the other sets of output blocks.
1981*d415bd75Srobert // If they are the same number, and have identical instructions, they are
1982*d415bd75Srobert // considered to be the same.
1983*d415bd75Srobert for (DenseMap<Value *, BasicBlock *> &CompBBs : OutputStoreBBs) {
1984*d415bd75Srobert Mismatch = false;
1985*d415bd75Srobert for (std::pair<Value *, BasicBlock *> &VToB : CompBBs) {
1986*d415bd75Srobert DenseMap<Value *, BasicBlock *>::iterator OutputBBIt =
1987*d415bd75Srobert OutputBBs.find(VToB.first);
1988*d415bd75Srobert if (OutputBBIt == OutputBBs.end()) {
1989*d415bd75Srobert Mismatch = true;
1990*d415bd75Srobert break;
199173471bf0Spatrick }
199273471bf0Spatrick
1993*d415bd75Srobert BasicBlock *CompBB = VToB.second;
1994*d415bd75Srobert BasicBlock *OutputBB = OutputBBIt->second;
1995*d415bd75Srobert if (CompBB->size() - 1 != OutputBB->size()) {
1996*d415bd75Srobert Mismatch = true;
1997*d415bd75Srobert break;
1998*d415bd75Srobert }
1999*d415bd75Srobert
200073471bf0Spatrick BasicBlock::iterator NIt = OutputBB->begin();
200173471bf0Spatrick for (Instruction &I : *CompBB) {
200273471bf0Spatrick if (isa<BranchInst>(&I))
200373471bf0Spatrick continue;
200473471bf0Spatrick
200573471bf0Spatrick if (!I.isIdenticalTo(&(*NIt))) {
2006*d415bd75Srobert Mismatch = true;
200773471bf0Spatrick break;
200873471bf0Spatrick }
200973471bf0Spatrick
201073471bf0Spatrick NIt++;
201173471bf0Spatrick }
2012*d415bd75Srobert }
2013*d415bd75Srobert
2014*d415bd75Srobert if (!Mismatch)
201573471bf0Spatrick return MatchingNum;
201673471bf0Spatrick
201773471bf0Spatrick MatchingNum++;
201873471bf0Spatrick }
201973471bf0Spatrick
2020*d415bd75Srobert return std::nullopt;
2021*d415bd75Srobert }
2022*d415bd75Srobert
2023*d415bd75Srobert /// Remove empty output blocks from the outlined region.
2024*d415bd75Srobert ///
2025*d415bd75Srobert /// \param BlocksToPrune - Mapping of return values output blocks for the \p
2026*d415bd75Srobert /// Region.
2027*d415bd75Srobert /// \param Region - The OutlinableRegion we are analyzing.
2028*d415bd75Srobert static bool
analyzeAndPruneOutputBlocks(DenseMap<Value *,BasicBlock * > & BlocksToPrune,OutlinableRegion & Region)2029*d415bd75Srobert analyzeAndPruneOutputBlocks(DenseMap<Value *, BasicBlock *> &BlocksToPrune,
2030*d415bd75Srobert OutlinableRegion &Region) {
2031*d415bd75Srobert bool AllRemoved = true;
2032*d415bd75Srobert Value *RetValueForBB;
2033*d415bd75Srobert BasicBlock *NewBB;
2034*d415bd75Srobert SmallVector<Value *, 4> ToRemove;
2035*d415bd75Srobert // Iterate over the output blocks created in the outlined section.
2036*d415bd75Srobert for (std::pair<Value *, BasicBlock *> &VtoBB : BlocksToPrune) {
2037*d415bd75Srobert RetValueForBB = VtoBB.first;
2038*d415bd75Srobert NewBB = VtoBB.second;
2039*d415bd75Srobert
2040*d415bd75Srobert // If there are no instructions, we remove it from the module, and also
2041*d415bd75Srobert // mark the value for removal from the return value to output block mapping.
2042*d415bd75Srobert if (NewBB->size() == 0) {
2043*d415bd75Srobert NewBB->eraseFromParent();
2044*d415bd75Srobert ToRemove.push_back(RetValueForBB);
2045*d415bd75Srobert continue;
2046*d415bd75Srobert }
2047*d415bd75Srobert
2048*d415bd75Srobert // Mark that we could not remove all the blocks since they were not all
2049*d415bd75Srobert // empty.
2050*d415bd75Srobert AllRemoved = false;
2051*d415bd75Srobert }
2052*d415bd75Srobert
2053*d415bd75Srobert // Remove the return value from the mapping.
2054*d415bd75Srobert for (Value *V : ToRemove)
2055*d415bd75Srobert BlocksToPrune.erase(V);
2056*d415bd75Srobert
2057*d415bd75Srobert // Mark the region as having the no output scheme.
2058*d415bd75Srobert if (AllRemoved)
2059*d415bd75Srobert Region.OutputBlockNum = -1;
2060*d415bd75Srobert
2061*d415bd75Srobert return AllRemoved;
206273471bf0Spatrick }
206373471bf0Spatrick
206473471bf0Spatrick /// For the outlined section, move needed the StoreInsts for the output
206573471bf0Spatrick /// registers into their own block. Then, determine if there is a duplicate
206673471bf0Spatrick /// output block already created.
206773471bf0Spatrick ///
206873471bf0Spatrick /// \param [in] OG - The OutlinableGroup of regions to be outlined.
206973471bf0Spatrick /// \param [in] Region - The OutlinableRegion that is being analyzed.
2070*d415bd75Srobert /// \param [in,out] OutputBBs - the blocks that stores for this region will be
207173471bf0Spatrick /// placed in.
2072*d415bd75Srobert /// \param [in] EndBBs - the final blocks of the extracted function.
207373471bf0Spatrick /// \param [in] OutputMappings - OutputMappings the mapping of values that have
207473471bf0Spatrick /// been replaced by a new output value.
207573471bf0Spatrick /// \param [in,out] OutputStoreBBs - The existing output blocks.
alignOutputBlockWithAggFunc(OutlinableGroup & OG,OutlinableRegion & Region,DenseMap<Value *,BasicBlock * > & OutputBBs,DenseMap<Value *,BasicBlock * > & EndBBs,const DenseMap<Value *,Value * > & OutputMappings,std::vector<DenseMap<Value *,BasicBlock * >> & OutputStoreBBs)2076*d415bd75Srobert static void alignOutputBlockWithAggFunc(
2077*d415bd75Srobert OutlinableGroup &OG, OutlinableRegion &Region,
2078*d415bd75Srobert DenseMap<Value *, BasicBlock *> &OutputBBs,
2079*d415bd75Srobert DenseMap<Value *, BasicBlock *> &EndBBs,
208073471bf0Spatrick const DenseMap<Value *, Value *> &OutputMappings,
2081*d415bd75Srobert std::vector<DenseMap<Value *, BasicBlock *>> &OutputStoreBBs) {
2082*d415bd75Srobert // If none of the output blocks have any instructions, this means that we do
2083*d415bd75Srobert // not have to determine if it matches any of the other output schemes, and we
2084*d415bd75Srobert // don't have to do anything else.
2085*d415bd75Srobert if (analyzeAndPruneOutputBlocks(OutputBBs, Region))
208673471bf0Spatrick return;
208773471bf0Spatrick
2088*d415bd75Srobert // Determine is there is a duplicate set of blocks.
2089*d415bd75Srobert std::optional<unsigned> MatchingBB =
2090*d415bd75Srobert findDuplicateOutputBlock(OutputBBs, OutputStoreBBs);
209173471bf0Spatrick
2092*d415bd75Srobert // If there is, we remove the new output blocks. If it does not,
2093*d415bd75Srobert // we add it to our list of sets of output blocks.
2094*d415bd75Srobert if (MatchingBB) {
209573471bf0Spatrick LLVM_DEBUG(dbgs() << "Set output block for region in function"
2096*d415bd75Srobert << Region.ExtractedFunction << " to " << *MatchingBB);
209773471bf0Spatrick
2098*d415bd75Srobert Region.OutputBlockNum = *MatchingBB;
2099*d415bd75Srobert for (std::pair<Value *, BasicBlock *> &VtoBB : OutputBBs)
2100*d415bd75Srobert VtoBB.second->eraseFromParent();
210173471bf0Spatrick return;
210273471bf0Spatrick }
210373471bf0Spatrick
210473471bf0Spatrick Region.OutputBlockNum = OutputStoreBBs.size();
210573471bf0Spatrick
2106*d415bd75Srobert Value *RetValueForBB;
2107*d415bd75Srobert BasicBlock *NewBB;
2108*d415bd75Srobert OutputStoreBBs.push_back(DenseMap<Value *, BasicBlock *>());
2109*d415bd75Srobert for (std::pair<Value *, BasicBlock *> &VtoBB : OutputBBs) {
2110*d415bd75Srobert RetValueForBB = VtoBB.first;
2111*d415bd75Srobert NewBB = VtoBB.second;
2112*d415bd75Srobert DenseMap<Value *, BasicBlock *>::iterator VBBIt =
2113*d415bd75Srobert EndBBs.find(RetValueForBB);
211473471bf0Spatrick LLVM_DEBUG(dbgs() << "Create output block for region in"
211573471bf0Spatrick << Region.ExtractedFunction << " to "
2116*d415bd75Srobert << *NewBB);
2117*d415bd75Srobert BranchInst::Create(VBBIt->second, NewBB);
2118*d415bd75Srobert OutputStoreBBs.back().insert(std::make_pair(RetValueForBB, NewBB));
2119*d415bd75Srobert }
2120*d415bd75Srobert }
2121*d415bd75Srobert
2122*d415bd75Srobert /// Takes in a mapping, \p OldMap of ConstantValues to BasicBlocks, sorts keys,
2123*d415bd75Srobert /// before creating a basic block for each \p NewMap, and inserting into the new
2124*d415bd75Srobert /// block. Each BasicBlock is named with the scheme "<basename>_<key_idx>".
2125*d415bd75Srobert ///
2126*d415bd75Srobert /// \param OldMap [in] - The mapping to base the new mapping off of.
2127*d415bd75Srobert /// \param NewMap [out] - The output mapping using the keys of \p OldMap.
2128*d415bd75Srobert /// \param ParentFunc [in] - The function to put the new basic block in.
2129*d415bd75Srobert /// \param BaseName [in] - The start of the BasicBlock names to be appended to
2130*d415bd75Srobert /// by an index value.
createAndInsertBasicBlocks(DenseMap<Value *,BasicBlock * > & OldMap,DenseMap<Value *,BasicBlock * > & NewMap,Function * ParentFunc,Twine BaseName)2131*d415bd75Srobert static void createAndInsertBasicBlocks(DenseMap<Value *, BasicBlock *> &OldMap,
2132*d415bd75Srobert DenseMap<Value *, BasicBlock *> &NewMap,
2133*d415bd75Srobert Function *ParentFunc, Twine BaseName) {
2134*d415bd75Srobert unsigned Idx = 0;
2135*d415bd75Srobert std::vector<Value *> SortedKeys;
2136*d415bd75Srobert
2137*d415bd75Srobert getSortedConstantKeys(SortedKeys, OldMap);
2138*d415bd75Srobert
2139*d415bd75Srobert for (Value *RetVal : SortedKeys) {
2140*d415bd75Srobert BasicBlock *NewBB = BasicBlock::Create(
2141*d415bd75Srobert ParentFunc->getContext(),
2142*d415bd75Srobert Twine(BaseName) + Twine("_") + Twine(static_cast<unsigned>(Idx++)),
2143*d415bd75Srobert ParentFunc);
2144*d415bd75Srobert NewMap.insert(std::make_pair(RetVal, NewBB));
2145*d415bd75Srobert }
214673471bf0Spatrick }
214773471bf0Spatrick
214873471bf0Spatrick /// Create the switch statement for outlined function to differentiate between
214973471bf0Spatrick /// all the output blocks.
215073471bf0Spatrick ///
215173471bf0Spatrick /// For the outlined section, determine if an outlined block already exists that
215273471bf0Spatrick /// matches the needed stores for the extracted section.
215373471bf0Spatrick /// \param [in] M - The module we are outlining from.
215473471bf0Spatrick /// \param [in] OG - The group of regions to be outlined.
2155*d415bd75Srobert /// \param [in] EndBBs - The final blocks of the extracted function.
215673471bf0Spatrick /// \param [in,out] OutputStoreBBs - The existing output blocks.
createSwitchStatement(Module & M,OutlinableGroup & OG,DenseMap<Value *,BasicBlock * > & EndBBs,std::vector<DenseMap<Value *,BasicBlock * >> & OutputStoreBBs)2157*d415bd75Srobert void createSwitchStatement(
2158*d415bd75Srobert Module &M, OutlinableGroup &OG, DenseMap<Value *, BasicBlock *> &EndBBs,
2159*d415bd75Srobert std::vector<DenseMap<Value *, BasicBlock *>> &OutputStoreBBs) {
216073471bf0Spatrick // We only need the switch statement if there is more than one store
2161*d415bd75Srobert // combination, or there is more than one set of output blocks. The first
2162*d415bd75Srobert // will occur when we store different sets of values for two different
2163*d415bd75Srobert // regions. The second will occur when we have two outputs that are combined
2164*d415bd75Srobert // in a PHINode outside of the region in one outlined instance, and are used
2165*d415bd75Srobert // seaparately in another. This will create the same set of OutputGVNs, but
2166*d415bd75Srobert // will generate two different output schemes.
216773471bf0Spatrick if (OG.OutputGVNCombinations.size() > 1) {
216873471bf0Spatrick Function *AggFunc = OG.OutlinedFunction;
2169*d415bd75Srobert // Create a final block for each different return block.
2170*d415bd75Srobert DenseMap<Value *, BasicBlock *> ReturnBBs;
2171*d415bd75Srobert createAndInsertBasicBlocks(OG.EndBBs, ReturnBBs, AggFunc, "final_block");
2172*d415bd75Srobert
2173*d415bd75Srobert for (std::pair<Value *, BasicBlock *> &RetBlockPair : ReturnBBs) {
2174*d415bd75Srobert std::pair<Value *, BasicBlock *> &OutputBlock =
2175*d415bd75Srobert *OG.EndBBs.find(RetBlockPair.first);
2176*d415bd75Srobert BasicBlock *ReturnBlock = RetBlockPair.second;
2177*d415bd75Srobert BasicBlock *EndBB = OutputBlock.second;
217873471bf0Spatrick Instruction *Term = EndBB->getTerminator();
2179*d415bd75Srobert // Move the return value to the final block instead of the original exit
2180*d415bd75Srobert // stub.
218173471bf0Spatrick Term->moveBefore(*ReturnBlock, ReturnBlock->end());
2182*d415bd75Srobert // Put the switch statement in the old end basic block for the function
2183*d415bd75Srobert // with a fall through to the new return block.
218473471bf0Spatrick LLVM_DEBUG(dbgs() << "Create switch statement in " << *AggFunc << " for "
218573471bf0Spatrick << OutputStoreBBs.size() << "\n");
218673471bf0Spatrick SwitchInst *SwitchI =
218773471bf0Spatrick SwitchInst::Create(AggFunc->getArg(AggFunc->arg_size() - 1),
218873471bf0Spatrick ReturnBlock, OutputStoreBBs.size(), EndBB);
218973471bf0Spatrick
219073471bf0Spatrick unsigned Idx = 0;
2191*d415bd75Srobert for (DenseMap<Value *, BasicBlock *> &OutputStoreBB : OutputStoreBBs) {
2192*d415bd75Srobert DenseMap<Value *, BasicBlock *>::iterator OSBBIt =
2193*d415bd75Srobert OutputStoreBB.find(OutputBlock.first);
2194*d415bd75Srobert
2195*d415bd75Srobert if (OSBBIt == OutputStoreBB.end())
2196*d415bd75Srobert continue;
2197*d415bd75Srobert
2198*d415bd75Srobert BasicBlock *BB = OSBBIt->second;
2199*d415bd75Srobert SwitchI->addCase(
2200*d415bd75Srobert ConstantInt::get(Type::getInt32Ty(M.getContext()), Idx), BB);
220173471bf0Spatrick Term = BB->getTerminator();
220273471bf0Spatrick Term->setSuccessor(0, ReturnBlock);
220373471bf0Spatrick Idx++;
220473471bf0Spatrick }
2205*d415bd75Srobert }
220673471bf0Spatrick return;
220773471bf0Spatrick }
220873471bf0Spatrick
2209*d415bd75Srobert assert(OutputStoreBBs.size() < 2 && "Different store sets not handled!");
2210*d415bd75Srobert
2211*d415bd75Srobert // If there needs to be stores, move them from the output blocks to their
2212*d415bd75Srobert // corresponding ending block. We do not check that the OutputGVNCombinations
2213*d415bd75Srobert // is equal to 1 here since that could just been the case where there are 0
2214*d415bd75Srobert // outputs. Instead, we check whether there is more than one set of output
2215*d415bd75Srobert // blocks since this is the only case where we would have to move the
2216*d415bd75Srobert // stores, and erase the extraneous blocks.
221773471bf0Spatrick if (OutputStoreBBs.size() == 1) {
221873471bf0Spatrick LLVM_DEBUG(dbgs() << "Move store instructions to the end block in "
221973471bf0Spatrick << *OG.OutlinedFunction << "\n");
2220*d415bd75Srobert DenseMap<Value *, BasicBlock *> OutputBlocks = OutputStoreBBs[0];
2221*d415bd75Srobert for (std::pair<Value *, BasicBlock *> &VBPair : OutputBlocks) {
2222*d415bd75Srobert DenseMap<Value *, BasicBlock *>::iterator EndBBIt =
2223*d415bd75Srobert EndBBs.find(VBPair.first);
2224*d415bd75Srobert assert(EndBBIt != EndBBs.end() && "Could not find end block");
2225*d415bd75Srobert BasicBlock *EndBB = EndBBIt->second;
2226*d415bd75Srobert BasicBlock *OutputBB = VBPair.second;
2227*d415bd75Srobert Instruction *Term = OutputBB->getTerminator();
222873471bf0Spatrick Term->eraseFromParent();
222973471bf0Spatrick Term = EndBB->getTerminator();
2230*d415bd75Srobert moveBBContents(*OutputBB, *EndBB);
223173471bf0Spatrick Term->moveBefore(*EndBB, EndBB->end());
2232*d415bd75Srobert OutputBB->eraseFromParent();
2233*d415bd75Srobert }
223473471bf0Spatrick }
223573471bf0Spatrick }
223673471bf0Spatrick
223773471bf0Spatrick /// Fill the new function that will serve as the replacement function for all of
223873471bf0Spatrick /// the extracted regions of a certain structure from the first region in the
223973471bf0Spatrick /// list of regions. Replace this first region's extracted function with the
224073471bf0Spatrick /// new overall function.
224173471bf0Spatrick ///
224273471bf0Spatrick /// \param [in] M - The module we are outlining from.
224373471bf0Spatrick /// \param [in] CurrentGroup - The group of regions to be outlined.
224473471bf0Spatrick /// \param [in,out] OutputStoreBBs - The output blocks for each different
224573471bf0Spatrick /// set of stores needed for the different functions.
224673471bf0Spatrick /// \param [in,out] FuncsToRemove - Extracted functions to erase from module
224773471bf0Spatrick /// once outlining is complete.
2248*d415bd75Srobert /// \param [in] OutputMappings - Extracted functions to erase from module
2249*d415bd75Srobert /// once outlining is complete.
fillOverallFunction(Module & M,OutlinableGroup & CurrentGroup,std::vector<DenseMap<Value *,BasicBlock * >> & OutputStoreBBs,std::vector<Function * > & FuncsToRemove,const DenseMap<Value *,Value * > & OutputMappings)2250*d415bd75Srobert static void fillOverallFunction(
2251*d415bd75Srobert Module &M, OutlinableGroup &CurrentGroup,
2252*d415bd75Srobert std::vector<DenseMap<Value *, BasicBlock *>> &OutputStoreBBs,
2253*d415bd75Srobert std::vector<Function *> &FuncsToRemove,
2254*d415bd75Srobert const DenseMap<Value *, Value *> &OutputMappings) {
225573471bf0Spatrick OutlinableRegion *CurrentOS = CurrentGroup.Regions[0];
225673471bf0Spatrick
225773471bf0Spatrick // Move first extracted function's instructions into new function.
225873471bf0Spatrick LLVM_DEBUG(dbgs() << "Move instructions from "
225973471bf0Spatrick << *CurrentOS->ExtractedFunction << " to instruction "
226073471bf0Spatrick << *CurrentGroup.OutlinedFunction << "\n");
2261*d415bd75Srobert moveFunctionData(*CurrentOS->ExtractedFunction,
2262*d415bd75Srobert *CurrentGroup.OutlinedFunction, CurrentGroup.EndBBs);
226373471bf0Spatrick
226473471bf0Spatrick // Transfer the attributes from the function to the new function.
2265*d415bd75Srobert for (Attribute A : CurrentOS->ExtractedFunction->getAttributes().getFnAttrs())
226673471bf0Spatrick CurrentGroup.OutlinedFunction->addFnAttr(A);
226773471bf0Spatrick
2268*d415bd75Srobert // Create a new set of output blocks for the first extracted function.
2269*d415bd75Srobert DenseMap<Value *, BasicBlock *> NewBBs;
2270*d415bd75Srobert createAndInsertBasicBlocks(CurrentGroup.EndBBs, NewBBs,
2271*d415bd75Srobert CurrentGroup.OutlinedFunction, "output_block_0");
227273471bf0Spatrick CurrentOS->OutputBlockNum = 0;
227373471bf0Spatrick
2274*d415bd75Srobert replaceArgumentUses(*CurrentOS, NewBBs, OutputMappings, true);
227573471bf0Spatrick replaceConstants(*CurrentOS);
227673471bf0Spatrick
2277*d415bd75Srobert // We first identify if any output blocks are empty, if they are we remove
2278*d415bd75Srobert // them. We then create a branch instruction to the basic block to the return
2279*d415bd75Srobert // block for the function for each non empty output block.
2280*d415bd75Srobert if (!analyzeAndPruneOutputBlocks(NewBBs, *CurrentOS)) {
2281*d415bd75Srobert OutputStoreBBs.push_back(DenseMap<Value *, BasicBlock *>());
2282*d415bd75Srobert for (std::pair<Value *, BasicBlock *> &VToBB : NewBBs) {
2283*d415bd75Srobert DenseMap<Value *, BasicBlock *>::iterator VBBIt =
2284*d415bd75Srobert CurrentGroup.EndBBs.find(VToBB.first);
2285*d415bd75Srobert BasicBlock *EndBB = VBBIt->second;
2286*d415bd75Srobert BranchInst::Create(EndBB, VToBB.second);
2287*d415bd75Srobert OutputStoreBBs.back().insert(VToBB);
2288*d415bd75Srobert }
228973471bf0Spatrick }
229073471bf0Spatrick
229173471bf0Spatrick // Replace the call to the extracted function with the outlined function.
229273471bf0Spatrick CurrentOS->Call = replaceCalledFunction(M, *CurrentOS);
229373471bf0Spatrick
229473471bf0Spatrick // We only delete the extracted functions at the end since we may need to
229573471bf0Spatrick // reference instructions contained in them for mapping purposes.
229673471bf0Spatrick FuncsToRemove.push_back(CurrentOS->ExtractedFunction);
229773471bf0Spatrick }
229873471bf0Spatrick
deduplicateExtractedSections(Module & M,OutlinableGroup & CurrentGroup,std::vector<Function * > & FuncsToRemove,unsigned & OutlinedFunctionNum)229973471bf0Spatrick void IROutliner::deduplicateExtractedSections(
230073471bf0Spatrick Module &M, OutlinableGroup &CurrentGroup,
230173471bf0Spatrick std::vector<Function *> &FuncsToRemove, unsigned &OutlinedFunctionNum) {
230273471bf0Spatrick createFunction(M, CurrentGroup, OutlinedFunctionNum);
230373471bf0Spatrick
2304*d415bd75Srobert std::vector<DenseMap<Value *, BasicBlock *>> OutputStoreBBs;
230573471bf0Spatrick
230673471bf0Spatrick OutlinableRegion *CurrentOS;
230773471bf0Spatrick
2308*d415bd75Srobert fillOverallFunction(M, CurrentGroup, OutputStoreBBs, FuncsToRemove,
2309*d415bd75Srobert OutputMappings);
231073471bf0Spatrick
2311*d415bd75Srobert std::vector<Value *> SortedKeys;
231273471bf0Spatrick for (unsigned Idx = 1; Idx < CurrentGroup.Regions.size(); Idx++) {
231373471bf0Spatrick CurrentOS = CurrentGroup.Regions[Idx];
231473471bf0Spatrick AttributeFuncs::mergeAttributesForOutlining(*CurrentGroup.OutlinedFunction,
231573471bf0Spatrick *CurrentOS->ExtractedFunction);
231673471bf0Spatrick
2317*d415bd75Srobert // Create a set of BasicBlocks, one for each return block, to hold the
2318*d415bd75Srobert // needed store instructions.
2319*d415bd75Srobert DenseMap<Value *, BasicBlock *> NewBBs;
2320*d415bd75Srobert createAndInsertBasicBlocks(
2321*d415bd75Srobert CurrentGroup.EndBBs, NewBBs, CurrentGroup.OutlinedFunction,
2322*d415bd75Srobert "output_block_" + Twine(static_cast<unsigned>(Idx)));
2323*d415bd75Srobert replaceArgumentUses(*CurrentOS, NewBBs, OutputMappings);
2324*d415bd75Srobert alignOutputBlockWithAggFunc(CurrentGroup, *CurrentOS, NewBBs,
2325*d415bd75Srobert CurrentGroup.EndBBs, OutputMappings,
232673471bf0Spatrick OutputStoreBBs);
232773471bf0Spatrick
232873471bf0Spatrick CurrentOS->Call = replaceCalledFunction(M, *CurrentOS);
232973471bf0Spatrick FuncsToRemove.push_back(CurrentOS->ExtractedFunction);
233073471bf0Spatrick }
233173471bf0Spatrick
233273471bf0Spatrick // Create a switch statement to handle the different output schemes.
2333*d415bd75Srobert createSwitchStatement(M, CurrentGroup, CurrentGroup.EndBBs, OutputStoreBBs);
233473471bf0Spatrick
233573471bf0Spatrick OutlinedFunctionNum++;
233673471bf0Spatrick }
233773471bf0Spatrick
2338*d415bd75Srobert /// Checks that the next instruction in the InstructionDataList matches the
2339*d415bd75Srobert /// next instruction in the module. If they do not, there could be the
2340*d415bd75Srobert /// possibility that extra code has been inserted, and we must ignore it.
2341*d415bd75Srobert ///
2342*d415bd75Srobert /// \param ID - The IRInstructionData to check the next instruction of.
2343*d415bd75Srobert /// \returns true if the InstructionDataList and actual instruction match.
nextIRInstructionDataMatchesNextInst(IRInstructionData & ID)2344*d415bd75Srobert static bool nextIRInstructionDataMatchesNextInst(IRInstructionData &ID) {
2345*d415bd75Srobert // We check if there is a discrepancy between the InstructionDataList
2346*d415bd75Srobert // and the actual next instruction in the module. If there is, it means
2347*d415bd75Srobert // that an extra instruction was added, likely by the CodeExtractor.
2348*d415bd75Srobert
2349*d415bd75Srobert // Since we do not have any similarity data about this particular
2350*d415bd75Srobert // instruction, we cannot confidently outline it, and must discard this
2351*d415bd75Srobert // candidate.
2352*d415bd75Srobert IRInstructionDataList::iterator NextIDIt = std::next(ID.getIterator());
2353*d415bd75Srobert Instruction *NextIDLInst = NextIDIt->Inst;
2354*d415bd75Srobert Instruction *NextModuleInst = nullptr;
2355*d415bd75Srobert if (!ID.Inst->isTerminator())
2356*d415bd75Srobert NextModuleInst = ID.Inst->getNextNonDebugInstruction();
2357*d415bd75Srobert else if (NextIDLInst != nullptr)
2358*d415bd75Srobert NextModuleInst =
2359*d415bd75Srobert &*NextIDIt->Inst->getParent()->instructionsWithoutDebug().begin();
2360*d415bd75Srobert
2361*d415bd75Srobert if (NextIDLInst && NextIDLInst != NextModuleInst)
2362*d415bd75Srobert return false;
2363*d415bd75Srobert
2364*d415bd75Srobert return true;
2365*d415bd75Srobert }
2366*d415bd75Srobert
isCompatibleWithAlreadyOutlinedCode(const OutlinableRegion & Region)2367*d415bd75Srobert bool IROutliner::isCompatibleWithAlreadyOutlinedCode(
2368*d415bd75Srobert const OutlinableRegion &Region) {
2369*d415bd75Srobert IRSimilarityCandidate *IRSC = Region.Candidate;
2370*d415bd75Srobert unsigned StartIdx = IRSC->getStartIdx();
2371*d415bd75Srobert unsigned EndIdx = IRSC->getEndIdx();
2372*d415bd75Srobert
2373*d415bd75Srobert // A check to make sure that we are not about to attempt to outline something
2374*d415bd75Srobert // that has already been outlined.
2375*d415bd75Srobert for (unsigned Idx = StartIdx; Idx <= EndIdx; Idx++)
2376*d415bd75Srobert if (Outlined.contains(Idx))
2377*d415bd75Srobert return false;
2378*d415bd75Srobert
2379*d415bd75Srobert // We check if the recorded instruction matches the actual next instruction,
2380*d415bd75Srobert // if it does not, we fix it in the InstructionDataList.
2381*d415bd75Srobert if (!Region.Candidate->backInstruction()->isTerminator()) {
2382*d415bd75Srobert Instruction *NewEndInst =
2383*d415bd75Srobert Region.Candidate->backInstruction()->getNextNonDebugInstruction();
2384*d415bd75Srobert assert(NewEndInst && "Next instruction is a nullptr?");
2385*d415bd75Srobert if (Region.Candidate->end()->Inst != NewEndInst) {
2386*d415bd75Srobert IRInstructionDataList *IDL = Region.Candidate->front()->IDL;
2387*d415bd75Srobert IRInstructionData *NewEndIRID = new (InstDataAllocator.Allocate())
2388*d415bd75Srobert IRInstructionData(*NewEndInst,
2389*d415bd75Srobert InstructionClassifier.visit(*NewEndInst), *IDL);
2390*d415bd75Srobert
2391*d415bd75Srobert // Insert the first IRInstructionData of the new region after the
2392*d415bd75Srobert // last IRInstructionData of the IRSimilarityCandidate.
2393*d415bd75Srobert IDL->insert(Region.Candidate->end(), *NewEndIRID);
2394*d415bd75Srobert }
2395*d415bd75Srobert }
2396*d415bd75Srobert
2397*d415bd75Srobert return none_of(*IRSC, [this](IRInstructionData &ID) {
2398*d415bd75Srobert if (!nextIRInstructionDataMatchesNextInst(ID))
2399*d415bd75Srobert return true;
2400*d415bd75Srobert
2401*d415bd75Srobert return !this->InstructionClassifier.visit(ID.Inst);
2402*d415bd75Srobert });
2403*d415bd75Srobert }
2404*d415bd75Srobert
pruneIncompatibleRegions(std::vector<IRSimilarityCandidate> & CandidateVec,OutlinableGroup & CurrentGroup)240573471bf0Spatrick void IROutliner::pruneIncompatibleRegions(
240673471bf0Spatrick std::vector<IRSimilarityCandidate> &CandidateVec,
240773471bf0Spatrick OutlinableGroup &CurrentGroup) {
240873471bf0Spatrick bool PreviouslyOutlined;
240973471bf0Spatrick
241073471bf0Spatrick // Sort from beginning to end, so the IRSimilarityCandidates are in order.
241173471bf0Spatrick stable_sort(CandidateVec, [](const IRSimilarityCandidate &LHS,
241273471bf0Spatrick const IRSimilarityCandidate &RHS) {
241373471bf0Spatrick return LHS.getStartIdx() < RHS.getStartIdx();
241473471bf0Spatrick });
241573471bf0Spatrick
2416*d415bd75Srobert IRSimilarityCandidate &FirstCandidate = CandidateVec[0];
2417*d415bd75Srobert // Since outlining a call and a branch instruction will be the same as only
2418*d415bd75Srobert // outlinining a call instruction, we ignore it as a space saving.
2419*d415bd75Srobert if (FirstCandidate.getLength() == 2) {
2420*d415bd75Srobert if (isa<CallInst>(FirstCandidate.front()->Inst) &&
2421*d415bd75Srobert isa<BranchInst>(FirstCandidate.back()->Inst))
2422*d415bd75Srobert return;
2423*d415bd75Srobert }
2424*d415bd75Srobert
242573471bf0Spatrick unsigned CurrentEndIdx = 0;
242673471bf0Spatrick for (IRSimilarityCandidate &IRSC : CandidateVec) {
242773471bf0Spatrick PreviouslyOutlined = false;
242873471bf0Spatrick unsigned StartIdx = IRSC.getStartIdx();
242973471bf0Spatrick unsigned EndIdx = IRSC.getEndIdx();
2430*d415bd75Srobert const Function &FnForCurrCand = *IRSC.getFunction();
243173471bf0Spatrick
243273471bf0Spatrick for (unsigned Idx = StartIdx; Idx <= EndIdx; Idx++)
243373471bf0Spatrick if (Outlined.contains(Idx)) {
243473471bf0Spatrick PreviouslyOutlined = true;
243573471bf0Spatrick break;
243673471bf0Spatrick }
243773471bf0Spatrick
243873471bf0Spatrick if (PreviouslyOutlined)
243973471bf0Spatrick continue;
244073471bf0Spatrick
2441*d415bd75Srobert // Check over the instructions, and if the basic block has its address
2442*d415bd75Srobert // taken for use somewhere else, we do not outline that block.
2443*d415bd75Srobert bool BBHasAddressTaken = any_of(IRSC, [](IRInstructionData &ID){
2444*d415bd75Srobert return ID.Inst->getParent()->hasAddressTaken();
2445*d415bd75Srobert });
2446*d415bd75Srobert
2447*d415bd75Srobert if (BBHasAddressTaken)
244873471bf0Spatrick continue;
244973471bf0Spatrick
2450*d415bd75Srobert if (FnForCurrCand.hasOptNone())
2451*d415bd75Srobert continue;
2452*d415bd75Srobert
2453*d415bd75Srobert if (FnForCurrCand.hasFnAttribute("nooutline")) {
2454*d415bd75Srobert LLVM_DEBUG({
2455*d415bd75Srobert dbgs() << "... Skipping function with nooutline attribute: "
2456*d415bd75Srobert << FnForCurrCand.getName() << "\n";
2457*d415bd75Srobert });
2458*d415bd75Srobert continue;
2459*d415bd75Srobert }
2460*d415bd75Srobert
246173471bf0Spatrick if (IRSC.front()->Inst->getFunction()->hasLinkOnceODRLinkage() &&
246273471bf0Spatrick !OutlineFromLinkODRs)
246373471bf0Spatrick continue;
246473471bf0Spatrick
246573471bf0Spatrick // Greedily prune out any regions that will overlap with already chosen
246673471bf0Spatrick // regions.
246773471bf0Spatrick if (CurrentEndIdx != 0 && StartIdx <= CurrentEndIdx)
246873471bf0Spatrick continue;
246973471bf0Spatrick
247073471bf0Spatrick bool BadInst = any_of(IRSC, [this](IRInstructionData &ID) {
2471*d415bd75Srobert if (!nextIRInstructionDataMatchesNextInst(ID))
247273471bf0Spatrick return true;
2473*d415bd75Srobert
247473471bf0Spatrick return !this->InstructionClassifier.visit(ID.Inst);
247573471bf0Spatrick });
247673471bf0Spatrick
247773471bf0Spatrick if (BadInst)
247873471bf0Spatrick continue;
247973471bf0Spatrick
248073471bf0Spatrick OutlinableRegion *OS = new (RegionAllocator.Allocate())
248173471bf0Spatrick OutlinableRegion(IRSC, CurrentGroup);
248273471bf0Spatrick CurrentGroup.Regions.push_back(OS);
248373471bf0Spatrick
248473471bf0Spatrick CurrentEndIdx = EndIdx;
248573471bf0Spatrick }
248673471bf0Spatrick }
248773471bf0Spatrick
248873471bf0Spatrick InstructionCost
findBenefitFromAllRegions(OutlinableGroup & CurrentGroup)248973471bf0Spatrick IROutliner::findBenefitFromAllRegions(OutlinableGroup &CurrentGroup) {
249073471bf0Spatrick InstructionCost RegionBenefit = 0;
249173471bf0Spatrick for (OutlinableRegion *Region : CurrentGroup.Regions) {
249273471bf0Spatrick TargetTransformInfo &TTI = getTTI(*Region->StartBB->getParent());
249373471bf0Spatrick // We add the number of instructions in the region to the benefit as an
249473471bf0Spatrick // estimate as to how much will be removed.
249573471bf0Spatrick RegionBenefit += Region->getBenefit(TTI);
249673471bf0Spatrick LLVM_DEBUG(dbgs() << "Adding: " << RegionBenefit
249773471bf0Spatrick << " saved instructions to overfall benefit.\n");
249873471bf0Spatrick }
249973471bf0Spatrick
250073471bf0Spatrick return RegionBenefit;
250173471bf0Spatrick }
250273471bf0Spatrick
2503*d415bd75Srobert /// For the \p OutputCanon number passed in find the value represented by this
2504*d415bd75Srobert /// canonical number. If it is from a PHINode, we pick the first incoming
2505*d415bd75Srobert /// value and return that Value instead.
2506*d415bd75Srobert ///
2507*d415bd75Srobert /// \param Region - The OutlinableRegion to get the Value from.
2508*d415bd75Srobert /// \param OutputCanon - The canonical number to find the Value from.
2509*d415bd75Srobert /// \returns The Value represented by a canonical number \p OutputCanon in \p
2510*d415bd75Srobert /// Region.
findOutputValueInRegion(OutlinableRegion & Region,unsigned OutputCanon)2511*d415bd75Srobert static Value *findOutputValueInRegion(OutlinableRegion &Region,
2512*d415bd75Srobert unsigned OutputCanon) {
2513*d415bd75Srobert OutlinableGroup &CurrentGroup = *Region.Parent;
2514*d415bd75Srobert // If the value is greater than the value in the tracker, we have a
2515*d415bd75Srobert // PHINode and will instead use one of the incoming values to find the
2516*d415bd75Srobert // type.
2517*d415bd75Srobert if (OutputCanon > CurrentGroup.PHINodeGVNTracker) {
2518*d415bd75Srobert auto It = CurrentGroup.PHINodeGVNToGVNs.find(OutputCanon);
2519*d415bd75Srobert assert(It != CurrentGroup.PHINodeGVNToGVNs.end() &&
2520*d415bd75Srobert "Could not find GVN set for PHINode number!");
2521*d415bd75Srobert assert(It->second.second.size() > 0 && "PHINode does not have any values!");
2522*d415bd75Srobert OutputCanon = *It->second.second.begin();
2523*d415bd75Srobert }
2524*d415bd75Srobert std::optional<unsigned> OGVN =
2525*d415bd75Srobert Region.Candidate->fromCanonicalNum(OutputCanon);
2526*d415bd75Srobert assert(OGVN && "Could not find GVN for Canonical Number?");
2527*d415bd75Srobert std::optional<Value *> OV = Region.Candidate->fromGVN(*OGVN);
2528*d415bd75Srobert assert(OV && "Could not find value for GVN?");
2529*d415bd75Srobert return *OV;
2530*d415bd75Srobert }
2531*d415bd75Srobert
253273471bf0Spatrick InstructionCost
findCostOutputReloads(OutlinableGroup & CurrentGroup)253373471bf0Spatrick IROutliner::findCostOutputReloads(OutlinableGroup &CurrentGroup) {
253473471bf0Spatrick InstructionCost OverallCost = 0;
253573471bf0Spatrick for (OutlinableRegion *Region : CurrentGroup.Regions) {
253673471bf0Spatrick TargetTransformInfo &TTI = getTTI(*Region->StartBB->getParent());
253773471bf0Spatrick
253873471bf0Spatrick // Each output incurs a load after the call, so we add that to the cost.
2539*d415bd75Srobert for (unsigned OutputCanon : Region->GVNStores) {
2540*d415bd75Srobert Value *V = findOutputValueInRegion(*Region, OutputCanon);
254173471bf0Spatrick InstructionCost LoadCost =
254273471bf0Spatrick TTI.getMemoryOpCost(Instruction::Load, V->getType(), Align(1), 0,
254373471bf0Spatrick TargetTransformInfo::TCK_CodeSize);
254473471bf0Spatrick
254573471bf0Spatrick LLVM_DEBUG(dbgs() << "Adding: " << LoadCost
254673471bf0Spatrick << " instructions to cost for output of type "
254773471bf0Spatrick << *V->getType() << "\n");
254873471bf0Spatrick OverallCost += LoadCost;
254973471bf0Spatrick }
255073471bf0Spatrick }
255173471bf0Spatrick
255273471bf0Spatrick return OverallCost;
255373471bf0Spatrick }
255473471bf0Spatrick
255573471bf0Spatrick /// Find the extra instructions needed to handle any output values for the
255673471bf0Spatrick /// region.
255773471bf0Spatrick ///
255873471bf0Spatrick /// \param [in] M - The Module to outline from.
255973471bf0Spatrick /// \param [in] CurrentGroup - The collection of OutlinableRegions to analyze.
256073471bf0Spatrick /// \param [in] TTI - The TargetTransformInfo used to collect information for
256173471bf0Spatrick /// new instruction costs.
256273471bf0Spatrick /// \returns the additional cost to handle the outputs.
findCostForOutputBlocks(Module & M,OutlinableGroup & CurrentGroup,TargetTransformInfo & TTI)256373471bf0Spatrick static InstructionCost findCostForOutputBlocks(Module &M,
256473471bf0Spatrick OutlinableGroup &CurrentGroup,
256573471bf0Spatrick TargetTransformInfo &TTI) {
256673471bf0Spatrick InstructionCost OutputCost = 0;
2567*d415bd75Srobert unsigned NumOutputBranches = 0;
2568*d415bd75Srobert
2569*d415bd75Srobert OutlinableRegion &FirstRegion = *CurrentGroup.Regions[0];
2570*d415bd75Srobert IRSimilarityCandidate &Candidate = *CurrentGroup.Regions[0]->Candidate;
2571*d415bd75Srobert DenseSet<BasicBlock *> CandidateBlocks;
2572*d415bd75Srobert Candidate.getBasicBlocks(CandidateBlocks);
2573*d415bd75Srobert
2574*d415bd75Srobert // Count the number of different output branches that point to blocks outside
2575*d415bd75Srobert // of the region.
2576*d415bd75Srobert DenseSet<BasicBlock *> FoundBlocks;
2577*d415bd75Srobert for (IRInstructionData &ID : Candidate) {
2578*d415bd75Srobert if (!isa<BranchInst>(ID.Inst))
2579*d415bd75Srobert continue;
2580*d415bd75Srobert
2581*d415bd75Srobert for (Value *V : ID.OperVals) {
2582*d415bd75Srobert BasicBlock *BB = static_cast<BasicBlock *>(V);
2583*d415bd75Srobert if (!CandidateBlocks.contains(BB) && FoundBlocks.insert(BB).second)
2584*d415bd75Srobert NumOutputBranches++;
2585*d415bd75Srobert }
2586*d415bd75Srobert }
2587*d415bd75Srobert
2588*d415bd75Srobert CurrentGroup.BranchesToOutside = NumOutputBranches;
258973471bf0Spatrick
259073471bf0Spatrick for (const ArrayRef<unsigned> &OutputUse :
259173471bf0Spatrick CurrentGroup.OutputGVNCombinations) {
2592*d415bd75Srobert for (unsigned OutputCanon : OutputUse) {
2593*d415bd75Srobert Value *V = findOutputValueInRegion(FirstRegion, OutputCanon);
259473471bf0Spatrick InstructionCost StoreCost =
259573471bf0Spatrick TTI.getMemoryOpCost(Instruction::Load, V->getType(), Align(1), 0,
259673471bf0Spatrick TargetTransformInfo::TCK_CodeSize);
259773471bf0Spatrick
259873471bf0Spatrick // An instruction cost is added for each store set that needs to occur for
259973471bf0Spatrick // various output combinations inside the function, plus a branch to
260073471bf0Spatrick // return to the exit block.
260173471bf0Spatrick LLVM_DEBUG(dbgs() << "Adding: " << StoreCost
260273471bf0Spatrick << " instructions to cost for output of type "
260373471bf0Spatrick << *V->getType() << "\n");
2604*d415bd75Srobert OutputCost += StoreCost * NumOutputBranches;
260573471bf0Spatrick }
260673471bf0Spatrick
260773471bf0Spatrick InstructionCost BranchCost =
260873471bf0Spatrick TTI.getCFInstrCost(Instruction::Br, TargetTransformInfo::TCK_CodeSize);
260973471bf0Spatrick LLVM_DEBUG(dbgs() << "Adding " << BranchCost << " to the current cost for"
261073471bf0Spatrick << " a branch instruction\n");
2611*d415bd75Srobert OutputCost += BranchCost * NumOutputBranches;
261273471bf0Spatrick }
261373471bf0Spatrick
261473471bf0Spatrick // If there is more than one output scheme, we must have a comparison and
261573471bf0Spatrick // branch for each different item in the switch statement.
261673471bf0Spatrick if (CurrentGroup.OutputGVNCombinations.size() > 1) {
261773471bf0Spatrick InstructionCost ComparisonCost = TTI.getCmpSelInstrCost(
261873471bf0Spatrick Instruction::ICmp, Type::getInt32Ty(M.getContext()),
261973471bf0Spatrick Type::getInt32Ty(M.getContext()), CmpInst::BAD_ICMP_PREDICATE,
262073471bf0Spatrick TargetTransformInfo::TCK_CodeSize);
262173471bf0Spatrick InstructionCost BranchCost =
262273471bf0Spatrick TTI.getCFInstrCost(Instruction::Br, TargetTransformInfo::TCK_CodeSize);
262373471bf0Spatrick
262473471bf0Spatrick unsigned DifferentBlocks = CurrentGroup.OutputGVNCombinations.size();
262573471bf0Spatrick InstructionCost TotalCost = ComparisonCost * BranchCost * DifferentBlocks;
262673471bf0Spatrick
262773471bf0Spatrick LLVM_DEBUG(dbgs() << "Adding: " << TotalCost
262873471bf0Spatrick << " instructions for each switch case for each different"
262973471bf0Spatrick << " output path in a function\n");
2630*d415bd75Srobert OutputCost += TotalCost * NumOutputBranches;
263173471bf0Spatrick }
263273471bf0Spatrick
263373471bf0Spatrick return OutputCost;
263473471bf0Spatrick }
263573471bf0Spatrick
findCostBenefit(Module & M,OutlinableGroup & CurrentGroup)263673471bf0Spatrick void IROutliner::findCostBenefit(Module &M, OutlinableGroup &CurrentGroup) {
263773471bf0Spatrick InstructionCost RegionBenefit = findBenefitFromAllRegions(CurrentGroup);
263873471bf0Spatrick CurrentGroup.Benefit += RegionBenefit;
263973471bf0Spatrick LLVM_DEBUG(dbgs() << "Current Benefit: " << CurrentGroup.Benefit << "\n");
264073471bf0Spatrick
264173471bf0Spatrick InstructionCost OutputReloadCost = findCostOutputReloads(CurrentGroup);
264273471bf0Spatrick CurrentGroup.Cost += OutputReloadCost;
264373471bf0Spatrick LLVM_DEBUG(dbgs() << "Current Cost: " << CurrentGroup.Cost << "\n");
264473471bf0Spatrick
264573471bf0Spatrick InstructionCost AverageRegionBenefit =
264673471bf0Spatrick RegionBenefit / CurrentGroup.Regions.size();
264773471bf0Spatrick unsigned OverallArgumentNum = CurrentGroup.ArgumentTypes.size();
264873471bf0Spatrick unsigned NumRegions = CurrentGroup.Regions.size();
264973471bf0Spatrick TargetTransformInfo &TTI =
265073471bf0Spatrick getTTI(*CurrentGroup.Regions[0]->Candidate->getFunction());
265173471bf0Spatrick
265273471bf0Spatrick // We add one region to the cost once, to account for the instructions added
265373471bf0Spatrick // inside of the newly created function.
265473471bf0Spatrick LLVM_DEBUG(dbgs() << "Adding: " << AverageRegionBenefit
265573471bf0Spatrick << " instructions to cost for body of new function.\n");
265673471bf0Spatrick CurrentGroup.Cost += AverageRegionBenefit;
265773471bf0Spatrick LLVM_DEBUG(dbgs() << "Current Cost: " << CurrentGroup.Cost << "\n");
265873471bf0Spatrick
265973471bf0Spatrick // For each argument, we must add an instruction for loading the argument
266073471bf0Spatrick // out of the register and into a value inside of the newly outlined function.
266173471bf0Spatrick LLVM_DEBUG(dbgs() << "Adding: " << OverallArgumentNum
266273471bf0Spatrick << " instructions to cost for each argument in the new"
266373471bf0Spatrick << " function.\n");
266473471bf0Spatrick CurrentGroup.Cost +=
266573471bf0Spatrick OverallArgumentNum * TargetTransformInfo::TCC_Basic;
266673471bf0Spatrick LLVM_DEBUG(dbgs() << "Current Cost: " << CurrentGroup.Cost << "\n");
266773471bf0Spatrick
266873471bf0Spatrick // Each argument needs to either be loaded into a register or onto the stack.
266973471bf0Spatrick // Some arguments will only be loaded into the stack once the argument
267073471bf0Spatrick // registers are filled.
267173471bf0Spatrick LLVM_DEBUG(dbgs() << "Adding: " << OverallArgumentNum
267273471bf0Spatrick << " instructions to cost for each argument in the new"
267373471bf0Spatrick << " function " << NumRegions << " times for the "
267473471bf0Spatrick << "needed argument handling at the call site.\n");
267573471bf0Spatrick CurrentGroup.Cost +=
267673471bf0Spatrick 2 * OverallArgumentNum * TargetTransformInfo::TCC_Basic * NumRegions;
267773471bf0Spatrick LLVM_DEBUG(dbgs() << "Current Cost: " << CurrentGroup.Cost << "\n");
267873471bf0Spatrick
267973471bf0Spatrick CurrentGroup.Cost += findCostForOutputBlocks(M, CurrentGroup, TTI);
268073471bf0Spatrick LLVM_DEBUG(dbgs() << "Current Cost: " << CurrentGroup.Cost << "\n");
268173471bf0Spatrick }
268273471bf0Spatrick
updateOutputMapping(OutlinableRegion & Region,ArrayRef<Value * > Outputs,LoadInst * LI)268373471bf0Spatrick void IROutliner::updateOutputMapping(OutlinableRegion &Region,
268473471bf0Spatrick ArrayRef<Value *> Outputs,
268573471bf0Spatrick LoadInst *LI) {
268673471bf0Spatrick // For and load instructions following the call
268773471bf0Spatrick Value *Operand = LI->getPointerOperand();
2688*d415bd75Srobert std::optional<unsigned> OutputIdx;
268973471bf0Spatrick // Find if the operand it is an output register.
269073471bf0Spatrick for (unsigned ArgIdx = Region.NumExtractedInputs;
269173471bf0Spatrick ArgIdx < Region.Call->arg_size(); ArgIdx++) {
269273471bf0Spatrick if (Operand == Region.Call->getArgOperand(ArgIdx)) {
269373471bf0Spatrick OutputIdx = ArgIdx - Region.NumExtractedInputs;
269473471bf0Spatrick break;
269573471bf0Spatrick }
269673471bf0Spatrick }
269773471bf0Spatrick
269873471bf0Spatrick // If we found an output register, place a mapping of the new value
269973471bf0Spatrick // to the original in the mapping.
2700*d415bd75Srobert if (!OutputIdx)
270173471bf0Spatrick return;
270273471bf0Spatrick
2703*d415bd75Srobert if (OutputMappings.find(Outputs[*OutputIdx]) == OutputMappings.end()) {
270473471bf0Spatrick LLVM_DEBUG(dbgs() << "Mapping extracted output " << *LI << " to "
2705*d415bd75Srobert << *Outputs[*OutputIdx] << "\n");
2706*d415bd75Srobert OutputMappings.insert(std::make_pair(LI, Outputs[*OutputIdx]));
270773471bf0Spatrick } else {
2708*d415bd75Srobert Value *Orig = OutputMappings.find(Outputs[*OutputIdx])->second;
270973471bf0Spatrick LLVM_DEBUG(dbgs() << "Mapping extracted output " << *Orig << " to "
2710*d415bd75Srobert << *Outputs[*OutputIdx] << "\n");
271173471bf0Spatrick OutputMappings.insert(std::make_pair(LI, Orig));
271273471bf0Spatrick }
271373471bf0Spatrick }
271473471bf0Spatrick
extractSection(OutlinableRegion & Region)271573471bf0Spatrick bool IROutliner::extractSection(OutlinableRegion &Region) {
271673471bf0Spatrick SetVector<Value *> ArgInputs, Outputs, SinkCands;
271773471bf0Spatrick assert(Region.StartBB && "StartBB for the OutlinableRegion is nullptr!");
2718*d415bd75Srobert BasicBlock *InitialStart = Region.StartBB;
271973471bf0Spatrick Function *OrigF = Region.StartBB->getParent();
272073471bf0Spatrick CodeExtractorAnalysisCache CEAC(*OrigF);
2721*d415bd75Srobert Region.ExtractedFunction =
2722*d415bd75Srobert Region.CE->extractCodeRegion(CEAC, ArgInputs, Outputs);
272373471bf0Spatrick
272473471bf0Spatrick // If the extraction was successful, find the BasicBlock, and reassign the
272573471bf0Spatrick // OutlinableRegion blocks
272673471bf0Spatrick if (!Region.ExtractedFunction) {
272773471bf0Spatrick LLVM_DEBUG(dbgs() << "CodeExtractor failed to outline " << Region.StartBB
272873471bf0Spatrick << "\n");
272973471bf0Spatrick Region.reattachCandidate();
273073471bf0Spatrick return false;
273173471bf0Spatrick }
273273471bf0Spatrick
2733*d415bd75Srobert // Get the block containing the called branch, and reassign the blocks as
2734*d415bd75Srobert // necessary. If the original block still exists, it is because we ended on
2735*d415bd75Srobert // a branch instruction, and so we move the contents into the block before
2736*d415bd75Srobert // and assign the previous block correctly.
2737*d415bd75Srobert User *InstAsUser = Region.ExtractedFunction->user_back();
2738*d415bd75Srobert BasicBlock *RewrittenBB = cast<Instruction>(InstAsUser)->getParent();
2739*d415bd75Srobert Region.PrevBB = RewrittenBB->getSinglePredecessor();
2740*d415bd75Srobert assert(Region.PrevBB && "PrevBB is nullptr?");
2741*d415bd75Srobert if (Region.PrevBB == InitialStart) {
2742*d415bd75Srobert BasicBlock *NewPrev = InitialStart->getSinglePredecessor();
2743*d415bd75Srobert Instruction *BI = NewPrev->getTerminator();
2744*d415bd75Srobert BI->eraseFromParent();
2745*d415bd75Srobert moveBBContents(*InitialStart, *NewPrev);
2746*d415bd75Srobert Region.PrevBB = NewPrev;
2747*d415bd75Srobert InitialStart->eraseFromParent();
2748*d415bd75Srobert }
2749*d415bd75Srobert
275073471bf0Spatrick Region.StartBB = RewrittenBB;
275173471bf0Spatrick Region.EndBB = RewrittenBB;
275273471bf0Spatrick
275373471bf0Spatrick // The sequences of outlinable regions has now changed. We must fix the
275473471bf0Spatrick // IRInstructionDataList for consistency. Although they may not be illegal
275573471bf0Spatrick // instructions, they should not be compared with anything else as they
275673471bf0Spatrick // should not be outlined in this round. So marking these as illegal is
275773471bf0Spatrick // allowed.
275873471bf0Spatrick IRInstructionDataList *IDL = Region.Candidate->front()->IDL;
275973471bf0Spatrick Instruction *BeginRewritten = &*RewrittenBB->begin();
276073471bf0Spatrick Instruction *EndRewritten = &*RewrittenBB->begin();
276173471bf0Spatrick Region.NewFront = new (InstDataAllocator.Allocate()) IRInstructionData(
276273471bf0Spatrick *BeginRewritten, InstructionClassifier.visit(*BeginRewritten), *IDL);
276373471bf0Spatrick Region.NewBack = new (InstDataAllocator.Allocate()) IRInstructionData(
276473471bf0Spatrick *EndRewritten, InstructionClassifier.visit(*EndRewritten), *IDL);
276573471bf0Spatrick
276673471bf0Spatrick // Insert the first IRInstructionData of the new region in front of the
276773471bf0Spatrick // first IRInstructionData of the IRSimilarityCandidate.
276873471bf0Spatrick IDL->insert(Region.Candidate->begin(), *Region.NewFront);
276973471bf0Spatrick // Insert the first IRInstructionData of the new region after the
277073471bf0Spatrick // last IRInstructionData of the IRSimilarityCandidate.
277173471bf0Spatrick IDL->insert(Region.Candidate->end(), *Region.NewBack);
277273471bf0Spatrick // Remove the IRInstructionData from the IRSimilarityCandidate.
277373471bf0Spatrick IDL->erase(Region.Candidate->begin(), std::prev(Region.Candidate->end()));
277473471bf0Spatrick
277573471bf0Spatrick assert(RewrittenBB != nullptr &&
277673471bf0Spatrick "Could not find a predecessor after extraction!");
277773471bf0Spatrick
277873471bf0Spatrick // Iterate over the new set of instructions to find the new call
277973471bf0Spatrick // instruction.
278073471bf0Spatrick for (Instruction &I : *RewrittenBB)
278173471bf0Spatrick if (CallInst *CI = dyn_cast<CallInst>(&I)) {
278273471bf0Spatrick if (Region.ExtractedFunction == CI->getCalledFunction())
278373471bf0Spatrick Region.Call = CI;
278473471bf0Spatrick } else if (LoadInst *LI = dyn_cast<LoadInst>(&I))
278573471bf0Spatrick updateOutputMapping(Region, Outputs.getArrayRef(), LI);
278673471bf0Spatrick Region.reattachCandidate();
278773471bf0Spatrick return true;
278873471bf0Spatrick }
278973471bf0Spatrick
doOutline(Module & M)279073471bf0Spatrick unsigned IROutliner::doOutline(Module &M) {
279173471bf0Spatrick // Find the possible similarity sections.
2792*d415bd75Srobert InstructionClassifier.EnableBranches = !DisableBranches;
2793*d415bd75Srobert InstructionClassifier.EnableIndirectCalls = !DisableIndirectCalls;
2794*d415bd75Srobert InstructionClassifier.EnableIntrinsics = !DisableIntrinsics;
2795*d415bd75Srobert
279673471bf0Spatrick IRSimilarityIdentifier &Identifier = getIRSI(M);
279773471bf0Spatrick SimilarityGroupList &SimilarityCandidates = *Identifier.getSimilarity();
279873471bf0Spatrick
279973471bf0Spatrick // Sort them by size of extracted sections
280073471bf0Spatrick unsigned OutlinedFunctionNum = 0;
280173471bf0Spatrick // If we only have one SimilarityGroup in SimilarityCandidates, we do not have
280273471bf0Spatrick // to sort them by the potential number of instructions to be outlined
280373471bf0Spatrick if (SimilarityCandidates.size() > 1)
280473471bf0Spatrick llvm::stable_sort(SimilarityCandidates,
280573471bf0Spatrick [](const std::vector<IRSimilarityCandidate> &LHS,
280673471bf0Spatrick const std::vector<IRSimilarityCandidate> &RHS) {
280773471bf0Spatrick return LHS[0].getLength() * LHS.size() >
280873471bf0Spatrick RHS[0].getLength() * RHS.size();
280973471bf0Spatrick });
2810*d415bd75Srobert // Creating OutlinableGroups for each SimilarityCandidate to be used in
2811*d415bd75Srobert // each of the following for loops to avoid making an allocator.
2812*d415bd75Srobert std::vector<OutlinableGroup> PotentialGroups(SimilarityCandidates.size());
281373471bf0Spatrick
281473471bf0Spatrick DenseSet<unsigned> NotSame;
2815*d415bd75Srobert std::vector<OutlinableGroup *> NegativeCostGroups;
2816*d415bd75Srobert std::vector<OutlinableRegion *> OutlinedRegions;
281773471bf0Spatrick // Iterate over the possible sets of similarity.
2818*d415bd75Srobert unsigned PotentialGroupIdx = 0;
281973471bf0Spatrick for (SimilarityGroup &CandidateVec : SimilarityCandidates) {
2820*d415bd75Srobert OutlinableGroup &CurrentGroup = PotentialGroups[PotentialGroupIdx++];
282173471bf0Spatrick
282273471bf0Spatrick // Remove entries that were previously outlined
282373471bf0Spatrick pruneIncompatibleRegions(CandidateVec, CurrentGroup);
282473471bf0Spatrick
282573471bf0Spatrick // We pruned the number of regions to 0 to 1, meaning that it's not worth
282673471bf0Spatrick // trying to outlined since there is no compatible similar instance of this
282773471bf0Spatrick // code.
282873471bf0Spatrick if (CurrentGroup.Regions.size() < 2)
282973471bf0Spatrick continue;
283073471bf0Spatrick
283173471bf0Spatrick // Determine if there are any values that are the same constant throughout
283273471bf0Spatrick // each section in the set.
283373471bf0Spatrick NotSame.clear();
283473471bf0Spatrick CurrentGroup.findSameConstants(NotSame);
283573471bf0Spatrick
283673471bf0Spatrick if (CurrentGroup.IgnoreGroup)
283773471bf0Spatrick continue;
283873471bf0Spatrick
283973471bf0Spatrick // Create a CodeExtractor for each outlinable region. Identify inputs and
284073471bf0Spatrick // outputs for each section using the code extractor and create the argument
284173471bf0Spatrick // types for the Aggregate Outlining Function.
2842*d415bd75Srobert OutlinedRegions.clear();
284373471bf0Spatrick for (OutlinableRegion *OS : CurrentGroup.Regions) {
284473471bf0Spatrick // Break the outlinable region out of its parent BasicBlock into its own
284573471bf0Spatrick // BasicBlocks (see function implementation).
284673471bf0Spatrick OS->splitCandidate();
2847*d415bd75Srobert
2848*d415bd75Srobert // There's a chance that when the region is split, extra instructions are
2849*d415bd75Srobert // added to the region. This makes the region no longer viable
2850*d415bd75Srobert // to be split, so we ignore it for outlining.
2851*d415bd75Srobert if (!OS->CandidateSplit)
2852*d415bd75Srobert continue;
2853*d415bd75Srobert
2854*d415bd75Srobert SmallVector<BasicBlock *> BE;
2855*d415bd75Srobert DenseSet<BasicBlock *> BlocksInRegion;
2856*d415bd75Srobert OS->Candidate->getBasicBlocks(BlocksInRegion, BE);
285773471bf0Spatrick OS->CE = new (ExtractorAllocator.Allocate())
285873471bf0Spatrick CodeExtractor(BE, nullptr, false, nullptr, nullptr, nullptr, false,
2859*d415bd75Srobert false, nullptr, "outlined");
286073471bf0Spatrick findAddInputsOutputs(M, *OS, NotSame);
286173471bf0Spatrick if (!OS->IgnoreRegion)
286273471bf0Spatrick OutlinedRegions.push_back(OS);
2863*d415bd75Srobert
2864*d415bd75Srobert // We recombine the blocks together now that we have gathered all the
2865*d415bd75Srobert // needed information.
286673471bf0Spatrick OS->reattachCandidate();
286773471bf0Spatrick }
286873471bf0Spatrick
286973471bf0Spatrick CurrentGroup.Regions = std::move(OutlinedRegions);
287073471bf0Spatrick
287173471bf0Spatrick if (CurrentGroup.Regions.empty())
287273471bf0Spatrick continue;
287373471bf0Spatrick
287473471bf0Spatrick CurrentGroup.collectGVNStoreSets(M);
287573471bf0Spatrick
287673471bf0Spatrick if (CostModel)
287773471bf0Spatrick findCostBenefit(M, CurrentGroup);
287873471bf0Spatrick
2879*d415bd75Srobert // If we are adhering to the cost model, skip those groups where the cost
2880*d415bd75Srobert // outweighs the benefits.
288173471bf0Spatrick if (CurrentGroup.Cost >= CurrentGroup.Benefit && CostModel) {
2882*d415bd75Srobert OptimizationRemarkEmitter &ORE =
2883*d415bd75Srobert getORE(*CurrentGroup.Regions[0]->Candidate->getFunction());
288473471bf0Spatrick ORE.emit([&]() {
288573471bf0Spatrick IRSimilarityCandidate *C = CurrentGroup.Regions[0]->Candidate;
288673471bf0Spatrick OptimizationRemarkMissed R(DEBUG_TYPE, "WouldNotDecreaseSize",
288773471bf0Spatrick C->frontInstruction());
288873471bf0Spatrick R << "did not outline "
288973471bf0Spatrick << ore::NV(std::to_string(CurrentGroup.Regions.size()))
289073471bf0Spatrick << " regions due to estimated increase of "
289173471bf0Spatrick << ore::NV("InstructionIncrease",
289273471bf0Spatrick CurrentGroup.Cost - CurrentGroup.Benefit)
289373471bf0Spatrick << " instructions at locations ";
289473471bf0Spatrick interleave(
289573471bf0Spatrick CurrentGroup.Regions.begin(), CurrentGroup.Regions.end(),
289673471bf0Spatrick [&R](OutlinableRegion *Region) {
289773471bf0Spatrick R << ore::NV(
289873471bf0Spatrick "DebugLoc",
289973471bf0Spatrick Region->Candidate->frontInstruction()->getDebugLoc());
290073471bf0Spatrick },
290173471bf0Spatrick [&R]() { R << " "; });
290273471bf0Spatrick return R;
290373471bf0Spatrick });
290473471bf0Spatrick continue;
290573471bf0Spatrick }
290673471bf0Spatrick
2907*d415bd75Srobert NegativeCostGroups.push_back(&CurrentGroup);
2908*d415bd75Srobert }
2909*d415bd75Srobert
2910*d415bd75Srobert ExtractorAllocator.DestroyAll();
2911*d415bd75Srobert
2912*d415bd75Srobert if (NegativeCostGroups.size() > 1)
2913*d415bd75Srobert stable_sort(NegativeCostGroups,
2914*d415bd75Srobert [](const OutlinableGroup *LHS, const OutlinableGroup *RHS) {
2915*d415bd75Srobert return LHS->Benefit - LHS->Cost > RHS->Benefit - RHS->Cost;
2916*d415bd75Srobert });
2917*d415bd75Srobert
2918*d415bd75Srobert std::vector<Function *> FuncsToRemove;
2919*d415bd75Srobert for (OutlinableGroup *CG : NegativeCostGroups) {
2920*d415bd75Srobert OutlinableGroup &CurrentGroup = *CG;
2921*d415bd75Srobert
2922*d415bd75Srobert OutlinedRegions.clear();
2923*d415bd75Srobert for (OutlinableRegion *Region : CurrentGroup.Regions) {
2924*d415bd75Srobert // We check whether our region is compatible with what has already been
2925*d415bd75Srobert // outlined, and whether we need to ignore this item.
2926*d415bd75Srobert if (!isCompatibleWithAlreadyOutlinedCode(*Region))
2927*d415bd75Srobert continue;
2928*d415bd75Srobert OutlinedRegions.push_back(Region);
2929*d415bd75Srobert }
2930*d415bd75Srobert
2931*d415bd75Srobert if (OutlinedRegions.size() < 2)
2932*d415bd75Srobert continue;
2933*d415bd75Srobert
2934*d415bd75Srobert // Reestimate the cost and benefit of the OutlinableGroup. Continue only if
2935*d415bd75Srobert // we are still outlining enough regions to make up for the added cost.
2936*d415bd75Srobert CurrentGroup.Regions = std::move(OutlinedRegions);
2937*d415bd75Srobert if (CostModel) {
2938*d415bd75Srobert CurrentGroup.Benefit = 0;
2939*d415bd75Srobert CurrentGroup.Cost = 0;
2940*d415bd75Srobert findCostBenefit(M, CurrentGroup);
2941*d415bd75Srobert if (CurrentGroup.Cost >= CurrentGroup.Benefit)
2942*d415bd75Srobert continue;
2943*d415bd75Srobert }
2944*d415bd75Srobert OutlinedRegions.clear();
2945*d415bd75Srobert for (OutlinableRegion *Region : CurrentGroup.Regions) {
2946*d415bd75Srobert Region->splitCandidate();
2947*d415bd75Srobert if (!Region->CandidateSplit)
2948*d415bd75Srobert continue;
2949*d415bd75Srobert OutlinedRegions.push_back(Region);
2950*d415bd75Srobert }
2951*d415bd75Srobert
2952*d415bd75Srobert CurrentGroup.Regions = std::move(OutlinedRegions);
2953*d415bd75Srobert if (CurrentGroup.Regions.size() < 2) {
2954*d415bd75Srobert for (OutlinableRegion *R : CurrentGroup.Regions)
2955*d415bd75Srobert R->reattachCandidate();
2956*d415bd75Srobert continue;
2957*d415bd75Srobert }
2958*d415bd75Srobert
295973471bf0Spatrick LLVM_DEBUG(dbgs() << "Outlining regions with cost " << CurrentGroup.Cost
296073471bf0Spatrick << " and benefit " << CurrentGroup.Benefit << "\n");
296173471bf0Spatrick
296273471bf0Spatrick // Create functions out of all the sections, and mark them as outlined.
296373471bf0Spatrick OutlinedRegions.clear();
296473471bf0Spatrick for (OutlinableRegion *OS : CurrentGroup.Regions) {
2965*d415bd75Srobert SmallVector<BasicBlock *> BE;
2966*d415bd75Srobert DenseSet<BasicBlock *> BlocksInRegion;
2967*d415bd75Srobert OS->Candidate->getBasicBlocks(BlocksInRegion, BE);
2968*d415bd75Srobert OS->CE = new (ExtractorAllocator.Allocate())
2969*d415bd75Srobert CodeExtractor(BE, nullptr, false, nullptr, nullptr, nullptr, false,
2970*d415bd75Srobert false, nullptr, "outlined");
297173471bf0Spatrick bool FunctionOutlined = extractSection(*OS);
297273471bf0Spatrick if (FunctionOutlined) {
297373471bf0Spatrick unsigned StartIdx = OS->Candidate->getStartIdx();
297473471bf0Spatrick unsigned EndIdx = OS->Candidate->getEndIdx();
297573471bf0Spatrick for (unsigned Idx = StartIdx; Idx <= EndIdx; Idx++)
297673471bf0Spatrick Outlined.insert(Idx);
297773471bf0Spatrick
297873471bf0Spatrick OutlinedRegions.push_back(OS);
297973471bf0Spatrick }
298073471bf0Spatrick }
298173471bf0Spatrick
298273471bf0Spatrick LLVM_DEBUG(dbgs() << "Outlined " << OutlinedRegions.size()
298373471bf0Spatrick << " with benefit " << CurrentGroup.Benefit
298473471bf0Spatrick << " and cost " << CurrentGroup.Cost << "\n");
298573471bf0Spatrick
298673471bf0Spatrick CurrentGroup.Regions = std::move(OutlinedRegions);
298773471bf0Spatrick
298873471bf0Spatrick if (CurrentGroup.Regions.empty())
298973471bf0Spatrick continue;
299073471bf0Spatrick
299173471bf0Spatrick OptimizationRemarkEmitter &ORE =
299273471bf0Spatrick getORE(*CurrentGroup.Regions[0]->Call->getFunction());
299373471bf0Spatrick ORE.emit([&]() {
299473471bf0Spatrick IRSimilarityCandidate *C = CurrentGroup.Regions[0]->Candidate;
299573471bf0Spatrick OptimizationRemark R(DEBUG_TYPE, "Outlined", C->front()->Inst);
299673471bf0Spatrick R << "outlined " << ore::NV(std::to_string(CurrentGroup.Regions.size()))
299773471bf0Spatrick << " regions with decrease of "
299873471bf0Spatrick << ore::NV("Benefit", CurrentGroup.Benefit - CurrentGroup.Cost)
299973471bf0Spatrick << " instructions at locations ";
300073471bf0Spatrick interleave(
300173471bf0Spatrick CurrentGroup.Regions.begin(), CurrentGroup.Regions.end(),
300273471bf0Spatrick [&R](OutlinableRegion *Region) {
300373471bf0Spatrick R << ore::NV("DebugLoc",
300473471bf0Spatrick Region->Candidate->frontInstruction()->getDebugLoc());
300573471bf0Spatrick },
300673471bf0Spatrick [&R]() { R << " "; });
300773471bf0Spatrick return R;
300873471bf0Spatrick });
300973471bf0Spatrick
301073471bf0Spatrick deduplicateExtractedSections(M, CurrentGroup, FuncsToRemove,
301173471bf0Spatrick OutlinedFunctionNum);
301273471bf0Spatrick }
301373471bf0Spatrick
301473471bf0Spatrick for (Function *F : FuncsToRemove)
301573471bf0Spatrick F->eraseFromParent();
301673471bf0Spatrick
301773471bf0Spatrick return OutlinedFunctionNum;
301873471bf0Spatrick }
301973471bf0Spatrick
run(Module & M)302073471bf0Spatrick bool IROutliner::run(Module &M) {
302173471bf0Spatrick CostModel = !NoCostModel;
302273471bf0Spatrick OutlineFromLinkODRs = EnableLinkOnceODRIROutlining;
302373471bf0Spatrick
302473471bf0Spatrick return doOutline(M) > 0;
302573471bf0Spatrick }
302673471bf0Spatrick
302773471bf0Spatrick // Pass Manager Boilerplate
3028*d415bd75Srobert namespace {
302973471bf0Spatrick class IROutlinerLegacyPass : public ModulePass {
303073471bf0Spatrick public:
303173471bf0Spatrick static char ID;
IROutlinerLegacyPass()303273471bf0Spatrick IROutlinerLegacyPass() : ModulePass(ID) {
303373471bf0Spatrick initializeIROutlinerLegacyPassPass(*PassRegistry::getPassRegistry());
303473471bf0Spatrick }
303573471bf0Spatrick
getAnalysisUsage(AnalysisUsage & AU) const303673471bf0Spatrick void getAnalysisUsage(AnalysisUsage &AU) const override {
303773471bf0Spatrick AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
303873471bf0Spatrick AU.addRequired<TargetTransformInfoWrapperPass>();
303973471bf0Spatrick AU.addRequired<IRSimilarityIdentifierWrapperPass>();
304073471bf0Spatrick }
304173471bf0Spatrick
304273471bf0Spatrick bool runOnModule(Module &M) override;
304373471bf0Spatrick };
3044*d415bd75Srobert } // namespace
304573471bf0Spatrick
runOnModule(Module & M)304673471bf0Spatrick bool IROutlinerLegacyPass::runOnModule(Module &M) {
304773471bf0Spatrick if (skipModule(M))
304873471bf0Spatrick return false;
304973471bf0Spatrick
305073471bf0Spatrick std::unique_ptr<OptimizationRemarkEmitter> ORE;
305173471bf0Spatrick auto GORE = [&ORE](Function &F) -> OptimizationRemarkEmitter & {
305273471bf0Spatrick ORE.reset(new OptimizationRemarkEmitter(&F));
3053*d415bd75Srobert return *ORE;
305473471bf0Spatrick };
305573471bf0Spatrick
305673471bf0Spatrick auto GTTI = [this](Function &F) -> TargetTransformInfo & {
305773471bf0Spatrick return this->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
305873471bf0Spatrick };
305973471bf0Spatrick
306073471bf0Spatrick auto GIRSI = [this](Module &) -> IRSimilarityIdentifier & {
306173471bf0Spatrick return this->getAnalysis<IRSimilarityIdentifierWrapperPass>().getIRSI();
306273471bf0Spatrick };
306373471bf0Spatrick
306473471bf0Spatrick return IROutliner(GTTI, GIRSI, GORE).run(M);
306573471bf0Spatrick }
306673471bf0Spatrick
run(Module & M,ModuleAnalysisManager & AM)306773471bf0Spatrick PreservedAnalyses IROutlinerPass::run(Module &M, ModuleAnalysisManager &AM) {
306873471bf0Spatrick auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
306973471bf0Spatrick
307073471bf0Spatrick std::function<TargetTransformInfo &(Function &)> GTTI =
307173471bf0Spatrick [&FAM](Function &F) -> TargetTransformInfo & {
307273471bf0Spatrick return FAM.getResult<TargetIRAnalysis>(F);
307373471bf0Spatrick };
307473471bf0Spatrick
307573471bf0Spatrick std::function<IRSimilarityIdentifier &(Module &)> GIRSI =
307673471bf0Spatrick [&AM](Module &M) -> IRSimilarityIdentifier & {
307773471bf0Spatrick return AM.getResult<IRSimilarityAnalysis>(M);
307873471bf0Spatrick };
307973471bf0Spatrick
308073471bf0Spatrick std::unique_ptr<OptimizationRemarkEmitter> ORE;
308173471bf0Spatrick std::function<OptimizationRemarkEmitter &(Function &)> GORE =
308273471bf0Spatrick [&ORE](Function &F) -> OptimizationRemarkEmitter & {
308373471bf0Spatrick ORE.reset(new OptimizationRemarkEmitter(&F));
3084*d415bd75Srobert return *ORE;
308573471bf0Spatrick };
308673471bf0Spatrick
308773471bf0Spatrick if (IROutliner(GTTI, GIRSI, GORE).run(M))
308873471bf0Spatrick return PreservedAnalyses::none();
308973471bf0Spatrick return PreservedAnalyses::all();
309073471bf0Spatrick }
309173471bf0Spatrick
309273471bf0Spatrick char IROutlinerLegacyPass::ID = 0;
309373471bf0Spatrick INITIALIZE_PASS_BEGIN(IROutlinerLegacyPass, "iroutliner", "IR Outliner", false,
309473471bf0Spatrick false)
INITIALIZE_PASS_DEPENDENCY(IRSimilarityIdentifierWrapperPass)309573471bf0Spatrick INITIALIZE_PASS_DEPENDENCY(IRSimilarityIdentifierWrapperPass)
309673471bf0Spatrick INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
309773471bf0Spatrick INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
309873471bf0Spatrick INITIALIZE_PASS_END(IROutlinerLegacyPass, "iroutliner", "IR Outliner", false,
309973471bf0Spatrick false)
310073471bf0Spatrick
310173471bf0Spatrick ModulePass *llvm::createIROutlinerPass() { return new IROutlinerLegacyPass(); }
3102