Path: blob/main/contrib/llvm-project/llvm/lib/Transforms/IPO/IROutliner.cpp
35294 views
//===- IROutliner.cpp -- Outline Similar Regions ----------------*- C++ -*-===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7///8/// \file9// Implementation for the IROutliner which is used by the IROutliner Pass.10//11//===----------------------------------------------------------------------===//1213#include "llvm/Transforms/IPO/IROutliner.h"14#include "llvm/Analysis/IRSimilarityIdentifier.h"15#include "llvm/Analysis/OptimizationRemarkEmitter.h"16#include "llvm/Analysis/TargetTransformInfo.h"17#include "llvm/IR/Attributes.h"18#include "llvm/IR/DIBuilder.h"19#include "llvm/IR/DebugInfo.h"20#include "llvm/IR/DebugInfoMetadata.h"21#include "llvm/IR/Dominators.h"22#include "llvm/IR/Mangler.h"23#include "llvm/IR/PassManager.h"24#include "llvm/Support/CommandLine.h"25#include "llvm/Transforms/IPO.h"26#include <optional>27#include <vector>2829#define DEBUG_TYPE "iroutliner"3031using namespace llvm;32using namespace IRSimilarity;3334// A command flag to be used for debugging to exclude branches from similarity35// matching and outlining.36namespace llvm {37extern cl::opt<bool> DisableBranches;3839// A command flag to be used for debugging to indirect calls from similarity40// matching and outlining.41extern cl::opt<bool> DisableIndirectCalls;4243// A command flag to be used for debugging to exclude intrinsics from similarity44// matching and outlining.45extern cl::opt<bool> DisableIntrinsics;4647} // namespace llvm4849// Set to true if the user wants the ir outliner to run on linkonceodr linkage50// functions. This is false by default because the linker can dedupe linkonceodr51// functions. Since the outliner is confined to a single module (modulo LTO),52// this is off by default. It should, however, be the default behavior in53// LTO.54static cl::opt<bool> EnableLinkOnceODRIROutlining(55"enable-linkonceodr-ir-outlining", cl::Hidden,56cl::desc("Enable the IR outliner on linkonceodr functions"),57cl::init(false));5859// This is a debug option to test small pieces of code to ensure that outlining60// works correctly.61static cl::opt<bool> NoCostModel(62"ir-outlining-no-cost", cl::init(false), cl::ReallyHidden,63cl::desc("Debug option to outline greedily, without restriction that "64"calculated benefit outweighs cost"));6566/// The OutlinableGroup holds all the overarching information for outlining67/// a set of regions that are structurally similar to one another, such as the68/// types of the overall function, the output blocks, the sets of stores needed69/// and a list of the different regions. This information is used in the70/// deduplication of extracted regions with the same structure.71struct OutlinableGroup {72/// The sections that could be outlined73std::vector<OutlinableRegion *> Regions;7475/// The argument types for the function created as the overall function to76/// replace the extracted function for each region.77std::vector<Type *> ArgumentTypes;78/// The FunctionType for the overall function.79FunctionType *OutlinedFunctionType = nullptr;80/// The Function for the collective overall function.81Function *OutlinedFunction = nullptr;8283/// Flag for whether we should not consider this group of OutlinableRegions84/// for extraction.85bool IgnoreGroup = false;8687/// The return blocks for the overall function.88DenseMap<Value *, BasicBlock *> EndBBs;8990/// The PHIBlocks with their corresponding return block based on the return91/// value as the key.92DenseMap<Value *, BasicBlock *> PHIBlocks;9394/// A set containing the different GVN store sets needed. Each array contains95/// a sorted list of the different values that need to be stored into output96/// registers.97DenseSet<ArrayRef<unsigned>> OutputGVNCombinations;9899/// Flag for whether the \ref ArgumentTypes have been defined after the100/// extraction of the first region.101bool InputTypesSet = false;102103/// The number of input values in \ref ArgumentTypes. Anything after this104/// index in ArgumentTypes is an output argument.105unsigned NumAggregateInputs = 0;106107/// The mapping of the canonical numbering of the values in outlined sections108/// to specific arguments.109DenseMap<unsigned, unsigned> CanonicalNumberToAggArg;110111/// The number of branches in the region target a basic block that is outside112/// of the region.113unsigned BranchesToOutside = 0;114115/// Tracker counting backwards from the highest unsigned value possible to116/// avoid conflicting with the GVNs of assigned values. We start at -3 since117/// -2 and -1 are assigned by the DenseMap.118unsigned PHINodeGVNTracker = -3;119120DenseMap<unsigned,121std::pair<std::pair<unsigned, unsigned>, SmallVector<unsigned, 2>>>122PHINodeGVNToGVNs;123DenseMap<hash_code, unsigned> GVNsToPHINodeGVN;124125/// The number of instructions that will be outlined by extracting \ref126/// Regions.127InstructionCost Benefit = 0;128/// The number of added instructions needed for the outlining of the \ref129/// Regions.130InstructionCost Cost = 0;131132/// The argument that needs to be marked with the swifterr attribute. If not133/// needed, there is no value.134std::optional<unsigned> SwiftErrorArgument;135136/// For the \ref Regions, we look at every Value. If it is a constant,137/// we check whether it is the same in Region.138///139/// \param [in,out] NotSame contains the global value numbers where the140/// constant is not always the same, and must be passed in as an argument.141void findSameConstants(DenseSet<unsigned> &NotSame);142143/// For the regions, look at each set of GVN stores needed and account for144/// each combination. Add an argument to the argument types if there is145/// more than one combination.146///147/// \param [in] M - The module we are outlining from.148void collectGVNStoreSets(Module &M);149};150151/// Move the contents of \p SourceBB to before the last instruction of \p152/// TargetBB.153/// \param SourceBB - the BasicBlock to pull Instructions from.154/// \param TargetBB - the BasicBlock to put Instruction into.155static void moveBBContents(BasicBlock &SourceBB, BasicBlock &TargetBB) {156TargetBB.splice(TargetBB.end(), &SourceBB);157}158159/// A function to sort the keys of \p Map, which must be a mapping of constant160/// values to basic blocks and return it in \p SortedKeys161///162/// \param SortedKeys - The vector the keys will be return in and sorted.163/// \param Map - The DenseMap containing keys to sort.164static void getSortedConstantKeys(std::vector<Value *> &SortedKeys,165DenseMap<Value *, BasicBlock *> &Map) {166for (auto &VtoBB : Map)167SortedKeys.push_back(VtoBB.first);168169// Here we expect to have either 1 value that is void (nullptr) or multiple170// values that are all constant integers.171if (SortedKeys.size() == 1) {172assert(!SortedKeys[0] && "Expected a single void value.");173return;174}175176stable_sort(SortedKeys, [](const Value *LHS, const Value *RHS) {177assert(LHS && RHS && "Expected non void values.");178const ConstantInt *LHSC = cast<ConstantInt>(LHS);179const ConstantInt *RHSC = cast<ConstantInt>(RHS);180181return LHSC->getLimitedValue() < RHSC->getLimitedValue();182});183}184185Value *OutlinableRegion::findCorrespondingValueIn(const OutlinableRegion &Other,186Value *V) {187std::optional<unsigned> GVN = Candidate->getGVN(V);188assert(GVN && "No GVN for incoming value");189std::optional<unsigned> CanonNum = Candidate->getCanonicalNum(*GVN);190std::optional<unsigned> FirstGVN =191Other.Candidate->fromCanonicalNum(*CanonNum);192std::optional<Value *> FoundValueOpt = Other.Candidate->fromGVN(*FirstGVN);193return FoundValueOpt.value_or(nullptr);194}195196BasicBlock *197OutlinableRegion::findCorrespondingBlockIn(const OutlinableRegion &Other,198BasicBlock *BB) {199Instruction *FirstNonPHI = BB->getFirstNonPHIOrDbg();200assert(FirstNonPHI && "block is empty?");201Value *CorrespondingVal = findCorrespondingValueIn(Other, FirstNonPHI);202if (!CorrespondingVal)203return nullptr;204BasicBlock *CorrespondingBlock =205cast<Instruction>(CorrespondingVal)->getParent();206return CorrespondingBlock;207}208209/// Rewrite the BranchInsts in the incoming blocks to \p PHIBlock that are found210/// in \p Included to branch to BasicBlock \p Replace if they currently branch211/// to the BasicBlock \p Find. This is used to fix up the incoming basic blocks212/// when PHINodes are included in outlined regions.213///214/// \param PHIBlock - The BasicBlock containing the PHINodes that need to be215/// checked.216/// \param Find - The successor block to be replaced.217/// \param Replace - The new succesor block to branch to.218/// \param Included - The set of blocks about to be outlined.219static void replaceTargetsFromPHINode(BasicBlock *PHIBlock, BasicBlock *Find,220BasicBlock *Replace,221DenseSet<BasicBlock *> &Included) {222for (PHINode &PN : PHIBlock->phis()) {223for (unsigned Idx = 0, PNEnd = PN.getNumIncomingValues(); Idx != PNEnd;224++Idx) {225// Check if the incoming block is included in the set of blocks being226// outlined.227BasicBlock *Incoming = PN.getIncomingBlock(Idx);228if (!Included.contains(Incoming))229continue;230231BranchInst *BI = dyn_cast<BranchInst>(Incoming->getTerminator());232assert(BI && "Not a branch instruction?");233// Look over the branching instructions into this block to see if we234// used to branch to Find in this outlined block.235for (unsigned Succ = 0, End = BI->getNumSuccessors(); Succ != End;236Succ++) {237// If we have found the block to replace, we do so here.238if (BI->getSuccessor(Succ) != Find)239continue;240BI->setSuccessor(Succ, Replace);241}242}243}244}245246247void OutlinableRegion::splitCandidate() {248assert(!CandidateSplit && "Candidate already split!");249250Instruction *BackInst = Candidate->backInstruction();251252Instruction *EndInst = nullptr;253// Check whether the last instruction is a terminator, if it is, we do254// not split on the following instruction. We leave the block as it is. We255// also check that this is not the last instruction in the Module, otherwise256// the check for whether the current following instruction matches the257// previously recorded instruction will be incorrect.258if (!BackInst->isTerminator() ||259BackInst->getParent() != &BackInst->getFunction()->back()) {260EndInst = Candidate->end()->Inst;261assert(EndInst && "Expected an end instruction?");262}263264// We check if the current instruction following the last instruction in the265// region is the same as the recorded instruction following the last266// instruction. If they do not match, there could be problems in rewriting267// the program after outlining, so we ignore it.268if (!BackInst->isTerminator() &&269EndInst != BackInst->getNextNonDebugInstruction())270return;271272Instruction *StartInst = (*Candidate->begin()).Inst;273assert(StartInst && "Expected a start instruction?");274StartBB = StartInst->getParent();275PrevBB = StartBB;276277DenseSet<BasicBlock *> BBSet;278Candidate->getBasicBlocks(BBSet);279280// We iterate over the instructions in the region, if we find a PHINode, we281// check if there are predecessors outside of the region, if there are,282// we ignore this region since we are unable to handle the severing of the283// phi node right now.284285// TODO: Handle extraneous inputs for PHINodes through variable number of286// inputs, similar to how outputs are handled.287BasicBlock::iterator It = StartInst->getIterator();288EndBB = BackInst->getParent();289BasicBlock *IBlock;290BasicBlock *PHIPredBlock = nullptr;291bool EndBBTermAndBackInstDifferent = EndBB->getTerminator() != BackInst;292while (PHINode *PN = dyn_cast<PHINode>(&*It)) {293unsigned NumPredsOutsideRegion = 0;294for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {295if (!BBSet.contains(PN->getIncomingBlock(i))) {296PHIPredBlock = PN->getIncomingBlock(i);297++NumPredsOutsideRegion;298continue;299}300301// We must consider the case there the incoming block to the PHINode is302// the same as the final block of the OutlinableRegion. If this is the303// case, the branch from this block must also be outlined to be valid.304IBlock = PN->getIncomingBlock(i);305if (IBlock == EndBB && EndBBTermAndBackInstDifferent) {306PHIPredBlock = PN->getIncomingBlock(i);307++NumPredsOutsideRegion;308}309}310311if (NumPredsOutsideRegion > 1)312return;313314It++;315}316317// If the region starts with a PHINode, but is not the initial instruction of318// the BasicBlock, we ignore this region for now.319if (isa<PHINode>(StartInst) && StartInst != &*StartBB->begin())320return;321322// If the region ends with a PHINode, but does not contain all of the phi node323// instructions of the region, we ignore it for now.324if (isa<PHINode>(BackInst) &&325BackInst != &*std::prev(EndBB->getFirstInsertionPt()))326return;327328// The basic block gets split like so:329// block: block:330// inst1 inst1331// inst2 inst2332// region1 br block_to_outline333// region2 block_to_outline:334// region3 -> region1335// region4 region2336// inst3 region3337// inst4 region4338// br block_after_outline339// block_after_outline:340// inst3341// inst4342343std::string OriginalName = PrevBB->getName().str();344345StartBB = PrevBB->splitBasicBlock(StartInst, OriginalName + "_to_outline");346PrevBB->replaceSuccessorsPhiUsesWith(PrevBB, StartBB);347// If there was a PHINode with an incoming block outside the region,348// make sure is correctly updated in the newly split block.349if (PHIPredBlock)350PrevBB->replaceSuccessorsPhiUsesWith(PHIPredBlock, PrevBB);351352CandidateSplit = true;353if (!BackInst->isTerminator()) {354EndBB = EndInst->getParent();355FollowBB = EndBB->splitBasicBlock(EndInst, OriginalName + "_after_outline");356EndBB->replaceSuccessorsPhiUsesWith(EndBB, FollowBB);357FollowBB->replaceSuccessorsPhiUsesWith(PrevBB, FollowBB);358} else {359EndBB = BackInst->getParent();360EndsInBranch = true;361FollowBB = nullptr;362}363364// Refind the basic block set.365BBSet.clear();366Candidate->getBasicBlocks(BBSet);367// For the phi nodes in the new starting basic block of the region, we368// reassign the targets of the basic blocks branching instructions.369replaceTargetsFromPHINode(StartBB, PrevBB, StartBB, BBSet);370if (FollowBB)371replaceTargetsFromPHINode(FollowBB, EndBB, FollowBB, BBSet);372}373374void OutlinableRegion::reattachCandidate() {375assert(CandidateSplit && "Candidate is not split!");376377// The basic block gets reattached like so:378// block: block:379// inst1 inst1380// inst2 inst2381// br block_to_outline region1382// block_to_outline: -> region2383// region1 region3384// region2 region4385// region3 inst3386// region4 inst4387// br block_after_outline388// block_after_outline:389// inst3390// inst4391assert(StartBB != nullptr && "StartBB for Candidate is not defined!");392393assert(PrevBB->getTerminator() && "Terminator removed from PrevBB!");394// Make sure PHINode references to the block we are merging into are395// updated to be incoming blocks from the predecessor to the current block.396397// NOTE: If this is updated such that the outlined block can have more than398// one incoming block to a PHINode, this logic will have to updated399// to handle multiple precessors instead.400401// We only need to update this if the outlined section contains a PHINode, if402// it does not, then the incoming block was never changed in the first place.403// On the other hand, if PrevBB has no predecessors, it means that all404// incoming blocks to the first block are contained in the region, and there405// will be nothing to update.406Instruction *StartInst = (*Candidate->begin()).Inst;407if (isa<PHINode>(StartInst) && !PrevBB->hasNPredecessors(0)) {408assert(!PrevBB->hasNPredecessorsOrMore(2) &&409"PrevBB has more than one predecessor. Should be 0 or 1.");410BasicBlock *BeforePrevBB = PrevBB->getSinglePredecessor();411PrevBB->replaceSuccessorsPhiUsesWith(PrevBB, BeforePrevBB);412}413PrevBB->getTerminator()->eraseFromParent();414415// If we reattaching after outlining, we iterate over the phi nodes to416// the initial block, and reassign the branch instructions of the incoming417// blocks to the block we are remerging into.418if (!ExtractedFunction) {419DenseSet<BasicBlock *> BBSet;420Candidate->getBasicBlocks(BBSet);421422replaceTargetsFromPHINode(StartBB, StartBB, PrevBB, BBSet);423if (!EndsInBranch)424replaceTargetsFromPHINode(FollowBB, FollowBB, EndBB, BBSet);425}426427moveBBContents(*StartBB, *PrevBB);428429BasicBlock *PlacementBB = PrevBB;430if (StartBB != EndBB)431PlacementBB = EndBB;432if (!EndsInBranch && PlacementBB->getUniqueSuccessor() != nullptr) {433assert(FollowBB != nullptr && "FollowBB for Candidate is not defined!");434assert(PlacementBB->getTerminator() && "Terminator removed from EndBB!");435PlacementBB->getTerminator()->eraseFromParent();436moveBBContents(*FollowBB, *PlacementBB);437PlacementBB->replaceSuccessorsPhiUsesWith(FollowBB, PlacementBB);438FollowBB->eraseFromParent();439}440441PrevBB->replaceSuccessorsPhiUsesWith(StartBB, PrevBB);442StartBB->eraseFromParent();443444// Make sure to save changes back to the StartBB.445StartBB = PrevBB;446EndBB = nullptr;447PrevBB = nullptr;448FollowBB = nullptr;449450CandidateSplit = false;451}452453/// Find whether \p V matches the Constants previously found for the \p GVN.454///455/// \param V - The value to check for consistency.456/// \param GVN - The global value number assigned to \p V.457/// \param GVNToConstant - The mapping of global value number to Constants.458/// \returns true if the Value matches the Constant mapped to by V and false if459/// it \p V is a Constant but does not match.460/// \returns std::nullopt if \p V is not a Constant.461static std::optional<bool>462constantMatches(Value *V, unsigned GVN,463DenseMap<unsigned, Constant *> &GVNToConstant) {464// See if we have a constants465Constant *CST = dyn_cast<Constant>(V);466if (!CST)467return std::nullopt;468469// Holds a mapping from a global value number to a Constant.470DenseMap<unsigned, Constant *>::iterator GVNToConstantIt;471bool Inserted;472473474// If we have a constant, try to make a new entry in the GVNToConstant.475std::tie(GVNToConstantIt, Inserted) =476GVNToConstant.insert(std::make_pair(GVN, CST));477// If it was found and is not equal, it is not the same. We do not478// handle this case yet, and exit early.479if (Inserted || (GVNToConstantIt->second == CST))480return true;481482return false;483}484485InstructionCost OutlinableRegion::getBenefit(TargetTransformInfo &TTI) {486InstructionCost Benefit = 0;487488// Estimate the benefit of outlining a specific sections of the program. We489// delegate mostly this task to the TargetTransformInfo so that if the target490// has specific changes, we can have a more accurate estimate.491492// However, getInstructionCost delegates the code size calculation for493// arithmetic instructions to getArithmeticInstrCost in494// include/Analysis/TargetTransformImpl.h, where it always estimates that the495// code size for a division and remainder instruction to be equal to 4, and496// everything else to 1. This is not an accurate representation of the497// division instruction for targets that have a native division instruction.498// To be overly conservative, we only add 1 to the number of instructions for499// each division instruction.500for (IRInstructionData &ID : *Candidate) {501Instruction *I = ID.Inst;502switch (I->getOpcode()) {503case Instruction::FDiv:504case Instruction::FRem:505case Instruction::SDiv:506case Instruction::SRem:507case Instruction::UDiv:508case Instruction::URem:509Benefit += 1;510break;511default:512Benefit += TTI.getInstructionCost(I, TargetTransformInfo::TCK_CodeSize);513break;514}515}516517return Benefit;518}519520/// Check the \p OutputMappings structure for value \p Input, if it exists521/// it has been used as an output for outlining, and has been renamed, and we522/// return the new value, otherwise, we return the same value.523///524/// \param OutputMappings [in] - The mapping of values to their renamed value525/// after being used as an output for an outlined region.526/// \param Input [in] - The value to find the remapped value of, if it exists.527/// \return The remapped value if it has been renamed, and the same value if has528/// not.529static Value *findOutputMapping(const DenseMap<Value *, Value *> OutputMappings,530Value *Input) {531DenseMap<Value *, Value *>::const_iterator OutputMapping =532OutputMappings.find(Input);533if (OutputMapping != OutputMappings.end())534return OutputMapping->second;535return Input;536}537538/// Find whether \p Region matches the global value numbering to Constant539/// mapping found so far.540///541/// \param Region - The OutlinableRegion we are checking for constants542/// \param GVNToConstant - The mapping of global value number to Constants.543/// \param NotSame - The set of global value numbers that do not have the same544/// constant in each region.545/// \returns true if all Constants are the same in every use of a Constant in \p546/// Region and false if not547static bool548collectRegionsConstants(OutlinableRegion &Region,549DenseMap<unsigned, Constant *> &GVNToConstant,550DenseSet<unsigned> &NotSame) {551bool ConstantsTheSame = true;552553IRSimilarityCandidate &C = *Region.Candidate;554for (IRInstructionData &ID : C) {555556// Iterate over the operands in an instruction. If the global value number,557// assigned by the IRSimilarityCandidate, has been seen before, we check if558// the number has been found to be not the same value in each instance.559for (Value *V : ID.OperVals) {560std::optional<unsigned> GVNOpt = C.getGVN(V);561assert(GVNOpt && "Expected a GVN for operand?");562unsigned GVN = *GVNOpt;563564// Check if this global value has been found to not be the same already.565if (NotSame.contains(GVN)) {566if (isa<Constant>(V))567ConstantsTheSame = false;568continue;569}570571// If it has been the same so far, we check the value for if the572// associated Constant value match the previous instances of the same573// global value number. If the global value does not map to a Constant,574// it is considered to not be the same value.575std::optional<bool> ConstantMatches =576constantMatches(V, GVN, GVNToConstant);577if (ConstantMatches) {578if (*ConstantMatches)579continue;580else581ConstantsTheSame = false;582}583584// While this value is a register, it might not have been previously,585// make sure we don't already have a constant mapped to this global value586// number.587if (GVNToConstant.contains(GVN))588ConstantsTheSame = false;589590NotSame.insert(GVN);591}592}593594return ConstantsTheSame;595}596597void OutlinableGroup::findSameConstants(DenseSet<unsigned> &NotSame) {598DenseMap<unsigned, Constant *> GVNToConstant;599600for (OutlinableRegion *Region : Regions)601collectRegionsConstants(*Region, GVNToConstant, NotSame);602}603604void OutlinableGroup::collectGVNStoreSets(Module &M) {605for (OutlinableRegion *OS : Regions)606OutputGVNCombinations.insert(OS->GVNStores);607608// We are adding an extracted argument to decide between which output path609// to use in the basic block. It is used in a switch statement and only610// needs to be an integer.611if (OutputGVNCombinations.size() > 1)612ArgumentTypes.push_back(Type::getInt32Ty(M.getContext()));613}614615/// Get the subprogram if it exists for one of the outlined regions.616///617/// \param [in] Group - The set of regions to find a subprogram for.618/// \returns the subprogram if it exists, or nullptr.619static DISubprogram *getSubprogramOrNull(OutlinableGroup &Group) {620for (OutlinableRegion *OS : Group.Regions)621if (Function *F = OS->Call->getFunction())622if (DISubprogram *SP = F->getSubprogram())623return SP;624625return nullptr;626}627628Function *IROutliner::createFunction(Module &M, OutlinableGroup &Group,629unsigned FunctionNameSuffix) {630assert(!Group.OutlinedFunction && "Function is already defined!");631632Type *RetTy = Type::getVoidTy(M.getContext());633// All extracted functions _should_ have the same return type at this point634// since the similarity identifier ensures that all branches outside of the635// region occur in the same place.636637// NOTE: Should we ever move to the model that uses a switch at every point638// needed, meaning that we could branch within the region or out, it is639// possible that we will need to switch to using the most general case all of640// the time.641for (OutlinableRegion *R : Group.Regions) {642Type *ExtractedFuncType = R->ExtractedFunction->getReturnType();643if ((RetTy->isVoidTy() && !ExtractedFuncType->isVoidTy()) ||644(RetTy->isIntegerTy(1) && ExtractedFuncType->isIntegerTy(16)))645RetTy = ExtractedFuncType;646}647648Group.OutlinedFunctionType = FunctionType::get(649RetTy, Group.ArgumentTypes, false);650651// These functions will only be called from within the same module, so652// we can set an internal linkage.653Group.OutlinedFunction = Function::Create(654Group.OutlinedFunctionType, GlobalValue::InternalLinkage,655"outlined_ir_func_" + std::to_string(FunctionNameSuffix), M);656657// Transfer the swifterr attribute to the correct function parameter.658if (Group.SwiftErrorArgument)659Group.OutlinedFunction->addParamAttr(*Group.SwiftErrorArgument,660Attribute::SwiftError);661662Group.OutlinedFunction->addFnAttr(Attribute::OptimizeForSize);663Group.OutlinedFunction->addFnAttr(Attribute::MinSize);664665// If there's a DISubprogram associated with this outlined function, then666// emit debug info for the outlined function.667if (DISubprogram *SP = getSubprogramOrNull(Group)) {668Function *F = Group.OutlinedFunction;669// We have a DISubprogram. Get its DICompileUnit.670DICompileUnit *CU = SP->getUnit();671DIBuilder DB(M, true, CU);672DIFile *Unit = SP->getFile();673Mangler Mg;674// Get the mangled name of the function for the linkage name.675std::string Dummy;676llvm::raw_string_ostream MangledNameStream(Dummy);677Mg.getNameWithPrefix(MangledNameStream, F, false);678679DISubprogram *OutlinedSP = DB.createFunction(680Unit /* Context */, F->getName(), Dummy,681Unit /* File */,6820 /* Line 0 is reserved for compiler-generated code. */,683DB.createSubroutineType(684DB.getOrCreateTypeArray(std::nullopt)), /* void type */6850, /* Line 0 is reserved for compiler-generated code. */686DINode::DIFlags::FlagArtificial /* Compiler-generated code. */,687/* Outlined code is optimized code by definition. */688DISubprogram::SPFlagDefinition | DISubprogram::SPFlagOptimized);689690// Don't add any new variables to the subprogram.691DB.finalizeSubprogram(OutlinedSP);692693// Attach subprogram to the function.694F->setSubprogram(OutlinedSP);695// We're done with the DIBuilder.696DB.finalize();697}698699return Group.OutlinedFunction;700}701702/// Move each BasicBlock in \p Old to \p New.703///704/// \param [in] Old - The function to move the basic blocks from.705/// \param [in] New - The function to move the basic blocks to.706/// \param [out] NewEnds - The return blocks of the new overall function.707static void moveFunctionData(Function &Old, Function &New,708DenseMap<Value *, BasicBlock *> &NewEnds) {709for (BasicBlock &CurrBB : llvm::make_early_inc_range(Old)) {710CurrBB.removeFromParent();711CurrBB.insertInto(&New);712Instruction *I = CurrBB.getTerminator();713714// For each block we find a return instruction is, it is a potential exit715// path for the function. We keep track of each block based on the return716// value here.717if (ReturnInst *RI = dyn_cast<ReturnInst>(I))718NewEnds.insert(std::make_pair(RI->getReturnValue(), &CurrBB));719720std::vector<Instruction *> DebugInsts;721722for (Instruction &Val : CurrBB) {723// Since debug-info originates from many different locations in the724// program, it will cause incorrect reporting from a debugger if we keep725// the same debug instructions. Drop non-intrinsic DbgVariableRecords726// here, collect intrinsics for removal later.727Val.dropDbgRecords();728729// We must handle the scoping of called functions differently than730// other outlined instructions.731if (!isa<CallInst>(&Val)) {732// Remove the debug information for outlined functions.733Val.setDebugLoc(DebugLoc());734735// Loop info metadata may contain line locations. Update them to have no736// value in the new subprogram since the outlined code could be from737// several locations.738auto updateLoopInfoLoc = [&New](Metadata *MD) -> Metadata * {739if (DISubprogram *SP = New.getSubprogram())740if (auto *Loc = dyn_cast_or_null<DILocation>(MD))741return DILocation::get(New.getContext(), Loc->getLine(),742Loc->getColumn(), SP, nullptr);743return MD;744};745updateLoopMetadataDebugLocations(Val, updateLoopInfoLoc);746continue;747}748749// From this point we are only handling call instructions.750CallInst *CI = cast<CallInst>(&Val);751752// Collect debug intrinsics for later removal.753if (isa<DbgInfoIntrinsic>(CI)) {754DebugInsts.push_back(&Val);755continue;756}757758// Edit the scope of called functions inside of outlined functions.759if (DISubprogram *SP = New.getSubprogram()) {760DILocation *DI = DILocation::get(New.getContext(), 0, 0, SP);761Val.setDebugLoc(DI);762}763}764765for (Instruction *I : DebugInsts)766I->eraseFromParent();767}768}769770/// Find the constants that will need to be lifted into arguments771/// as they are not the same in each instance of the region.772///773/// \param [in] C - The IRSimilarityCandidate containing the region we are774/// analyzing.775/// \param [in] NotSame - The set of global value numbers that do not have a776/// single Constant across all OutlinableRegions similar to \p C.777/// \param [out] Inputs - The list containing the global value numbers of the778/// arguments needed for the region of code.779static void findConstants(IRSimilarityCandidate &C, DenseSet<unsigned> &NotSame,780std::vector<unsigned> &Inputs) {781DenseSet<unsigned> Seen;782// Iterate over the instructions, and find what constants will need to be783// extracted into arguments.784for (IRInstructionDataList::iterator IDIt = C.begin(), EndIDIt = C.end();785IDIt != EndIDIt; IDIt++) {786for (Value *V : (*IDIt).OperVals) {787// Since these are stored before any outlining, they will be in the788// global value numbering.789unsigned GVN = *C.getGVN(V);790if (isa<Constant>(V))791if (NotSame.contains(GVN) && !Seen.contains(GVN)) {792Inputs.push_back(GVN);793Seen.insert(GVN);794}795}796}797}798799/// Find the GVN for the inputs that have been found by the CodeExtractor.800///801/// \param [in] C - The IRSimilarityCandidate containing the region we are802/// analyzing.803/// \param [in] CurrentInputs - The set of inputs found by the804/// CodeExtractor.805/// \param [in] OutputMappings - The mapping of values that have been replaced806/// by a new output value.807/// \param [out] EndInputNumbers - The global value numbers for the extracted808/// arguments.809static void mapInputsToGVNs(IRSimilarityCandidate &C,810SetVector<Value *> &CurrentInputs,811const DenseMap<Value *, Value *> &OutputMappings,812std::vector<unsigned> &EndInputNumbers) {813// Get the Global Value Number for each input. We check if the Value has been814// replaced by a different value at output, and use the original value before815// replacement.816for (Value *Input : CurrentInputs) {817assert(Input && "Have a nullptr as an input");818if (OutputMappings.contains(Input))819Input = OutputMappings.find(Input)->second;820assert(C.getGVN(Input) && "Could not find a numbering for the given input");821EndInputNumbers.push_back(*C.getGVN(Input));822}823}824825/// Find the original value for the \p ArgInput values if any one of them was826/// replaced during a previous extraction.827///828/// \param [in] ArgInputs - The inputs to be extracted by the code extractor.829/// \param [in] OutputMappings - The mapping of values that have been replaced830/// by a new output value.831/// \param [out] RemappedArgInputs - The remapped values according to832/// \p OutputMappings that will be extracted.833static void834remapExtractedInputs(const ArrayRef<Value *> ArgInputs,835const DenseMap<Value *, Value *> &OutputMappings,836SetVector<Value *> &RemappedArgInputs) {837// Get the global value number for each input that will be extracted as an838// argument by the code extractor, remapping if needed for reloaded values.839for (Value *Input : ArgInputs) {840if (OutputMappings.contains(Input))841Input = OutputMappings.find(Input)->second;842RemappedArgInputs.insert(Input);843}844}845846/// Find the input GVNs and the output values for a region of Instructions.847/// Using the code extractor, we collect the inputs to the extracted function.848///849/// The \p Region can be identified as needing to be ignored in this function.850/// It should be checked whether it should be ignored after a call to this851/// function.852///853/// \param [in,out] Region - The region of code to be analyzed.854/// \param [out] InputGVNs - The global value numbers for the extracted855/// arguments.856/// \param [in] NotSame - The global value numbers in the region that do not857/// have the same constant value in the regions structurally similar to858/// \p Region.859/// \param [in] OutputMappings - The mapping of values that have been replaced860/// by a new output value after extraction.861/// \param [out] ArgInputs - The values of the inputs to the extracted function.862/// \param [out] Outputs - The set of values extracted by the CodeExtractor863/// as outputs.864static void getCodeExtractorArguments(865OutlinableRegion &Region, std::vector<unsigned> &InputGVNs,866DenseSet<unsigned> &NotSame, DenseMap<Value *, Value *> &OutputMappings,867SetVector<Value *> &ArgInputs, SetVector<Value *> &Outputs) {868IRSimilarityCandidate &C = *Region.Candidate;869870// OverallInputs are the inputs to the region found by the CodeExtractor,871// SinkCands and HoistCands are used by the CodeExtractor to find sunken872// allocas of values whose lifetimes are contained completely within the873// outlined region. PremappedInputs are the arguments found by the874// CodeExtractor, removing conditions such as sunken allocas, but that875// may need to be remapped due to the extracted output values replacing876// the original values. We use DummyOutputs for this first run of finding877// inputs and outputs since the outputs could change during findAllocas,878// the correct set of extracted outputs will be in the final Outputs ValueSet.879SetVector<Value *> OverallInputs, PremappedInputs, SinkCands, HoistCands,880DummyOutputs;881882// Use the code extractor to get the inputs and outputs, without sunken883// allocas or removing llvm.assumes.884CodeExtractor *CE = Region.CE;885CE->findInputsOutputs(OverallInputs, DummyOutputs, SinkCands);886assert(Region.StartBB && "Region must have a start BasicBlock!");887Function *OrigF = Region.StartBB->getParent();888CodeExtractorAnalysisCache CEAC(*OrigF);889BasicBlock *Dummy = nullptr;890891// The region may be ineligible due to VarArgs in the parent function. In this892// case we ignore the region.893if (!CE->isEligible()) {894Region.IgnoreRegion = true;895return;896}897898// Find if any values are going to be sunk into the function when extracted899CE->findAllocas(CEAC, SinkCands, HoistCands, Dummy);900CE->findInputsOutputs(PremappedInputs, Outputs, SinkCands);901902// TODO: Support regions with sunken allocas: values whose lifetimes are903// contained completely within the outlined region. These are not guaranteed904// to be the same in every region, so we must elevate them all to arguments905// when they appear. If these values are not equal, it means there is some906// Input in OverallInputs that was removed for ArgInputs.907if (OverallInputs.size() != PremappedInputs.size()) {908Region.IgnoreRegion = true;909return;910}911912findConstants(C, NotSame, InputGVNs);913914mapInputsToGVNs(C, OverallInputs, OutputMappings, InputGVNs);915916remapExtractedInputs(PremappedInputs.getArrayRef(), OutputMappings,917ArgInputs);918919// Sort the GVNs, since we now have constants included in the \ref InputGVNs920// we need to make sure they are in a deterministic order.921stable_sort(InputGVNs);922}923924/// Look over the inputs and map each input argument to an argument in the925/// overall function for the OutlinableRegions. This creates a way to replace926/// the arguments of the extracted function with the arguments of the new927/// overall function.928///929/// \param [in,out] Region - The region of code to be analyzed.930/// \param [in] InputGVNs - The global value numbering of the input values931/// collected.932/// \param [in] ArgInputs - The values of the arguments to the extracted933/// function.934static void935findExtractedInputToOverallInputMapping(OutlinableRegion &Region,936std::vector<unsigned> &InputGVNs,937SetVector<Value *> &ArgInputs) {938939IRSimilarityCandidate &C = *Region.Candidate;940OutlinableGroup &Group = *Region.Parent;941942// This counts the argument number in the overall function.943unsigned TypeIndex = 0;944945// This counts the argument number in the extracted function.946unsigned OriginalIndex = 0;947948// Find the mapping of the extracted arguments to the arguments for the949// overall function. Since there may be extra arguments in the overall950// function to account for the extracted constants, we have two different951// counters as we find extracted arguments, and as we come across overall952// arguments.953954// Additionally, in our first pass, for the first extracted function,955// we find argument locations for the canonical value numbering. This956// numbering overrides any discovered location for the extracted code.957for (unsigned InputVal : InputGVNs) {958std::optional<unsigned> CanonicalNumberOpt = C.getCanonicalNum(InputVal);959assert(CanonicalNumberOpt && "Canonical number not found?");960unsigned CanonicalNumber = *CanonicalNumberOpt;961962std::optional<Value *> InputOpt = C.fromGVN(InputVal);963assert(InputOpt && "Global value number not found?");964Value *Input = *InputOpt;965966DenseMap<unsigned, unsigned>::iterator AggArgIt =967Group.CanonicalNumberToAggArg.find(CanonicalNumber);968969if (!Group.InputTypesSet) {970Group.ArgumentTypes.push_back(Input->getType());971// If the input value has a swifterr attribute, make sure to mark the972// argument in the overall function.973if (Input->isSwiftError()) {974assert(975!Group.SwiftErrorArgument &&976"Argument already marked with swifterr for this OutlinableGroup!");977Group.SwiftErrorArgument = TypeIndex;978}979}980981// Check if we have a constant. If we do add it to the overall argument982// number to Constant map for the region, and continue to the next input.983if (Constant *CST = dyn_cast<Constant>(Input)) {984if (AggArgIt != Group.CanonicalNumberToAggArg.end())985Region.AggArgToConstant.insert(std::make_pair(AggArgIt->second, CST));986else {987Group.CanonicalNumberToAggArg.insert(988std::make_pair(CanonicalNumber, TypeIndex));989Region.AggArgToConstant.insert(std::make_pair(TypeIndex, CST));990}991TypeIndex++;992continue;993}994995// It is not a constant, we create the mapping from extracted argument list996// to the overall argument list, using the canonical location, if it exists.997assert(ArgInputs.count(Input) && "Input cannot be found!");998999if (AggArgIt != Group.CanonicalNumberToAggArg.end()) {1000if (OriginalIndex != AggArgIt->second)1001Region.ChangedArgOrder = true;1002Region.ExtractedArgToAgg.insert(1003std::make_pair(OriginalIndex, AggArgIt->second));1004Region.AggArgToExtracted.insert(1005std::make_pair(AggArgIt->second, OriginalIndex));1006} else {1007Group.CanonicalNumberToAggArg.insert(1008std::make_pair(CanonicalNumber, TypeIndex));1009Region.ExtractedArgToAgg.insert(std::make_pair(OriginalIndex, TypeIndex));1010Region.AggArgToExtracted.insert(std::make_pair(TypeIndex, OriginalIndex));1011}1012OriginalIndex++;1013TypeIndex++;1014}10151016// If the function type definitions for the OutlinableGroup holding the region1017// have not been set, set the length of the inputs here. We should have the1018// same inputs for all of the different regions contained in the1019// OutlinableGroup since they are all structurally similar to one another.1020if (!Group.InputTypesSet) {1021Group.NumAggregateInputs = TypeIndex;1022Group.InputTypesSet = true;1023}10241025Region.NumExtractedInputs = OriginalIndex;1026}10271028/// Check if the \p V has any uses outside of the region other than \p PN.1029///1030/// \param V [in] - The value to check.1031/// \param PHILoc [in] - The location in the PHINode of \p V.1032/// \param PN [in] - The PHINode using \p V.1033/// \param Exits [in] - The potential blocks we exit to from the outlined1034/// region.1035/// \param BlocksInRegion [in] - The basic blocks contained in the region.1036/// \returns true if \p V has any use soutside its region other than \p PN.1037static bool outputHasNonPHI(Value *V, unsigned PHILoc, PHINode &PN,1038SmallPtrSet<BasicBlock *, 1> &Exits,1039DenseSet<BasicBlock *> &BlocksInRegion) {1040// We check to see if the value is used by the PHINode from some other1041// predecessor not included in the region. If it is, we make sure1042// to keep it as an output.1043if (any_of(llvm::seq<unsigned>(0, PN.getNumIncomingValues()),1044[PHILoc, &PN, V, &BlocksInRegion](unsigned Idx) {1045return (Idx != PHILoc && V == PN.getIncomingValue(Idx) &&1046!BlocksInRegion.contains(PN.getIncomingBlock(Idx)));1047}))1048return true;10491050// Check if the value is used by any other instructions outside the region.1051return any_of(V->users(), [&Exits, &BlocksInRegion](User *U) {1052Instruction *I = dyn_cast<Instruction>(U);1053if (!I)1054return false;10551056// If the use of the item is inside the region, we skip it. Uses1057// inside the region give us useful information about how the item could be1058// used as an output.1059BasicBlock *Parent = I->getParent();1060if (BlocksInRegion.contains(Parent))1061return false;10621063// If it's not a PHINode then we definitely know the use matters. This1064// output value will not completely combined with another item in a PHINode1065// as it is directly reference by another non-phi instruction1066if (!isa<PHINode>(I))1067return true;10681069// If we have a PHINode outside one of the exit locations, then it1070// can be considered an outside use as well. If there is a PHINode1071// contained in the Exit where this values use matters, it will be1072// caught when we analyze that PHINode.1073if (!Exits.contains(Parent))1074return true;10751076return false;1077});1078}10791080/// Test whether \p CurrentExitFromRegion contains any PhiNodes that should be1081/// considered outputs. A PHINodes is an output when more than one incoming1082/// value has been marked by the CodeExtractor as an output.1083///1084/// \param CurrentExitFromRegion [in] - The block to analyze.1085/// \param PotentialExitsFromRegion [in] - The potential exit blocks from the1086/// region.1087/// \param RegionBlocks [in] - The basic blocks in the region.1088/// \param Outputs [in, out] - The existing outputs for the region, we may add1089/// PHINodes to this as we find that they replace output values.1090/// \param OutputsReplacedByPHINode [out] - A set containing outputs that are1091/// totally replaced by a PHINode.1092/// \param OutputsWithNonPhiUses [out] - A set containing outputs that are used1093/// in PHINodes, but have other uses, and should still be considered outputs.1094static void analyzeExitPHIsForOutputUses(1095BasicBlock *CurrentExitFromRegion,1096SmallPtrSet<BasicBlock *, 1> &PotentialExitsFromRegion,1097DenseSet<BasicBlock *> &RegionBlocks, SetVector<Value *> &Outputs,1098DenseSet<Value *> &OutputsReplacedByPHINode,1099DenseSet<Value *> &OutputsWithNonPhiUses) {1100for (PHINode &PN : CurrentExitFromRegion->phis()) {1101// Find all incoming values from the outlining region.1102SmallVector<unsigned, 2> IncomingVals;1103for (unsigned I = 0, E = PN.getNumIncomingValues(); I < E; ++I)1104if (RegionBlocks.contains(PN.getIncomingBlock(I)))1105IncomingVals.push_back(I);11061107// Do not process PHI if there are no predecessors from region.1108unsigned NumIncomingVals = IncomingVals.size();1109if (NumIncomingVals == 0)1110continue;11111112// If there is one predecessor, we mark it as a value that needs to be kept1113// as an output.1114if (NumIncomingVals == 1) {1115Value *V = PN.getIncomingValue(*IncomingVals.begin());1116OutputsWithNonPhiUses.insert(V);1117OutputsReplacedByPHINode.erase(V);1118continue;1119}11201121// This PHINode will be used as an output value, so we add it to our list.1122Outputs.insert(&PN);11231124// Not all of the incoming values should be ignored as other inputs and1125// outputs may have uses in outlined region. If they have other uses1126// outside of the single PHINode we should not skip over it.1127for (unsigned Idx : IncomingVals) {1128Value *V = PN.getIncomingValue(Idx);1129if (outputHasNonPHI(V, Idx, PN, PotentialExitsFromRegion, RegionBlocks)) {1130OutputsWithNonPhiUses.insert(V);1131OutputsReplacedByPHINode.erase(V);1132continue;1133}1134if (!OutputsWithNonPhiUses.contains(V))1135OutputsReplacedByPHINode.insert(V);1136}1137}1138}11391140// Represents the type for the unsigned number denoting the output number for1141// phi node, along with the canonical number for the exit block.1142using ArgLocWithBBCanon = std::pair<unsigned, unsigned>;1143// The list of canonical numbers for the incoming values to a PHINode.1144using CanonList = SmallVector<unsigned, 2>;1145// The pair type representing the set of canonical values being combined in the1146// PHINode, along with the location data for the PHINode.1147using PHINodeData = std::pair<ArgLocWithBBCanon, CanonList>;11481149/// Encode \p PND as an integer for easy lookup based on the argument location,1150/// the parent BasicBlock canonical numbering, and the canonical numbering of1151/// the values stored in the PHINode.1152///1153/// \param PND - The data to hash.1154/// \returns The hash code of \p PND.1155static hash_code encodePHINodeData(PHINodeData &PND) {1156return llvm::hash_combine(1157llvm::hash_value(PND.first.first), llvm::hash_value(PND.first.second),1158llvm::hash_combine_range(PND.second.begin(), PND.second.end()));1159}11601161/// Create a special GVN for PHINodes that will be used outside of1162/// the region. We create a hash code based on the Canonical number of the1163/// parent BasicBlock, the canonical numbering of the values stored in the1164/// PHINode and the aggregate argument location. This is used to find whether1165/// this PHINode type has been given a canonical numbering already. If not, we1166/// assign it a value and store it for later use. The value is returned to1167/// identify different output schemes for the set of regions.1168///1169/// \param Region - The region that \p PN is an output for.1170/// \param PN - The PHINode we are analyzing.1171/// \param Blocks - The blocks for the region we are analyzing.1172/// \param AggArgIdx - The argument \p PN will be stored into.1173/// \returns An optional holding the assigned canonical number, or std::nullopt1174/// if there is some attribute of the PHINode blocking it from being used.1175static std::optional<unsigned> getGVNForPHINode(OutlinableRegion &Region,1176PHINode *PN,1177DenseSet<BasicBlock *> &Blocks,1178unsigned AggArgIdx) {1179OutlinableGroup &Group = *Region.Parent;1180IRSimilarityCandidate &Cand = *Region.Candidate;1181BasicBlock *PHIBB = PN->getParent();1182CanonList PHIGVNs;1183Value *Incoming;1184BasicBlock *IncomingBlock;1185for (unsigned Idx = 0, EIdx = PN->getNumIncomingValues(); Idx < EIdx; Idx++) {1186Incoming = PN->getIncomingValue(Idx);1187IncomingBlock = PN->getIncomingBlock(Idx);1188// If we cannot find a GVN, and the incoming block is included in the region1189// this means that the input to the PHINode is not included in the region we1190// are trying to analyze, meaning, that if it was outlined, we would be1191// adding an extra input. We ignore this case for now, and so ignore the1192// region.1193std::optional<unsigned> OGVN = Cand.getGVN(Incoming);1194if (!OGVN && Blocks.contains(IncomingBlock)) {1195Region.IgnoreRegion = true;1196return std::nullopt;1197}11981199// If the incoming block isn't in the region, we don't have to worry about1200// this incoming value.1201if (!Blocks.contains(IncomingBlock))1202continue;12031204// Collect the canonical numbers of the values in the PHINode.1205unsigned GVN = *OGVN;1206OGVN = Cand.getCanonicalNum(GVN);1207assert(OGVN && "No GVN found for incoming value?");1208PHIGVNs.push_back(*OGVN);12091210// Find the incoming block and use the canonical numbering as well to define1211// the hash for the PHINode.1212OGVN = Cand.getGVN(IncomingBlock);12131214// If there is no number for the incoming block, it is because we have1215// split the candidate basic blocks. So we use the previous block that it1216// was split from to find the valid global value numbering for the PHINode.1217if (!OGVN) {1218assert(Cand.getStartBB() == IncomingBlock &&1219"Unknown basic block used in exit path PHINode.");12201221BasicBlock *PrevBlock = nullptr;1222// Iterate over the predecessors to the incoming block of the1223// PHINode, when we find a block that is not contained in the region1224// we know that this is the first block that we split from, and should1225// have a valid global value numbering.1226for (BasicBlock *Pred : predecessors(IncomingBlock))1227if (!Blocks.contains(Pred)) {1228PrevBlock = Pred;1229break;1230}1231assert(PrevBlock && "Expected a predecessor not in the reigon!");1232OGVN = Cand.getGVN(PrevBlock);1233}1234GVN = *OGVN;1235OGVN = Cand.getCanonicalNum(GVN);1236assert(OGVN && "No GVN found for incoming block?");1237PHIGVNs.push_back(*OGVN);1238}12391240// Now that we have the GVNs for the incoming values, we are going to combine1241// them with the GVN of the incoming bock, and the output location of the1242// PHINode to generate a hash value representing this instance of the PHINode.1243DenseMap<hash_code, unsigned>::iterator GVNToPHIIt;1244DenseMap<unsigned, PHINodeData>::iterator PHIToGVNIt;1245std::optional<unsigned> BBGVN = Cand.getGVN(PHIBB);1246assert(BBGVN && "Could not find GVN for the incoming block!");12471248BBGVN = Cand.getCanonicalNum(*BBGVN);1249assert(BBGVN && "Could not find canonical number for the incoming block!");1250// Create a pair of the exit block canonical value, and the aggregate1251// argument location, connected to the canonical numbers stored in the1252// PHINode.1253PHINodeData TemporaryPair =1254std::make_pair(std::make_pair(*BBGVN, AggArgIdx), PHIGVNs);1255hash_code PHINodeDataHash = encodePHINodeData(TemporaryPair);12561257// Look for and create a new entry in our connection between canonical1258// numbers for PHINodes, and the set of objects we just created.1259GVNToPHIIt = Group.GVNsToPHINodeGVN.find(PHINodeDataHash);1260if (GVNToPHIIt == Group.GVNsToPHINodeGVN.end()) {1261bool Inserted = false;1262std::tie(PHIToGVNIt, Inserted) = Group.PHINodeGVNToGVNs.insert(1263std::make_pair(Group.PHINodeGVNTracker, TemporaryPair));1264std::tie(GVNToPHIIt, Inserted) = Group.GVNsToPHINodeGVN.insert(1265std::make_pair(PHINodeDataHash, Group.PHINodeGVNTracker--));1266}12671268return GVNToPHIIt->second;1269}12701271/// Create a mapping of the output arguments for the \p Region to the output1272/// arguments of the overall outlined function.1273///1274/// \param [in,out] Region - The region of code to be analyzed.1275/// \param [in] Outputs - The values found by the code extractor.1276static void1277findExtractedOutputToOverallOutputMapping(Module &M, OutlinableRegion &Region,1278SetVector<Value *> &Outputs) {1279OutlinableGroup &Group = *Region.Parent;1280IRSimilarityCandidate &C = *Region.Candidate;12811282SmallVector<BasicBlock *> BE;1283DenseSet<BasicBlock *> BlocksInRegion;1284C.getBasicBlocks(BlocksInRegion, BE);12851286// Find the exits to the region.1287SmallPtrSet<BasicBlock *, 1> Exits;1288for (BasicBlock *Block : BE)1289for (BasicBlock *Succ : successors(Block))1290if (!BlocksInRegion.contains(Succ))1291Exits.insert(Succ);12921293// After determining which blocks exit to PHINodes, we add these PHINodes to1294// the set of outputs to be processed. We also check the incoming values of1295// the PHINodes for whether they should no longer be considered outputs.1296DenseSet<Value *> OutputsReplacedByPHINode;1297DenseSet<Value *> OutputsWithNonPhiUses;1298for (BasicBlock *ExitBB : Exits)1299analyzeExitPHIsForOutputUses(ExitBB, Exits, BlocksInRegion, Outputs,1300OutputsReplacedByPHINode,1301OutputsWithNonPhiUses);13021303// This counts the argument number in the extracted function.1304unsigned OriginalIndex = Region.NumExtractedInputs;13051306// This counts the argument number in the overall function.1307unsigned TypeIndex = Group.NumAggregateInputs;1308bool TypeFound;1309DenseSet<unsigned> AggArgsUsed;13101311// Iterate over the output types and identify if there is an aggregate pointer1312// type whose base type matches the current output type. If there is, we mark1313// that we will use this output register for this value. If not we add another1314// type to the overall argument type list. We also store the GVNs used for1315// stores to identify which values will need to be moved into an special1316// block that holds the stores to the output registers.1317for (Value *Output : Outputs) {1318TypeFound = false;1319// We can do this since it is a result value, and will have a number1320// that is necessarily the same. BUT if in the future, the instructions1321// do not have to be in same order, but are functionally the same, we will1322// have to use a different scheme, as one-to-one correspondence is not1323// guaranteed.1324unsigned ArgumentSize = Group.ArgumentTypes.size();13251326// If the output is combined in a PHINode, we make sure to skip over it.1327if (OutputsReplacedByPHINode.contains(Output))1328continue;13291330unsigned AggArgIdx = 0;1331for (unsigned Jdx = TypeIndex; Jdx < ArgumentSize; Jdx++) {1332if (!isa<PointerType>(Group.ArgumentTypes[Jdx]))1333continue;13341335if (AggArgsUsed.contains(Jdx))1336continue;13371338TypeFound = true;1339AggArgsUsed.insert(Jdx);1340Region.ExtractedArgToAgg.insert(std::make_pair(OriginalIndex, Jdx));1341Region.AggArgToExtracted.insert(std::make_pair(Jdx, OriginalIndex));1342AggArgIdx = Jdx;1343break;1344}13451346// We were unable to find an unused type in the output type set that matches1347// the output, so we add a pointer type to the argument types of the overall1348// function to handle this output and create a mapping to it.1349if (!TypeFound) {1350Group.ArgumentTypes.push_back(PointerType::get(Output->getContext(),1351M.getDataLayout().getAllocaAddrSpace()));1352// Mark the new pointer type as the last value in the aggregate argument1353// list.1354unsigned ArgTypeIdx = Group.ArgumentTypes.size() - 1;1355AggArgsUsed.insert(ArgTypeIdx);1356Region.ExtractedArgToAgg.insert(1357std::make_pair(OriginalIndex, ArgTypeIdx));1358Region.AggArgToExtracted.insert(1359std::make_pair(ArgTypeIdx, OriginalIndex));1360AggArgIdx = ArgTypeIdx;1361}13621363// TODO: Adapt to the extra input from the PHINode.1364PHINode *PN = dyn_cast<PHINode>(Output);13651366std::optional<unsigned> GVN;1367if (PN && !BlocksInRegion.contains(PN->getParent())) {1368// Values outside the region can be combined into PHINode when we1369// have multiple exits. We collect both of these into a list to identify1370// which values are being used in the PHINode. Each list identifies a1371// different PHINode, and a different output. We store the PHINode as it's1372// own canonical value. These canonical values are also dependent on the1373// output argument it is saved to.13741375// If two PHINodes have the same canonical values, but different aggregate1376// argument locations, then they will have distinct Canonical Values.1377GVN = getGVNForPHINode(Region, PN, BlocksInRegion, AggArgIdx);1378if (!GVN)1379return;1380} else {1381// If we do not have a PHINode we use the global value numbering for the1382// output value, to find the canonical number to add to the set of stored1383// values.1384GVN = C.getGVN(Output);1385GVN = C.getCanonicalNum(*GVN);1386}13871388// Each region has a potentially unique set of outputs. We save which1389// values are output in a list of canonical values so we can differentiate1390// among the different store schemes.1391Region.GVNStores.push_back(*GVN);13921393OriginalIndex++;1394TypeIndex++;1395}13961397// We sort the stored values to make sure that we are not affected by analysis1398// order when determining what combination of items were stored.1399stable_sort(Region.GVNStores);1400}14011402void IROutliner::findAddInputsOutputs(Module &M, OutlinableRegion &Region,1403DenseSet<unsigned> &NotSame) {1404std::vector<unsigned> Inputs;1405SetVector<Value *> ArgInputs, Outputs;14061407getCodeExtractorArguments(Region, Inputs, NotSame, OutputMappings, ArgInputs,1408Outputs);14091410if (Region.IgnoreRegion)1411return;14121413// Map the inputs found by the CodeExtractor to the arguments found for1414// the overall function.1415findExtractedInputToOverallInputMapping(Region, Inputs, ArgInputs);14161417// Map the outputs found by the CodeExtractor to the arguments found for1418// the overall function.1419findExtractedOutputToOverallOutputMapping(M, Region, Outputs);1420}14211422/// Replace the extracted function in the Region with a call to the overall1423/// function constructed from the deduplicated similar regions, replacing and1424/// remapping the values passed to the extracted function as arguments to the1425/// new arguments of the overall function.1426///1427/// \param [in] M - The module to outline from.1428/// \param [in] Region - The regions of extracted code to be replaced with a new1429/// function.1430/// \returns a call instruction with the replaced function.1431CallInst *replaceCalledFunction(Module &M, OutlinableRegion &Region) {1432std::vector<Value *> NewCallArgs;1433DenseMap<unsigned, unsigned>::iterator ArgPair;14341435OutlinableGroup &Group = *Region.Parent;1436CallInst *Call = Region.Call;1437assert(Call && "Call to replace is nullptr?");1438Function *AggFunc = Group.OutlinedFunction;1439assert(AggFunc && "Function to replace with is nullptr?");14401441// If the arguments are the same size, there are not values that need to be1442// made into an argument, the argument ordering has not been change, or1443// different output registers to handle. We can simply replace the called1444// function in this case.1445if (!Region.ChangedArgOrder && AggFunc->arg_size() == Call->arg_size()) {1446LLVM_DEBUG(dbgs() << "Replace call to " << *Call << " with call to "1447<< *AggFunc << " with same number of arguments\n");1448Call->setCalledFunction(AggFunc);1449return Call;1450}14511452// We have a different number of arguments than the new function, so1453// we need to use our previously mappings off extracted argument to overall1454// function argument, and constants to overall function argument to create the1455// new argument list.1456for (unsigned AggArgIdx = 0; AggArgIdx < AggFunc->arg_size(); AggArgIdx++) {14571458if (AggArgIdx == AggFunc->arg_size() - 1 &&1459Group.OutputGVNCombinations.size() > 1) {1460// If we are on the last argument, and we need to differentiate between1461// output blocks, add an integer to the argument list to determine1462// what block to take1463LLVM_DEBUG(dbgs() << "Set switch block argument to "1464<< Region.OutputBlockNum << "\n");1465NewCallArgs.push_back(ConstantInt::get(Type::getInt32Ty(M.getContext()),1466Region.OutputBlockNum));1467continue;1468}14691470ArgPair = Region.AggArgToExtracted.find(AggArgIdx);1471if (ArgPair != Region.AggArgToExtracted.end()) {1472Value *ArgumentValue = Call->getArgOperand(ArgPair->second);1473// If we found the mapping from the extracted function to the overall1474// function, we simply add it to the argument list. We use the same1475// value, it just needs to honor the new order of arguments.1476LLVM_DEBUG(dbgs() << "Setting argument " << AggArgIdx << " to value "1477<< *ArgumentValue << "\n");1478NewCallArgs.push_back(ArgumentValue);1479continue;1480}14811482// If it is a constant, we simply add it to the argument list as a value.1483if (Region.AggArgToConstant.contains(AggArgIdx)) {1484Constant *CST = Region.AggArgToConstant.find(AggArgIdx)->second;1485LLVM_DEBUG(dbgs() << "Setting argument " << AggArgIdx << " to value "1486<< *CST << "\n");1487NewCallArgs.push_back(CST);1488continue;1489}14901491// Add a nullptr value if the argument is not found in the extracted1492// function. If we cannot find a value, it means it is not in use1493// for the region, so we should not pass anything to it.1494LLVM_DEBUG(dbgs() << "Setting argument " << AggArgIdx << " to nullptr\n");1495NewCallArgs.push_back(ConstantPointerNull::get(1496static_cast<PointerType *>(AggFunc->getArg(AggArgIdx)->getType())));1497}14981499LLVM_DEBUG(dbgs() << "Replace call to " << *Call << " with call to "1500<< *AggFunc << " with new set of arguments\n");1501// Create the new call instruction and erase the old one.1502Call = CallInst::Create(AggFunc->getFunctionType(), AggFunc, NewCallArgs, "",1503Call->getIterator());15041505// It is possible that the call to the outlined function is either the first1506// instruction is in the new block, the last instruction, or both. If either1507// of these is the case, we need to make sure that we replace the instruction1508// in the IRInstructionData struct with the new call.1509CallInst *OldCall = Region.Call;1510if (Region.NewFront->Inst == OldCall)1511Region.NewFront->Inst = Call;1512if (Region.NewBack->Inst == OldCall)1513Region.NewBack->Inst = Call;15141515// Transfer any debug information.1516Call->setDebugLoc(Region.Call->getDebugLoc());1517// Since our output may determine which branch we go to, we make sure to1518// propogate this new call value through the module.1519OldCall->replaceAllUsesWith(Call);15201521// Remove the old instruction.1522OldCall->eraseFromParent();1523Region.Call = Call;15241525// Make sure that the argument in the new function has the SwiftError1526// argument.1527if (Group.SwiftErrorArgument)1528Call->addParamAttr(*Group.SwiftErrorArgument, Attribute::SwiftError);15291530return Call;1531}15321533/// Find or create a BasicBlock in the outlined function containing PhiBlocks1534/// for \p RetVal.1535///1536/// \param Group - The OutlinableGroup containing the information about the1537/// overall outlined function.1538/// \param RetVal - The return value or exit option that we are currently1539/// evaluating.1540/// \returns The found or newly created BasicBlock to contain the needed1541/// PHINodes to be used as outputs.1542static BasicBlock *findOrCreatePHIBlock(OutlinableGroup &Group, Value *RetVal) {1543DenseMap<Value *, BasicBlock *>::iterator PhiBlockForRetVal,1544ReturnBlockForRetVal;1545PhiBlockForRetVal = Group.PHIBlocks.find(RetVal);1546ReturnBlockForRetVal = Group.EndBBs.find(RetVal);1547assert(ReturnBlockForRetVal != Group.EndBBs.end() &&1548"Could not find output value!");1549BasicBlock *ReturnBB = ReturnBlockForRetVal->second;15501551// Find if a PHIBlock exists for this return value already. If it is1552// the first time we are analyzing this, we will not, so we record it.1553PhiBlockForRetVal = Group.PHIBlocks.find(RetVal);1554if (PhiBlockForRetVal != Group.PHIBlocks.end())1555return PhiBlockForRetVal->second;15561557// If we did not find a block, we create one, and insert it into the1558// overall function and record it.1559bool Inserted = false;1560BasicBlock *PHIBlock = BasicBlock::Create(ReturnBB->getContext(), "phi_block",1561ReturnBB->getParent());1562std::tie(PhiBlockForRetVal, Inserted) =1563Group.PHIBlocks.insert(std::make_pair(RetVal, PHIBlock));15641565// We find the predecessors of the return block in the newly created outlined1566// function in order to point them to the new PHIBlock rather than the already1567// existing return block.1568SmallVector<BranchInst *, 2> BranchesToChange;1569for (BasicBlock *Pred : predecessors(ReturnBB))1570BranchesToChange.push_back(cast<BranchInst>(Pred->getTerminator()));15711572// Now we mark the branch instructions found, and change the references of the1573// return block to the newly created PHIBlock.1574for (BranchInst *BI : BranchesToChange)1575for (unsigned Succ = 0, End = BI->getNumSuccessors(); Succ < End; Succ++) {1576if (BI->getSuccessor(Succ) != ReturnBB)1577continue;1578BI->setSuccessor(Succ, PHIBlock);1579}15801581BranchInst::Create(ReturnBB, PHIBlock);15821583return PhiBlockForRetVal->second;1584}15851586/// For the function call now representing the \p Region, find the passed value1587/// to that call that represents Argument \p A at the call location if the1588/// call has already been replaced with a call to the overall, aggregate1589/// function.1590///1591/// \param A - The Argument to get the passed value for.1592/// \param Region - The extracted Region corresponding to the outlined function.1593/// \returns The Value representing \p A at the call site.1594static Value *1595getPassedArgumentInAlreadyOutlinedFunction(const Argument *A,1596const OutlinableRegion &Region) {1597// If we don't need to adjust the argument number at all (since the call1598// has already been replaced by a call to the overall outlined function)1599// we can just get the specified argument.1600return Region.Call->getArgOperand(A->getArgNo());1601}16021603/// For the function call now representing the \p Region, find the passed value1604/// to that call that represents Argument \p A at the call location if the1605/// call has only been replaced by the call to the aggregate function.1606///1607/// \param A - The Argument to get the passed value for.1608/// \param Region - The extracted Region corresponding to the outlined function.1609/// \returns The Value representing \p A at the call site.1610static Value *1611getPassedArgumentAndAdjustArgumentLocation(const Argument *A,1612const OutlinableRegion &Region) {1613unsigned ArgNum = A->getArgNo();16141615// If it is a constant, we can look at our mapping from when we created1616// the outputs to figure out what the constant value is.1617if (Region.AggArgToConstant.count(ArgNum))1618return Region.AggArgToConstant.find(ArgNum)->second;16191620// If it is not a constant, and we are not looking at the overall function, we1621// need to adjust which argument we are looking at.1622ArgNum = Region.AggArgToExtracted.find(ArgNum)->second;1623return Region.Call->getArgOperand(ArgNum);1624}16251626/// Find the canonical numbering for the incoming Values into the PHINode \p PN.1627///1628/// \param PN [in] - The PHINode that we are finding the canonical numbers for.1629/// \param Region [in] - The OutlinableRegion containing \p PN.1630/// \param OutputMappings [in] - The mapping of output values from outlined1631/// region to their original values.1632/// \param CanonNums [out] - The canonical numbering for the incoming values to1633/// \p PN paired with their incoming block.1634/// \param ReplacedWithOutlinedCall - A flag to use the extracted function call1635/// of \p Region rather than the overall function's call.1636static void findCanonNumsForPHI(1637PHINode *PN, OutlinableRegion &Region,1638const DenseMap<Value *, Value *> &OutputMappings,1639SmallVector<std::pair<unsigned, BasicBlock *>> &CanonNums,1640bool ReplacedWithOutlinedCall = true) {1641// Iterate over the incoming values.1642for (unsigned Idx = 0, EIdx = PN->getNumIncomingValues(); Idx < EIdx; Idx++) {1643Value *IVal = PN->getIncomingValue(Idx);1644BasicBlock *IBlock = PN->getIncomingBlock(Idx);1645// If we have an argument as incoming value, we need to grab the passed1646// value from the call itself.1647if (Argument *A = dyn_cast<Argument>(IVal)) {1648if (ReplacedWithOutlinedCall)1649IVal = getPassedArgumentInAlreadyOutlinedFunction(A, Region);1650else1651IVal = getPassedArgumentAndAdjustArgumentLocation(A, Region);1652}16531654// Get the original value if it has been replaced by an output value.1655IVal = findOutputMapping(OutputMappings, IVal);16561657// Find and add the canonical number for the incoming value.1658std::optional<unsigned> GVN = Region.Candidate->getGVN(IVal);1659assert(GVN && "No GVN for incoming value");1660std::optional<unsigned> CanonNum = Region.Candidate->getCanonicalNum(*GVN);1661assert(CanonNum && "No Canonical Number for GVN");1662CanonNums.push_back(std::make_pair(*CanonNum, IBlock));1663}1664}16651666/// Find, or add PHINode \p PN to the combined PHINode Block \p OverallPHIBlock1667/// in order to condense the number of instructions added to the outlined1668/// function.1669///1670/// \param PN [in] - The PHINode that we are finding the canonical numbers for.1671/// \param Region [in] - The OutlinableRegion containing \p PN.1672/// \param OverallPhiBlock [in] - The overall PHIBlock we are trying to find1673/// \p PN in.1674/// \param OutputMappings [in] - The mapping of output values from outlined1675/// region to their original values.1676/// \param UsedPHIs [in, out] - The PHINodes in the block that have already been1677/// matched.1678/// \return the newly found or created PHINode in \p OverallPhiBlock.1679static PHINode*1680findOrCreatePHIInBlock(PHINode &PN, OutlinableRegion &Region,1681BasicBlock *OverallPhiBlock,1682const DenseMap<Value *, Value *> &OutputMappings,1683DenseSet<PHINode *> &UsedPHIs) {1684OutlinableGroup &Group = *Region.Parent;168516861687// A list of the canonical numbering assigned to each incoming value, paired1688// with the incoming block for the PHINode passed into this function.1689SmallVector<std::pair<unsigned, BasicBlock *>> PNCanonNums;16901691// We have to use the extracted function since we have merged this region into1692// the overall function yet. We make sure to reassign the argument numbering1693// since it is possible that the argument ordering is different between the1694// functions.1695findCanonNumsForPHI(&PN, Region, OutputMappings, PNCanonNums,1696/* ReplacedWithOutlinedCall = */ false);16971698OutlinableRegion *FirstRegion = Group.Regions[0];16991700// A list of the canonical numbering assigned to each incoming value, paired1701// with the incoming block for the PHINode that we are currently comparing1702// the passed PHINode to.1703SmallVector<std::pair<unsigned, BasicBlock *>> CurrentCanonNums;17041705// Find the Canonical Numbering for each PHINode, if it matches, we replace1706// the uses of the PHINode we are searching for, with the found PHINode.1707for (PHINode &CurrPN : OverallPhiBlock->phis()) {1708// If this PHINode has already been matched to another PHINode to be merged,1709// we skip it.1710if (UsedPHIs.contains(&CurrPN))1711continue;17121713CurrentCanonNums.clear();1714findCanonNumsForPHI(&CurrPN, *FirstRegion, OutputMappings, CurrentCanonNums,1715/* ReplacedWithOutlinedCall = */ true);17161717// If the list of incoming values is not the same length, then they cannot1718// match since there is not an analogue for each incoming value.1719if (PNCanonNums.size() != CurrentCanonNums.size())1720continue;17211722bool FoundMatch = true;17231724// We compare the canonical value for each incoming value in the passed1725// in PHINode to one already present in the outlined region. If the1726// incoming values do not match, then the PHINodes do not match.17271728// We also check to make sure that the incoming block matches as well by1729// finding the corresponding incoming block in the combined outlined region1730// for the current outlined region.1731for (unsigned Idx = 0, Edx = PNCanonNums.size(); Idx < Edx; ++Idx) {1732std::pair<unsigned, BasicBlock *> ToCompareTo = CurrentCanonNums[Idx];1733std::pair<unsigned, BasicBlock *> ToAdd = PNCanonNums[Idx];1734if (ToCompareTo.first != ToAdd.first) {1735FoundMatch = false;1736break;1737}17381739BasicBlock *CorrespondingBlock =1740Region.findCorrespondingBlockIn(*FirstRegion, ToAdd.second);1741assert(CorrespondingBlock && "Found block is nullptr");1742if (CorrespondingBlock != ToCompareTo.second) {1743FoundMatch = false;1744break;1745}1746}17471748// If all incoming values and branches matched, then we can merge1749// into the found PHINode.1750if (FoundMatch) {1751UsedPHIs.insert(&CurrPN);1752return &CurrPN;1753}1754}17551756// If we've made it here, it means we weren't able to replace the PHINode, so1757// we must insert it ourselves.1758PHINode *NewPN = cast<PHINode>(PN.clone());1759NewPN->insertBefore(&*OverallPhiBlock->begin());1760for (unsigned Idx = 0, Edx = NewPN->getNumIncomingValues(); Idx < Edx;1761Idx++) {1762Value *IncomingVal = NewPN->getIncomingValue(Idx);1763BasicBlock *IncomingBlock = NewPN->getIncomingBlock(Idx);17641765// Find corresponding basic block in the overall function for the incoming1766// block.1767BasicBlock *BlockToUse =1768Region.findCorrespondingBlockIn(*FirstRegion, IncomingBlock);1769NewPN->setIncomingBlock(Idx, BlockToUse);17701771// If we have an argument we make sure we replace using the argument from1772// the correct function.1773if (Argument *A = dyn_cast<Argument>(IncomingVal)) {1774Value *Val = Group.OutlinedFunction->getArg(A->getArgNo());1775NewPN->setIncomingValue(Idx, Val);1776continue;1777}17781779// Find the corresponding value in the overall function.1780IncomingVal = findOutputMapping(OutputMappings, IncomingVal);1781Value *Val = Region.findCorrespondingValueIn(*FirstRegion, IncomingVal);1782assert(Val && "Value is nullptr?");1783DenseMap<Value *, Value *>::iterator RemappedIt =1784FirstRegion->RemappedArguments.find(Val);1785if (RemappedIt != FirstRegion->RemappedArguments.end())1786Val = RemappedIt->second;1787NewPN->setIncomingValue(Idx, Val);1788}1789return NewPN;1790}17911792// Within an extracted function, replace the argument uses of the extracted1793// region with the arguments of the function for an OutlinableGroup.1794//1795/// \param [in] Region - The region of extracted code to be changed.1796/// \param [in,out] OutputBBs - The BasicBlock for the output stores for this1797/// region.1798/// \param [in] FirstFunction - A flag to indicate whether we are using this1799/// function to define the overall outlined function for all the regions, or1800/// if we are operating on one of the following regions.1801static void1802replaceArgumentUses(OutlinableRegion &Region,1803DenseMap<Value *, BasicBlock *> &OutputBBs,1804const DenseMap<Value *, Value *> &OutputMappings,1805bool FirstFunction = false) {1806OutlinableGroup &Group = *Region.Parent;1807assert(Region.ExtractedFunction && "Region has no extracted function?");18081809Function *DominatingFunction = Region.ExtractedFunction;1810if (FirstFunction)1811DominatingFunction = Group.OutlinedFunction;1812DominatorTree DT(*DominatingFunction);1813DenseSet<PHINode *> UsedPHIs;18141815for (unsigned ArgIdx = 0; ArgIdx < Region.ExtractedFunction->arg_size();1816ArgIdx++) {1817assert(Region.ExtractedArgToAgg.contains(ArgIdx) &&1818"No mapping from extracted to outlined?");1819unsigned AggArgIdx = Region.ExtractedArgToAgg.find(ArgIdx)->second;1820Argument *AggArg = Group.OutlinedFunction->getArg(AggArgIdx);1821Argument *Arg = Region.ExtractedFunction->getArg(ArgIdx);1822// The argument is an input, so we can simply replace it with the overall1823// argument value1824if (ArgIdx < Region.NumExtractedInputs) {1825LLVM_DEBUG(dbgs() << "Replacing uses of input " << *Arg << " in function "1826<< *Region.ExtractedFunction << " with " << *AggArg1827<< " in function " << *Group.OutlinedFunction << "\n");1828Arg->replaceAllUsesWith(AggArg);1829Value *V = Region.Call->getArgOperand(ArgIdx);1830Region.RemappedArguments.insert(std::make_pair(V, AggArg));1831continue;1832}18331834// If we are replacing an output, we place the store value in its own1835// block inside the overall function before replacing the use of the output1836// in the function.1837assert(Arg->hasOneUse() && "Output argument can only have one use");1838User *InstAsUser = Arg->user_back();1839assert(InstAsUser && "User is nullptr!");18401841Instruction *I = cast<Instruction>(InstAsUser);1842BasicBlock *BB = I->getParent();1843SmallVector<BasicBlock *, 4> Descendants;1844DT.getDescendants(BB, Descendants);1845bool EdgeAdded = false;1846if (Descendants.size() == 0) {1847EdgeAdded = true;1848DT.insertEdge(&DominatingFunction->getEntryBlock(), BB);1849DT.getDescendants(BB, Descendants);1850}18511852// Iterate over the following blocks, looking for return instructions,1853// if we find one, find the corresponding output block for the return value1854// and move our store instruction there.1855for (BasicBlock *DescendBB : Descendants) {1856ReturnInst *RI = dyn_cast<ReturnInst>(DescendBB->getTerminator());1857if (!RI)1858continue;1859Value *RetVal = RI->getReturnValue();1860auto VBBIt = OutputBBs.find(RetVal);1861assert(VBBIt != OutputBBs.end() && "Could not find output value!");18621863// If this is storing a PHINode, we must make sure it is included in the1864// overall function.1865StoreInst *SI = cast<StoreInst>(I);18661867Value *ValueOperand = SI->getValueOperand();18681869StoreInst *NewI = cast<StoreInst>(I->clone());1870NewI->setDebugLoc(DebugLoc());1871BasicBlock *OutputBB = VBBIt->second;1872NewI->insertInto(OutputBB, OutputBB->end());1873LLVM_DEBUG(dbgs() << "Move store for instruction " << *I << " to "1874<< *OutputBB << "\n");18751876// If this is storing a PHINode, we must make sure it is included in the1877// overall function.1878if (!isa<PHINode>(ValueOperand) ||1879Region.Candidate->getGVN(ValueOperand).has_value()) {1880if (FirstFunction)1881continue;1882Value *CorrVal =1883Region.findCorrespondingValueIn(*Group.Regions[0], ValueOperand);1884assert(CorrVal && "Value is nullptr?");1885NewI->setOperand(0, CorrVal);1886continue;1887}1888PHINode *PN = cast<PHINode>(SI->getValueOperand());1889// If it has a value, it was not split by the code extractor, which1890// is what we are looking for.1891if (Region.Candidate->getGVN(PN))1892continue;18931894// We record the parent block for the PHINode in the Region so that1895// we can exclude it from checks later on.1896Region.PHIBlocks.insert(std::make_pair(RetVal, PN->getParent()));18971898// If this is the first function, we do not need to worry about mergiing1899// this with any other block in the overall outlined function, so we can1900// just continue.1901if (FirstFunction) {1902BasicBlock *PHIBlock = PN->getParent();1903Group.PHIBlocks.insert(std::make_pair(RetVal, PHIBlock));1904continue;1905}19061907// We look for the aggregate block that contains the PHINodes leading into1908// this exit path. If we can't find one, we create one.1909BasicBlock *OverallPhiBlock = findOrCreatePHIBlock(Group, RetVal);19101911// For our PHINode, we find the combined canonical numbering, and1912// attempt to find a matching PHINode in the overall PHIBlock. If we1913// cannot, we copy the PHINode and move it into this new block.1914PHINode *NewPN = findOrCreatePHIInBlock(*PN, Region, OverallPhiBlock,1915OutputMappings, UsedPHIs);1916NewI->setOperand(0, NewPN);1917}19181919// If we added an edge for basic blocks without a predecessor, we remove it1920// here.1921if (EdgeAdded)1922DT.deleteEdge(&DominatingFunction->getEntryBlock(), BB);1923I->eraseFromParent();19241925LLVM_DEBUG(dbgs() << "Replacing uses of output " << *Arg << " in function "1926<< *Region.ExtractedFunction << " with " << *AggArg1927<< " in function " << *Group.OutlinedFunction << "\n");1928Arg->replaceAllUsesWith(AggArg);1929}1930}19311932/// Within an extracted function, replace the constants that need to be lifted1933/// into arguments with the actual argument.1934///1935/// \param Region [in] - The region of extracted code to be changed.1936void replaceConstants(OutlinableRegion &Region) {1937OutlinableGroup &Group = *Region.Parent;1938// Iterate over the constants that need to be elevated into arguments1939for (std::pair<unsigned, Constant *> &Const : Region.AggArgToConstant) {1940unsigned AggArgIdx = Const.first;1941Function *OutlinedFunction = Group.OutlinedFunction;1942assert(OutlinedFunction && "Overall Function is not defined?");1943Constant *CST = Const.second;1944Argument *Arg = Group.OutlinedFunction->getArg(AggArgIdx);1945// Identify the argument it will be elevated to, and replace instances of1946// that constant in the function.19471948// TODO: If in the future constants do not have one global value number,1949// i.e. a constant 1 could be mapped to several values, this check will1950// have to be more strict. It cannot be using only replaceUsesWithIf.19511952LLVM_DEBUG(dbgs() << "Replacing uses of constant " << *CST1953<< " in function " << *OutlinedFunction << " with "1954<< *Arg << "\n");1955CST->replaceUsesWithIf(Arg, [OutlinedFunction](Use &U) {1956if (Instruction *I = dyn_cast<Instruction>(U.getUser()))1957return I->getFunction() == OutlinedFunction;1958return false;1959});1960}1961}19621963/// It is possible that there is a basic block that already performs the same1964/// stores. This returns a duplicate block, if it exists1965///1966/// \param OutputBBs [in] the blocks we are looking for a duplicate of.1967/// \param OutputStoreBBs [in] The existing output blocks.1968/// \returns an optional value with the number output block if there is a match.1969std::optional<unsigned> findDuplicateOutputBlock(1970DenseMap<Value *, BasicBlock *> &OutputBBs,1971std::vector<DenseMap<Value *, BasicBlock *>> &OutputStoreBBs) {19721973bool Mismatch = false;1974unsigned MatchingNum = 0;1975// We compare the new set output blocks to the other sets of output blocks.1976// If they are the same number, and have identical instructions, they are1977// considered to be the same.1978for (DenseMap<Value *, BasicBlock *> &CompBBs : OutputStoreBBs) {1979Mismatch = false;1980for (std::pair<Value *, BasicBlock *> &VToB : CompBBs) {1981DenseMap<Value *, BasicBlock *>::iterator OutputBBIt =1982OutputBBs.find(VToB.first);1983if (OutputBBIt == OutputBBs.end()) {1984Mismatch = true;1985break;1986}19871988BasicBlock *CompBB = VToB.second;1989BasicBlock *OutputBB = OutputBBIt->second;1990if (CompBB->size() - 1 != OutputBB->size()) {1991Mismatch = true;1992break;1993}19941995BasicBlock::iterator NIt = OutputBB->begin();1996for (Instruction &I : *CompBB) {1997if (isa<BranchInst>(&I))1998continue;19992000if (!I.isIdenticalTo(&(*NIt))) {2001Mismatch = true;2002break;2003}20042005NIt++;2006}2007}20082009if (!Mismatch)2010return MatchingNum;20112012MatchingNum++;2013}20142015return std::nullopt;2016}20172018/// Remove empty output blocks from the outlined region.2019///2020/// \param BlocksToPrune - Mapping of return values output blocks for the \p2021/// Region.2022/// \param Region - The OutlinableRegion we are analyzing.2023static bool2024analyzeAndPruneOutputBlocks(DenseMap<Value *, BasicBlock *> &BlocksToPrune,2025OutlinableRegion &Region) {2026bool AllRemoved = true;2027Value *RetValueForBB;2028BasicBlock *NewBB;2029SmallVector<Value *, 4> ToRemove;2030// Iterate over the output blocks created in the outlined section.2031for (std::pair<Value *, BasicBlock *> &VtoBB : BlocksToPrune) {2032RetValueForBB = VtoBB.first;2033NewBB = VtoBB.second;20342035// If there are no instructions, we remove it from the module, and also2036// mark the value for removal from the return value to output block mapping.2037if (NewBB->size() == 0) {2038NewBB->eraseFromParent();2039ToRemove.push_back(RetValueForBB);2040continue;2041}20422043// Mark that we could not remove all the blocks since they were not all2044// empty.2045AllRemoved = false;2046}20472048// Remove the return value from the mapping.2049for (Value *V : ToRemove)2050BlocksToPrune.erase(V);20512052// Mark the region as having the no output scheme.2053if (AllRemoved)2054Region.OutputBlockNum = -1;20552056return AllRemoved;2057}20582059/// For the outlined section, move needed the StoreInsts for the output2060/// registers into their own block. Then, determine if there is a duplicate2061/// output block already created.2062///2063/// \param [in] OG - The OutlinableGroup of regions to be outlined.2064/// \param [in] Region - The OutlinableRegion that is being analyzed.2065/// \param [in,out] OutputBBs - the blocks that stores for this region will be2066/// placed in.2067/// \param [in] EndBBs - the final blocks of the extracted function.2068/// \param [in] OutputMappings - OutputMappings the mapping of values that have2069/// been replaced by a new output value.2070/// \param [in,out] OutputStoreBBs - The existing output blocks.2071static void alignOutputBlockWithAggFunc(2072OutlinableGroup &OG, OutlinableRegion &Region,2073DenseMap<Value *, BasicBlock *> &OutputBBs,2074DenseMap<Value *, BasicBlock *> &EndBBs,2075const DenseMap<Value *, Value *> &OutputMappings,2076std::vector<DenseMap<Value *, BasicBlock *>> &OutputStoreBBs) {2077// If none of the output blocks have any instructions, this means that we do2078// not have to determine if it matches any of the other output schemes, and we2079// don't have to do anything else.2080if (analyzeAndPruneOutputBlocks(OutputBBs, Region))2081return;20822083// Determine is there is a duplicate set of blocks.2084std::optional<unsigned> MatchingBB =2085findDuplicateOutputBlock(OutputBBs, OutputStoreBBs);20862087// If there is, we remove the new output blocks. If it does not,2088// we add it to our list of sets of output blocks.2089if (MatchingBB) {2090LLVM_DEBUG(dbgs() << "Set output block for region in function"2091<< Region.ExtractedFunction << " to " << *MatchingBB);20922093Region.OutputBlockNum = *MatchingBB;2094for (std::pair<Value *, BasicBlock *> &VtoBB : OutputBBs)2095VtoBB.second->eraseFromParent();2096return;2097}20982099Region.OutputBlockNum = OutputStoreBBs.size();21002101Value *RetValueForBB;2102BasicBlock *NewBB;2103OutputStoreBBs.push_back(DenseMap<Value *, BasicBlock *>());2104for (std::pair<Value *, BasicBlock *> &VtoBB : OutputBBs) {2105RetValueForBB = VtoBB.first;2106NewBB = VtoBB.second;2107DenseMap<Value *, BasicBlock *>::iterator VBBIt =2108EndBBs.find(RetValueForBB);2109LLVM_DEBUG(dbgs() << "Create output block for region in"2110<< Region.ExtractedFunction << " to "2111<< *NewBB);2112BranchInst::Create(VBBIt->second, NewBB);2113OutputStoreBBs.back().insert(std::make_pair(RetValueForBB, NewBB));2114}2115}21162117/// Takes in a mapping, \p OldMap of ConstantValues to BasicBlocks, sorts keys,2118/// before creating a basic block for each \p NewMap, and inserting into the new2119/// block. Each BasicBlock is named with the scheme "<basename>_<key_idx>".2120///2121/// \param OldMap [in] - The mapping to base the new mapping off of.2122/// \param NewMap [out] - The output mapping using the keys of \p OldMap.2123/// \param ParentFunc [in] - The function to put the new basic block in.2124/// \param BaseName [in] - The start of the BasicBlock names to be appended to2125/// by an index value.2126static void createAndInsertBasicBlocks(DenseMap<Value *, BasicBlock *> &OldMap,2127DenseMap<Value *, BasicBlock *> &NewMap,2128Function *ParentFunc, Twine BaseName) {2129unsigned Idx = 0;2130std::vector<Value *> SortedKeys;21312132getSortedConstantKeys(SortedKeys, OldMap);21332134for (Value *RetVal : SortedKeys) {2135BasicBlock *NewBB = BasicBlock::Create(2136ParentFunc->getContext(),2137Twine(BaseName) + Twine("_") + Twine(static_cast<unsigned>(Idx++)),2138ParentFunc);2139NewMap.insert(std::make_pair(RetVal, NewBB));2140}2141}21422143/// Create the switch statement for outlined function to differentiate between2144/// all the output blocks.2145///2146/// For the outlined section, determine if an outlined block already exists that2147/// matches the needed stores for the extracted section.2148/// \param [in] M - The module we are outlining from.2149/// \param [in] OG - The group of regions to be outlined.2150/// \param [in] EndBBs - The final blocks of the extracted function.2151/// \param [in,out] OutputStoreBBs - The existing output blocks.2152void createSwitchStatement(2153Module &M, OutlinableGroup &OG, DenseMap<Value *, BasicBlock *> &EndBBs,2154std::vector<DenseMap<Value *, BasicBlock *>> &OutputStoreBBs) {2155// We only need the switch statement if there is more than one store2156// combination, or there is more than one set of output blocks. The first2157// will occur when we store different sets of values for two different2158// regions. The second will occur when we have two outputs that are combined2159// in a PHINode outside of the region in one outlined instance, and are used2160// seaparately in another. This will create the same set of OutputGVNs, but2161// will generate two different output schemes.2162if (OG.OutputGVNCombinations.size() > 1) {2163Function *AggFunc = OG.OutlinedFunction;2164// Create a final block for each different return block.2165DenseMap<Value *, BasicBlock *> ReturnBBs;2166createAndInsertBasicBlocks(OG.EndBBs, ReturnBBs, AggFunc, "final_block");21672168for (std::pair<Value *, BasicBlock *> &RetBlockPair : ReturnBBs) {2169std::pair<Value *, BasicBlock *> &OutputBlock =2170*OG.EndBBs.find(RetBlockPair.first);2171BasicBlock *ReturnBlock = RetBlockPair.second;2172BasicBlock *EndBB = OutputBlock.second;2173Instruction *Term = EndBB->getTerminator();2174// Move the return value to the final block instead of the original exit2175// stub.2176Term->moveBefore(*ReturnBlock, ReturnBlock->end());2177// Put the switch statement in the old end basic block for the function2178// with a fall through to the new return block.2179LLVM_DEBUG(dbgs() << "Create switch statement in " << *AggFunc << " for "2180<< OutputStoreBBs.size() << "\n");2181SwitchInst *SwitchI =2182SwitchInst::Create(AggFunc->getArg(AggFunc->arg_size() - 1),2183ReturnBlock, OutputStoreBBs.size(), EndBB);21842185unsigned Idx = 0;2186for (DenseMap<Value *, BasicBlock *> &OutputStoreBB : OutputStoreBBs) {2187DenseMap<Value *, BasicBlock *>::iterator OSBBIt =2188OutputStoreBB.find(OutputBlock.first);21892190if (OSBBIt == OutputStoreBB.end())2191continue;21922193BasicBlock *BB = OSBBIt->second;2194SwitchI->addCase(2195ConstantInt::get(Type::getInt32Ty(M.getContext()), Idx), BB);2196Term = BB->getTerminator();2197Term->setSuccessor(0, ReturnBlock);2198Idx++;2199}2200}2201return;2202}22032204assert(OutputStoreBBs.size() < 2 && "Different store sets not handled!");22052206// If there needs to be stores, move them from the output blocks to their2207// corresponding ending block. We do not check that the OutputGVNCombinations2208// is equal to 1 here since that could just been the case where there are 02209// outputs. Instead, we check whether there is more than one set of output2210// blocks since this is the only case where we would have to move the2211// stores, and erase the extraneous blocks.2212if (OutputStoreBBs.size() == 1) {2213LLVM_DEBUG(dbgs() << "Move store instructions to the end block in "2214<< *OG.OutlinedFunction << "\n");2215DenseMap<Value *, BasicBlock *> OutputBlocks = OutputStoreBBs[0];2216for (std::pair<Value *, BasicBlock *> &VBPair : OutputBlocks) {2217DenseMap<Value *, BasicBlock *>::iterator EndBBIt =2218EndBBs.find(VBPair.first);2219assert(EndBBIt != EndBBs.end() && "Could not find end block");2220BasicBlock *EndBB = EndBBIt->second;2221BasicBlock *OutputBB = VBPair.second;2222Instruction *Term = OutputBB->getTerminator();2223Term->eraseFromParent();2224Term = EndBB->getTerminator();2225moveBBContents(*OutputBB, *EndBB);2226Term->moveBefore(*EndBB, EndBB->end());2227OutputBB->eraseFromParent();2228}2229}2230}22312232/// Fill the new function that will serve as the replacement function for all of2233/// the extracted regions of a certain structure from the first region in the2234/// list of regions. Replace this first region's extracted function with the2235/// new overall function.2236///2237/// \param [in] M - The module we are outlining from.2238/// \param [in] CurrentGroup - The group of regions to be outlined.2239/// \param [in,out] OutputStoreBBs - The output blocks for each different2240/// set of stores needed for the different functions.2241/// \param [in,out] FuncsToRemove - Extracted functions to erase from module2242/// once outlining is complete.2243/// \param [in] OutputMappings - Extracted functions to erase from module2244/// once outlining is complete.2245static void fillOverallFunction(2246Module &M, OutlinableGroup &CurrentGroup,2247std::vector<DenseMap<Value *, BasicBlock *>> &OutputStoreBBs,2248std::vector<Function *> &FuncsToRemove,2249const DenseMap<Value *, Value *> &OutputMappings) {2250OutlinableRegion *CurrentOS = CurrentGroup.Regions[0];22512252// Move first extracted function's instructions into new function.2253LLVM_DEBUG(dbgs() << "Move instructions from "2254<< *CurrentOS->ExtractedFunction << " to instruction "2255<< *CurrentGroup.OutlinedFunction << "\n");2256moveFunctionData(*CurrentOS->ExtractedFunction,2257*CurrentGroup.OutlinedFunction, CurrentGroup.EndBBs);22582259// Transfer the attributes from the function to the new function.2260for (Attribute A : CurrentOS->ExtractedFunction->getAttributes().getFnAttrs())2261CurrentGroup.OutlinedFunction->addFnAttr(A);22622263// Create a new set of output blocks for the first extracted function.2264DenseMap<Value *, BasicBlock *> NewBBs;2265createAndInsertBasicBlocks(CurrentGroup.EndBBs, NewBBs,2266CurrentGroup.OutlinedFunction, "output_block_0");2267CurrentOS->OutputBlockNum = 0;22682269replaceArgumentUses(*CurrentOS, NewBBs, OutputMappings, true);2270replaceConstants(*CurrentOS);22712272// We first identify if any output blocks are empty, if they are we remove2273// them. We then create a branch instruction to the basic block to the return2274// block for the function for each non empty output block.2275if (!analyzeAndPruneOutputBlocks(NewBBs, *CurrentOS)) {2276OutputStoreBBs.push_back(DenseMap<Value *, BasicBlock *>());2277for (std::pair<Value *, BasicBlock *> &VToBB : NewBBs) {2278DenseMap<Value *, BasicBlock *>::iterator VBBIt =2279CurrentGroup.EndBBs.find(VToBB.first);2280BasicBlock *EndBB = VBBIt->second;2281BranchInst::Create(EndBB, VToBB.second);2282OutputStoreBBs.back().insert(VToBB);2283}2284}22852286// Replace the call to the extracted function with the outlined function.2287CurrentOS->Call = replaceCalledFunction(M, *CurrentOS);22882289// We only delete the extracted functions at the end since we may need to2290// reference instructions contained in them for mapping purposes.2291FuncsToRemove.push_back(CurrentOS->ExtractedFunction);2292}22932294void IROutliner::deduplicateExtractedSections(2295Module &M, OutlinableGroup &CurrentGroup,2296std::vector<Function *> &FuncsToRemove, unsigned &OutlinedFunctionNum) {2297createFunction(M, CurrentGroup, OutlinedFunctionNum);22982299std::vector<DenseMap<Value *, BasicBlock *>> OutputStoreBBs;23002301OutlinableRegion *CurrentOS;23022303fillOverallFunction(M, CurrentGroup, OutputStoreBBs, FuncsToRemove,2304OutputMappings);23052306std::vector<Value *> SortedKeys;2307for (unsigned Idx = 1; Idx < CurrentGroup.Regions.size(); Idx++) {2308CurrentOS = CurrentGroup.Regions[Idx];2309AttributeFuncs::mergeAttributesForOutlining(*CurrentGroup.OutlinedFunction,2310*CurrentOS->ExtractedFunction);23112312// Create a set of BasicBlocks, one for each return block, to hold the2313// needed store instructions.2314DenseMap<Value *, BasicBlock *> NewBBs;2315createAndInsertBasicBlocks(2316CurrentGroup.EndBBs, NewBBs, CurrentGroup.OutlinedFunction,2317"output_block_" + Twine(static_cast<unsigned>(Idx)));2318replaceArgumentUses(*CurrentOS, NewBBs, OutputMappings);2319alignOutputBlockWithAggFunc(CurrentGroup, *CurrentOS, NewBBs,2320CurrentGroup.EndBBs, OutputMappings,2321OutputStoreBBs);23222323CurrentOS->Call = replaceCalledFunction(M, *CurrentOS);2324FuncsToRemove.push_back(CurrentOS->ExtractedFunction);2325}23262327// Create a switch statement to handle the different output schemes.2328createSwitchStatement(M, CurrentGroup, CurrentGroup.EndBBs, OutputStoreBBs);23292330OutlinedFunctionNum++;2331}23322333/// Checks that the next instruction in the InstructionDataList matches the2334/// next instruction in the module. If they do not, there could be the2335/// possibility that extra code has been inserted, and we must ignore it.2336///2337/// \param ID - The IRInstructionData to check the next instruction of.2338/// \returns true if the InstructionDataList and actual instruction match.2339static bool nextIRInstructionDataMatchesNextInst(IRInstructionData &ID) {2340// We check if there is a discrepancy between the InstructionDataList2341// and the actual next instruction in the module. If there is, it means2342// that an extra instruction was added, likely by the CodeExtractor.23432344// Since we do not have any similarity data about this particular2345// instruction, we cannot confidently outline it, and must discard this2346// candidate.2347IRInstructionDataList::iterator NextIDIt = std::next(ID.getIterator());2348Instruction *NextIDLInst = NextIDIt->Inst;2349Instruction *NextModuleInst = nullptr;2350if (!ID.Inst->isTerminator())2351NextModuleInst = ID.Inst->getNextNonDebugInstruction();2352else if (NextIDLInst != nullptr)2353NextModuleInst =2354&*NextIDIt->Inst->getParent()->instructionsWithoutDebug().begin();23552356if (NextIDLInst && NextIDLInst != NextModuleInst)2357return false;23582359return true;2360}23612362bool IROutliner::isCompatibleWithAlreadyOutlinedCode(2363const OutlinableRegion &Region) {2364IRSimilarityCandidate *IRSC = Region.Candidate;2365unsigned StartIdx = IRSC->getStartIdx();2366unsigned EndIdx = IRSC->getEndIdx();23672368// A check to make sure that we are not about to attempt to outline something2369// that has already been outlined.2370for (unsigned Idx = StartIdx; Idx <= EndIdx; Idx++)2371if (Outlined.contains(Idx))2372return false;23732374// We check if the recorded instruction matches the actual next instruction,2375// if it does not, we fix it in the InstructionDataList.2376if (!Region.Candidate->backInstruction()->isTerminator()) {2377Instruction *NewEndInst =2378Region.Candidate->backInstruction()->getNextNonDebugInstruction();2379assert(NewEndInst && "Next instruction is a nullptr?");2380if (Region.Candidate->end()->Inst != NewEndInst) {2381IRInstructionDataList *IDL = Region.Candidate->front()->IDL;2382IRInstructionData *NewEndIRID = new (InstDataAllocator.Allocate())2383IRInstructionData(*NewEndInst,2384InstructionClassifier.visit(*NewEndInst), *IDL);23852386// Insert the first IRInstructionData of the new region after the2387// last IRInstructionData of the IRSimilarityCandidate.2388IDL->insert(Region.Candidate->end(), *NewEndIRID);2389}2390}23912392return none_of(*IRSC, [this](IRInstructionData &ID) {2393if (!nextIRInstructionDataMatchesNextInst(ID))2394return true;23952396return !this->InstructionClassifier.visit(ID.Inst);2397});2398}23992400void IROutliner::pruneIncompatibleRegions(2401std::vector<IRSimilarityCandidate> &CandidateVec,2402OutlinableGroup &CurrentGroup) {2403bool PreviouslyOutlined;24042405// Sort from beginning to end, so the IRSimilarityCandidates are in order.2406stable_sort(CandidateVec, [](const IRSimilarityCandidate &LHS,2407const IRSimilarityCandidate &RHS) {2408return LHS.getStartIdx() < RHS.getStartIdx();2409});24102411IRSimilarityCandidate &FirstCandidate = CandidateVec[0];2412// Since outlining a call and a branch instruction will be the same as only2413// outlinining a call instruction, we ignore it as a space saving.2414if (FirstCandidate.getLength() == 2) {2415if (isa<CallInst>(FirstCandidate.front()->Inst) &&2416isa<BranchInst>(FirstCandidate.back()->Inst))2417return;2418}24192420unsigned CurrentEndIdx = 0;2421for (IRSimilarityCandidate &IRSC : CandidateVec) {2422PreviouslyOutlined = false;2423unsigned StartIdx = IRSC.getStartIdx();2424unsigned EndIdx = IRSC.getEndIdx();2425const Function &FnForCurrCand = *IRSC.getFunction();24262427for (unsigned Idx = StartIdx; Idx <= EndIdx; Idx++)2428if (Outlined.contains(Idx)) {2429PreviouslyOutlined = true;2430break;2431}24322433if (PreviouslyOutlined)2434continue;24352436// Check over the instructions, and if the basic block has its address2437// taken for use somewhere else, we do not outline that block.2438bool BBHasAddressTaken = any_of(IRSC, [](IRInstructionData &ID){2439return ID.Inst->getParent()->hasAddressTaken();2440});24412442if (BBHasAddressTaken)2443continue;24442445if (FnForCurrCand.hasOptNone())2446continue;24472448if (FnForCurrCand.hasFnAttribute("nooutline")) {2449LLVM_DEBUG({2450dbgs() << "... Skipping function with nooutline attribute: "2451<< FnForCurrCand.getName() << "\n";2452});2453continue;2454}24552456if (IRSC.front()->Inst->getFunction()->hasLinkOnceODRLinkage() &&2457!OutlineFromLinkODRs)2458continue;24592460// Greedily prune out any regions that will overlap with already chosen2461// regions.2462if (CurrentEndIdx != 0 && StartIdx <= CurrentEndIdx)2463continue;24642465bool BadInst = any_of(IRSC, [this](IRInstructionData &ID) {2466if (!nextIRInstructionDataMatchesNextInst(ID))2467return true;24682469return !this->InstructionClassifier.visit(ID.Inst);2470});24712472if (BadInst)2473continue;24742475OutlinableRegion *OS = new (RegionAllocator.Allocate())2476OutlinableRegion(IRSC, CurrentGroup);2477CurrentGroup.Regions.push_back(OS);24782479CurrentEndIdx = EndIdx;2480}2481}24822483InstructionCost2484IROutliner::findBenefitFromAllRegions(OutlinableGroup &CurrentGroup) {2485InstructionCost RegionBenefit = 0;2486for (OutlinableRegion *Region : CurrentGroup.Regions) {2487TargetTransformInfo &TTI = getTTI(*Region->StartBB->getParent());2488// We add the number of instructions in the region to the benefit as an2489// estimate as to how much will be removed.2490RegionBenefit += Region->getBenefit(TTI);2491LLVM_DEBUG(dbgs() << "Adding: " << RegionBenefit2492<< " saved instructions to overfall benefit.\n");2493}24942495return RegionBenefit;2496}24972498/// For the \p OutputCanon number passed in find the value represented by this2499/// canonical number. If it is from a PHINode, we pick the first incoming2500/// value and return that Value instead.2501///2502/// \param Region - The OutlinableRegion to get the Value from.2503/// \param OutputCanon - The canonical number to find the Value from.2504/// \returns The Value represented by a canonical number \p OutputCanon in \p2505/// Region.2506static Value *findOutputValueInRegion(OutlinableRegion &Region,2507unsigned OutputCanon) {2508OutlinableGroup &CurrentGroup = *Region.Parent;2509// If the value is greater than the value in the tracker, we have a2510// PHINode and will instead use one of the incoming values to find the2511// type.2512if (OutputCanon > CurrentGroup.PHINodeGVNTracker) {2513auto It = CurrentGroup.PHINodeGVNToGVNs.find(OutputCanon);2514assert(It != CurrentGroup.PHINodeGVNToGVNs.end() &&2515"Could not find GVN set for PHINode number!");2516assert(It->second.second.size() > 0 && "PHINode does not have any values!");2517OutputCanon = *It->second.second.begin();2518}2519std::optional<unsigned> OGVN =2520Region.Candidate->fromCanonicalNum(OutputCanon);2521assert(OGVN && "Could not find GVN for Canonical Number?");2522std::optional<Value *> OV = Region.Candidate->fromGVN(*OGVN);2523assert(OV && "Could not find value for GVN?");2524return *OV;2525}25262527InstructionCost2528IROutliner::findCostOutputReloads(OutlinableGroup &CurrentGroup) {2529InstructionCost OverallCost = 0;2530for (OutlinableRegion *Region : CurrentGroup.Regions) {2531TargetTransformInfo &TTI = getTTI(*Region->StartBB->getParent());25322533// Each output incurs a load after the call, so we add that to the cost.2534for (unsigned OutputCanon : Region->GVNStores) {2535Value *V = findOutputValueInRegion(*Region, OutputCanon);2536InstructionCost LoadCost =2537TTI.getMemoryOpCost(Instruction::Load, V->getType(), Align(1), 0,2538TargetTransformInfo::TCK_CodeSize);25392540LLVM_DEBUG(dbgs() << "Adding: " << LoadCost2541<< " instructions to cost for output of type "2542<< *V->getType() << "\n");2543OverallCost += LoadCost;2544}2545}25462547return OverallCost;2548}25492550/// Find the extra instructions needed to handle any output values for the2551/// region.2552///2553/// \param [in] M - The Module to outline from.2554/// \param [in] CurrentGroup - The collection of OutlinableRegions to analyze.2555/// \param [in] TTI - The TargetTransformInfo used to collect information for2556/// new instruction costs.2557/// \returns the additional cost to handle the outputs.2558static InstructionCost findCostForOutputBlocks(Module &M,2559OutlinableGroup &CurrentGroup,2560TargetTransformInfo &TTI) {2561InstructionCost OutputCost = 0;2562unsigned NumOutputBranches = 0;25632564OutlinableRegion &FirstRegion = *CurrentGroup.Regions[0];2565IRSimilarityCandidate &Candidate = *CurrentGroup.Regions[0]->Candidate;2566DenseSet<BasicBlock *> CandidateBlocks;2567Candidate.getBasicBlocks(CandidateBlocks);25682569// Count the number of different output branches that point to blocks outside2570// of the region.2571DenseSet<BasicBlock *> FoundBlocks;2572for (IRInstructionData &ID : Candidate) {2573if (!isa<BranchInst>(ID.Inst))2574continue;25752576for (Value *V : ID.OperVals) {2577BasicBlock *BB = static_cast<BasicBlock *>(V);2578if (!CandidateBlocks.contains(BB) && FoundBlocks.insert(BB).second)2579NumOutputBranches++;2580}2581}25822583CurrentGroup.BranchesToOutside = NumOutputBranches;25842585for (const ArrayRef<unsigned> &OutputUse :2586CurrentGroup.OutputGVNCombinations) {2587for (unsigned OutputCanon : OutputUse) {2588Value *V = findOutputValueInRegion(FirstRegion, OutputCanon);2589InstructionCost StoreCost =2590TTI.getMemoryOpCost(Instruction::Load, V->getType(), Align(1), 0,2591TargetTransformInfo::TCK_CodeSize);25922593// An instruction cost is added for each store set that needs to occur for2594// various output combinations inside the function, plus a branch to2595// return to the exit block.2596LLVM_DEBUG(dbgs() << "Adding: " << StoreCost2597<< " instructions to cost for output of type "2598<< *V->getType() << "\n");2599OutputCost += StoreCost * NumOutputBranches;2600}26012602InstructionCost BranchCost =2603TTI.getCFInstrCost(Instruction::Br, TargetTransformInfo::TCK_CodeSize);2604LLVM_DEBUG(dbgs() << "Adding " << BranchCost << " to the current cost for"2605<< " a branch instruction\n");2606OutputCost += BranchCost * NumOutputBranches;2607}26082609// If there is more than one output scheme, we must have a comparison and2610// branch for each different item in the switch statement.2611if (CurrentGroup.OutputGVNCombinations.size() > 1) {2612InstructionCost ComparisonCost = TTI.getCmpSelInstrCost(2613Instruction::ICmp, Type::getInt32Ty(M.getContext()),2614Type::getInt32Ty(M.getContext()), CmpInst::BAD_ICMP_PREDICATE,2615TargetTransformInfo::TCK_CodeSize);2616InstructionCost BranchCost =2617TTI.getCFInstrCost(Instruction::Br, TargetTransformInfo::TCK_CodeSize);26182619unsigned DifferentBlocks = CurrentGroup.OutputGVNCombinations.size();2620InstructionCost TotalCost = ComparisonCost * BranchCost * DifferentBlocks;26212622LLVM_DEBUG(dbgs() << "Adding: " << TotalCost2623<< " instructions for each switch case for each different"2624<< " output path in a function\n");2625OutputCost += TotalCost * NumOutputBranches;2626}26272628return OutputCost;2629}26302631void IROutliner::findCostBenefit(Module &M, OutlinableGroup &CurrentGroup) {2632InstructionCost RegionBenefit = findBenefitFromAllRegions(CurrentGroup);2633CurrentGroup.Benefit += RegionBenefit;2634LLVM_DEBUG(dbgs() << "Current Benefit: " << CurrentGroup.Benefit << "\n");26352636InstructionCost OutputReloadCost = findCostOutputReloads(CurrentGroup);2637CurrentGroup.Cost += OutputReloadCost;2638LLVM_DEBUG(dbgs() << "Current Cost: " << CurrentGroup.Cost << "\n");26392640InstructionCost AverageRegionBenefit =2641RegionBenefit / CurrentGroup.Regions.size();2642unsigned OverallArgumentNum = CurrentGroup.ArgumentTypes.size();2643unsigned NumRegions = CurrentGroup.Regions.size();2644TargetTransformInfo &TTI =2645getTTI(*CurrentGroup.Regions[0]->Candidate->getFunction());26462647// We add one region to the cost once, to account for the instructions added2648// inside of the newly created function.2649LLVM_DEBUG(dbgs() << "Adding: " << AverageRegionBenefit2650<< " instructions to cost for body of new function.\n");2651CurrentGroup.Cost += AverageRegionBenefit;2652LLVM_DEBUG(dbgs() << "Current Cost: " << CurrentGroup.Cost << "\n");26532654// For each argument, we must add an instruction for loading the argument2655// out of the register and into a value inside of the newly outlined function.2656LLVM_DEBUG(dbgs() << "Adding: " << OverallArgumentNum2657<< " instructions to cost for each argument in the new"2658<< " function.\n");2659CurrentGroup.Cost +=2660OverallArgumentNum * TargetTransformInfo::TCC_Basic;2661LLVM_DEBUG(dbgs() << "Current Cost: " << CurrentGroup.Cost << "\n");26622663// Each argument needs to either be loaded into a register or onto the stack.2664// Some arguments will only be loaded into the stack once the argument2665// registers are filled.2666LLVM_DEBUG(dbgs() << "Adding: " << OverallArgumentNum2667<< " instructions to cost for each argument in the new"2668<< " function " << NumRegions << " times for the "2669<< "needed argument handling at the call site.\n");2670CurrentGroup.Cost +=26712 * OverallArgumentNum * TargetTransformInfo::TCC_Basic * NumRegions;2672LLVM_DEBUG(dbgs() << "Current Cost: " << CurrentGroup.Cost << "\n");26732674CurrentGroup.Cost += findCostForOutputBlocks(M, CurrentGroup, TTI);2675LLVM_DEBUG(dbgs() << "Current Cost: " << CurrentGroup.Cost << "\n");2676}26772678void IROutliner::updateOutputMapping(OutlinableRegion &Region,2679ArrayRef<Value *> Outputs,2680LoadInst *LI) {2681// For and load instructions following the call2682Value *Operand = LI->getPointerOperand();2683std::optional<unsigned> OutputIdx;2684// Find if the operand it is an output register.2685for (unsigned ArgIdx = Region.NumExtractedInputs;2686ArgIdx < Region.Call->arg_size(); ArgIdx++) {2687if (Operand == Region.Call->getArgOperand(ArgIdx)) {2688OutputIdx = ArgIdx - Region.NumExtractedInputs;2689break;2690}2691}26922693// If we found an output register, place a mapping of the new value2694// to the original in the mapping.2695if (!OutputIdx)2696return;26972698if (!OutputMappings.contains(Outputs[*OutputIdx])) {2699LLVM_DEBUG(dbgs() << "Mapping extracted output " << *LI << " to "2700<< *Outputs[*OutputIdx] << "\n");2701OutputMappings.insert(std::make_pair(LI, Outputs[*OutputIdx]));2702} else {2703Value *Orig = OutputMappings.find(Outputs[*OutputIdx])->second;2704LLVM_DEBUG(dbgs() << "Mapping extracted output " << *Orig << " to "2705<< *Outputs[*OutputIdx] << "\n");2706OutputMappings.insert(std::make_pair(LI, Orig));2707}2708}27092710bool IROutliner::extractSection(OutlinableRegion &Region) {2711SetVector<Value *> ArgInputs, Outputs, SinkCands;2712assert(Region.StartBB && "StartBB for the OutlinableRegion is nullptr!");2713BasicBlock *InitialStart = Region.StartBB;2714Function *OrigF = Region.StartBB->getParent();2715CodeExtractorAnalysisCache CEAC(*OrigF);2716Region.ExtractedFunction =2717Region.CE->extractCodeRegion(CEAC, ArgInputs, Outputs);27182719// If the extraction was successful, find the BasicBlock, and reassign the2720// OutlinableRegion blocks2721if (!Region.ExtractedFunction) {2722LLVM_DEBUG(dbgs() << "CodeExtractor failed to outline " << Region.StartBB2723<< "\n");2724Region.reattachCandidate();2725return false;2726}27272728// Get the block containing the called branch, and reassign the blocks as2729// necessary. If the original block still exists, it is because we ended on2730// a branch instruction, and so we move the contents into the block before2731// and assign the previous block correctly.2732User *InstAsUser = Region.ExtractedFunction->user_back();2733BasicBlock *RewrittenBB = cast<Instruction>(InstAsUser)->getParent();2734Region.PrevBB = RewrittenBB->getSinglePredecessor();2735assert(Region.PrevBB && "PrevBB is nullptr?");2736if (Region.PrevBB == InitialStart) {2737BasicBlock *NewPrev = InitialStart->getSinglePredecessor();2738Instruction *BI = NewPrev->getTerminator();2739BI->eraseFromParent();2740moveBBContents(*InitialStart, *NewPrev);2741Region.PrevBB = NewPrev;2742InitialStart->eraseFromParent();2743}27442745Region.StartBB = RewrittenBB;2746Region.EndBB = RewrittenBB;27472748// The sequences of outlinable regions has now changed. We must fix the2749// IRInstructionDataList for consistency. Although they may not be illegal2750// instructions, they should not be compared with anything else as they2751// should not be outlined in this round. So marking these as illegal is2752// allowed.2753IRInstructionDataList *IDL = Region.Candidate->front()->IDL;2754Instruction *BeginRewritten = &*RewrittenBB->begin();2755Instruction *EndRewritten = &*RewrittenBB->begin();2756Region.NewFront = new (InstDataAllocator.Allocate()) IRInstructionData(2757*BeginRewritten, InstructionClassifier.visit(*BeginRewritten), *IDL);2758Region.NewBack = new (InstDataAllocator.Allocate()) IRInstructionData(2759*EndRewritten, InstructionClassifier.visit(*EndRewritten), *IDL);27602761// Insert the first IRInstructionData of the new region in front of the2762// first IRInstructionData of the IRSimilarityCandidate.2763IDL->insert(Region.Candidate->begin(), *Region.NewFront);2764// Insert the first IRInstructionData of the new region after the2765// last IRInstructionData of the IRSimilarityCandidate.2766IDL->insert(Region.Candidate->end(), *Region.NewBack);2767// Remove the IRInstructionData from the IRSimilarityCandidate.2768IDL->erase(Region.Candidate->begin(), std::prev(Region.Candidate->end()));27692770assert(RewrittenBB != nullptr &&2771"Could not find a predecessor after extraction!");27722773// Iterate over the new set of instructions to find the new call2774// instruction.2775for (Instruction &I : *RewrittenBB)2776if (CallInst *CI = dyn_cast<CallInst>(&I)) {2777if (Region.ExtractedFunction == CI->getCalledFunction())2778Region.Call = CI;2779} else if (LoadInst *LI = dyn_cast<LoadInst>(&I))2780updateOutputMapping(Region, Outputs.getArrayRef(), LI);2781Region.reattachCandidate();2782return true;2783}27842785unsigned IROutliner::doOutline(Module &M) {2786// Find the possible similarity sections.2787InstructionClassifier.EnableBranches = !DisableBranches;2788InstructionClassifier.EnableIndirectCalls = !DisableIndirectCalls;2789InstructionClassifier.EnableIntrinsics = !DisableIntrinsics;27902791IRSimilarityIdentifier &Identifier = getIRSI(M);2792SimilarityGroupList &SimilarityCandidates = *Identifier.getSimilarity();27932794// Sort them by size of extracted sections2795unsigned OutlinedFunctionNum = 0;2796// If we only have one SimilarityGroup in SimilarityCandidates, we do not have2797// to sort them by the potential number of instructions to be outlined2798if (SimilarityCandidates.size() > 1)2799llvm::stable_sort(SimilarityCandidates,2800[](const std::vector<IRSimilarityCandidate> &LHS,2801const std::vector<IRSimilarityCandidate> &RHS) {2802return LHS[0].getLength() * LHS.size() >2803RHS[0].getLength() * RHS.size();2804});2805// Creating OutlinableGroups for each SimilarityCandidate to be used in2806// each of the following for loops to avoid making an allocator.2807std::vector<OutlinableGroup> PotentialGroups(SimilarityCandidates.size());28082809DenseSet<unsigned> NotSame;2810std::vector<OutlinableGroup *> NegativeCostGroups;2811std::vector<OutlinableRegion *> OutlinedRegions;2812// Iterate over the possible sets of similarity.2813unsigned PotentialGroupIdx = 0;2814for (SimilarityGroup &CandidateVec : SimilarityCandidates) {2815OutlinableGroup &CurrentGroup = PotentialGroups[PotentialGroupIdx++];28162817// Remove entries that were previously outlined2818pruneIncompatibleRegions(CandidateVec, CurrentGroup);28192820// We pruned the number of regions to 0 to 1, meaning that it's not worth2821// trying to outlined since there is no compatible similar instance of this2822// code.2823if (CurrentGroup.Regions.size() < 2)2824continue;28252826// Determine if there are any values that are the same constant throughout2827// each section in the set.2828NotSame.clear();2829CurrentGroup.findSameConstants(NotSame);28302831if (CurrentGroup.IgnoreGroup)2832continue;28332834// Create a CodeExtractor for each outlinable region. Identify inputs and2835// outputs for each section using the code extractor and create the argument2836// types for the Aggregate Outlining Function.2837OutlinedRegions.clear();2838for (OutlinableRegion *OS : CurrentGroup.Regions) {2839// Break the outlinable region out of its parent BasicBlock into its own2840// BasicBlocks (see function implementation).2841OS->splitCandidate();28422843// There's a chance that when the region is split, extra instructions are2844// added to the region. This makes the region no longer viable2845// to be split, so we ignore it for outlining.2846if (!OS->CandidateSplit)2847continue;28482849SmallVector<BasicBlock *> BE;2850DenseSet<BasicBlock *> BlocksInRegion;2851OS->Candidate->getBasicBlocks(BlocksInRegion, BE);2852OS->CE = new (ExtractorAllocator.Allocate())2853CodeExtractor(BE, nullptr, false, nullptr, nullptr, nullptr, false,2854false, nullptr, "outlined");2855findAddInputsOutputs(M, *OS, NotSame);2856if (!OS->IgnoreRegion)2857OutlinedRegions.push_back(OS);28582859// We recombine the blocks together now that we have gathered all the2860// needed information.2861OS->reattachCandidate();2862}28632864CurrentGroup.Regions = std::move(OutlinedRegions);28652866if (CurrentGroup.Regions.empty())2867continue;28682869CurrentGroup.collectGVNStoreSets(M);28702871if (CostModel)2872findCostBenefit(M, CurrentGroup);28732874// If we are adhering to the cost model, skip those groups where the cost2875// outweighs the benefits.2876if (CurrentGroup.Cost >= CurrentGroup.Benefit && CostModel) {2877OptimizationRemarkEmitter &ORE =2878getORE(*CurrentGroup.Regions[0]->Candidate->getFunction());2879ORE.emit([&]() {2880IRSimilarityCandidate *C = CurrentGroup.Regions[0]->Candidate;2881OptimizationRemarkMissed R(DEBUG_TYPE, "WouldNotDecreaseSize",2882C->frontInstruction());2883R << "did not outline "2884<< ore::NV(std::to_string(CurrentGroup.Regions.size()))2885<< " regions due to estimated increase of "2886<< ore::NV("InstructionIncrease",2887CurrentGroup.Cost - CurrentGroup.Benefit)2888<< " instructions at locations ";2889interleave(2890CurrentGroup.Regions.begin(), CurrentGroup.Regions.end(),2891[&R](OutlinableRegion *Region) {2892R << ore::NV(2893"DebugLoc",2894Region->Candidate->frontInstruction()->getDebugLoc());2895},2896[&R]() { R << " "; });2897return R;2898});2899continue;2900}29012902NegativeCostGroups.push_back(&CurrentGroup);2903}29042905ExtractorAllocator.DestroyAll();29062907if (NegativeCostGroups.size() > 1)2908stable_sort(NegativeCostGroups,2909[](const OutlinableGroup *LHS, const OutlinableGroup *RHS) {2910return LHS->Benefit - LHS->Cost > RHS->Benefit - RHS->Cost;2911});29122913std::vector<Function *> FuncsToRemove;2914for (OutlinableGroup *CG : NegativeCostGroups) {2915OutlinableGroup &CurrentGroup = *CG;29162917OutlinedRegions.clear();2918for (OutlinableRegion *Region : CurrentGroup.Regions) {2919// We check whether our region is compatible with what has already been2920// outlined, and whether we need to ignore this item.2921if (!isCompatibleWithAlreadyOutlinedCode(*Region))2922continue;2923OutlinedRegions.push_back(Region);2924}29252926if (OutlinedRegions.size() < 2)2927continue;29282929// Reestimate the cost and benefit of the OutlinableGroup. Continue only if2930// we are still outlining enough regions to make up for the added cost.2931CurrentGroup.Regions = std::move(OutlinedRegions);2932if (CostModel) {2933CurrentGroup.Benefit = 0;2934CurrentGroup.Cost = 0;2935findCostBenefit(M, CurrentGroup);2936if (CurrentGroup.Cost >= CurrentGroup.Benefit)2937continue;2938}2939OutlinedRegions.clear();2940for (OutlinableRegion *Region : CurrentGroup.Regions) {2941Region->splitCandidate();2942if (!Region->CandidateSplit)2943continue;2944OutlinedRegions.push_back(Region);2945}29462947CurrentGroup.Regions = std::move(OutlinedRegions);2948if (CurrentGroup.Regions.size() < 2) {2949for (OutlinableRegion *R : CurrentGroup.Regions)2950R->reattachCandidate();2951continue;2952}29532954LLVM_DEBUG(dbgs() << "Outlining regions with cost " << CurrentGroup.Cost2955<< " and benefit " << CurrentGroup.Benefit << "\n");29562957// Create functions out of all the sections, and mark them as outlined.2958OutlinedRegions.clear();2959for (OutlinableRegion *OS : CurrentGroup.Regions) {2960SmallVector<BasicBlock *> BE;2961DenseSet<BasicBlock *> BlocksInRegion;2962OS->Candidate->getBasicBlocks(BlocksInRegion, BE);2963OS->CE = new (ExtractorAllocator.Allocate())2964CodeExtractor(BE, nullptr, false, nullptr, nullptr, nullptr, false,2965false, nullptr, "outlined");2966bool FunctionOutlined = extractSection(*OS);2967if (FunctionOutlined) {2968unsigned StartIdx = OS->Candidate->getStartIdx();2969unsigned EndIdx = OS->Candidate->getEndIdx();2970for (unsigned Idx = StartIdx; Idx <= EndIdx; Idx++)2971Outlined.insert(Idx);29722973OutlinedRegions.push_back(OS);2974}2975}29762977LLVM_DEBUG(dbgs() << "Outlined " << OutlinedRegions.size()2978<< " with benefit " << CurrentGroup.Benefit2979<< " and cost " << CurrentGroup.Cost << "\n");29802981CurrentGroup.Regions = std::move(OutlinedRegions);29822983if (CurrentGroup.Regions.empty())2984continue;29852986OptimizationRemarkEmitter &ORE =2987getORE(*CurrentGroup.Regions[0]->Call->getFunction());2988ORE.emit([&]() {2989IRSimilarityCandidate *C = CurrentGroup.Regions[0]->Candidate;2990OptimizationRemark R(DEBUG_TYPE, "Outlined", C->front()->Inst);2991R << "outlined " << ore::NV(std::to_string(CurrentGroup.Regions.size()))2992<< " regions with decrease of "2993<< ore::NV("Benefit", CurrentGroup.Benefit - CurrentGroup.Cost)2994<< " instructions at locations ";2995interleave(2996CurrentGroup.Regions.begin(), CurrentGroup.Regions.end(),2997[&R](OutlinableRegion *Region) {2998R << ore::NV("DebugLoc",2999Region->Candidate->frontInstruction()->getDebugLoc());3000},3001[&R]() { R << " "; });3002return R;3003});30043005deduplicateExtractedSections(M, CurrentGroup, FuncsToRemove,3006OutlinedFunctionNum);3007}30083009for (Function *F : FuncsToRemove)3010F->eraseFromParent();30113012return OutlinedFunctionNum;3013}30143015bool IROutliner::run(Module &M) {3016CostModel = !NoCostModel;3017OutlineFromLinkODRs = EnableLinkOnceODRIROutlining;30183019return doOutline(M) > 0;3020}30213022PreservedAnalyses IROutlinerPass::run(Module &M, ModuleAnalysisManager &AM) {3023auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();30243025std::function<TargetTransformInfo &(Function &)> GTTI =3026[&FAM](Function &F) -> TargetTransformInfo & {3027return FAM.getResult<TargetIRAnalysis>(F);3028};30293030std::function<IRSimilarityIdentifier &(Module &)> GIRSI =3031[&AM](Module &M) -> IRSimilarityIdentifier & {3032return AM.getResult<IRSimilarityAnalysis>(M);3033};30343035std::unique_ptr<OptimizationRemarkEmitter> ORE;3036std::function<OptimizationRemarkEmitter &(Function &)> GORE =3037[&ORE](Function &F) -> OptimizationRemarkEmitter & {3038ORE.reset(new OptimizationRemarkEmitter(&F));3039return *ORE;3040};30413042if (IROutliner(GTTI, GIRSI, GORE).run(M))3043return PreservedAnalyses::none();3044return PreservedAnalyses::all();3045}304630473048