Path: blob/main/contrib/llvm-project/llvm/lib/Transforms/Utils/CodeExtractor.cpp
35271 views
//===- CodeExtractor.cpp - Pull code region into a new function -----------===//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// This file implements the interface to tear out a code region, such as an9// individual loop or a parallel section, into a new function, replacing it with10// a call to the new function.11//12//===----------------------------------------------------------------------===//1314#include "llvm/Transforms/Utils/CodeExtractor.h"15#include "llvm/ADT/ArrayRef.h"16#include "llvm/ADT/DenseMap.h"17#include "llvm/ADT/STLExtras.h"18#include "llvm/ADT/SetVector.h"19#include "llvm/ADT/SmallPtrSet.h"20#include "llvm/ADT/SmallVector.h"21#include "llvm/Analysis/AssumptionCache.h"22#include "llvm/Analysis/BlockFrequencyInfo.h"23#include "llvm/Analysis/BlockFrequencyInfoImpl.h"24#include "llvm/Analysis/BranchProbabilityInfo.h"25#include "llvm/Analysis/LoopInfo.h"26#include "llvm/IR/Argument.h"27#include "llvm/IR/Attributes.h"28#include "llvm/IR/BasicBlock.h"29#include "llvm/IR/CFG.h"30#include "llvm/IR/Constant.h"31#include "llvm/IR/Constants.h"32#include "llvm/IR/DIBuilder.h"33#include "llvm/IR/DataLayout.h"34#include "llvm/IR/DebugInfo.h"35#include "llvm/IR/DebugInfoMetadata.h"36#include "llvm/IR/DerivedTypes.h"37#include "llvm/IR/Dominators.h"38#include "llvm/IR/Function.h"39#include "llvm/IR/GlobalValue.h"40#include "llvm/IR/InstIterator.h"41#include "llvm/IR/InstrTypes.h"42#include "llvm/IR/Instruction.h"43#include "llvm/IR/Instructions.h"44#include "llvm/IR/IntrinsicInst.h"45#include "llvm/IR/Intrinsics.h"46#include "llvm/IR/LLVMContext.h"47#include "llvm/IR/MDBuilder.h"48#include "llvm/IR/Module.h"49#include "llvm/IR/PatternMatch.h"50#include "llvm/IR/Type.h"51#include "llvm/IR/User.h"52#include "llvm/IR/Value.h"53#include "llvm/IR/Verifier.h"54#include "llvm/Support/BlockFrequency.h"55#include "llvm/Support/BranchProbability.h"56#include "llvm/Support/Casting.h"57#include "llvm/Support/CommandLine.h"58#include "llvm/Support/Debug.h"59#include "llvm/Support/ErrorHandling.h"60#include "llvm/Support/raw_ostream.h"61#include "llvm/Transforms/Utils/BasicBlockUtils.h"62#include <cassert>63#include <cstdint>64#include <iterator>65#include <map>66#include <utility>67#include <vector>6869using namespace llvm;70using namespace llvm::PatternMatch;71using ProfileCount = Function::ProfileCount;7273#define DEBUG_TYPE "code-extractor"7475// Provide a command-line option to aggregate function arguments into a struct76// for functions produced by the code extractor. This is useful when converting77// extracted functions to pthread-based code, as only one argument (void*) can78// be passed in to pthread_create().79static cl::opt<bool>80AggregateArgsOpt("aggregate-extracted-args", cl::Hidden,81cl::desc("Aggregate arguments to code-extracted functions"));8283/// Test whether a block is valid for extraction.84static bool isBlockValidForExtraction(const BasicBlock &BB,85const SetVector<BasicBlock *> &Result,86bool AllowVarArgs, bool AllowAlloca) {87// taking the address of a basic block moved to another function is illegal88if (BB.hasAddressTaken())89return false;9091// don't hoist code that uses another basicblock address, as it's likely to92// lead to unexpected behavior, like cross-function jumps93SmallPtrSet<User const *, 16> Visited;94SmallVector<User const *, 16> ToVisit;9596for (Instruction const &Inst : BB)97ToVisit.push_back(&Inst);9899while (!ToVisit.empty()) {100User const *Curr = ToVisit.pop_back_val();101if (!Visited.insert(Curr).second)102continue;103if (isa<BlockAddress const>(Curr))104return false; // even a reference to self is likely to be not compatible105106if (isa<Instruction>(Curr) && cast<Instruction>(Curr)->getParent() != &BB)107continue;108109for (auto const &U : Curr->operands()) {110if (auto *UU = dyn_cast<User>(U))111ToVisit.push_back(UU);112}113}114115// If explicitly requested, allow vastart and alloca. For invoke instructions116// verify that extraction is valid.117for (BasicBlock::const_iterator I = BB.begin(), E = BB.end(); I != E; ++I) {118if (isa<AllocaInst>(I)) {119if (!AllowAlloca)120return false;121continue;122}123124if (const auto *II = dyn_cast<InvokeInst>(I)) {125// Unwind destination (either a landingpad, catchswitch, or cleanuppad)126// must be a part of the subgraph which is being extracted.127if (auto *UBB = II->getUnwindDest())128if (!Result.count(UBB))129return false;130continue;131}132133// All catch handlers of a catchswitch instruction as well as the unwind134// destination must be in the subgraph.135if (const auto *CSI = dyn_cast<CatchSwitchInst>(I)) {136if (auto *UBB = CSI->getUnwindDest())137if (!Result.count(UBB))138return false;139for (const auto *HBB : CSI->handlers())140if (!Result.count(const_cast<BasicBlock*>(HBB)))141return false;142continue;143}144145// Make sure that entire catch handler is within subgraph. It is sufficient146// to check that catch return's block is in the list.147if (const auto *CPI = dyn_cast<CatchPadInst>(I)) {148for (const auto *U : CPI->users())149if (const auto *CRI = dyn_cast<CatchReturnInst>(U))150if (!Result.count(const_cast<BasicBlock*>(CRI->getParent())))151return false;152continue;153}154155// And do similar checks for cleanup handler - the entire handler must be156// in subgraph which is going to be extracted. For cleanup return should157// additionally check that the unwind destination is also in the subgraph.158if (const auto *CPI = dyn_cast<CleanupPadInst>(I)) {159for (const auto *U : CPI->users())160if (const auto *CRI = dyn_cast<CleanupReturnInst>(U))161if (!Result.count(const_cast<BasicBlock*>(CRI->getParent())))162return false;163continue;164}165if (const auto *CRI = dyn_cast<CleanupReturnInst>(I)) {166if (auto *UBB = CRI->getUnwindDest())167if (!Result.count(UBB))168return false;169continue;170}171172if (const CallInst *CI = dyn_cast<CallInst>(I)) {173if (const Function *F = CI->getCalledFunction()) {174auto IID = F->getIntrinsicID();175if (IID == Intrinsic::vastart) {176if (AllowVarArgs)177continue;178else179return false;180}181182// Currently, we miscompile outlined copies of eh_typid_for. There are183// proposals for fixing this in llvm.org/PR39545.184if (IID == Intrinsic::eh_typeid_for)185return false;186}187}188}189190return true;191}192193/// Build a set of blocks to extract if the input blocks are viable.194static SetVector<BasicBlock *>195buildExtractionBlockSet(ArrayRef<BasicBlock *> BBs, DominatorTree *DT,196bool AllowVarArgs, bool AllowAlloca) {197assert(!BBs.empty() && "The set of blocks to extract must be non-empty");198SetVector<BasicBlock *> Result;199200// Loop over the blocks, adding them to our set-vector, and aborting with an201// empty set if we encounter invalid blocks.202for (BasicBlock *BB : BBs) {203// If this block is dead, don't process it.204if (DT && !DT->isReachableFromEntry(BB))205continue;206207if (!Result.insert(BB))208llvm_unreachable("Repeated basic blocks in extraction input");209}210211LLVM_DEBUG(dbgs() << "Region front block: " << Result.front()->getName()212<< '\n');213214for (auto *BB : Result) {215if (!isBlockValidForExtraction(*BB, Result, AllowVarArgs, AllowAlloca))216return {};217218// Make sure that the first block is not a landing pad.219if (BB == Result.front()) {220if (BB->isEHPad()) {221LLVM_DEBUG(dbgs() << "The first block cannot be an unwind block\n");222return {};223}224continue;225}226227// All blocks other than the first must not have predecessors outside of228// the subgraph which is being extracted.229for (auto *PBB : predecessors(BB))230if (!Result.count(PBB)) {231LLVM_DEBUG(dbgs() << "No blocks in this region may have entries from "232"outside the region except for the first block!\n"233<< "Problematic source BB: " << BB->getName() << "\n"234<< "Problematic destination BB: " << PBB->getName()235<< "\n");236return {};237}238}239240return Result;241}242243CodeExtractor::CodeExtractor(ArrayRef<BasicBlock *> BBs, DominatorTree *DT,244bool AggregateArgs, BlockFrequencyInfo *BFI,245BranchProbabilityInfo *BPI, AssumptionCache *AC,246bool AllowVarArgs, bool AllowAlloca,247BasicBlock *AllocationBlock, std::string Suffix,248bool ArgsInZeroAddressSpace)249: DT(DT), AggregateArgs(AggregateArgs || AggregateArgsOpt), BFI(BFI),250BPI(BPI), AC(AC), AllocationBlock(AllocationBlock),251AllowVarArgs(AllowVarArgs),252Blocks(buildExtractionBlockSet(BBs, DT, AllowVarArgs, AllowAlloca)),253Suffix(Suffix), ArgsInZeroAddressSpace(ArgsInZeroAddressSpace) {}254255CodeExtractor::CodeExtractor(DominatorTree &DT, Loop &L, bool AggregateArgs,256BlockFrequencyInfo *BFI,257BranchProbabilityInfo *BPI, AssumptionCache *AC,258std::string Suffix)259: DT(&DT), AggregateArgs(AggregateArgs || AggregateArgsOpt), BFI(BFI),260BPI(BPI), AC(AC), AllocationBlock(nullptr), AllowVarArgs(false),261Blocks(buildExtractionBlockSet(L.getBlocks(), &DT,262/* AllowVarArgs */ false,263/* AllowAlloca */ false)),264Suffix(Suffix) {}265266/// definedInRegion - Return true if the specified value is defined in the267/// extracted region.268static bool definedInRegion(const SetVector<BasicBlock *> &Blocks, Value *V) {269if (Instruction *I = dyn_cast<Instruction>(V))270if (Blocks.count(I->getParent()))271return true;272return false;273}274275/// definedInCaller - Return true if the specified value is defined in the276/// function being code extracted, but not in the region being extracted.277/// These values must be passed in as live-ins to the function.278static bool definedInCaller(const SetVector<BasicBlock *> &Blocks, Value *V) {279if (isa<Argument>(V)) return true;280if (Instruction *I = dyn_cast<Instruction>(V))281if (!Blocks.count(I->getParent()))282return true;283return false;284}285286static BasicBlock *getCommonExitBlock(const SetVector<BasicBlock *> &Blocks) {287BasicBlock *CommonExitBlock = nullptr;288auto hasNonCommonExitSucc = [&](BasicBlock *Block) {289for (auto *Succ : successors(Block)) {290// Internal edges, ok.291if (Blocks.count(Succ))292continue;293if (!CommonExitBlock) {294CommonExitBlock = Succ;295continue;296}297if (CommonExitBlock != Succ)298return true;299}300return false;301};302303if (any_of(Blocks, hasNonCommonExitSucc))304return nullptr;305306return CommonExitBlock;307}308309CodeExtractorAnalysisCache::CodeExtractorAnalysisCache(Function &F) {310for (BasicBlock &BB : F) {311for (Instruction &II : BB.instructionsWithoutDebug())312if (auto *AI = dyn_cast<AllocaInst>(&II))313Allocas.push_back(AI);314315findSideEffectInfoForBlock(BB);316}317}318319void CodeExtractorAnalysisCache::findSideEffectInfoForBlock(BasicBlock &BB) {320for (Instruction &II : BB.instructionsWithoutDebug()) {321unsigned Opcode = II.getOpcode();322Value *MemAddr = nullptr;323switch (Opcode) {324case Instruction::Store:325case Instruction::Load: {326if (Opcode == Instruction::Store) {327StoreInst *SI = cast<StoreInst>(&II);328MemAddr = SI->getPointerOperand();329} else {330LoadInst *LI = cast<LoadInst>(&II);331MemAddr = LI->getPointerOperand();332}333// Global variable can not be aliased with locals.334if (isa<Constant>(MemAddr))335break;336Value *Base = MemAddr->stripInBoundsConstantOffsets();337if (!isa<AllocaInst>(Base)) {338SideEffectingBlocks.insert(&BB);339return;340}341BaseMemAddrs[&BB].insert(Base);342break;343}344default: {345IntrinsicInst *IntrInst = dyn_cast<IntrinsicInst>(&II);346if (IntrInst) {347if (IntrInst->isLifetimeStartOrEnd())348break;349SideEffectingBlocks.insert(&BB);350return;351}352// Treat all the other cases conservatively if it has side effects.353if (II.mayHaveSideEffects()) {354SideEffectingBlocks.insert(&BB);355return;356}357}358}359}360}361362bool CodeExtractorAnalysisCache::doesBlockContainClobberOfAddr(363BasicBlock &BB, AllocaInst *Addr) const {364if (SideEffectingBlocks.count(&BB))365return true;366auto It = BaseMemAddrs.find(&BB);367if (It != BaseMemAddrs.end())368return It->second.count(Addr);369return false;370}371372bool CodeExtractor::isLegalToShrinkwrapLifetimeMarkers(373const CodeExtractorAnalysisCache &CEAC, Instruction *Addr) const {374AllocaInst *AI = cast<AllocaInst>(Addr->stripInBoundsConstantOffsets());375Function *Func = (*Blocks.begin())->getParent();376for (BasicBlock &BB : *Func) {377if (Blocks.count(&BB))378continue;379if (CEAC.doesBlockContainClobberOfAddr(BB, AI))380return false;381}382return true;383}384385BasicBlock *386CodeExtractor::findOrCreateBlockForHoisting(BasicBlock *CommonExitBlock) {387BasicBlock *SinglePredFromOutlineRegion = nullptr;388assert(!Blocks.count(CommonExitBlock) &&389"Expect a block outside the region!");390for (auto *Pred : predecessors(CommonExitBlock)) {391if (!Blocks.count(Pred))392continue;393if (!SinglePredFromOutlineRegion) {394SinglePredFromOutlineRegion = Pred;395} else if (SinglePredFromOutlineRegion != Pred) {396SinglePredFromOutlineRegion = nullptr;397break;398}399}400401if (SinglePredFromOutlineRegion)402return SinglePredFromOutlineRegion;403404#ifndef NDEBUG405auto getFirstPHI = [](BasicBlock *BB) {406BasicBlock::iterator I = BB->begin();407PHINode *FirstPhi = nullptr;408while (I != BB->end()) {409PHINode *Phi = dyn_cast<PHINode>(I);410if (!Phi)411break;412if (!FirstPhi) {413FirstPhi = Phi;414break;415}416}417return FirstPhi;418};419// If there are any phi nodes, the single pred either exists or has already420// be created before code extraction.421assert(!getFirstPHI(CommonExitBlock) && "Phi not expected");422#endif423424BasicBlock *NewExitBlock = CommonExitBlock->splitBasicBlock(425CommonExitBlock->getFirstNonPHI()->getIterator());426427for (BasicBlock *Pred :428llvm::make_early_inc_range(predecessors(CommonExitBlock))) {429if (Blocks.count(Pred))430continue;431Pred->getTerminator()->replaceUsesOfWith(CommonExitBlock, NewExitBlock);432}433// Now add the old exit block to the outline region.434Blocks.insert(CommonExitBlock);435OldTargets.push_back(NewExitBlock);436return CommonExitBlock;437}438439// Find the pair of life time markers for address 'Addr' that are either440// defined inside the outline region or can legally be shrinkwrapped into the441// outline region. If there are not other untracked uses of the address, return442// the pair of markers if found; otherwise return a pair of nullptr.443CodeExtractor::LifetimeMarkerInfo444CodeExtractor::getLifetimeMarkers(const CodeExtractorAnalysisCache &CEAC,445Instruction *Addr,446BasicBlock *ExitBlock) const {447LifetimeMarkerInfo Info;448449for (User *U : Addr->users()) {450IntrinsicInst *IntrInst = dyn_cast<IntrinsicInst>(U);451if (IntrInst) {452// We don't model addresses with multiple start/end markers, but the453// markers do not need to be in the region.454if (IntrInst->getIntrinsicID() == Intrinsic::lifetime_start) {455if (Info.LifeStart)456return {};457Info.LifeStart = IntrInst;458continue;459}460if (IntrInst->getIntrinsicID() == Intrinsic::lifetime_end) {461if (Info.LifeEnd)462return {};463Info.LifeEnd = IntrInst;464continue;465}466// At this point, permit debug uses outside of the region.467// This is fixed in a later call to fixupDebugInfoPostExtraction().468if (isa<DbgInfoIntrinsic>(IntrInst))469continue;470}471// Find untracked uses of the address, bail.472if (!definedInRegion(Blocks, U))473return {};474}475476if (!Info.LifeStart || !Info.LifeEnd)477return {};478479Info.SinkLifeStart = !definedInRegion(Blocks, Info.LifeStart);480Info.HoistLifeEnd = !definedInRegion(Blocks, Info.LifeEnd);481// Do legality check.482if ((Info.SinkLifeStart || Info.HoistLifeEnd) &&483!isLegalToShrinkwrapLifetimeMarkers(CEAC, Addr))484return {};485486// Check to see if we have a place to do hoisting, if not, bail.487if (Info.HoistLifeEnd && !ExitBlock)488return {};489490return Info;491}492493void CodeExtractor::findAllocas(const CodeExtractorAnalysisCache &CEAC,494ValueSet &SinkCands, ValueSet &HoistCands,495BasicBlock *&ExitBlock) const {496Function *Func = (*Blocks.begin())->getParent();497ExitBlock = getCommonExitBlock(Blocks);498499auto moveOrIgnoreLifetimeMarkers =500[&](const LifetimeMarkerInfo &LMI) -> bool {501if (!LMI.LifeStart)502return false;503if (LMI.SinkLifeStart) {504LLVM_DEBUG(dbgs() << "Sinking lifetime.start: " << *LMI.LifeStart505<< "\n");506SinkCands.insert(LMI.LifeStart);507}508if (LMI.HoistLifeEnd) {509LLVM_DEBUG(dbgs() << "Hoisting lifetime.end: " << *LMI.LifeEnd << "\n");510HoistCands.insert(LMI.LifeEnd);511}512return true;513};514515// Look up allocas in the original function in CodeExtractorAnalysisCache, as516// this is much faster than walking all the instructions.517for (AllocaInst *AI : CEAC.getAllocas()) {518BasicBlock *BB = AI->getParent();519if (Blocks.count(BB))520continue;521522// As a prior call to extractCodeRegion() may have shrinkwrapped the alloca,523// check whether it is actually still in the original function.524Function *AIFunc = BB->getParent();525if (AIFunc != Func)526continue;527528LifetimeMarkerInfo MarkerInfo = getLifetimeMarkers(CEAC, AI, ExitBlock);529bool Moved = moveOrIgnoreLifetimeMarkers(MarkerInfo);530if (Moved) {531LLVM_DEBUG(dbgs() << "Sinking alloca: " << *AI << "\n");532SinkCands.insert(AI);533continue;534}535536// Find bitcasts in the outlined region that have lifetime marker users537// outside that region. Replace the lifetime marker use with an538// outside region bitcast to avoid unnecessary alloca/reload instructions539// and extra lifetime markers.540SmallVector<Instruction *, 2> LifetimeBitcastUsers;541for (User *U : AI->users()) {542if (!definedInRegion(Blocks, U))543continue;544545if (U->stripInBoundsConstantOffsets() != AI)546continue;547548Instruction *Bitcast = cast<Instruction>(U);549for (User *BU : Bitcast->users()) {550IntrinsicInst *IntrInst = dyn_cast<IntrinsicInst>(BU);551if (!IntrInst)552continue;553554if (!IntrInst->isLifetimeStartOrEnd())555continue;556557if (definedInRegion(Blocks, IntrInst))558continue;559560LLVM_DEBUG(dbgs() << "Replace use of extracted region bitcast"561<< *Bitcast << " in out-of-region lifetime marker "562<< *IntrInst << "\n");563LifetimeBitcastUsers.push_back(IntrInst);564}565}566567for (Instruction *I : LifetimeBitcastUsers) {568Module *M = AIFunc->getParent();569LLVMContext &Ctx = M->getContext();570auto *Int8PtrTy = PointerType::getUnqual(Ctx);571CastInst *CastI =572CastInst::CreatePointerCast(AI, Int8PtrTy, "lt.cast", I->getIterator());573I->replaceUsesOfWith(I->getOperand(1), CastI);574}575576// Follow any bitcasts.577SmallVector<Instruction *, 2> Bitcasts;578SmallVector<LifetimeMarkerInfo, 2> BitcastLifetimeInfo;579for (User *U : AI->users()) {580if (U->stripInBoundsConstantOffsets() == AI) {581Instruction *Bitcast = cast<Instruction>(U);582LifetimeMarkerInfo LMI = getLifetimeMarkers(CEAC, Bitcast, ExitBlock);583if (LMI.LifeStart) {584Bitcasts.push_back(Bitcast);585BitcastLifetimeInfo.push_back(LMI);586continue;587}588}589590// Found unknown use of AI.591if (!definedInRegion(Blocks, U)) {592Bitcasts.clear();593break;594}595}596597// Either no bitcasts reference the alloca or there are unknown uses.598if (Bitcasts.empty())599continue;600601LLVM_DEBUG(dbgs() << "Sinking alloca (via bitcast): " << *AI << "\n");602SinkCands.insert(AI);603for (unsigned I = 0, E = Bitcasts.size(); I != E; ++I) {604Instruction *BitcastAddr = Bitcasts[I];605const LifetimeMarkerInfo &LMI = BitcastLifetimeInfo[I];606assert(LMI.LifeStart &&607"Unsafe to sink bitcast without lifetime markers");608moveOrIgnoreLifetimeMarkers(LMI);609if (!definedInRegion(Blocks, BitcastAddr)) {610LLVM_DEBUG(dbgs() << "Sinking bitcast-of-alloca: " << *BitcastAddr611<< "\n");612SinkCands.insert(BitcastAddr);613}614}615}616}617618bool CodeExtractor::isEligible() const {619if (Blocks.empty())620return false;621BasicBlock *Header = *Blocks.begin();622Function *F = Header->getParent();623624// For functions with varargs, check that varargs handling is only done in the625// outlined function, i.e vastart and vaend are only used in outlined blocks.626if (AllowVarArgs && F->getFunctionType()->isVarArg()) {627auto containsVarArgIntrinsic = [](const Instruction &I) {628if (const CallInst *CI = dyn_cast<CallInst>(&I))629if (const Function *Callee = CI->getCalledFunction())630return Callee->getIntrinsicID() == Intrinsic::vastart ||631Callee->getIntrinsicID() == Intrinsic::vaend;632return false;633};634635for (auto &BB : *F) {636if (Blocks.count(&BB))637continue;638if (llvm::any_of(BB, containsVarArgIntrinsic))639return false;640}641}642return true;643}644645void CodeExtractor::findInputsOutputs(ValueSet &Inputs, ValueSet &Outputs,646const ValueSet &SinkCands) const {647for (BasicBlock *BB : Blocks) {648// If a used value is defined outside the region, it's an input. If an649// instruction is used outside the region, it's an output.650for (Instruction &II : *BB) {651for (auto &OI : II.operands()) {652Value *V = OI;653if (!SinkCands.count(V) && definedInCaller(Blocks, V))654Inputs.insert(V);655}656657for (User *U : II.users())658if (!definedInRegion(Blocks, U)) {659Outputs.insert(&II);660break;661}662}663}664}665666/// severSplitPHINodesOfEntry - If a PHI node has multiple inputs from outside667/// of the region, we need to split the entry block of the region so that the668/// PHI node is easier to deal with.669void CodeExtractor::severSplitPHINodesOfEntry(BasicBlock *&Header) {670unsigned NumPredsFromRegion = 0;671unsigned NumPredsOutsideRegion = 0;672673if (Header != &Header->getParent()->getEntryBlock()) {674PHINode *PN = dyn_cast<PHINode>(Header->begin());675if (!PN) return; // No PHI nodes.676677// If the header node contains any PHI nodes, check to see if there is more678// than one entry from outside the region. If so, we need to sever the679// header block into two.680for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)681if (Blocks.count(PN->getIncomingBlock(i)))682++NumPredsFromRegion;683else684++NumPredsOutsideRegion;685686// If there is one (or fewer) predecessor from outside the region, we don't687// need to do anything special.688if (NumPredsOutsideRegion <= 1) return;689}690691// Otherwise, we need to split the header block into two pieces: one692// containing PHI nodes merging values from outside of the region, and a693// second that contains all of the code for the block and merges back any694// incoming values from inside of the region.695BasicBlock *NewBB = SplitBlock(Header, Header->getFirstNonPHI(), DT);696697// We only want to code extract the second block now, and it becomes the new698// header of the region.699BasicBlock *OldPred = Header;700Blocks.remove(OldPred);701Blocks.insert(NewBB);702Header = NewBB;703704// Okay, now we need to adjust the PHI nodes and any branches from within the705// region to go to the new header block instead of the old header block.706if (NumPredsFromRegion) {707PHINode *PN = cast<PHINode>(OldPred->begin());708// Loop over all of the predecessors of OldPred that are in the region,709// changing them to branch to NewBB instead.710for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)711if (Blocks.count(PN->getIncomingBlock(i))) {712Instruction *TI = PN->getIncomingBlock(i)->getTerminator();713TI->replaceUsesOfWith(OldPred, NewBB);714}715716// Okay, everything within the region is now branching to the right block, we717// just have to update the PHI nodes now, inserting PHI nodes into NewBB.718BasicBlock::iterator AfterPHIs;719for (AfterPHIs = OldPred->begin(); isa<PHINode>(AfterPHIs); ++AfterPHIs) {720PHINode *PN = cast<PHINode>(AfterPHIs);721// Create a new PHI node in the new region, which has an incoming value722// from OldPred of PN.723PHINode *NewPN = PHINode::Create(PN->getType(), 1 + NumPredsFromRegion,724PN->getName() + ".ce");725NewPN->insertBefore(NewBB->begin());726PN->replaceAllUsesWith(NewPN);727NewPN->addIncoming(PN, OldPred);728729// Loop over all of the incoming value in PN, moving them to NewPN if they730// are from the extracted region.731for (unsigned i = 0; i != PN->getNumIncomingValues(); ++i) {732if (Blocks.count(PN->getIncomingBlock(i))) {733NewPN->addIncoming(PN->getIncomingValue(i), PN->getIncomingBlock(i));734PN->removeIncomingValue(i);735--i;736}737}738}739}740}741742/// severSplitPHINodesOfExits - if PHI nodes in exit blocks have inputs from743/// outlined region, we split these PHIs on two: one with inputs from region744/// and other with remaining incoming blocks; then first PHIs are placed in745/// outlined region.746void CodeExtractor::severSplitPHINodesOfExits(747const SetVector<BasicBlock *> &Exits) {748for (BasicBlock *ExitBB : Exits) {749BasicBlock *NewBB = nullptr;750751for (PHINode &PN : ExitBB->phis()) {752// Find all incoming values from the outlining region.753SmallVector<unsigned, 2> IncomingVals;754for (unsigned i = 0; i < PN.getNumIncomingValues(); ++i)755if (Blocks.count(PN.getIncomingBlock(i)))756IncomingVals.push_back(i);757758// Do not process PHI if there is one (or fewer) predecessor from region.759// If PHI has exactly one predecessor from region, only this one incoming760// will be replaced on codeRepl block, so it should be safe to skip PHI.761if (IncomingVals.size() <= 1)762continue;763764// Create block for new PHIs and add it to the list of outlined if it765// wasn't done before.766if (!NewBB) {767NewBB = BasicBlock::Create(ExitBB->getContext(),768ExitBB->getName() + ".split",769ExitBB->getParent(), ExitBB);770NewBB->IsNewDbgInfoFormat = ExitBB->IsNewDbgInfoFormat;771SmallVector<BasicBlock *, 4> Preds(predecessors(ExitBB));772for (BasicBlock *PredBB : Preds)773if (Blocks.count(PredBB))774PredBB->getTerminator()->replaceUsesOfWith(ExitBB, NewBB);775BranchInst::Create(ExitBB, NewBB);776Blocks.insert(NewBB);777}778779// Split this PHI.780PHINode *NewPN = PHINode::Create(PN.getType(), IncomingVals.size(),781PN.getName() + ".ce");782NewPN->insertBefore(NewBB->getFirstNonPHIIt());783for (unsigned i : IncomingVals)784NewPN->addIncoming(PN.getIncomingValue(i), PN.getIncomingBlock(i));785for (unsigned i : reverse(IncomingVals))786PN.removeIncomingValue(i, false);787PN.addIncoming(NewPN, NewBB);788}789}790}791792void CodeExtractor::splitReturnBlocks() {793for (BasicBlock *Block : Blocks)794if (ReturnInst *RI = dyn_cast<ReturnInst>(Block->getTerminator())) {795BasicBlock *New =796Block->splitBasicBlock(RI->getIterator(), Block->getName() + ".ret");797if (DT) {798// Old dominates New. New node dominates all other nodes dominated799// by Old.800DomTreeNode *OldNode = DT->getNode(Block);801SmallVector<DomTreeNode *, 8> Children(OldNode->begin(),802OldNode->end());803804DomTreeNode *NewNode = DT->addNewBlock(New, Block);805806for (DomTreeNode *I : Children)807DT->changeImmediateDominator(I, NewNode);808}809}810}811812/// constructFunction - make a function based on inputs and outputs, as follows:813/// f(in0, ..., inN, out0, ..., outN)814Function *CodeExtractor::constructFunction(const ValueSet &inputs,815const ValueSet &outputs,816BasicBlock *header,817BasicBlock *newRootNode,818BasicBlock *newHeader,819Function *oldFunction,820Module *M) {821LLVM_DEBUG(dbgs() << "inputs: " << inputs.size() << "\n");822LLVM_DEBUG(dbgs() << "outputs: " << outputs.size() << "\n");823824// This function returns unsigned, outputs will go back by reference.825switch (NumExitBlocks) {826case 0:827case 1: RetTy = Type::getVoidTy(header->getContext()); break;828case 2: RetTy = Type::getInt1Ty(header->getContext()); break;829default: RetTy = Type::getInt16Ty(header->getContext()); break;830}831832std::vector<Type *> ParamTy;833std::vector<Type *> AggParamTy;834ValueSet StructValues;835const DataLayout &DL = M->getDataLayout();836837// Add the types of the input values to the function's argument list838for (Value *value : inputs) {839LLVM_DEBUG(dbgs() << "value used in func: " << *value << "\n");840if (AggregateArgs && !ExcludeArgsFromAggregate.contains(value)) {841AggParamTy.push_back(value->getType());842StructValues.insert(value);843} else844ParamTy.push_back(value->getType());845}846847// Add the types of the output values to the function's argument list.848for (Value *output : outputs) {849LLVM_DEBUG(dbgs() << "instr used in func: " << *output << "\n");850if (AggregateArgs && !ExcludeArgsFromAggregate.contains(output)) {851AggParamTy.push_back(output->getType());852StructValues.insert(output);853} else854ParamTy.push_back(855PointerType::get(output->getType(), DL.getAllocaAddrSpace()));856}857858assert(859(ParamTy.size() + AggParamTy.size()) ==860(inputs.size() + outputs.size()) &&861"Number of scalar and aggregate params does not match inputs, outputs");862assert((StructValues.empty() || AggregateArgs) &&863"Expeced StructValues only with AggregateArgs set");864865// Concatenate scalar and aggregate params in ParamTy.866size_t NumScalarParams = ParamTy.size();867StructType *StructTy = nullptr;868if (AggregateArgs && !AggParamTy.empty()) {869StructTy = StructType::get(M->getContext(), AggParamTy);870ParamTy.push_back(PointerType::get(871StructTy, ArgsInZeroAddressSpace ? 0 : DL.getAllocaAddrSpace()));872}873874LLVM_DEBUG({875dbgs() << "Function type: " << *RetTy << " f(";876for (Type *i : ParamTy)877dbgs() << *i << ", ";878dbgs() << ")\n";879});880881FunctionType *funcType = FunctionType::get(882RetTy, ParamTy, AllowVarArgs && oldFunction->isVarArg());883884std::string SuffixToUse =885Suffix.empty()886? (header->getName().empty() ? "extracted" : header->getName().str())887: Suffix;888// Create the new function889Function *newFunction = Function::Create(890funcType, GlobalValue::InternalLinkage, oldFunction->getAddressSpace(),891oldFunction->getName() + "." + SuffixToUse, M);892newFunction->IsNewDbgInfoFormat = oldFunction->IsNewDbgInfoFormat;893894// Inherit all of the target dependent attributes and white-listed895// target independent attributes.896// (e.g. If the extracted region contains a call to an x86.sse897// instruction we need to make sure that the extracted region has the898// "target-features" attribute allowing it to be lowered.899// FIXME: This should be changed to check to see if a specific900// attribute can not be inherited.901for (const auto &Attr : oldFunction->getAttributes().getFnAttrs()) {902if (Attr.isStringAttribute()) {903if (Attr.getKindAsString() == "thunk")904continue;905} else906switch (Attr.getKindAsEnum()) {907// Those attributes cannot be propagated safely. Explicitly list them908// here so we get a warning if new attributes are added.909case Attribute::AllocSize:910case Attribute::Builtin:911case Attribute::Convergent:912case Attribute::JumpTable:913case Attribute::Naked:914case Attribute::NoBuiltin:915case Attribute::NoMerge:916case Attribute::NoReturn:917case Attribute::NoSync:918case Attribute::ReturnsTwice:919case Attribute::Speculatable:920case Attribute::StackAlignment:921case Attribute::WillReturn:922case Attribute::AllocKind:923case Attribute::PresplitCoroutine:924case Attribute::Memory:925case Attribute::NoFPClass:926case Attribute::CoroDestroyOnlyWhenComplete:927continue;928// Those attributes should be safe to propagate to the extracted function.929case Attribute::AlwaysInline:930case Attribute::Cold:931case Attribute::DisableSanitizerInstrumentation:932case Attribute::FnRetThunkExtern:933case Attribute::Hot:934case Attribute::HybridPatchable:935case Attribute::NoRecurse:936case Attribute::InlineHint:937case Attribute::MinSize:938case Attribute::NoCallback:939case Attribute::NoDuplicate:940case Attribute::NoFree:941case Attribute::NoImplicitFloat:942case Attribute::NoInline:943case Attribute::NonLazyBind:944case Attribute::NoRedZone:945case Attribute::NoUnwind:946case Attribute::NoSanitizeBounds:947case Attribute::NoSanitizeCoverage:948case Attribute::NullPointerIsValid:949case Attribute::OptimizeForDebugging:950case Attribute::OptForFuzzing:951case Attribute::OptimizeNone:952case Attribute::OptimizeForSize:953case Attribute::SafeStack:954case Attribute::ShadowCallStack:955case Attribute::SanitizeAddress:956case Attribute::SanitizeMemory:957case Attribute::SanitizeNumericalStability:958case Attribute::SanitizeThread:959case Attribute::SanitizeHWAddress:960case Attribute::SanitizeMemTag:961case Attribute::SpeculativeLoadHardening:962case Attribute::StackProtect:963case Attribute::StackProtectReq:964case Attribute::StackProtectStrong:965case Attribute::StrictFP:966case Attribute::UWTable:967case Attribute::VScaleRange:968case Attribute::NoCfCheck:969case Attribute::MustProgress:970case Attribute::NoProfile:971case Attribute::SkipProfile:972break;973// These attributes cannot be applied to functions.974case Attribute::Alignment:975case Attribute::AllocatedPointer:976case Attribute::AllocAlign:977case Attribute::ByVal:978case Attribute::Dereferenceable:979case Attribute::DereferenceableOrNull:980case Attribute::ElementType:981case Attribute::InAlloca:982case Attribute::InReg:983case Attribute::Nest:984case Attribute::NoAlias:985case Attribute::NoCapture:986case Attribute::NoUndef:987case Attribute::NonNull:988case Attribute::Preallocated:989case Attribute::ReadNone:990case Attribute::ReadOnly:991case Attribute::Returned:992case Attribute::SExt:993case Attribute::StructRet:994case Attribute::SwiftError:995case Attribute::SwiftSelf:996case Attribute::SwiftAsync:997case Attribute::ZExt:998case Attribute::ImmArg:999case Attribute::ByRef:1000case Attribute::WriteOnly:1001case Attribute::Writable:1002case Attribute::DeadOnUnwind:1003case Attribute::Range:1004case Attribute::Initializes:1005// These are not really attributes.1006case Attribute::None:1007case Attribute::EndAttrKinds:1008case Attribute::EmptyKey:1009case Attribute::TombstoneKey:1010llvm_unreachable("Not a function attribute");1011}10121013newFunction->addFnAttr(Attr);1014}10151016if (NumExitBlocks == 0) {1017// Mark the new function `noreturn` if applicable. Terminators which resume1018// exception propagation are treated as returning instructions. This is to1019// avoid inserting traps after calls to outlined functions which unwind.1020if (none_of(Blocks, [](const BasicBlock *BB) {1021const Instruction *Term = BB->getTerminator();1022return isa<ReturnInst>(Term) || isa<ResumeInst>(Term);1023}))1024newFunction->setDoesNotReturn();1025}10261027newFunction->insert(newFunction->end(), newRootNode);10281029// Create scalar and aggregate iterators to name all of the arguments we1030// inserted.1031Function::arg_iterator ScalarAI = newFunction->arg_begin();1032Function::arg_iterator AggAI = std::next(ScalarAI, NumScalarParams);10331034// Rewrite all users of the inputs in the extracted region to use the1035// arguments (or appropriate addressing into struct) instead.1036for (unsigned i = 0, e = inputs.size(), aggIdx = 0; i != e; ++i) {1037Value *RewriteVal;1038if (AggregateArgs && StructValues.contains(inputs[i])) {1039Value *Idx[2];1040Idx[0] = Constant::getNullValue(Type::getInt32Ty(header->getContext()));1041Idx[1] = ConstantInt::get(Type::getInt32Ty(header->getContext()), aggIdx);1042BasicBlock::iterator TI = newFunction->begin()->getTerminator()->getIterator();1043GetElementPtrInst *GEP = GetElementPtrInst::Create(1044StructTy, &*AggAI, Idx, "gep_" + inputs[i]->getName(), TI);1045RewriteVal = new LoadInst(StructTy->getElementType(aggIdx), GEP,1046"loadgep_" + inputs[i]->getName(), TI);1047++aggIdx;1048} else1049RewriteVal = &*ScalarAI++;10501051std::vector<User *> Users(inputs[i]->user_begin(), inputs[i]->user_end());1052for (User *use : Users)1053if (Instruction *inst = dyn_cast<Instruction>(use))1054if (Blocks.count(inst->getParent()))1055inst->replaceUsesOfWith(inputs[i], RewriteVal);1056}10571058// Set names for input and output arguments.1059if (NumScalarParams) {1060ScalarAI = newFunction->arg_begin();1061for (unsigned i = 0, e = inputs.size(); i != e; ++i, ++ScalarAI)1062if (!StructValues.contains(inputs[i]))1063ScalarAI->setName(inputs[i]->getName());1064for (unsigned i = 0, e = outputs.size(); i != e; ++i, ++ScalarAI)1065if (!StructValues.contains(outputs[i]))1066ScalarAI->setName(outputs[i]->getName() + ".out");1067}10681069// Rewrite branches to basic blocks outside of the loop to new dummy blocks1070// within the new function. This must be done before we lose track of which1071// blocks were originally in the code region.1072std::vector<User *> Users(header->user_begin(), header->user_end());1073for (auto &U : Users)1074// The BasicBlock which contains the branch is not in the region1075// modify the branch target to a new block1076if (Instruction *I = dyn_cast<Instruction>(U))1077if (I->isTerminator() && I->getFunction() == oldFunction &&1078!Blocks.count(I->getParent()))1079I->replaceUsesOfWith(header, newHeader);10801081return newFunction;1082}10831084/// Erase lifetime.start markers which reference inputs to the extraction1085/// region, and insert the referenced memory into \p LifetimesStart.1086///1087/// The extraction region is defined by a set of blocks (\p Blocks), and a set1088/// of allocas which will be moved from the caller function into the extracted1089/// function (\p SunkAllocas).1090static void eraseLifetimeMarkersOnInputs(const SetVector<BasicBlock *> &Blocks,1091const SetVector<Value *> &SunkAllocas,1092SetVector<Value *> &LifetimesStart) {1093for (BasicBlock *BB : Blocks) {1094for (Instruction &I : llvm::make_early_inc_range(*BB)) {1095auto *II = dyn_cast<IntrinsicInst>(&I);1096if (!II || !II->isLifetimeStartOrEnd())1097continue;10981099// Get the memory operand of the lifetime marker. If the underlying1100// object is a sunk alloca, or is otherwise defined in the extraction1101// region, the lifetime marker must not be erased.1102Value *Mem = II->getOperand(1)->stripInBoundsOffsets();1103if (SunkAllocas.count(Mem) || definedInRegion(Blocks, Mem))1104continue;11051106if (II->getIntrinsicID() == Intrinsic::lifetime_start)1107LifetimesStart.insert(Mem);1108II->eraseFromParent();1109}1110}1111}11121113/// Insert lifetime start/end markers surrounding the call to the new function1114/// for objects defined in the caller.1115static void insertLifetimeMarkersSurroundingCall(1116Module *M, ArrayRef<Value *> LifetimesStart, ArrayRef<Value *> LifetimesEnd,1117CallInst *TheCall) {1118LLVMContext &Ctx = M->getContext();1119auto NegativeOne = ConstantInt::getSigned(Type::getInt64Ty(Ctx), -1);1120Instruction *Term = TheCall->getParent()->getTerminator();11211122// Emit lifetime markers for the pointers given in \p Objects. Insert the1123// markers before the call if \p InsertBefore, and after the call otherwise.1124auto insertMarkers = [&](Intrinsic::ID MarkerFunc, ArrayRef<Value *> Objects,1125bool InsertBefore) {1126for (Value *Mem : Objects) {1127assert((!isa<Instruction>(Mem) || cast<Instruction>(Mem)->getFunction() ==1128TheCall->getFunction()) &&1129"Input memory not defined in original function");11301131Function *Func = Intrinsic::getDeclaration(M, MarkerFunc, Mem->getType());1132auto Marker = CallInst::Create(Func, {NegativeOne, Mem});1133if (InsertBefore)1134Marker->insertBefore(TheCall);1135else1136Marker->insertBefore(Term);1137}1138};11391140if (!LifetimesStart.empty()) {1141insertMarkers(Intrinsic::lifetime_start, LifetimesStart,1142/*InsertBefore=*/true);1143}11441145if (!LifetimesEnd.empty()) {1146insertMarkers(Intrinsic::lifetime_end, LifetimesEnd,1147/*InsertBefore=*/false);1148}1149}11501151/// emitCallAndSwitchStatement - This method sets up the caller side by adding1152/// the call instruction, splitting any PHI nodes in the header block as1153/// necessary.1154CallInst *CodeExtractor::emitCallAndSwitchStatement(Function *newFunction,1155BasicBlock *codeReplacer,1156ValueSet &inputs,1157ValueSet &outputs) {1158// Emit a call to the new function, passing in: *pointer to struct (if1159// aggregating parameters), or plan inputs and allocated memory for outputs1160std::vector<Value *> params, ReloadOutputs, Reloads;1161ValueSet StructValues;11621163Module *M = newFunction->getParent();1164LLVMContext &Context = M->getContext();1165const DataLayout &DL = M->getDataLayout();1166CallInst *call = nullptr;11671168// Add inputs as params, or to be filled into the struct1169unsigned ScalarInputArgNo = 0;1170SmallVector<unsigned, 1> SwiftErrorArgs;1171for (Value *input : inputs) {1172if (AggregateArgs && !ExcludeArgsFromAggregate.contains(input))1173StructValues.insert(input);1174else {1175params.push_back(input);1176if (input->isSwiftError())1177SwiftErrorArgs.push_back(ScalarInputArgNo);1178}1179++ScalarInputArgNo;1180}11811182// Create allocas for the outputs1183unsigned ScalarOutputArgNo = 0;1184for (Value *output : outputs) {1185if (AggregateArgs && !ExcludeArgsFromAggregate.contains(output)) {1186StructValues.insert(output);1187} else {1188AllocaInst *alloca =1189new AllocaInst(output->getType(), DL.getAllocaAddrSpace(),1190nullptr, output->getName() + ".loc",1191codeReplacer->getParent()->front().begin());1192ReloadOutputs.push_back(alloca);1193params.push_back(alloca);1194++ScalarOutputArgNo;1195}1196}11971198StructType *StructArgTy = nullptr;1199AllocaInst *Struct = nullptr;1200unsigned NumAggregatedInputs = 0;1201if (AggregateArgs && !StructValues.empty()) {1202std::vector<Type *> ArgTypes;1203for (Value *V : StructValues)1204ArgTypes.push_back(V->getType());12051206// Allocate a struct at the beginning of this function1207StructArgTy = StructType::get(newFunction->getContext(), ArgTypes);1208Struct = new AllocaInst(1209StructArgTy, DL.getAllocaAddrSpace(), nullptr, "structArg",1210AllocationBlock ? AllocationBlock->getFirstInsertionPt()1211: codeReplacer->getParent()->front().begin());12121213if (ArgsInZeroAddressSpace && DL.getAllocaAddrSpace() != 0) {1214auto *StructSpaceCast = new AddrSpaceCastInst(1215Struct, PointerType ::get(Context, 0), "structArg.ascast");1216StructSpaceCast->insertAfter(Struct);1217params.push_back(StructSpaceCast);1218} else {1219params.push_back(Struct);1220}1221// Store aggregated inputs in the struct.1222for (unsigned i = 0, e = StructValues.size(); i != e; ++i) {1223if (inputs.contains(StructValues[i])) {1224Value *Idx[2];1225Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));1226Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), i);1227GetElementPtrInst *GEP = GetElementPtrInst::Create(1228StructArgTy, Struct, Idx, "gep_" + StructValues[i]->getName());1229GEP->insertInto(codeReplacer, codeReplacer->end());1230new StoreInst(StructValues[i], GEP, codeReplacer);1231NumAggregatedInputs++;1232}1233}1234}12351236// Emit the call to the function1237call = CallInst::Create(newFunction, params,1238NumExitBlocks > 1 ? "targetBlock" : "");1239// Add debug location to the new call, if the original function has debug1240// info. In that case, the terminator of the entry block of the extracted1241// function contains the first debug location of the extracted function,1242// set in extractCodeRegion.1243if (codeReplacer->getParent()->getSubprogram()) {1244if (auto DL = newFunction->getEntryBlock().getTerminator()->getDebugLoc())1245call->setDebugLoc(DL);1246}1247call->insertInto(codeReplacer, codeReplacer->end());12481249// Set swifterror parameter attributes.1250for (unsigned SwiftErrArgNo : SwiftErrorArgs) {1251call->addParamAttr(SwiftErrArgNo, Attribute::SwiftError);1252newFunction->addParamAttr(SwiftErrArgNo, Attribute::SwiftError);1253}12541255// Reload the outputs passed in by reference, use the struct if output is in1256// the aggregate or reload from the scalar argument.1257for (unsigned i = 0, e = outputs.size(), scalarIdx = 0,1258aggIdx = NumAggregatedInputs;1259i != e; ++i) {1260Value *Output = nullptr;1261if (AggregateArgs && StructValues.contains(outputs[i])) {1262Value *Idx[2];1263Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));1264Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), aggIdx);1265GetElementPtrInst *GEP = GetElementPtrInst::Create(1266StructArgTy, Struct, Idx, "gep_reload_" + outputs[i]->getName());1267GEP->insertInto(codeReplacer, codeReplacer->end());1268Output = GEP;1269++aggIdx;1270} else {1271Output = ReloadOutputs[scalarIdx];1272++scalarIdx;1273}1274LoadInst *load = new LoadInst(outputs[i]->getType(), Output,1275outputs[i]->getName() + ".reload",1276codeReplacer);1277Reloads.push_back(load);1278std::vector<User *> Users(outputs[i]->user_begin(), outputs[i]->user_end());1279for (User *U : Users) {1280Instruction *inst = cast<Instruction>(U);1281if (!Blocks.count(inst->getParent()))1282inst->replaceUsesOfWith(outputs[i], load);1283}1284}12851286// Now we can emit a switch statement using the call as a value.1287SwitchInst *TheSwitch =1288SwitchInst::Create(Constant::getNullValue(Type::getInt16Ty(Context)),1289codeReplacer, 0, codeReplacer);12901291// Since there may be multiple exits from the original region, make the new1292// function return an unsigned, switch on that number. This loop iterates1293// over all of the blocks in the extracted region, updating any terminator1294// instructions in the to-be-extracted region that branch to blocks that are1295// not in the region to be extracted.1296std::map<BasicBlock *, BasicBlock *> ExitBlockMap;12971298// Iterate over the previously collected targets, and create new blocks inside1299// the function to branch to.1300unsigned switchVal = 0;1301for (BasicBlock *OldTarget : OldTargets) {1302if (Blocks.count(OldTarget))1303continue;1304BasicBlock *&NewTarget = ExitBlockMap[OldTarget];1305if (NewTarget)1306continue;13071308// If we don't already have an exit stub for this non-extracted1309// destination, create one now!1310NewTarget = BasicBlock::Create(Context,1311OldTarget->getName() + ".exitStub",1312newFunction);1313unsigned SuccNum = switchVal++;13141315Value *brVal = nullptr;1316assert(NumExitBlocks < 0xffff && "too many exit blocks for switch");1317switch (NumExitBlocks) {1318case 0:1319case 1: break; // No value needed.1320case 2: // Conditional branch, return a bool1321brVal = ConstantInt::get(Type::getInt1Ty(Context), !SuccNum);1322break;1323default:1324brVal = ConstantInt::get(Type::getInt16Ty(Context), SuccNum);1325break;1326}13271328ReturnInst::Create(Context, brVal, NewTarget);13291330// Update the switch instruction.1331TheSwitch->addCase(ConstantInt::get(Type::getInt16Ty(Context),1332SuccNum),1333OldTarget);1334}13351336for (BasicBlock *Block : Blocks) {1337Instruction *TI = Block->getTerminator();1338for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {1339if (Blocks.count(TI->getSuccessor(i)))1340continue;1341BasicBlock *OldTarget = TI->getSuccessor(i);1342// add a new basic block which returns the appropriate value1343BasicBlock *NewTarget = ExitBlockMap[OldTarget];1344assert(NewTarget && "Unknown target block!");13451346// rewrite the original branch instruction with this new target1347TI->setSuccessor(i, NewTarget);1348}1349}13501351// Store the arguments right after the definition of output value.1352// This should be proceeded after creating exit stubs to be ensure that invoke1353// result restore will be placed in the outlined function.1354Function::arg_iterator ScalarOutputArgBegin = newFunction->arg_begin();1355std::advance(ScalarOutputArgBegin, ScalarInputArgNo);1356Function::arg_iterator AggOutputArgBegin = newFunction->arg_begin();1357std::advance(AggOutputArgBegin, ScalarInputArgNo + ScalarOutputArgNo);13581359for (unsigned i = 0, e = outputs.size(), aggIdx = NumAggregatedInputs; i != e;1360++i) {1361auto *OutI = dyn_cast<Instruction>(outputs[i]);1362if (!OutI)1363continue;13641365// Find proper insertion point.1366BasicBlock::iterator InsertPt;1367// In case OutI is an invoke, we insert the store at the beginning in the1368// 'normal destination' BB. Otherwise we insert the store right after OutI.1369if (auto *InvokeI = dyn_cast<InvokeInst>(OutI))1370InsertPt = InvokeI->getNormalDest()->getFirstInsertionPt();1371else if (auto *Phi = dyn_cast<PHINode>(OutI))1372InsertPt = Phi->getParent()->getFirstInsertionPt();1373else1374InsertPt = std::next(OutI->getIterator());13751376assert((InsertPt->getFunction() == newFunction ||1377Blocks.count(InsertPt->getParent())) &&1378"InsertPt should be in new function");1379if (AggregateArgs && StructValues.contains(outputs[i])) {1380assert(AggOutputArgBegin != newFunction->arg_end() &&1381"Number of aggregate output arguments should match "1382"the number of defined values");1383Value *Idx[2];1384Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));1385Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), aggIdx);1386GetElementPtrInst *GEP = GetElementPtrInst::Create(1387StructArgTy, &*AggOutputArgBegin, Idx, "gep_" + outputs[i]->getName(),1388InsertPt);1389new StoreInst(outputs[i], GEP, InsertPt);1390++aggIdx;1391// Since there should be only one struct argument aggregating1392// all the output values, we shouldn't increment AggOutputArgBegin, which1393// always points to the struct argument, in this case.1394} else {1395assert(ScalarOutputArgBegin != newFunction->arg_end() &&1396"Number of scalar output arguments should match "1397"the number of defined values");1398new StoreInst(outputs[i], &*ScalarOutputArgBegin, InsertPt);1399++ScalarOutputArgBegin;1400}1401}14021403// Now that we've done the deed, simplify the switch instruction.1404Type *OldFnRetTy = TheSwitch->getParent()->getParent()->getReturnType();1405switch (NumExitBlocks) {1406case 0:1407// There are no successors (the block containing the switch itself), which1408// means that previously this was the last part of the function, and hence1409// this should be rewritten as a `ret` or `unreachable`.1410if (newFunction->doesNotReturn()) {1411// If fn is no return, end with an unreachable terminator.1412(void)new UnreachableInst(Context, TheSwitch->getIterator());1413} else if (OldFnRetTy->isVoidTy()) {1414// We have no return value.1415ReturnInst::Create(Context, nullptr,1416TheSwitch->getIterator()); // Return void1417} else if (OldFnRetTy == TheSwitch->getCondition()->getType()) {1418// return what we have1419ReturnInst::Create(Context, TheSwitch->getCondition(),1420TheSwitch->getIterator());1421} else {1422// Otherwise we must have code extracted an unwind or something, just1423// return whatever we want.1424ReturnInst::Create(Context, Constant::getNullValue(OldFnRetTy),1425TheSwitch->getIterator());1426}14271428TheSwitch->eraseFromParent();1429break;1430case 1:1431// Only a single destination, change the switch into an unconditional1432// branch.1433BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch->getIterator());1434TheSwitch->eraseFromParent();1435break;1436case 2:1437BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch->getSuccessor(2),1438call, TheSwitch->getIterator());1439TheSwitch->eraseFromParent();1440break;1441default:1442// Otherwise, make the default destination of the switch instruction be one1443// of the other successors.1444TheSwitch->setCondition(call);1445TheSwitch->setDefaultDest(TheSwitch->getSuccessor(NumExitBlocks));1446// Remove redundant case1447TheSwitch->removeCase(SwitchInst::CaseIt(TheSwitch, NumExitBlocks-1));1448break;1449}14501451// Insert lifetime markers around the reloads of any output values. The1452// allocas output values are stored in are only in-use in the codeRepl block.1453insertLifetimeMarkersSurroundingCall(M, ReloadOutputs, ReloadOutputs, call);14541455return call;1456}14571458void CodeExtractor::moveCodeToFunction(Function *newFunction) {1459auto newFuncIt = newFunction->front().getIterator();1460for (BasicBlock *Block : Blocks) {1461// Delete the basic block from the old function, and the list of blocks1462Block->removeFromParent();14631464// Insert this basic block into the new function1465// Insert the original blocks after the entry block created1466// for the new function. The entry block may be followed1467// by a set of exit blocks at this point, but these exit1468// blocks better be placed at the end of the new function.1469newFuncIt = newFunction->insert(std::next(newFuncIt), Block);1470}1471}14721473void CodeExtractor::calculateNewCallTerminatorWeights(1474BasicBlock *CodeReplacer,1475DenseMap<BasicBlock *, BlockFrequency> &ExitWeights,1476BranchProbabilityInfo *BPI) {1477using Distribution = BlockFrequencyInfoImplBase::Distribution;1478using BlockNode = BlockFrequencyInfoImplBase::BlockNode;14791480// Update the branch weights for the exit block.1481Instruction *TI = CodeReplacer->getTerminator();1482SmallVector<unsigned, 8> BranchWeights(TI->getNumSuccessors(), 0);14831484// Block Frequency distribution with dummy node.1485Distribution BranchDist;14861487SmallVector<BranchProbability, 4> EdgeProbabilities(1488TI->getNumSuccessors(), BranchProbability::getUnknown());14891490// Add each of the frequencies of the successors.1491for (unsigned i = 0, e = TI->getNumSuccessors(); i < e; ++i) {1492BlockNode ExitNode(i);1493uint64_t ExitFreq = ExitWeights[TI->getSuccessor(i)].getFrequency();1494if (ExitFreq != 0)1495BranchDist.addExit(ExitNode, ExitFreq);1496else1497EdgeProbabilities[i] = BranchProbability::getZero();1498}14991500// Check for no total weight.1501if (BranchDist.Total == 0) {1502BPI->setEdgeProbability(CodeReplacer, EdgeProbabilities);1503return;1504}15051506// Normalize the distribution so that they can fit in unsigned.1507BranchDist.normalize();15081509// Create normalized branch weights and set the metadata.1510for (unsigned I = 0, E = BranchDist.Weights.size(); I < E; ++I) {1511const auto &Weight = BranchDist.Weights[I];15121513// Get the weight and update the current BFI.1514BranchWeights[Weight.TargetNode.Index] = Weight.Amount;1515BranchProbability BP(Weight.Amount, BranchDist.Total);1516EdgeProbabilities[Weight.TargetNode.Index] = BP;1517}1518BPI->setEdgeProbability(CodeReplacer, EdgeProbabilities);1519TI->setMetadata(1520LLVMContext::MD_prof,1521MDBuilder(TI->getContext()).createBranchWeights(BranchWeights));1522}15231524/// Erase debug info intrinsics which refer to values in \p F but aren't in1525/// \p F.1526static void eraseDebugIntrinsicsWithNonLocalRefs(Function &F) {1527for (Instruction &I : instructions(F)) {1528SmallVector<DbgVariableIntrinsic *, 4> DbgUsers;1529SmallVector<DbgVariableRecord *, 4> DbgVariableRecords;1530findDbgUsers(DbgUsers, &I, &DbgVariableRecords);1531for (DbgVariableIntrinsic *DVI : DbgUsers)1532if (DVI->getFunction() != &F)1533DVI->eraseFromParent();1534for (DbgVariableRecord *DVR : DbgVariableRecords)1535if (DVR->getFunction() != &F)1536DVR->eraseFromParent();1537}1538}15391540/// Fix up the debug info in the old and new functions by pointing line1541/// locations and debug intrinsics to the new subprogram scope, and by deleting1542/// intrinsics which point to values outside of the new function.1543static void fixupDebugInfoPostExtraction(Function &OldFunc, Function &NewFunc,1544CallInst &TheCall) {1545DISubprogram *OldSP = OldFunc.getSubprogram();1546LLVMContext &Ctx = OldFunc.getContext();15471548if (!OldSP) {1549// Erase any debug info the new function contains.1550stripDebugInfo(NewFunc);1551// Make sure the old function doesn't contain any non-local metadata refs.1552eraseDebugIntrinsicsWithNonLocalRefs(NewFunc);1553return;1554}15551556// Create a subprogram for the new function. Leave out a description of the1557// function arguments, as the parameters don't correspond to anything at the1558// source level.1559assert(OldSP->getUnit() && "Missing compile unit for subprogram");1560DIBuilder DIB(*OldFunc.getParent(), /*AllowUnresolved=*/false,1561OldSP->getUnit());1562auto SPType =1563DIB.createSubroutineType(DIB.getOrCreateTypeArray(std::nullopt));1564DISubprogram::DISPFlags SPFlags = DISubprogram::SPFlagDefinition |1565DISubprogram::SPFlagOptimized |1566DISubprogram::SPFlagLocalToUnit;1567auto NewSP = DIB.createFunction(1568OldSP->getUnit(), NewFunc.getName(), NewFunc.getName(), OldSP->getFile(),1569/*LineNo=*/0, SPType, /*ScopeLine=*/0, DINode::FlagZero, SPFlags);1570NewFunc.setSubprogram(NewSP);15711572auto IsInvalidLocation = [&NewFunc](Value *Location) {1573// Location is invalid if it isn't a constant or an instruction, or is an1574// instruction but isn't in the new function.1575if (!Location ||1576(!isa<Constant>(Location) && !isa<Instruction>(Location)))1577return true;1578Instruction *LocationInst = dyn_cast<Instruction>(Location);1579return LocationInst && LocationInst->getFunction() != &NewFunc;1580};15811582// Debug intrinsics in the new function need to be updated in one of two1583// ways:1584// 1) They need to be deleted, because they describe a value in the old1585// function.1586// 2) They need to point to fresh metadata, e.g. because they currently1587// point to a variable in the wrong scope.1588SmallDenseMap<DINode *, DINode *> RemappedMetadata;1589SmallVector<Instruction *, 4> DebugIntrinsicsToDelete;1590SmallVector<DbgVariableRecord *, 4> DVRsToDelete;1591DenseMap<const MDNode *, MDNode *> Cache;15921593auto GetUpdatedDIVariable = [&](DILocalVariable *OldVar) {1594DINode *&NewVar = RemappedMetadata[OldVar];1595if (!NewVar) {1596DILocalScope *NewScope = DILocalScope::cloneScopeForSubprogram(1597*OldVar->getScope(), *NewSP, Ctx, Cache);1598NewVar = DIB.createAutoVariable(1599NewScope, OldVar->getName(), OldVar->getFile(), OldVar->getLine(),1600OldVar->getType(), /*AlwaysPreserve=*/false, DINode::FlagZero,1601OldVar->getAlignInBits());1602}1603return cast<DILocalVariable>(NewVar);1604};16051606auto UpdateDbgLabel = [&](auto *LabelRecord) {1607// Point the label record to a fresh label within the new function if1608// the record was not inlined from some other function.1609if (LabelRecord->getDebugLoc().getInlinedAt())1610return;1611DILabel *OldLabel = LabelRecord->getLabel();1612DINode *&NewLabel = RemappedMetadata[OldLabel];1613if (!NewLabel) {1614DILocalScope *NewScope = DILocalScope::cloneScopeForSubprogram(1615*OldLabel->getScope(), *NewSP, Ctx, Cache);1616NewLabel = DILabel::get(Ctx, NewScope, OldLabel->getName(),1617OldLabel->getFile(), OldLabel->getLine());1618}1619LabelRecord->setLabel(cast<DILabel>(NewLabel));1620};16211622auto UpdateDbgRecordsOnInst = [&](Instruction &I) -> void {1623for (DbgRecord &DR : I.getDbgRecordRange()) {1624if (DbgLabelRecord *DLR = dyn_cast<DbgLabelRecord>(&DR)) {1625UpdateDbgLabel(DLR);1626continue;1627}16281629DbgVariableRecord &DVR = cast<DbgVariableRecord>(DR);1630// Apply the two updates that dbg.values get: invalid operands, and1631// variable metadata fixup.1632if (any_of(DVR.location_ops(), IsInvalidLocation)) {1633DVRsToDelete.push_back(&DVR);1634continue;1635}1636if (DVR.isDbgAssign() && IsInvalidLocation(DVR.getAddress())) {1637DVRsToDelete.push_back(&DVR);1638continue;1639}1640if (!DVR.getDebugLoc().getInlinedAt())1641DVR.setVariable(GetUpdatedDIVariable(DVR.getVariable()));1642}1643};16441645for (Instruction &I : instructions(NewFunc)) {1646UpdateDbgRecordsOnInst(I);16471648auto *DII = dyn_cast<DbgInfoIntrinsic>(&I);1649if (!DII)1650continue;16511652// Point the intrinsic to a fresh label within the new function if the1653// intrinsic was not inlined from some other function.1654if (auto *DLI = dyn_cast<DbgLabelInst>(&I)) {1655UpdateDbgLabel(DLI);1656continue;1657}16581659auto *DVI = cast<DbgVariableIntrinsic>(DII);1660// If any of the used locations are invalid, delete the intrinsic.1661if (any_of(DVI->location_ops(), IsInvalidLocation)) {1662DebugIntrinsicsToDelete.push_back(DVI);1663continue;1664}1665// DbgAssign intrinsics have an extra Value argument:1666if (auto *DAI = dyn_cast<DbgAssignIntrinsic>(DVI);1667DAI && IsInvalidLocation(DAI->getAddress())) {1668DebugIntrinsicsToDelete.push_back(DVI);1669continue;1670}1671// If the variable was in the scope of the old function, i.e. it was not1672// inlined, point the intrinsic to a fresh variable within the new function.1673if (!DVI->getDebugLoc().getInlinedAt())1674DVI->setVariable(GetUpdatedDIVariable(DVI->getVariable()));1675}16761677for (auto *DII : DebugIntrinsicsToDelete)1678DII->eraseFromParent();1679for (auto *DVR : DVRsToDelete)1680DVR->getMarker()->MarkedInstr->dropOneDbgRecord(DVR);1681DIB.finalizeSubprogram(NewSP);16821683// Fix up the scope information attached to the line locations and the1684// debug assignment metadata in the new function.1685DenseMap<DIAssignID *, DIAssignID *> AssignmentIDMap;1686for (Instruction &I : instructions(NewFunc)) {1687if (const DebugLoc &DL = I.getDebugLoc())1688I.setDebugLoc(1689DebugLoc::replaceInlinedAtSubprogram(DL, *NewSP, Ctx, Cache));1690for (DbgRecord &DR : I.getDbgRecordRange())1691DR.setDebugLoc(DebugLoc::replaceInlinedAtSubprogram(DR.getDebugLoc(),1692*NewSP, Ctx, Cache));16931694// Loop info metadata may contain line locations. Fix them up.1695auto updateLoopInfoLoc = [&Ctx, &Cache, NewSP](Metadata *MD) -> Metadata * {1696if (auto *Loc = dyn_cast_or_null<DILocation>(MD))1697return DebugLoc::replaceInlinedAtSubprogram(Loc, *NewSP, Ctx, Cache);1698return MD;1699};1700updateLoopMetadataDebugLocations(I, updateLoopInfoLoc);1701at::remapAssignID(AssignmentIDMap, I);1702}1703if (!TheCall.getDebugLoc())1704TheCall.setDebugLoc(DILocation::get(Ctx, 0, 0, OldSP));17051706eraseDebugIntrinsicsWithNonLocalRefs(NewFunc);1707}17081709Function *1710CodeExtractor::extractCodeRegion(const CodeExtractorAnalysisCache &CEAC) {1711ValueSet Inputs, Outputs;1712return extractCodeRegion(CEAC, Inputs, Outputs);1713}17141715Function *1716CodeExtractor::extractCodeRegion(const CodeExtractorAnalysisCache &CEAC,1717ValueSet &inputs, ValueSet &outputs) {1718if (!isEligible())1719return nullptr;17201721// Assumption: this is a single-entry code region, and the header is the first1722// block in the region.1723BasicBlock *header = *Blocks.begin();1724Function *oldFunction = header->getParent();17251726// Calculate the entry frequency of the new function before we change the root1727// block.1728BlockFrequency EntryFreq;1729if (BFI) {1730assert(BPI && "Both BPI and BFI are required to preserve profile info");1731for (BasicBlock *Pred : predecessors(header)) {1732if (Blocks.count(Pred))1733continue;1734EntryFreq +=1735BFI->getBlockFreq(Pred) * BPI->getEdgeProbability(Pred, header);1736}1737}17381739// Remove @llvm.assume calls that will be moved to the new function from the1740// old function's assumption cache.1741for (BasicBlock *Block : Blocks) {1742for (Instruction &I : llvm::make_early_inc_range(*Block)) {1743if (auto *AI = dyn_cast<AssumeInst>(&I)) {1744if (AC)1745AC->unregisterAssumption(AI);1746AI->eraseFromParent();1747}1748}1749}17501751// If we have any return instructions in the region, split those blocks so1752// that the return is not in the region.1753splitReturnBlocks();17541755// Calculate the exit blocks for the extracted region and the total exit1756// weights for each of those blocks.1757DenseMap<BasicBlock *, BlockFrequency> ExitWeights;1758SetVector<BasicBlock *> ExitBlocks;1759for (BasicBlock *Block : Blocks) {1760for (BasicBlock *Succ : successors(Block)) {1761if (!Blocks.count(Succ)) {1762// Update the branch weight for this successor.1763if (BFI) {1764BlockFrequency &BF = ExitWeights[Succ];1765BF += BFI->getBlockFreq(Block) * BPI->getEdgeProbability(Block, Succ);1766}1767ExitBlocks.insert(Succ);1768}1769}1770}1771NumExitBlocks = ExitBlocks.size();17721773for (BasicBlock *Block : Blocks) {1774for (BasicBlock *OldTarget : successors(Block))1775if (!Blocks.contains(OldTarget))1776OldTargets.push_back(OldTarget);1777}17781779// If we have to split PHI nodes of the entry or exit blocks, do so now.1780severSplitPHINodesOfEntry(header);1781severSplitPHINodesOfExits(ExitBlocks);17821783// This takes place of the original loop1784BasicBlock *codeReplacer = BasicBlock::Create(header->getContext(),1785"codeRepl", oldFunction,1786header);1787codeReplacer->IsNewDbgInfoFormat = oldFunction->IsNewDbgInfoFormat;17881789// The new function needs a root node because other nodes can branch to the1790// head of the region, but the entry node of a function cannot have preds.1791BasicBlock *newFuncRoot = BasicBlock::Create(header->getContext(),1792"newFuncRoot");1793newFuncRoot->IsNewDbgInfoFormat = oldFunction->IsNewDbgInfoFormat;17941795auto *BranchI = BranchInst::Create(header);1796// If the original function has debug info, we have to add a debug location1797// to the new branch instruction from the artificial entry block.1798// We use the debug location of the first instruction in the extracted1799// blocks, as there is no other equivalent line in the source code.1800if (oldFunction->getSubprogram()) {1801any_of(Blocks, [&BranchI](const BasicBlock *BB) {1802return any_of(*BB, [&BranchI](const Instruction &I) {1803if (!I.getDebugLoc())1804return false;1805// Don't use source locations attached to debug-intrinsics: they could1806// be from completely unrelated scopes.1807if (isa<DbgInfoIntrinsic>(I))1808return false;1809BranchI->setDebugLoc(I.getDebugLoc());1810return true;1811});1812});1813}1814BranchI->insertInto(newFuncRoot, newFuncRoot->end());18151816ValueSet SinkingCands, HoistingCands;1817BasicBlock *CommonExit = nullptr;1818findAllocas(CEAC, SinkingCands, HoistingCands, CommonExit);1819assert(HoistingCands.empty() || CommonExit);18201821// Find inputs to, outputs from the code region.1822findInputsOutputs(inputs, outputs, SinkingCands);18231824// Now sink all instructions which only have non-phi uses inside the region.1825// Group the allocas at the start of the block, so that any bitcast uses of1826// the allocas are well-defined.1827AllocaInst *FirstSunkAlloca = nullptr;1828for (auto *II : SinkingCands) {1829if (auto *AI = dyn_cast<AllocaInst>(II)) {1830AI->moveBefore(*newFuncRoot, newFuncRoot->getFirstInsertionPt());1831if (!FirstSunkAlloca)1832FirstSunkAlloca = AI;1833}1834}1835assert((SinkingCands.empty() || FirstSunkAlloca) &&1836"Did not expect a sink candidate without any allocas");1837for (auto *II : SinkingCands) {1838if (!isa<AllocaInst>(II)) {1839cast<Instruction>(II)->moveAfter(FirstSunkAlloca);1840}1841}18421843if (!HoistingCands.empty()) {1844auto *HoistToBlock = findOrCreateBlockForHoisting(CommonExit);1845Instruction *TI = HoistToBlock->getTerminator();1846for (auto *II : HoistingCands)1847cast<Instruction>(II)->moveBefore(TI);1848}18491850// Collect objects which are inputs to the extraction region and also1851// referenced by lifetime start markers within it. The effects of these1852// markers must be replicated in the calling function to prevent the stack1853// coloring pass from merging slots which store input objects.1854ValueSet LifetimesStart;1855eraseLifetimeMarkersOnInputs(Blocks, SinkingCands, LifetimesStart);18561857// Construct new function based on inputs/outputs & add allocas for all defs.1858Function *newFunction =1859constructFunction(inputs, outputs, header, newFuncRoot, codeReplacer,1860oldFunction, oldFunction->getParent());18611862// Update the entry count of the function.1863if (BFI) {1864auto Count = BFI->getProfileCountFromFreq(EntryFreq);1865if (Count)1866newFunction->setEntryCount(1867ProfileCount(*Count, Function::PCT_Real)); // FIXME1868BFI->setBlockFreq(codeReplacer, EntryFreq);1869}18701871CallInst *TheCall =1872emitCallAndSwitchStatement(newFunction, codeReplacer, inputs, outputs);18731874moveCodeToFunction(newFunction);18751876// Replicate the effects of any lifetime start/end markers which referenced1877// input objects in the extraction region by placing markers around the call.1878insertLifetimeMarkersSurroundingCall(1879oldFunction->getParent(), LifetimesStart.getArrayRef(), {}, TheCall);18801881// Propagate personality info to the new function if there is one.1882if (oldFunction->hasPersonalityFn())1883newFunction->setPersonalityFn(oldFunction->getPersonalityFn());18841885// Update the branch weights for the exit block.1886if (BFI && NumExitBlocks > 1)1887calculateNewCallTerminatorWeights(codeReplacer, ExitWeights, BPI);18881889// Loop over all of the PHI nodes in the header and exit blocks, and change1890// any references to the old incoming edge to be the new incoming edge.1891for (BasicBlock::iterator I = header->begin(); isa<PHINode>(I); ++I) {1892PHINode *PN = cast<PHINode>(I);1893for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)1894if (!Blocks.count(PN->getIncomingBlock(i)))1895PN->setIncomingBlock(i, newFuncRoot);1896}18971898for (BasicBlock *ExitBB : ExitBlocks)1899for (PHINode &PN : ExitBB->phis()) {1900Value *IncomingCodeReplacerVal = nullptr;1901for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {1902// Ignore incoming values from outside of the extracted region.1903if (!Blocks.count(PN.getIncomingBlock(i)))1904continue;19051906// Ensure that there is only one incoming value from codeReplacer.1907if (!IncomingCodeReplacerVal) {1908PN.setIncomingBlock(i, codeReplacer);1909IncomingCodeReplacerVal = PN.getIncomingValue(i);1910} else1911assert(IncomingCodeReplacerVal == PN.getIncomingValue(i) &&1912"PHI has two incompatbile incoming values from codeRepl");1913}1914}19151916fixupDebugInfoPostExtraction(*oldFunction, *newFunction, *TheCall);19171918LLVM_DEBUG(if (verifyFunction(*newFunction, &errs())) {1919newFunction->dump();1920report_fatal_error("verification of newFunction failed!");1921});1922LLVM_DEBUG(if (verifyFunction(*oldFunction))1923report_fatal_error("verification of oldFunction failed!"));1924LLVM_DEBUG(if (AC && verifyAssumptionCache(*oldFunction, *newFunction, AC))1925report_fatal_error("Stale Asumption cache for old Function!"));1926return newFunction;1927}19281929bool CodeExtractor::verifyAssumptionCache(const Function &OldFunc,1930const Function &NewFunc,1931AssumptionCache *AC) {1932for (auto AssumeVH : AC->assumptions()) {1933auto *I = dyn_cast_or_null<CallInst>(AssumeVH);1934if (!I)1935continue;19361937// There shouldn't be any llvm.assume intrinsics in the new function.1938if (I->getFunction() != &OldFunc)1939return true;19401941// There shouldn't be any stale affected values in the assumption cache1942// that were previously in the old function, but that have now been moved1943// to the new function.1944for (auto AffectedValVH : AC->assumptionsFor(I->getOperand(0))) {1945auto *AffectedCI = dyn_cast_or_null<CallInst>(AffectedValVH);1946if (!AffectedCI)1947continue;1948if (AffectedCI->getFunction() != &OldFunc)1949return true;1950auto *AssumedInst = cast<Instruction>(AffectedCI->getOperand(0));1951if (AssumedInst->getFunction() != &OldFunc)1952return true;1953}1954}1955return false;1956}19571958void CodeExtractor::excludeArgFromAggregate(Value *Arg) {1959ExcludeArgsFromAggregate.insert(Arg);1960}196119621963