1f22ef01cSRoman Divacky //===- CodeExtractor.cpp - Pull code region into a new function -----------===//
2f22ef01cSRoman Divacky //
3f22ef01cSRoman Divacky // The LLVM Compiler Infrastructure
4f22ef01cSRoman Divacky //
5f22ef01cSRoman Divacky // This file is distributed under the University of Illinois Open Source
6f22ef01cSRoman Divacky // License. See LICENSE.TXT for details.
7f22ef01cSRoman Divacky //
8f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
9f22ef01cSRoman Divacky //
10f22ef01cSRoman Divacky // This file implements the interface to tear out a code region, such as an
11f22ef01cSRoman Divacky // individual loop or a parallel section, into a new function, replacing it with
12f22ef01cSRoman Divacky // a call to the new function.
13f22ef01cSRoman Divacky //
14f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
15f22ef01cSRoman Divacky
167ae0e2c9SDimitry Andric #include "llvm/Transforms/Utils/CodeExtractor.h"
172cab237bSDimitry Andric #include "llvm/ADT/ArrayRef.h"
182cab237bSDimitry Andric #include "llvm/ADT/DenseMap.h"
192cab237bSDimitry Andric #include "llvm/ADT/Optional.h"
20139f7f9bSDimitry Andric #include "llvm/ADT/STLExtras.h"
2191bc56edSDimitry Andric #include "llvm/ADT/SetVector.h"
222cab237bSDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
232cab237bSDimitry Andric #include "llvm/ADT/SmallVector.h"
24d88c1a5aSDimitry Andric #include "llvm/Analysis/BlockFrequencyInfo.h"
25d88c1a5aSDimitry Andric #include "llvm/Analysis/BlockFrequencyInfoImpl.h"
26d88c1a5aSDimitry Andric #include "llvm/Analysis/BranchProbabilityInfo.h"
27f22ef01cSRoman Divacky #include "llvm/Analysis/LoopInfo.h"
282cab237bSDimitry Andric #include "llvm/IR/Argument.h"
292cab237bSDimitry Andric #include "llvm/IR/Attributes.h"
302cab237bSDimitry Andric #include "llvm/IR/BasicBlock.h"
312cab237bSDimitry Andric #include "llvm/IR/CFG.h"
322cab237bSDimitry Andric #include "llvm/IR/Constant.h"
33139f7f9bSDimitry Andric #include "llvm/IR/Constants.h"
342cab237bSDimitry Andric #include "llvm/IR/DataLayout.h"
35139f7f9bSDimitry Andric #include "llvm/IR/DerivedTypes.h"
3691bc56edSDimitry Andric #include "llvm/IR/Dominators.h"
372cab237bSDimitry Andric #include "llvm/IR/Function.h"
382cab237bSDimitry Andric #include "llvm/IR/GlobalValue.h"
392cab237bSDimitry Andric #include "llvm/IR/InstrTypes.h"
402cab237bSDimitry Andric #include "llvm/IR/Instruction.h"
41139f7f9bSDimitry Andric #include "llvm/IR/Instructions.h"
42f9448bf3SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
43139f7f9bSDimitry Andric #include "llvm/IR/Intrinsics.h"
44139f7f9bSDimitry Andric #include "llvm/IR/LLVMContext.h"
45d88c1a5aSDimitry Andric #include "llvm/IR/MDBuilder.h"
46139f7f9bSDimitry Andric #include "llvm/IR/Module.h"
472cab237bSDimitry Andric #include "llvm/IR/Type.h"
482cab237bSDimitry Andric #include "llvm/IR/User.h"
492cab237bSDimitry Andric #include "llvm/IR/Value.h"
5091bc56edSDimitry Andric #include "llvm/IR/Verifier.h"
51139f7f9bSDimitry Andric #include "llvm/Pass.h"
52d88c1a5aSDimitry Andric #include "llvm/Support/BlockFrequency.h"
532cab237bSDimitry Andric #include "llvm/Support/BranchProbability.h"
542cab237bSDimitry Andric #include "llvm/Support/Casting.h"
55f22ef01cSRoman Divacky #include "llvm/Support/CommandLine.h"
56f22ef01cSRoman Divacky #include "llvm/Support/Debug.h"
57f22ef01cSRoman Divacky #include "llvm/Support/ErrorHandling.h"
58f22ef01cSRoman Divacky #include "llvm/Support/raw_ostream.h"
59139f7f9bSDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h"
60*b5893f02SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
612cab237bSDimitry Andric #include <cassert>
622cab237bSDimitry Andric #include <cstdint>
632cab237bSDimitry Andric #include <iterator>
642cab237bSDimitry Andric #include <map>
65f22ef01cSRoman Divacky #include <set>
662cab237bSDimitry Andric #include <utility>
672cab237bSDimitry Andric #include <vector>
682cab237bSDimitry Andric
69f22ef01cSRoman Divacky using namespace llvm;
704ba319b5SDimitry Andric using ProfileCount = Function::ProfileCount;
71f22ef01cSRoman Divacky
7291bc56edSDimitry Andric #define DEBUG_TYPE "code-extractor"
7391bc56edSDimitry Andric
74f22ef01cSRoman Divacky // Provide a command-line option to aggregate function arguments into a struct
75f22ef01cSRoman Divacky // for functions produced by the code extractor. This is useful when converting
76f22ef01cSRoman Divacky // extracted functions to pthread-based code, as only one argument (void*) can
77f22ef01cSRoman Divacky // be passed in to pthread_create().
78f22ef01cSRoman Divacky static cl::opt<bool>
79f22ef01cSRoman Divacky AggregateArgsOpt("aggregate-extracted-args", cl::Hidden,
80f22ef01cSRoman Divacky cl::desc("Aggregate arguments to code-extracted functions"));
81f22ef01cSRoman Divacky
824ba319b5SDimitry Andric /// Test whether a block is valid for extraction.
isBlockValidForExtraction(const BasicBlock & BB,const SetVector<BasicBlock * > & Result,bool AllowVarArgs,bool AllowAlloca)834ba319b5SDimitry Andric static bool isBlockValidForExtraction(const BasicBlock &BB,
844ba319b5SDimitry Andric const SetVector<BasicBlock *> &Result,
854ba319b5SDimitry Andric bool AllowVarArgs, bool AllowAlloca) {
86a580b014SDimitry Andric // taking the address of a basic block moved to another function is illegal
87a580b014SDimitry Andric if (BB.hasAddressTaken())
88a580b014SDimitry Andric return false;
89a580b014SDimitry Andric
90a580b014SDimitry Andric // don't hoist code that uses another basicblock address, as it's likely to
91a580b014SDimitry Andric // lead to unexpected behavior, like cross-function jumps
92a580b014SDimitry Andric SmallPtrSet<User const *, 16> Visited;
93a580b014SDimitry Andric SmallVector<User const *, 16> ToVisit;
94a580b014SDimitry Andric
95a580b014SDimitry Andric for (Instruction const &Inst : BB)
96a580b014SDimitry Andric ToVisit.push_back(&Inst);
97a580b014SDimitry Andric
98a580b014SDimitry Andric while (!ToVisit.empty()) {
99a580b014SDimitry Andric User const *Curr = ToVisit.pop_back_val();
100a580b014SDimitry Andric if (!Visited.insert(Curr).second)
101a580b014SDimitry Andric continue;
102a580b014SDimitry Andric if (isa<BlockAddress const>(Curr))
103a580b014SDimitry Andric return false; // even a reference to self is likely to be not compatible
104a580b014SDimitry Andric
105a580b014SDimitry Andric if (isa<Instruction>(Curr) && cast<Instruction>(Curr)->getParent() != &BB)
106a580b014SDimitry Andric continue;
107a580b014SDimitry Andric
108a580b014SDimitry Andric for (auto const &U : Curr->operands()) {
109a580b014SDimitry Andric if (auto *UU = dyn_cast<User>(U))
110a580b014SDimitry Andric ToVisit.push_back(UU);
111a580b014SDimitry Andric }
112a580b014SDimitry Andric }
113f22ef01cSRoman Divacky
1144ba319b5SDimitry Andric // If explicitly requested, allow vastart and alloca. For invoke instructions
1154ba319b5SDimitry Andric // verify that extraction is valid.
1167ae0e2c9SDimitry Andric for (BasicBlock::const_iterator I = BB.begin(), E = BB.end(); I != E; ++I) {
1174ba319b5SDimitry Andric if (isa<AllocaInst>(I)) {
1184ba319b5SDimitry Andric if (!AllowAlloca)
1197ae0e2c9SDimitry Andric return false;
1204ba319b5SDimitry Andric continue;
1214ba319b5SDimitry Andric }
1224ba319b5SDimitry Andric
1234ba319b5SDimitry Andric if (const auto *II = dyn_cast<InvokeInst>(I)) {
1244ba319b5SDimitry Andric // Unwind destination (either a landingpad, catchswitch, or cleanuppad)
1254ba319b5SDimitry Andric // must be a part of the subgraph which is being extracted.
1264ba319b5SDimitry Andric if (auto *UBB = II->getUnwindDest())
1274ba319b5SDimitry Andric if (!Result.count(UBB))
1284ba319b5SDimitry Andric return false;
1294ba319b5SDimitry Andric continue;
1304ba319b5SDimitry Andric }
1314ba319b5SDimitry Andric
1324ba319b5SDimitry Andric // All catch handlers of a catchswitch instruction as well as the unwind
1334ba319b5SDimitry Andric // destination must be in the subgraph.
1344ba319b5SDimitry Andric if (const auto *CSI = dyn_cast<CatchSwitchInst>(I)) {
1354ba319b5SDimitry Andric if (auto *UBB = CSI->getUnwindDest())
1364ba319b5SDimitry Andric if (!Result.count(UBB))
1374ba319b5SDimitry Andric return false;
1384ba319b5SDimitry Andric for (auto *HBB : CSI->handlers())
1394ba319b5SDimitry Andric if (!Result.count(const_cast<BasicBlock*>(HBB)))
1404ba319b5SDimitry Andric return false;
1414ba319b5SDimitry Andric continue;
1424ba319b5SDimitry Andric }
1434ba319b5SDimitry Andric
1444ba319b5SDimitry Andric // Make sure that entire catch handler is within subgraph. It is sufficient
1454ba319b5SDimitry Andric // to check that catch return's block is in the list.
1464ba319b5SDimitry Andric if (const auto *CPI = dyn_cast<CatchPadInst>(I)) {
1474ba319b5SDimitry Andric for (const auto *U : CPI->users())
1484ba319b5SDimitry Andric if (const auto *CRI = dyn_cast<CatchReturnInst>(U))
1494ba319b5SDimitry Andric if (!Result.count(const_cast<BasicBlock*>(CRI->getParent())))
1504ba319b5SDimitry Andric return false;
1514ba319b5SDimitry Andric continue;
1524ba319b5SDimitry Andric }
1534ba319b5SDimitry Andric
1544ba319b5SDimitry Andric // And do similar checks for cleanup handler - the entire handler must be
1554ba319b5SDimitry Andric // in subgraph which is going to be extracted. For cleanup return should
1564ba319b5SDimitry Andric // additionally check that the unwind destination is also in the subgraph.
1574ba319b5SDimitry Andric if (const auto *CPI = dyn_cast<CleanupPadInst>(I)) {
1584ba319b5SDimitry Andric for (const auto *U : CPI->users())
1594ba319b5SDimitry Andric if (const auto *CRI = dyn_cast<CleanupReturnInst>(U))
1604ba319b5SDimitry Andric if (!Result.count(const_cast<BasicBlock*>(CRI->getParent())))
1614ba319b5SDimitry Andric return false;
1624ba319b5SDimitry Andric continue;
1634ba319b5SDimitry Andric }
1644ba319b5SDimitry Andric if (const auto *CRI = dyn_cast<CleanupReturnInst>(I)) {
1654ba319b5SDimitry Andric if (auto *UBB = CRI->getUnwindDest())
1664ba319b5SDimitry Andric if (!Result.count(UBB))
1674ba319b5SDimitry Andric return false;
1684ba319b5SDimitry Andric continue;
1694ba319b5SDimitry Andric }
1704ba319b5SDimitry Andric
171*b5893f02SDimitry Andric if (const CallInst *CI = dyn_cast<CallInst>(I)) {
172*b5893f02SDimitry Andric if (const Function *F = CI->getCalledFunction()) {
173*b5893f02SDimitry Andric auto IID = F->getIntrinsicID();
174*b5893f02SDimitry Andric if (IID == Intrinsic::vastart) {
1752cab237bSDimitry Andric if (AllowVarArgs)
1762cab237bSDimitry Andric continue;
1772cab237bSDimitry Andric else
1787ae0e2c9SDimitry Andric return false;
1797ae0e2c9SDimitry Andric }
180*b5893f02SDimitry Andric
181*b5893f02SDimitry Andric // Currently, we miscompile outlined copies of eh_typid_for. There are
182*b5893f02SDimitry Andric // proposals for fixing this in llvm.org/PR39545.
183*b5893f02SDimitry Andric if (IID == Intrinsic::eh_typeid_for)
184*b5893f02SDimitry Andric return false;
185*b5893f02SDimitry Andric }
186*b5893f02SDimitry Andric }
1872cab237bSDimitry Andric }
188f22ef01cSRoman Divacky
1897ae0e2c9SDimitry Andric return true;
1907ae0e2c9SDimitry Andric }
191f22ef01cSRoman Divacky
1924ba319b5SDimitry Andric /// Build a set of blocks to extract if the input blocks are viable.
19351690af2SDimitry Andric static SetVector<BasicBlock *>
buildExtractionBlockSet(ArrayRef<BasicBlock * > BBs,DominatorTree * DT,bool AllowVarArgs,bool AllowAlloca)1942cab237bSDimitry Andric buildExtractionBlockSet(ArrayRef<BasicBlock *> BBs, DominatorTree *DT,
1954ba319b5SDimitry Andric bool AllowVarArgs, bool AllowAlloca) {
19651690af2SDimitry Andric assert(!BBs.empty() && "The set of blocks to extract must be non-empty");
1977ae0e2c9SDimitry Andric SetVector<BasicBlock *> Result;
1987ae0e2c9SDimitry Andric
1997ae0e2c9SDimitry Andric // Loop over the blocks, adding them to our set-vector, and aborting with an
2007ae0e2c9SDimitry Andric // empty set if we encounter invalid blocks.
20151690af2SDimitry Andric for (BasicBlock *BB : BBs) {
20251690af2SDimitry Andric // If this block is dead, don't process it.
20351690af2SDimitry Andric if (DT && !DT->isReachableFromEntry(BB))
20451690af2SDimitry Andric continue;
20551690af2SDimitry Andric
20651690af2SDimitry Andric if (!Result.insert(BB))
20751690af2SDimitry Andric llvm_unreachable("Repeated basic blocks in extraction input");
20851690af2SDimitry Andric }
2097ae0e2c9SDimitry Andric
2104ba319b5SDimitry Andric for (auto *BB : Result) {
2114ba319b5SDimitry Andric if (!isBlockValidForExtraction(*BB, Result, AllowVarArgs, AllowAlloca))
2124ba319b5SDimitry Andric return {};
2134ba319b5SDimitry Andric
2144ba319b5SDimitry Andric // Make sure that the first block is not a landing pad.
2154ba319b5SDimitry Andric if (BB == Result.front()) {
2164ba319b5SDimitry Andric if (BB->isEHPad()) {
2174ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "The first block cannot be an unwind block\n");
2184ba319b5SDimitry Andric return {};
2194ba319b5SDimitry Andric }
2204ba319b5SDimitry Andric continue;
2214ba319b5SDimitry Andric }
2224ba319b5SDimitry Andric
2234ba319b5SDimitry Andric // All blocks other than the first must not have predecessors outside of
2244ba319b5SDimitry Andric // the subgraph which is being extracted.
2254ba319b5SDimitry Andric for (auto *PBB : predecessors(BB))
2264ba319b5SDimitry Andric if (!Result.count(PBB)) {
2274ba319b5SDimitry Andric LLVM_DEBUG(
2284ba319b5SDimitry Andric dbgs() << "No blocks in this region may have entries from "
2294ba319b5SDimitry Andric "outside the region except for the first block!\n");
2304ba319b5SDimitry Andric return {};
2314ba319b5SDimitry Andric }
2324ba319b5SDimitry Andric }
2337ae0e2c9SDimitry Andric
2347ae0e2c9SDimitry Andric return Result;
2357ae0e2c9SDimitry Andric }
2367ae0e2c9SDimitry Andric
CodeExtractor(ArrayRef<BasicBlock * > BBs,DominatorTree * DT,bool AggregateArgs,BlockFrequencyInfo * BFI,BranchProbabilityInfo * BPI,bool AllowVarArgs,bool AllowAlloca,std::string Suffix)2377ae0e2c9SDimitry Andric CodeExtractor::CodeExtractor(ArrayRef<BasicBlock *> BBs, DominatorTree *DT,
238d88c1a5aSDimitry Andric bool AggregateArgs, BlockFrequencyInfo *BFI,
2394ba319b5SDimitry Andric BranchProbabilityInfo *BPI, bool AllowVarArgs,
240*b5893f02SDimitry Andric bool AllowAlloca, std::string Suffix)
241d88c1a5aSDimitry Andric : DT(DT), AggregateArgs(AggregateArgs || AggregateArgsOpt), BFI(BFI),
2422cab237bSDimitry Andric BPI(BPI), AllowVarArgs(AllowVarArgs),
243*b5893f02SDimitry Andric Blocks(buildExtractionBlockSet(BBs, DT, AllowVarArgs, AllowAlloca)),
244*b5893f02SDimitry Andric Suffix(Suffix) {}
2457ae0e2c9SDimitry Andric
CodeExtractor(DominatorTree & DT,Loop & L,bool AggregateArgs,BlockFrequencyInfo * BFI,BranchProbabilityInfo * BPI,std::string Suffix)246d88c1a5aSDimitry Andric CodeExtractor::CodeExtractor(DominatorTree &DT, Loop &L, bool AggregateArgs,
247d88c1a5aSDimitry Andric BlockFrequencyInfo *BFI,
248*b5893f02SDimitry Andric BranchProbabilityInfo *BPI, std::string Suffix)
249d88c1a5aSDimitry Andric : DT(&DT), AggregateArgs(AggregateArgs || AggregateArgsOpt), BFI(BFI),
2502cab237bSDimitry Andric BPI(BPI), AllowVarArgs(false),
2512cab237bSDimitry Andric Blocks(buildExtractionBlockSet(L.getBlocks(), &DT,
2524ba319b5SDimitry Andric /* AllowVarArgs */ false,
253*b5893f02SDimitry Andric /* AllowAlloca */ false)),
254*b5893f02SDimitry Andric Suffix(Suffix) {}
2557ae0e2c9SDimitry Andric
256f22ef01cSRoman Divacky /// definedInRegion - Return true if the specified value is defined in the
257f22ef01cSRoman Divacky /// extracted region.
definedInRegion(const SetVector<BasicBlock * > & Blocks,Value * V)2587ae0e2c9SDimitry Andric static bool definedInRegion(const SetVector<BasicBlock *> &Blocks, Value *V) {
259f22ef01cSRoman Divacky if (Instruction *I = dyn_cast<Instruction>(V))
2607ae0e2c9SDimitry Andric if (Blocks.count(I->getParent()))
261f22ef01cSRoman Divacky return true;
262f22ef01cSRoman Divacky return false;
263f22ef01cSRoman Divacky }
264f22ef01cSRoman Divacky
265f22ef01cSRoman Divacky /// definedInCaller - Return true if the specified value is defined in the
266f22ef01cSRoman Divacky /// function being code extracted, but not in the region being extracted.
267f22ef01cSRoman Divacky /// These values must be passed in as live-ins to the function.
definedInCaller(const SetVector<BasicBlock * > & Blocks,Value * V)2687ae0e2c9SDimitry Andric static bool definedInCaller(const SetVector<BasicBlock *> &Blocks, Value *V) {
269f22ef01cSRoman Divacky if (isa<Argument>(V)) return true;
270f22ef01cSRoman Divacky if (Instruction *I = dyn_cast<Instruction>(V))
2717ae0e2c9SDimitry Andric if (!Blocks.count(I->getParent()))
272f22ef01cSRoman Divacky return true;
273f22ef01cSRoman Divacky return false;
274f22ef01cSRoman Divacky }
275f22ef01cSRoman Divacky
getCommonExitBlock(const SetVector<BasicBlock * > & Blocks)27624d58133SDimitry Andric static BasicBlock *getCommonExitBlock(const SetVector<BasicBlock *> &Blocks) {
27724d58133SDimitry Andric BasicBlock *CommonExitBlock = nullptr;
27824d58133SDimitry Andric auto hasNonCommonExitSucc = [&](BasicBlock *Block) {
27924d58133SDimitry Andric for (auto *Succ : successors(Block)) {
28024d58133SDimitry Andric // Internal edges, ok.
28124d58133SDimitry Andric if (Blocks.count(Succ))
28224d58133SDimitry Andric continue;
28324d58133SDimitry Andric if (!CommonExitBlock) {
28424d58133SDimitry Andric CommonExitBlock = Succ;
28524d58133SDimitry Andric continue;
28624d58133SDimitry Andric }
28724d58133SDimitry Andric if (CommonExitBlock == Succ)
28824d58133SDimitry Andric continue;
28924d58133SDimitry Andric
29024d58133SDimitry Andric return true;
29124d58133SDimitry Andric }
29224d58133SDimitry Andric return false;
29324d58133SDimitry Andric };
29424d58133SDimitry Andric
29524d58133SDimitry Andric if (any_of(Blocks, hasNonCommonExitSucc))
29624d58133SDimitry Andric return nullptr;
29724d58133SDimitry Andric
29824d58133SDimitry Andric return CommonExitBlock;
29924d58133SDimitry Andric }
30024d58133SDimitry Andric
isLegalToShrinkwrapLifetimeMarkers(Instruction * Addr) const30124d58133SDimitry Andric bool CodeExtractor::isLegalToShrinkwrapLifetimeMarkers(
30224d58133SDimitry Andric Instruction *Addr) const {
30324d58133SDimitry Andric AllocaInst *AI = cast<AllocaInst>(Addr->stripInBoundsConstantOffsets());
304f9448bf3SDimitry Andric Function *Func = (*Blocks.begin())->getParent();
305f9448bf3SDimitry Andric for (BasicBlock &BB : *Func) {
306f9448bf3SDimitry Andric if (Blocks.count(&BB))
307f9448bf3SDimitry Andric continue;
308f9448bf3SDimitry Andric for (Instruction &II : BB) {
30924d58133SDimitry Andric if (isa<DbgInfoIntrinsic>(II))
31024d58133SDimitry Andric continue;
31124d58133SDimitry Andric
31224d58133SDimitry Andric unsigned Opcode = II.getOpcode();
31324d58133SDimitry Andric Value *MemAddr = nullptr;
31424d58133SDimitry Andric switch (Opcode) {
31524d58133SDimitry Andric case Instruction::Store:
31624d58133SDimitry Andric case Instruction::Load: {
31724d58133SDimitry Andric if (Opcode == Instruction::Store) {
31824d58133SDimitry Andric StoreInst *SI = cast<StoreInst>(&II);
31924d58133SDimitry Andric MemAddr = SI->getPointerOperand();
32024d58133SDimitry Andric } else {
32124d58133SDimitry Andric LoadInst *LI = cast<LoadInst>(&II);
32224d58133SDimitry Andric MemAddr = LI->getPointerOperand();
32324d58133SDimitry Andric }
32424d58133SDimitry Andric // Global variable can not be aliased with locals.
32524d58133SDimitry Andric if (dyn_cast<Constant>(MemAddr))
32624d58133SDimitry Andric break;
32724d58133SDimitry Andric Value *Base = MemAddr->stripInBoundsConstantOffsets();
32824d58133SDimitry Andric if (!dyn_cast<AllocaInst>(Base) || Base == AI)
32924d58133SDimitry Andric return false;
33024d58133SDimitry Andric break;
33124d58133SDimitry Andric }
33224d58133SDimitry Andric default: {
33324d58133SDimitry Andric IntrinsicInst *IntrInst = dyn_cast<IntrinsicInst>(&II);
33424d58133SDimitry Andric if (IntrInst) {
335*b5893f02SDimitry Andric if (IntrInst->isLifetimeStartOrEnd())
33624d58133SDimitry Andric break;
33724d58133SDimitry Andric return false;
33824d58133SDimitry Andric }
33924d58133SDimitry Andric // Treat all the other cases conservatively if it has side effects.
34024d58133SDimitry Andric if (II.mayHaveSideEffects())
34124d58133SDimitry Andric return false;
34224d58133SDimitry Andric }
34324d58133SDimitry Andric }
34424d58133SDimitry Andric }
34524d58133SDimitry Andric }
34624d58133SDimitry Andric
34724d58133SDimitry Andric return true;
34824d58133SDimitry Andric }
34924d58133SDimitry Andric
35024d58133SDimitry Andric BasicBlock *
findOrCreateBlockForHoisting(BasicBlock * CommonExitBlock)35124d58133SDimitry Andric CodeExtractor::findOrCreateBlockForHoisting(BasicBlock *CommonExitBlock) {
35224d58133SDimitry Andric BasicBlock *SinglePredFromOutlineRegion = nullptr;
35324d58133SDimitry Andric assert(!Blocks.count(CommonExitBlock) &&
35424d58133SDimitry Andric "Expect a block outside the region!");
35524d58133SDimitry Andric for (auto *Pred : predecessors(CommonExitBlock)) {
35624d58133SDimitry Andric if (!Blocks.count(Pred))
35724d58133SDimitry Andric continue;
35824d58133SDimitry Andric if (!SinglePredFromOutlineRegion) {
35924d58133SDimitry Andric SinglePredFromOutlineRegion = Pred;
36024d58133SDimitry Andric } else if (SinglePredFromOutlineRegion != Pred) {
36124d58133SDimitry Andric SinglePredFromOutlineRegion = nullptr;
36224d58133SDimitry Andric break;
36324d58133SDimitry Andric }
36424d58133SDimitry Andric }
36524d58133SDimitry Andric
36624d58133SDimitry Andric if (SinglePredFromOutlineRegion)
36724d58133SDimitry Andric return SinglePredFromOutlineRegion;
36824d58133SDimitry Andric
36924d58133SDimitry Andric #ifndef NDEBUG
37024d58133SDimitry Andric auto getFirstPHI = [](BasicBlock *BB) {
37124d58133SDimitry Andric BasicBlock::iterator I = BB->begin();
37224d58133SDimitry Andric PHINode *FirstPhi = nullptr;
37324d58133SDimitry Andric while (I != BB->end()) {
37424d58133SDimitry Andric PHINode *Phi = dyn_cast<PHINode>(I);
37524d58133SDimitry Andric if (!Phi)
37624d58133SDimitry Andric break;
37724d58133SDimitry Andric if (!FirstPhi) {
37824d58133SDimitry Andric FirstPhi = Phi;
37924d58133SDimitry Andric break;
38024d58133SDimitry Andric }
38124d58133SDimitry Andric }
38224d58133SDimitry Andric return FirstPhi;
38324d58133SDimitry Andric };
38424d58133SDimitry Andric // If there are any phi nodes, the single pred either exists or has already
38524d58133SDimitry Andric // be created before code extraction.
38624d58133SDimitry Andric assert(!getFirstPHI(CommonExitBlock) && "Phi not expected");
38724d58133SDimitry Andric #endif
38824d58133SDimitry Andric
38924d58133SDimitry Andric BasicBlock *NewExitBlock = CommonExitBlock->splitBasicBlock(
39024d58133SDimitry Andric CommonExitBlock->getFirstNonPHI()->getIterator());
39124d58133SDimitry Andric
3922cab237bSDimitry Andric for (auto PI = pred_begin(CommonExitBlock), PE = pred_end(CommonExitBlock);
3932cab237bSDimitry Andric PI != PE;) {
3942cab237bSDimitry Andric BasicBlock *Pred = *PI++;
39524d58133SDimitry Andric if (Blocks.count(Pred))
39624d58133SDimitry Andric continue;
39724d58133SDimitry Andric Pred->getTerminator()->replaceUsesOfWith(CommonExitBlock, NewExitBlock);
39824d58133SDimitry Andric }
39924d58133SDimitry Andric // Now add the old exit block to the outline region.
40024d58133SDimitry Andric Blocks.insert(CommonExitBlock);
40124d58133SDimitry Andric return CommonExitBlock;
40224d58133SDimitry Andric }
40324d58133SDimitry Andric
findAllocas(ValueSet & SinkCands,ValueSet & HoistCands,BasicBlock * & ExitBlock) const40424d58133SDimitry Andric void CodeExtractor::findAllocas(ValueSet &SinkCands, ValueSet &HoistCands,
40524d58133SDimitry Andric BasicBlock *&ExitBlock) const {
40624d58133SDimitry Andric Function *Func = (*Blocks.begin())->getParent();
40724d58133SDimitry Andric ExitBlock = getCommonExitBlock(Blocks);
40824d58133SDimitry Andric
40924d58133SDimitry Andric for (BasicBlock &BB : *Func) {
41024d58133SDimitry Andric if (Blocks.count(&BB))
41124d58133SDimitry Andric continue;
41224d58133SDimitry Andric for (Instruction &II : BB) {
413f9448bf3SDimitry Andric auto *AI = dyn_cast<AllocaInst>(&II);
414f9448bf3SDimitry Andric if (!AI)
415f9448bf3SDimitry Andric continue;
416f9448bf3SDimitry Andric
41724d58133SDimitry Andric // Find the pair of life time markers for address 'Addr' that are either
41824d58133SDimitry Andric // defined inside the outline region or can legally be shrinkwrapped into
41924d58133SDimitry Andric // the outline region. If there are not other untracked uses of the
42024d58133SDimitry Andric // address, return the pair of markers if found; otherwise return a pair
42124d58133SDimitry Andric // of nullptr.
42224d58133SDimitry Andric auto GetLifeTimeMarkers =
42324d58133SDimitry Andric [&](Instruction *Addr, bool &SinkLifeStart,
42424d58133SDimitry Andric bool &HoistLifeEnd) -> std::pair<Instruction *, Instruction *> {
425f9448bf3SDimitry Andric Instruction *LifeStart = nullptr, *LifeEnd = nullptr;
426f9448bf3SDimitry Andric
42724d58133SDimitry Andric for (User *U : Addr->users()) {
428f9448bf3SDimitry Andric IntrinsicInst *IntrInst = dyn_cast<IntrinsicInst>(U);
429f9448bf3SDimitry Andric if (IntrInst) {
43024d58133SDimitry Andric if (IntrInst->getIntrinsicID() == Intrinsic::lifetime_start) {
43124d58133SDimitry Andric // Do not handle the case where AI has multiple start markers.
43224d58133SDimitry Andric if (LifeStart)
43324d58133SDimitry Andric return std::make_pair<Instruction *>(nullptr, nullptr);
434f9448bf3SDimitry Andric LifeStart = IntrInst;
43524d58133SDimitry Andric }
43624d58133SDimitry Andric if (IntrInst->getIntrinsicID() == Intrinsic::lifetime_end) {
43724d58133SDimitry Andric if (LifeEnd)
43824d58133SDimitry Andric return std::make_pair<Instruction *>(nullptr, nullptr);
439f9448bf3SDimitry Andric LifeEnd = IntrInst;
440f9448bf3SDimitry Andric }
44124d58133SDimitry Andric continue;
442f9448bf3SDimitry Andric }
44324d58133SDimitry Andric // Find untracked uses of the address, bail.
44424d58133SDimitry Andric if (!definedInRegion(Blocks, U))
44524d58133SDimitry Andric return std::make_pair<Instruction *>(nullptr, nullptr);
44624d58133SDimitry Andric }
44724d58133SDimitry Andric
44824d58133SDimitry Andric if (!LifeStart || !LifeEnd)
44924d58133SDimitry Andric return std::make_pair<Instruction *>(nullptr, nullptr);
45024d58133SDimitry Andric
45124d58133SDimitry Andric SinkLifeStart = !definedInRegion(Blocks, LifeStart);
45224d58133SDimitry Andric HoistLifeEnd = !definedInRegion(Blocks, LifeEnd);
45324d58133SDimitry Andric // Do legality Check.
45424d58133SDimitry Andric if ((SinkLifeStart || HoistLifeEnd) &&
45524d58133SDimitry Andric !isLegalToShrinkwrapLifetimeMarkers(Addr))
45624d58133SDimitry Andric return std::make_pair<Instruction *>(nullptr, nullptr);
45724d58133SDimitry Andric
45824d58133SDimitry Andric // Check to see if we have a place to do hoisting, if not, bail.
45924d58133SDimitry Andric if (HoistLifeEnd && !ExitBlock)
46024d58133SDimitry Andric return std::make_pair<Instruction *>(nullptr, nullptr);
46124d58133SDimitry Andric
46224d58133SDimitry Andric return std::make_pair(LifeStart, LifeEnd);
463f9448bf3SDimitry Andric };
464f9448bf3SDimitry Andric
46524d58133SDimitry Andric bool SinkLifeStart = false, HoistLifeEnd = false;
46624d58133SDimitry Andric auto Markers = GetLifeTimeMarkers(AI, SinkLifeStart, HoistLifeEnd);
46724d58133SDimitry Andric
46824d58133SDimitry Andric if (Markers.first) {
46924d58133SDimitry Andric if (SinkLifeStart)
47024d58133SDimitry Andric SinkCands.insert(Markers.first);
471f9448bf3SDimitry Andric SinkCands.insert(AI);
47224d58133SDimitry Andric if (HoistLifeEnd)
47324d58133SDimitry Andric HoistCands.insert(Markers.second);
474f9448bf3SDimitry Andric continue;
475f9448bf3SDimitry Andric }
476f9448bf3SDimitry Andric
47724d58133SDimitry Andric // Follow the bitcast.
478f9448bf3SDimitry Andric Instruction *MarkerAddr = nullptr;
479f9448bf3SDimitry Andric for (User *U : AI->users()) {
48024d58133SDimitry Andric if (U->stripInBoundsConstantOffsets() == AI) {
48124d58133SDimitry Andric SinkLifeStart = false;
48224d58133SDimitry Andric HoistLifeEnd = false;
483f9448bf3SDimitry Andric Instruction *Bitcast = cast<Instruction>(U);
48424d58133SDimitry Andric Markers = GetLifeTimeMarkers(Bitcast, SinkLifeStart, HoistLifeEnd);
48524d58133SDimitry Andric if (Markers.first) {
486f9448bf3SDimitry Andric MarkerAddr = Bitcast;
487f9448bf3SDimitry Andric continue;
488f9448bf3SDimitry Andric }
489f9448bf3SDimitry Andric }
49024d58133SDimitry Andric
49124d58133SDimitry Andric // Found unknown use of AI.
492f9448bf3SDimitry Andric if (!definedInRegion(Blocks, U)) {
493f9448bf3SDimitry Andric MarkerAddr = nullptr;
494f9448bf3SDimitry Andric break;
495f9448bf3SDimitry Andric }
496f9448bf3SDimitry Andric }
49724d58133SDimitry Andric
498f9448bf3SDimitry Andric if (MarkerAddr) {
49924d58133SDimitry Andric if (SinkLifeStart)
50024d58133SDimitry Andric SinkCands.insert(Markers.first);
501f9448bf3SDimitry Andric if (!definedInRegion(Blocks, MarkerAddr))
502f9448bf3SDimitry Andric SinkCands.insert(MarkerAddr);
503f9448bf3SDimitry Andric SinkCands.insert(AI);
50424d58133SDimitry Andric if (HoistLifeEnd)
50524d58133SDimitry Andric HoistCands.insert(Markers.second);
506f9448bf3SDimitry Andric }
507f9448bf3SDimitry Andric }
508f9448bf3SDimitry Andric }
509f9448bf3SDimitry Andric }
510f9448bf3SDimitry Andric
findInputsOutputs(ValueSet & Inputs,ValueSet & Outputs,const ValueSet & SinkCands) const511f9448bf3SDimitry Andric void CodeExtractor::findInputsOutputs(ValueSet &Inputs, ValueSet &Outputs,
512f9448bf3SDimitry Andric const ValueSet &SinkCands) const {
5133ca95b02SDimitry Andric for (BasicBlock *BB : Blocks) {
5147ae0e2c9SDimitry Andric // If a used value is defined outside the region, it's an input. If an
5157ae0e2c9SDimitry Andric // instruction is used outside the region, it's an output.
5163ca95b02SDimitry Andric for (Instruction &II : *BB) {
5173ca95b02SDimitry Andric for (User::op_iterator OI = II.op_begin(), OE = II.op_end(); OI != OE;
518f9448bf3SDimitry Andric ++OI) {
519f9448bf3SDimitry Andric Value *V = *OI;
520f9448bf3SDimitry Andric if (!SinkCands.count(V) && definedInCaller(Blocks, V))
521f9448bf3SDimitry Andric Inputs.insert(V);
522f9448bf3SDimitry Andric }
523f22ef01cSRoman Divacky
5243ca95b02SDimitry Andric for (User *U : II.users())
52591bc56edSDimitry Andric if (!definedInRegion(Blocks, U)) {
5263ca95b02SDimitry Andric Outputs.insert(&II);
5277ae0e2c9SDimitry Andric break;
5287ae0e2c9SDimitry Andric }
5297ae0e2c9SDimitry Andric }
5307ae0e2c9SDimitry Andric }
531f22ef01cSRoman Divacky }
532f22ef01cSRoman Divacky
533*b5893f02SDimitry Andric /// severSplitPHINodesOfEntry - If a PHI node has multiple inputs from outside
534*b5893f02SDimitry Andric /// of the region, we need to split the entry block of the region so that the
535*b5893f02SDimitry Andric /// PHI node is easier to deal with.
severSplitPHINodesOfEntry(BasicBlock * & Header)536*b5893f02SDimitry Andric void CodeExtractor::severSplitPHINodesOfEntry(BasicBlock *&Header) {
5373b0f4066SDimitry Andric unsigned NumPredsFromRegion = 0;
538f22ef01cSRoman Divacky unsigned NumPredsOutsideRegion = 0;
539f22ef01cSRoman Divacky
540f22ef01cSRoman Divacky if (Header != &Header->getParent()->getEntryBlock()) {
541f22ef01cSRoman Divacky PHINode *PN = dyn_cast<PHINode>(Header->begin());
542f22ef01cSRoman Divacky if (!PN) return; // No PHI nodes.
543f22ef01cSRoman Divacky
544f22ef01cSRoman Divacky // If the header node contains any PHI nodes, check to see if there is more
545f22ef01cSRoman Divacky // than one entry from outside the region. If so, we need to sever the
546f22ef01cSRoman Divacky // header block into two.
547f22ef01cSRoman Divacky for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
5487ae0e2c9SDimitry Andric if (Blocks.count(PN->getIncomingBlock(i)))
5493b0f4066SDimitry Andric ++NumPredsFromRegion;
550f22ef01cSRoman Divacky else
551f22ef01cSRoman Divacky ++NumPredsOutsideRegion;
552f22ef01cSRoman Divacky
553f22ef01cSRoman Divacky // If there is one (or fewer) predecessor from outside the region, we don't
554f22ef01cSRoman Divacky // need to do anything special.
555f22ef01cSRoman Divacky if (NumPredsOutsideRegion <= 1) return;
556f22ef01cSRoman Divacky }
557f22ef01cSRoman Divacky
558f22ef01cSRoman Divacky // Otherwise, we need to split the header block into two pieces: one
559f22ef01cSRoman Divacky // containing PHI nodes merging values from outside of the region, and a
560f22ef01cSRoman Divacky // second that contains all of the code for the block and merges back any
561f22ef01cSRoman Divacky // incoming values from inside of the region.
5622cab237bSDimitry Andric BasicBlock *NewBB = SplitBlock(Header, Header->getFirstNonPHI(), DT);
563f22ef01cSRoman Divacky
564f22ef01cSRoman Divacky // We only want to code extract the second block now, and it becomes the new
565f22ef01cSRoman Divacky // header of the region.
566f22ef01cSRoman Divacky BasicBlock *OldPred = Header;
5677ae0e2c9SDimitry Andric Blocks.remove(OldPred);
5687ae0e2c9SDimitry Andric Blocks.insert(NewBB);
569f22ef01cSRoman Divacky Header = NewBB;
570f22ef01cSRoman Divacky
571f22ef01cSRoman Divacky // Okay, now we need to adjust the PHI nodes and any branches from within the
572f22ef01cSRoman Divacky // region to go to the new header block instead of the old header block.
5733b0f4066SDimitry Andric if (NumPredsFromRegion) {
574f22ef01cSRoman Divacky PHINode *PN = cast<PHINode>(OldPred->begin());
575f22ef01cSRoman Divacky // Loop over all of the predecessors of OldPred that are in the region,
576f22ef01cSRoman Divacky // changing them to branch to NewBB instead.
577f22ef01cSRoman Divacky for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
5787ae0e2c9SDimitry Andric if (Blocks.count(PN->getIncomingBlock(i))) {
579*b5893f02SDimitry Andric Instruction *TI = PN->getIncomingBlock(i)->getTerminator();
580f22ef01cSRoman Divacky TI->replaceUsesOfWith(OldPred, NewBB);
581f22ef01cSRoman Divacky }
582f22ef01cSRoman Divacky
5833b0f4066SDimitry Andric // Okay, everything within the region is now branching to the right block, we
584f22ef01cSRoman Divacky // just have to update the PHI nodes now, inserting PHI nodes into NewBB.
58551690af2SDimitry Andric BasicBlock::iterator AfterPHIs;
586f22ef01cSRoman Divacky for (AfterPHIs = OldPred->begin(); isa<PHINode>(AfterPHIs); ++AfterPHIs) {
587f22ef01cSRoman Divacky PHINode *PN = cast<PHINode>(AfterPHIs);
588f22ef01cSRoman Divacky // Create a new PHI node in the new region, which has an incoming value
589f22ef01cSRoman Divacky // from OldPred of PN.
5903b0f4066SDimitry Andric PHINode *NewPN = PHINode::Create(PN->getType(), 1 + NumPredsFromRegion,
5917d523365SDimitry Andric PN->getName() + ".ce", &NewBB->front());
59251690af2SDimitry Andric PN->replaceAllUsesWith(NewPN);
593f22ef01cSRoman Divacky NewPN->addIncoming(PN, OldPred);
594f22ef01cSRoman Divacky
595f22ef01cSRoman Divacky // Loop over all of the incoming value in PN, moving them to NewPN if they
596f22ef01cSRoman Divacky // are from the extracted region.
597f22ef01cSRoman Divacky for (unsigned i = 0; i != PN->getNumIncomingValues(); ++i) {
5987ae0e2c9SDimitry Andric if (Blocks.count(PN->getIncomingBlock(i))) {
599f22ef01cSRoman Divacky NewPN->addIncoming(PN->getIncomingValue(i), PN->getIncomingBlock(i));
600f22ef01cSRoman Divacky PN->removeIncomingValue(i);
601f22ef01cSRoman Divacky --i;
602f22ef01cSRoman Divacky }
603f22ef01cSRoman Divacky }
604f22ef01cSRoman Divacky }
605f22ef01cSRoman Divacky }
606f22ef01cSRoman Divacky }
607f22ef01cSRoman Divacky
608*b5893f02SDimitry Andric /// severSplitPHINodesOfExits - if PHI nodes in exit blocks have inputs from
609*b5893f02SDimitry Andric /// outlined region, we split these PHIs on two: one with inputs from region
610*b5893f02SDimitry Andric /// and other with remaining incoming blocks; then first PHIs are placed in
611*b5893f02SDimitry Andric /// outlined region.
severSplitPHINodesOfExits(const SmallPtrSetImpl<BasicBlock * > & Exits)612*b5893f02SDimitry Andric void CodeExtractor::severSplitPHINodesOfExits(
613*b5893f02SDimitry Andric const SmallPtrSetImpl<BasicBlock *> &Exits) {
614*b5893f02SDimitry Andric for (BasicBlock *ExitBB : Exits) {
615*b5893f02SDimitry Andric BasicBlock *NewBB = nullptr;
616*b5893f02SDimitry Andric
617*b5893f02SDimitry Andric for (PHINode &PN : ExitBB->phis()) {
618*b5893f02SDimitry Andric // Find all incoming values from the outlining region.
619*b5893f02SDimitry Andric SmallVector<unsigned, 2> IncomingVals;
620*b5893f02SDimitry Andric for (unsigned i = 0; i < PN.getNumIncomingValues(); ++i)
621*b5893f02SDimitry Andric if (Blocks.count(PN.getIncomingBlock(i)))
622*b5893f02SDimitry Andric IncomingVals.push_back(i);
623*b5893f02SDimitry Andric
624*b5893f02SDimitry Andric // Do not process PHI if there is one (or fewer) predecessor from region.
625*b5893f02SDimitry Andric // If PHI has exactly one predecessor from region, only this one incoming
626*b5893f02SDimitry Andric // will be replaced on codeRepl block, so it should be safe to skip PHI.
627*b5893f02SDimitry Andric if (IncomingVals.size() <= 1)
628*b5893f02SDimitry Andric continue;
629*b5893f02SDimitry Andric
630*b5893f02SDimitry Andric // Create block for new PHIs and add it to the list of outlined if it
631*b5893f02SDimitry Andric // wasn't done before.
632*b5893f02SDimitry Andric if (!NewBB) {
633*b5893f02SDimitry Andric NewBB = BasicBlock::Create(ExitBB->getContext(),
634*b5893f02SDimitry Andric ExitBB->getName() + ".split",
635*b5893f02SDimitry Andric ExitBB->getParent(), ExitBB);
636*b5893f02SDimitry Andric SmallVector<BasicBlock *, 4> Preds(pred_begin(ExitBB),
637*b5893f02SDimitry Andric pred_end(ExitBB));
638*b5893f02SDimitry Andric for (BasicBlock *PredBB : Preds)
639*b5893f02SDimitry Andric if (Blocks.count(PredBB))
640*b5893f02SDimitry Andric PredBB->getTerminator()->replaceUsesOfWith(ExitBB, NewBB);
641*b5893f02SDimitry Andric BranchInst::Create(ExitBB, NewBB);
642*b5893f02SDimitry Andric Blocks.insert(NewBB);
643*b5893f02SDimitry Andric }
644*b5893f02SDimitry Andric
645*b5893f02SDimitry Andric // Split this PHI.
646*b5893f02SDimitry Andric PHINode *NewPN =
647*b5893f02SDimitry Andric PHINode::Create(PN.getType(), IncomingVals.size(),
648*b5893f02SDimitry Andric PN.getName() + ".ce", NewBB->getFirstNonPHI());
649*b5893f02SDimitry Andric for (unsigned i : IncomingVals)
650*b5893f02SDimitry Andric NewPN->addIncoming(PN.getIncomingValue(i), PN.getIncomingBlock(i));
651*b5893f02SDimitry Andric for (unsigned i : reverse(IncomingVals))
652*b5893f02SDimitry Andric PN.removeIncomingValue(i, false);
653*b5893f02SDimitry Andric PN.addIncoming(NewPN, NewBB);
654*b5893f02SDimitry Andric }
655*b5893f02SDimitry Andric }
656*b5893f02SDimitry Andric }
657*b5893f02SDimitry Andric
splitReturnBlocks()658f22ef01cSRoman Divacky void CodeExtractor::splitReturnBlocks() {
6593ca95b02SDimitry Andric for (BasicBlock *Block : Blocks)
6603ca95b02SDimitry Andric if (ReturnInst *RI = dyn_cast<ReturnInst>(Block->getTerminator())) {
6617d523365SDimitry Andric BasicBlock *New =
6623ca95b02SDimitry Andric Block->splitBasicBlock(RI->getIterator(), Block->getName() + ".ret");
663f22ef01cSRoman Divacky if (DT) {
6642754fe60SDimitry Andric // Old dominates New. New node dominates all other nodes dominated
665f22ef01cSRoman Divacky // by Old.
6663ca95b02SDimitry Andric DomTreeNode *OldNode = DT->getNode(Block);
6673ca95b02SDimitry Andric SmallVector<DomTreeNode *, 8> Children(OldNode->begin(),
6683ca95b02SDimitry Andric OldNode->end());
669f22ef01cSRoman Divacky
6703ca95b02SDimitry Andric DomTreeNode *NewNode = DT->addNewBlock(New, Block);
671f22ef01cSRoman Divacky
6723ca95b02SDimitry Andric for (DomTreeNode *I : Children)
6733ca95b02SDimitry Andric DT->changeImmediateDominator(I, NewNode);
674f22ef01cSRoman Divacky }
675f22ef01cSRoman Divacky }
676f22ef01cSRoman Divacky }
677f22ef01cSRoman Divacky
678f22ef01cSRoman Divacky /// constructFunction - make a function based on inputs and outputs, as follows:
679f22ef01cSRoman Divacky /// f(in0, ..., inN, out0, ..., outN)
constructFunction(const ValueSet & inputs,const ValueSet & outputs,BasicBlock * header,BasicBlock * newRootNode,BasicBlock * newHeader,Function * oldFunction,Module * M)6807ae0e2c9SDimitry Andric Function *CodeExtractor::constructFunction(const ValueSet &inputs,
6817ae0e2c9SDimitry Andric const ValueSet &outputs,
682f22ef01cSRoman Divacky BasicBlock *header,
683f22ef01cSRoman Divacky BasicBlock *newRootNode,
684f22ef01cSRoman Divacky BasicBlock *newHeader,
685f22ef01cSRoman Divacky Function *oldFunction,
686f22ef01cSRoman Divacky Module *M) {
6874ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "inputs: " << inputs.size() << "\n");
6884ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "outputs: " << outputs.size() << "\n");
689f22ef01cSRoman Divacky
690f22ef01cSRoman Divacky // This function returns unsigned, outputs will go back by reference.
691f22ef01cSRoman Divacky switch (NumExitBlocks) {
692f22ef01cSRoman Divacky case 0:
693f22ef01cSRoman Divacky case 1: RetTy = Type::getVoidTy(header->getContext()); break;
694f22ef01cSRoman Divacky case 2: RetTy = Type::getInt1Ty(header->getContext()); break;
695f22ef01cSRoman Divacky default: RetTy = Type::getInt16Ty(header->getContext()); break;
696f22ef01cSRoman Divacky }
697f22ef01cSRoman Divacky
69817a519f9SDimitry Andric std::vector<Type *> paramTy;
699f22ef01cSRoman Divacky
700f22ef01cSRoman Divacky // Add the types of the input values to the function's argument list
7013ca95b02SDimitry Andric for (Value *value : inputs) {
7024ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "value used in func: " << *value << "\n");
703f22ef01cSRoman Divacky paramTy.push_back(value->getType());
704f22ef01cSRoman Divacky }
705f22ef01cSRoman Divacky
706f22ef01cSRoman Divacky // Add the types of the output values to the function's argument list.
7073ca95b02SDimitry Andric for (Value *output : outputs) {
7084ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "instr used in func: " << *output << "\n");
709f22ef01cSRoman Divacky if (AggregateArgs)
7103ca95b02SDimitry Andric paramTy.push_back(output->getType());
711f22ef01cSRoman Divacky else
7123ca95b02SDimitry Andric paramTy.push_back(PointerType::getUnqual(output->getType()));
713f22ef01cSRoman Divacky }
714f22ef01cSRoman Divacky
7154ba319b5SDimitry Andric LLVM_DEBUG({
7163ca95b02SDimitry Andric dbgs() << "Function type: " << *RetTy << " f(";
7173ca95b02SDimitry Andric for (Type *i : paramTy)
7183ca95b02SDimitry Andric dbgs() << *i << ", ";
7193ca95b02SDimitry Andric dbgs() << ")\n";
7203ca95b02SDimitry Andric });
721f22ef01cSRoman Divacky
722ff0cc061SDimitry Andric StructType *StructTy;
723f22ef01cSRoman Divacky if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
724ff0cc061SDimitry Andric StructTy = StructType::get(M->getContext(), paramTy);
725f22ef01cSRoman Divacky paramTy.clear();
726ff0cc061SDimitry Andric paramTy.push_back(PointerType::getUnqual(StructTy));
727f22ef01cSRoman Divacky }
7286122f3e6SDimitry Andric FunctionType *funcType =
7292cab237bSDimitry Andric FunctionType::get(RetTy, paramTy,
7302cab237bSDimitry Andric AllowVarArgs && oldFunction->isVarArg());
731f22ef01cSRoman Divacky
732*b5893f02SDimitry Andric std::string SuffixToUse =
733*b5893f02SDimitry Andric Suffix.empty()
734*b5893f02SDimitry Andric ? (header->getName().empty() ? "extracted" : header->getName().str())
735*b5893f02SDimitry Andric : Suffix;
736f22ef01cSRoman Divacky // Create the new function
737*b5893f02SDimitry Andric Function *newFunction = Function::Create(
738*b5893f02SDimitry Andric funcType, GlobalValue::InternalLinkage, oldFunction->getAddressSpace(),
739*b5893f02SDimitry Andric oldFunction->getName() + "." + SuffixToUse, M);
740f22ef01cSRoman Divacky // If the old function is no-throw, so is the new one.
741f22ef01cSRoman Divacky if (oldFunction->doesNotThrow())
7423861d79fSDimitry Andric newFunction->setDoesNotThrow();
743f22ef01cSRoman Divacky
744d88c1a5aSDimitry Andric // Inherit the uwtable attribute if we need to.
745d88c1a5aSDimitry Andric if (oldFunction->hasUWTable())
746d88c1a5aSDimitry Andric newFunction->setHasUWTable();
747d88c1a5aSDimitry Andric
7484ba319b5SDimitry Andric // Inherit all of the target dependent attributes and white-listed
7494ba319b5SDimitry Andric // target independent attributes.
750d88c1a5aSDimitry Andric // (e.g. If the extracted region contains a call to an x86.sse
751d88c1a5aSDimitry Andric // instruction we need to make sure that the extracted region has the
752d88c1a5aSDimitry Andric // "target-features" attribute allowing it to be lowered.
753d88c1a5aSDimitry Andric // FIXME: This should be changed to check to see if a specific
754d88c1a5aSDimitry Andric // attribute can not be inherited.
7554ba319b5SDimitry Andric for (const auto &Attr : oldFunction->getAttributes().getFnAttributes()) {
7564ba319b5SDimitry Andric if (Attr.isStringAttribute()) {
7574ba319b5SDimitry Andric if (Attr.getKindAsString() == "thunk")
7584ba319b5SDimitry Andric continue;
7594ba319b5SDimitry Andric } else
7604ba319b5SDimitry Andric switch (Attr.getKindAsEnum()) {
7614ba319b5SDimitry Andric // Those attributes cannot be propagated safely. Explicitly list them
7624ba319b5SDimitry Andric // here so we get a warning if new attributes are added. This list also
7634ba319b5SDimitry Andric // includes non-function attributes.
7644ba319b5SDimitry Andric case Attribute::Alignment:
7654ba319b5SDimitry Andric case Attribute::AllocSize:
7664ba319b5SDimitry Andric case Attribute::ArgMemOnly:
7674ba319b5SDimitry Andric case Attribute::Builtin:
7684ba319b5SDimitry Andric case Attribute::ByVal:
7694ba319b5SDimitry Andric case Attribute::Convergent:
7704ba319b5SDimitry Andric case Attribute::Dereferenceable:
7714ba319b5SDimitry Andric case Attribute::DereferenceableOrNull:
7724ba319b5SDimitry Andric case Attribute::InAlloca:
7734ba319b5SDimitry Andric case Attribute::InReg:
7744ba319b5SDimitry Andric case Attribute::InaccessibleMemOnly:
7754ba319b5SDimitry Andric case Attribute::InaccessibleMemOrArgMemOnly:
7764ba319b5SDimitry Andric case Attribute::JumpTable:
7774ba319b5SDimitry Andric case Attribute::Naked:
7784ba319b5SDimitry Andric case Attribute::Nest:
7794ba319b5SDimitry Andric case Attribute::NoAlias:
7804ba319b5SDimitry Andric case Attribute::NoBuiltin:
7814ba319b5SDimitry Andric case Attribute::NoCapture:
7824ba319b5SDimitry Andric case Attribute::NoReturn:
7834ba319b5SDimitry Andric case Attribute::None:
7844ba319b5SDimitry Andric case Attribute::NonNull:
7854ba319b5SDimitry Andric case Attribute::ReadNone:
7864ba319b5SDimitry Andric case Attribute::ReadOnly:
7874ba319b5SDimitry Andric case Attribute::Returned:
7884ba319b5SDimitry Andric case Attribute::ReturnsTwice:
7894ba319b5SDimitry Andric case Attribute::SExt:
7904ba319b5SDimitry Andric case Attribute::Speculatable:
7914ba319b5SDimitry Andric case Attribute::StackAlignment:
7924ba319b5SDimitry Andric case Attribute::StructRet:
7934ba319b5SDimitry Andric case Attribute::SwiftError:
7944ba319b5SDimitry Andric case Attribute::SwiftSelf:
7954ba319b5SDimitry Andric case Attribute::WriteOnly:
7964ba319b5SDimitry Andric case Attribute::ZExt:
7974ba319b5SDimitry Andric case Attribute::EndAttrKinds:
7984ba319b5SDimitry Andric continue;
7994ba319b5SDimitry Andric // Those attributes should be safe to propagate to the extracted function.
8004ba319b5SDimitry Andric case Attribute::AlwaysInline:
8014ba319b5SDimitry Andric case Attribute::Cold:
8024ba319b5SDimitry Andric case Attribute::NoRecurse:
8034ba319b5SDimitry Andric case Attribute::InlineHint:
8044ba319b5SDimitry Andric case Attribute::MinSize:
8054ba319b5SDimitry Andric case Attribute::NoDuplicate:
8064ba319b5SDimitry Andric case Attribute::NoImplicitFloat:
8074ba319b5SDimitry Andric case Attribute::NoInline:
8084ba319b5SDimitry Andric case Attribute::NonLazyBind:
8094ba319b5SDimitry Andric case Attribute::NoRedZone:
8104ba319b5SDimitry Andric case Attribute::NoUnwind:
8114ba319b5SDimitry Andric case Attribute::OptForFuzzing:
8124ba319b5SDimitry Andric case Attribute::OptimizeNone:
8134ba319b5SDimitry Andric case Attribute::OptimizeForSize:
8144ba319b5SDimitry Andric case Attribute::SafeStack:
8154ba319b5SDimitry Andric case Attribute::ShadowCallStack:
8164ba319b5SDimitry Andric case Attribute::SanitizeAddress:
8174ba319b5SDimitry Andric case Attribute::SanitizeMemory:
8184ba319b5SDimitry Andric case Attribute::SanitizeThread:
8194ba319b5SDimitry Andric case Attribute::SanitizeHWAddress:
820*b5893f02SDimitry Andric case Attribute::SpeculativeLoadHardening:
8214ba319b5SDimitry Andric case Attribute::StackProtect:
8224ba319b5SDimitry Andric case Attribute::StackProtectReq:
8234ba319b5SDimitry Andric case Attribute::StackProtectStrong:
8244ba319b5SDimitry Andric case Attribute::StrictFP:
8254ba319b5SDimitry Andric case Attribute::UWTable:
8264ba319b5SDimitry Andric case Attribute::NoCfCheck:
8274ba319b5SDimitry Andric break;
8284ba319b5SDimitry Andric }
829d88c1a5aSDimitry Andric
8304ba319b5SDimitry Andric newFunction->addFnAttr(Attr);
8314ba319b5SDimitry Andric }
832f22ef01cSRoman Divacky newFunction->getBasicBlockList().push_back(newRootNode);
833f22ef01cSRoman Divacky
834f22ef01cSRoman Divacky // Create an iterator to name all of the arguments we inserted.
835f22ef01cSRoman Divacky Function::arg_iterator AI = newFunction->arg_begin();
836f22ef01cSRoman Divacky
837f22ef01cSRoman Divacky // Rewrite all users of the inputs in the extracted region to use the
838f22ef01cSRoman Divacky // arguments (or appropriate addressing into struct) instead.
839f22ef01cSRoman Divacky for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
840f22ef01cSRoman Divacky Value *RewriteVal;
841f22ef01cSRoman Divacky if (AggregateArgs) {
842f22ef01cSRoman Divacky Value *Idx[2];
843f22ef01cSRoman Divacky Idx[0] = Constant::getNullValue(Type::getInt32Ty(header->getContext()));
844f22ef01cSRoman Divacky Idx[1] = ConstantInt::get(Type::getInt32Ty(header->getContext()), i);
845*b5893f02SDimitry Andric Instruction *TI = newFunction->begin()->getTerminator();
846ff0cc061SDimitry Andric GetElementPtrInst *GEP = GetElementPtrInst::Create(
8477d523365SDimitry Andric StructTy, &*AI, Idx, "gep_" + inputs[i]->getName(), TI);
848f22ef01cSRoman Divacky RewriteVal = new LoadInst(GEP, "loadgep_" + inputs[i]->getName(), TI);
849f22ef01cSRoman Divacky } else
8507d523365SDimitry Andric RewriteVal = &*AI++;
851f22ef01cSRoman Divacky
85291bc56edSDimitry Andric std::vector<User *> Users(inputs[i]->user_begin(), inputs[i]->user_end());
8533ca95b02SDimitry Andric for (User *use : Users)
8543ca95b02SDimitry Andric if (Instruction *inst = dyn_cast<Instruction>(use))
8557ae0e2c9SDimitry Andric if (Blocks.count(inst->getParent()))
856f22ef01cSRoman Divacky inst->replaceUsesOfWith(inputs[i], RewriteVal);
857f22ef01cSRoman Divacky }
858f22ef01cSRoman Divacky
859f22ef01cSRoman Divacky // Set names for input and output arguments.
860f22ef01cSRoman Divacky if (!AggregateArgs) {
861f22ef01cSRoman Divacky AI = newFunction->arg_begin();
862f22ef01cSRoman Divacky for (unsigned i = 0, e = inputs.size(); i != e; ++i, ++AI)
863f22ef01cSRoman Divacky AI->setName(inputs[i]->getName());
864f22ef01cSRoman Divacky for (unsigned i = 0, e = outputs.size(); i != e; ++i, ++AI)
865f22ef01cSRoman Divacky AI->setName(outputs[i]->getName()+".out");
866f22ef01cSRoman Divacky }
867f22ef01cSRoman Divacky
868f22ef01cSRoman Divacky // Rewrite branches to basic blocks outside of the loop to new dummy blocks
869f22ef01cSRoman Divacky // within the new function. This must be done before we lose track of which
870f22ef01cSRoman Divacky // blocks were originally in the code region.
87191bc56edSDimitry Andric std::vector<User *> Users(header->user_begin(), header->user_end());
872f22ef01cSRoman Divacky for (unsigned i = 0, e = Users.size(); i != e; ++i)
873f22ef01cSRoman Divacky // The BasicBlock which contains the branch is not in the region
874f22ef01cSRoman Divacky // modify the branch target to a new block
875*b5893f02SDimitry Andric if (Instruction *I = dyn_cast<Instruction>(Users[i]))
876*b5893f02SDimitry Andric if (I->isTerminator() && !Blocks.count(I->getParent()) &&
877*b5893f02SDimitry Andric I->getParent()->getParent() == oldFunction)
878*b5893f02SDimitry Andric I->replaceUsesOfWith(header, newHeader);
879f22ef01cSRoman Divacky
880f22ef01cSRoman Divacky return newFunction;
881f22ef01cSRoman Divacky }
882f22ef01cSRoman Divacky
883f22ef01cSRoman Divacky /// emitCallAndSwitchStatement - This method sets up the caller side by adding
884f22ef01cSRoman Divacky /// the call instruction, splitting any PHI nodes in the header block as
885f22ef01cSRoman Divacky /// necessary.
emitCallAndSwitchStatement(Function * newFunction,BasicBlock * codeReplacer,ValueSet & inputs,ValueSet & outputs)886*b5893f02SDimitry Andric CallInst *CodeExtractor::emitCallAndSwitchStatement(Function *newFunction,
887*b5893f02SDimitry Andric BasicBlock *codeReplacer,
888*b5893f02SDimitry Andric ValueSet &inputs,
889*b5893f02SDimitry Andric ValueSet &outputs) {
890f22ef01cSRoman Divacky // Emit a call to the new function, passing in: *pointer to struct (if
891f22ef01cSRoman Divacky // aggregating parameters), or plan inputs and allocated memory for outputs
892f22ef01cSRoman Divacky std::vector<Value *> params, StructValues, ReloadOutputs, Reloads;
893f22ef01cSRoman Divacky
8947a7e6055SDimitry Andric Module *M = newFunction->getParent();
8957a7e6055SDimitry Andric LLVMContext &Context = M->getContext();
8967a7e6055SDimitry Andric const DataLayout &DL = M->getDataLayout();
897*b5893f02SDimitry Andric CallInst *call = nullptr;
898f22ef01cSRoman Divacky
899f22ef01cSRoman Divacky // Add inputs as params, or to be filled into the struct
9003ca95b02SDimitry Andric for (Value *input : inputs)
901f22ef01cSRoman Divacky if (AggregateArgs)
9023ca95b02SDimitry Andric StructValues.push_back(input);
903f22ef01cSRoman Divacky else
9043ca95b02SDimitry Andric params.push_back(input);
905f22ef01cSRoman Divacky
906f22ef01cSRoman Divacky // Create allocas for the outputs
9073ca95b02SDimitry Andric for (Value *output : outputs) {
908f22ef01cSRoman Divacky if (AggregateArgs) {
9093ca95b02SDimitry Andric StructValues.push_back(output);
910f22ef01cSRoman Divacky } else {
911f22ef01cSRoman Divacky AllocaInst *alloca =
9127a7e6055SDimitry Andric new AllocaInst(output->getType(), DL.getAllocaAddrSpace(),
9137a7e6055SDimitry Andric nullptr, output->getName() + ".loc",
9147d523365SDimitry Andric &codeReplacer->getParent()->front().front());
915f22ef01cSRoman Divacky ReloadOutputs.push_back(alloca);
916f22ef01cSRoman Divacky params.push_back(alloca);
917f22ef01cSRoman Divacky }
918f22ef01cSRoman Divacky }
919f22ef01cSRoman Divacky
920ff0cc061SDimitry Andric StructType *StructArgTy = nullptr;
92191bc56edSDimitry Andric AllocaInst *Struct = nullptr;
922f22ef01cSRoman Divacky if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
92317a519f9SDimitry Andric std::vector<Type *> ArgTypes;
9247ae0e2c9SDimitry Andric for (ValueSet::iterator v = StructValues.begin(),
925f22ef01cSRoman Divacky ve = StructValues.end(); v != ve; ++v)
926f22ef01cSRoman Divacky ArgTypes.push_back((*v)->getType());
927f22ef01cSRoman Divacky
928f22ef01cSRoman Divacky // Allocate a struct at the beginning of this function
929ff0cc061SDimitry Andric StructArgTy = StructType::get(newFunction->getContext(), ArgTypes);
9307a7e6055SDimitry Andric Struct = new AllocaInst(StructArgTy, DL.getAllocaAddrSpace(), nullptr,
9317a7e6055SDimitry Andric "structArg",
9327d523365SDimitry Andric &codeReplacer->getParent()->front().front());
933f22ef01cSRoman Divacky params.push_back(Struct);
934f22ef01cSRoman Divacky
935f22ef01cSRoman Divacky for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
936f22ef01cSRoman Divacky Value *Idx[2];
937f22ef01cSRoman Divacky Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
938f22ef01cSRoman Divacky Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), i);
939ff0cc061SDimitry Andric GetElementPtrInst *GEP = GetElementPtrInst::Create(
940ff0cc061SDimitry Andric StructArgTy, Struct, Idx, "gep_" + StructValues[i]->getName());
941f22ef01cSRoman Divacky codeReplacer->getInstList().push_back(GEP);
942f22ef01cSRoman Divacky StoreInst *SI = new StoreInst(StructValues[i], GEP);
943f22ef01cSRoman Divacky codeReplacer->getInstList().push_back(SI);
944f22ef01cSRoman Divacky }
945f22ef01cSRoman Divacky }
946f22ef01cSRoman Divacky
947f22ef01cSRoman Divacky // Emit the call to the function
948*b5893f02SDimitry Andric call = CallInst::Create(newFunction, params,
949f22ef01cSRoman Divacky NumExitBlocks > 1 ? "targetBlock" : "");
9502cab237bSDimitry Andric // Add debug location to the new call, if the original function has debug
9512cab237bSDimitry Andric // info. In that case, the terminator of the entry block of the extracted
9522cab237bSDimitry Andric // function contains the first debug location of the extracted function,
9532cab237bSDimitry Andric // set in extractCodeRegion.
9542cab237bSDimitry Andric if (codeReplacer->getParent()->getSubprogram()) {
9552cab237bSDimitry Andric if (auto DL = newFunction->getEntryBlock().getTerminator()->getDebugLoc())
9562cab237bSDimitry Andric call->setDebugLoc(DL);
9572cab237bSDimitry Andric }
958f22ef01cSRoman Divacky codeReplacer->getInstList().push_back(call);
959f22ef01cSRoman Divacky
960f22ef01cSRoman Divacky Function::arg_iterator OutputArgBegin = newFunction->arg_begin();
961f22ef01cSRoman Divacky unsigned FirstOut = inputs.size();
962f22ef01cSRoman Divacky if (!AggregateArgs)
963f22ef01cSRoman Divacky std::advance(OutputArgBegin, inputs.size());
964f22ef01cSRoman Divacky
9652cab237bSDimitry Andric // Reload the outputs passed in by reference.
9662cab237bSDimitry Andric Function::arg_iterator OAI = OutputArgBegin;
967f22ef01cSRoman Divacky for (unsigned i = 0, e = outputs.size(); i != e; ++i) {
96891bc56edSDimitry Andric Value *Output = nullptr;
969f22ef01cSRoman Divacky if (AggregateArgs) {
970f22ef01cSRoman Divacky Value *Idx[2];
971f22ef01cSRoman Divacky Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
972f22ef01cSRoman Divacky Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), FirstOut + i);
973ff0cc061SDimitry Andric GetElementPtrInst *GEP = GetElementPtrInst::Create(
974ff0cc061SDimitry Andric StructArgTy, Struct, Idx, "gep_reload_" + outputs[i]->getName());
975f22ef01cSRoman Divacky codeReplacer->getInstList().push_back(GEP);
976f22ef01cSRoman Divacky Output = GEP;
977f22ef01cSRoman Divacky } else {
978f22ef01cSRoman Divacky Output = ReloadOutputs[i];
979f22ef01cSRoman Divacky }
980f22ef01cSRoman Divacky LoadInst *load = new LoadInst(Output, outputs[i]->getName()+".reload");
981f22ef01cSRoman Divacky Reloads.push_back(load);
982f22ef01cSRoman Divacky codeReplacer->getInstList().push_back(load);
98391bc56edSDimitry Andric std::vector<User *> Users(outputs[i]->user_begin(), outputs[i]->user_end());
984f22ef01cSRoman Divacky for (unsigned u = 0, e = Users.size(); u != e; ++u) {
985f22ef01cSRoman Divacky Instruction *inst = cast<Instruction>(Users[u]);
9867ae0e2c9SDimitry Andric if (!Blocks.count(inst->getParent()))
987f22ef01cSRoman Divacky inst->replaceUsesOfWith(outputs[i], load);
988f22ef01cSRoman Divacky }
9892cab237bSDimitry Andric
9902cab237bSDimitry Andric // Store to argument right after the definition of output value.
9912cab237bSDimitry Andric auto *OutI = dyn_cast<Instruction>(outputs[i]);
9922cab237bSDimitry Andric if (!OutI)
9932cab237bSDimitry Andric continue;
994*b5893f02SDimitry Andric
9952cab237bSDimitry Andric // Find proper insertion point.
996*b5893f02SDimitry Andric BasicBlock::iterator InsertPt;
997*b5893f02SDimitry Andric // In case OutI is an invoke, we insert the store at the beginning in the
998*b5893f02SDimitry Andric // 'normal destination' BB. Otherwise we insert the store right after OutI.
999*b5893f02SDimitry Andric if (auto *InvokeI = dyn_cast<InvokeInst>(OutI))
1000*b5893f02SDimitry Andric InsertPt = InvokeI->getNormalDest()->getFirstInsertionPt();
1001*b5893f02SDimitry Andric else if (auto *Phi = dyn_cast<PHINode>(OutI))
1002*b5893f02SDimitry Andric InsertPt = Phi->getParent()->getFirstInsertionPt();
1003*b5893f02SDimitry Andric else
1004*b5893f02SDimitry Andric InsertPt = std::next(OutI->getIterator());
10052cab237bSDimitry Andric
10062cab237bSDimitry Andric assert(OAI != newFunction->arg_end() &&
10072cab237bSDimitry Andric "Number of output arguments should match "
10082cab237bSDimitry Andric "the amount of defined values");
10092cab237bSDimitry Andric if (AggregateArgs) {
10102cab237bSDimitry Andric Value *Idx[2];
10112cab237bSDimitry Andric Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
10122cab237bSDimitry Andric Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), FirstOut + i);
10132cab237bSDimitry Andric GetElementPtrInst *GEP = GetElementPtrInst::Create(
1014*b5893f02SDimitry Andric StructArgTy, &*OAI, Idx, "gep_" + outputs[i]->getName(), &*InsertPt);
1015*b5893f02SDimitry Andric new StoreInst(outputs[i], GEP, &*InsertPt);
10162cab237bSDimitry Andric // Since there should be only one struct argument aggregating
10172cab237bSDimitry Andric // all the output values, we shouldn't increment OAI, which always
10182cab237bSDimitry Andric // points to the struct argument, in this case.
10192cab237bSDimitry Andric } else {
1020*b5893f02SDimitry Andric new StoreInst(outputs[i], &*OAI, &*InsertPt);
10212cab237bSDimitry Andric ++OAI;
10222cab237bSDimitry Andric }
1023f22ef01cSRoman Divacky }
1024f22ef01cSRoman Divacky
1025f22ef01cSRoman Divacky // Now we can emit a switch statement using the call as a value.
1026f22ef01cSRoman Divacky SwitchInst *TheSwitch =
1027f22ef01cSRoman Divacky SwitchInst::Create(Constant::getNullValue(Type::getInt16Ty(Context)),
1028f22ef01cSRoman Divacky codeReplacer, 0, codeReplacer);
1029f22ef01cSRoman Divacky
1030f22ef01cSRoman Divacky // Since there may be multiple exits from the original region, make the new
1031f22ef01cSRoman Divacky // function return an unsigned, switch on that number. This loop iterates
1032f22ef01cSRoman Divacky // over all of the blocks in the extracted region, updating any terminator
1033f22ef01cSRoman Divacky // instructions in the to-be-extracted region that branch to blocks that are
1034f22ef01cSRoman Divacky // not in the region to be extracted.
1035f22ef01cSRoman Divacky std::map<BasicBlock *, BasicBlock *> ExitBlockMap;
1036f22ef01cSRoman Divacky
1037f22ef01cSRoman Divacky unsigned switchVal = 0;
10383ca95b02SDimitry Andric for (BasicBlock *Block : Blocks) {
1039*b5893f02SDimitry Andric Instruction *TI = Block->getTerminator();
1040f22ef01cSRoman Divacky for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
10417ae0e2c9SDimitry Andric if (!Blocks.count(TI->getSuccessor(i))) {
1042f22ef01cSRoman Divacky BasicBlock *OldTarget = TI->getSuccessor(i);
1043f22ef01cSRoman Divacky // add a new basic block which returns the appropriate value
1044f22ef01cSRoman Divacky BasicBlock *&NewTarget = ExitBlockMap[OldTarget];
1045f22ef01cSRoman Divacky if (!NewTarget) {
1046f22ef01cSRoman Divacky // If we don't already have an exit stub for this non-extracted
1047f22ef01cSRoman Divacky // destination, create one now!
1048f22ef01cSRoman Divacky NewTarget = BasicBlock::Create(Context,
1049f22ef01cSRoman Divacky OldTarget->getName() + ".exitStub",
1050f22ef01cSRoman Divacky newFunction);
1051f22ef01cSRoman Divacky unsigned SuccNum = switchVal++;
1052f22ef01cSRoman Divacky
105391bc56edSDimitry Andric Value *brVal = nullptr;
1054f22ef01cSRoman Divacky switch (NumExitBlocks) {
1055f22ef01cSRoman Divacky case 0:
1056f22ef01cSRoman Divacky case 1: break; // No value needed.
1057f22ef01cSRoman Divacky case 2: // Conditional branch, return a bool
1058f22ef01cSRoman Divacky brVal = ConstantInt::get(Type::getInt1Ty(Context), !SuccNum);
1059f22ef01cSRoman Divacky break;
1060f22ef01cSRoman Divacky default:
1061f22ef01cSRoman Divacky brVal = ConstantInt::get(Type::getInt16Ty(Context), SuccNum);
1062f22ef01cSRoman Divacky break;
1063f22ef01cSRoman Divacky }
1064f22ef01cSRoman Divacky
10652cab237bSDimitry Andric ReturnInst::Create(Context, brVal, NewTarget);
1066f22ef01cSRoman Divacky
1067f22ef01cSRoman Divacky // Update the switch instruction.
1068f22ef01cSRoman Divacky TheSwitch->addCase(ConstantInt::get(Type::getInt16Ty(Context),
1069f22ef01cSRoman Divacky SuccNum),
1070f22ef01cSRoman Divacky OldTarget);
1071f22ef01cSRoman Divacky }
1072f22ef01cSRoman Divacky
1073f22ef01cSRoman Divacky // rewrite the original branch instruction with this new target
1074f22ef01cSRoman Divacky TI->setSuccessor(i, NewTarget);
1075f22ef01cSRoman Divacky }
1076f22ef01cSRoman Divacky }
1077f22ef01cSRoman Divacky
1078f22ef01cSRoman Divacky // Now that we've done the deed, simplify the switch instruction.
10796122f3e6SDimitry Andric Type *OldFnRetTy = TheSwitch->getParent()->getParent()->getReturnType();
1080f22ef01cSRoman Divacky switch (NumExitBlocks) {
1081f22ef01cSRoman Divacky case 0:
1082f22ef01cSRoman Divacky // There are no successors (the block containing the switch itself), which
1083f22ef01cSRoman Divacky // means that previously this was the last part of the function, and hence
1084f22ef01cSRoman Divacky // this should be rewritten as a `ret'
1085f22ef01cSRoman Divacky
1086f22ef01cSRoman Divacky // Check if the function should return a value
1087f22ef01cSRoman Divacky if (OldFnRetTy->isVoidTy()) {
108891bc56edSDimitry Andric ReturnInst::Create(Context, nullptr, TheSwitch); // Return void
1089f22ef01cSRoman Divacky } else if (OldFnRetTy == TheSwitch->getCondition()->getType()) {
1090f22ef01cSRoman Divacky // return what we have
1091f22ef01cSRoman Divacky ReturnInst::Create(Context, TheSwitch->getCondition(), TheSwitch);
1092f22ef01cSRoman Divacky } else {
1093f22ef01cSRoman Divacky // Otherwise we must have code extracted an unwind or something, just
1094f22ef01cSRoman Divacky // return whatever we want.
1095f22ef01cSRoman Divacky ReturnInst::Create(Context,
1096f22ef01cSRoman Divacky Constant::getNullValue(OldFnRetTy), TheSwitch);
1097f22ef01cSRoman Divacky }
1098f22ef01cSRoman Divacky
1099f22ef01cSRoman Divacky TheSwitch->eraseFromParent();
1100f22ef01cSRoman Divacky break;
1101f22ef01cSRoman Divacky case 1:
1102f22ef01cSRoman Divacky // Only a single destination, change the switch into an unconditional
1103f22ef01cSRoman Divacky // branch.
1104f22ef01cSRoman Divacky BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch);
1105f22ef01cSRoman Divacky TheSwitch->eraseFromParent();
1106f22ef01cSRoman Divacky break;
1107f22ef01cSRoman Divacky case 2:
1108f22ef01cSRoman Divacky BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch->getSuccessor(2),
1109f22ef01cSRoman Divacky call, TheSwitch);
1110f22ef01cSRoman Divacky TheSwitch->eraseFromParent();
1111f22ef01cSRoman Divacky break;
1112f22ef01cSRoman Divacky default:
1113f22ef01cSRoman Divacky // Otherwise, make the default destination of the switch instruction be one
1114f22ef01cSRoman Divacky // of the other successors.
1115dff0c46cSDimitry Andric TheSwitch->setCondition(call);
1116dff0c46cSDimitry Andric TheSwitch->setDefaultDest(TheSwitch->getSuccessor(NumExitBlocks));
1117dff0c46cSDimitry Andric // Remove redundant case
1118f785676fSDimitry Andric TheSwitch->removeCase(SwitchInst::CaseIt(TheSwitch, NumExitBlocks-1));
1119f22ef01cSRoman Divacky break;
1120f22ef01cSRoman Divacky }
1121*b5893f02SDimitry Andric
1122*b5893f02SDimitry Andric return call;
1123f22ef01cSRoman Divacky }
1124f22ef01cSRoman Divacky
moveCodeToFunction(Function * newFunction)1125f22ef01cSRoman Divacky void CodeExtractor::moveCodeToFunction(Function *newFunction) {
11267ae0e2c9SDimitry Andric Function *oldFunc = (*Blocks.begin())->getParent();
1127f22ef01cSRoman Divacky Function::BasicBlockListType &oldBlocks = oldFunc->getBasicBlockList();
1128f22ef01cSRoman Divacky Function::BasicBlockListType &newBlocks = newFunction->getBasicBlockList();
1129f22ef01cSRoman Divacky
11303ca95b02SDimitry Andric for (BasicBlock *Block : Blocks) {
1131f22ef01cSRoman Divacky // Delete the basic block from the old function, and the list of blocks
11323ca95b02SDimitry Andric oldBlocks.remove(Block);
1133f22ef01cSRoman Divacky
1134f22ef01cSRoman Divacky // Insert this basic block into the new function
11353ca95b02SDimitry Andric newBlocks.push_back(Block);
1136f22ef01cSRoman Divacky }
1137f22ef01cSRoman Divacky }
1138f22ef01cSRoman Divacky
calculateNewCallTerminatorWeights(BasicBlock * CodeReplacer,DenseMap<BasicBlock *,BlockFrequency> & ExitWeights,BranchProbabilityInfo * BPI)1139d88c1a5aSDimitry Andric void CodeExtractor::calculateNewCallTerminatorWeights(
1140d88c1a5aSDimitry Andric BasicBlock *CodeReplacer,
1141d88c1a5aSDimitry Andric DenseMap<BasicBlock *, BlockFrequency> &ExitWeights,
1142d88c1a5aSDimitry Andric BranchProbabilityInfo *BPI) {
11432cab237bSDimitry Andric using Distribution = BlockFrequencyInfoImplBase::Distribution;
11442cab237bSDimitry Andric using BlockNode = BlockFrequencyInfoImplBase::BlockNode;
1145d88c1a5aSDimitry Andric
1146d88c1a5aSDimitry Andric // Update the branch weights for the exit block.
1147*b5893f02SDimitry Andric Instruction *TI = CodeReplacer->getTerminator();
1148d88c1a5aSDimitry Andric SmallVector<unsigned, 8> BranchWeights(TI->getNumSuccessors(), 0);
1149d88c1a5aSDimitry Andric
1150d88c1a5aSDimitry Andric // Block Frequency distribution with dummy node.
1151d88c1a5aSDimitry Andric Distribution BranchDist;
1152d88c1a5aSDimitry Andric
1153d88c1a5aSDimitry Andric // Add each of the frequencies of the successors.
1154d88c1a5aSDimitry Andric for (unsigned i = 0, e = TI->getNumSuccessors(); i < e; ++i) {
1155d88c1a5aSDimitry Andric BlockNode ExitNode(i);
1156d88c1a5aSDimitry Andric uint64_t ExitFreq = ExitWeights[TI->getSuccessor(i)].getFrequency();
1157d88c1a5aSDimitry Andric if (ExitFreq != 0)
1158d88c1a5aSDimitry Andric BranchDist.addExit(ExitNode, ExitFreq);
1159d88c1a5aSDimitry Andric else
1160d88c1a5aSDimitry Andric BPI->setEdgeProbability(CodeReplacer, i, BranchProbability::getZero());
1161d88c1a5aSDimitry Andric }
1162d88c1a5aSDimitry Andric
1163d88c1a5aSDimitry Andric // Check for no total weight.
1164d88c1a5aSDimitry Andric if (BranchDist.Total == 0)
1165d88c1a5aSDimitry Andric return;
1166d88c1a5aSDimitry Andric
1167d88c1a5aSDimitry Andric // Normalize the distribution so that they can fit in unsigned.
1168d88c1a5aSDimitry Andric BranchDist.normalize();
1169d88c1a5aSDimitry Andric
1170d88c1a5aSDimitry Andric // Create normalized branch weights and set the metadata.
1171d88c1a5aSDimitry Andric for (unsigned I = 0, E = BranchDist.Weights.size(); I < E; ++I) {
1172d88c1a5aSDimitry Andric const auto &Weight = BranchDist.Weights[I];
1173d88c1a5aSDimitry Andric
1174d88c1a5aSDimitry Andric // Get the weight and update the current BFI.
1175d88c1a5aSDimitry Andric BranchWeights[Weight.TargetNode.Index] = Weight.Amount;
1176d88c1a5aSDimitry Andric BranchProbability BP(Weight.Amount, BranchDist.Total);
1177d88c1a5aSDimitry Andric BPI->setEdgeProbability(CodeReplacer, Weight.TargetNode.Index, BP);
1178d88c1a5aSDimitry Andric }
1179d88c1a5aSDimitry Andric TI->setMetadata(
1180d88c1a5aSDimitry Andric LLVMContext::MD_prof,
1181d88c1a5aSDimitry Andric MDBuilder(TI->getContext()).createBranchWeights(BranchWeights));
1182d88c1a5aSDimitry Andric }
1183d88c1a5aSDimitry Andric
1184*b5893f02SDimitry Andric /// Scan the extraction region for lifetime markers which reference inputs.
1185*b5893f02SDimitry Andric /// Erase these markers. Return the inputs which were referenced.
1186*b5893f02SDimitry Andric ///
1187*b5893f02SDimitry Andric /// The extraction region is defined by a set of blocks (\p Blocks), and a set
1188*b5893f02SDimitry Andric /// of allocas which will be moved from the caller function into the extracted
1189*b5893f02SDimitry Andric /// function (\p SunkAllocas).
1190*b5893f02SDimitry Andric static SetVector<Value *>
eraseLifetimeMarkersOnInputs(const SetVector<BasicBlock * > & Blocks,const SetVector<Value * > & SunkAllocas)1191*b5893f02SDimitry Andric eraseLifetimeMarkersOnInputs(const SetVector<BasicBlock *> &Blocks,
1192*b5893f02SDimitry Andric const SetVector<Value *> &SunkAllocas) {
1193*b5893f02SDimitry Andric SetVector<Value *> InputObjectsWithLifetime;
1194*b5893f02SDimitry Andric for (BasicBlock *BB : Blocks) {
1195*b5893f02SDimitry Andric for (auto It = BB->begin(), End = BB->end(); It != End;) {
1196*b5893f02SDimitry Andric auto *II = dyn_cast<IntrinsicInst>(&*It);
1197*b5893f02SDimitry Andric ++It;
1198*b5893f02SDimitry Andric if (!II || !II->isLifetimeStartOrEnd())
1199*b5893f02SDimitry Andric continue;
1200*b5893f02SDimitry Andric
1201*b5893f02SDimitry Andric // Get the memory operand of the lifetime marker. If the underlying
1202*b5893f02SDimitry Andric // object is a sunk alloca, or is otherwise defined in the extraction
1203*b5893f02SDimitry Andric // region, the lifetime marker must not be erased.
1204*b5893f02SDimitry Andric Value *Mem = II->getOperand(1)->stripInBoundsOffsets();
1205*b5893f02SDimitry Andric if (SunkAllocas.count(Mem) || definedInRegion(Blocks, Mem))
1206*b5893f02SDimitry Andric continue;
1207*b5893f02SDimitry Andric
1208*b5893f02SDimitry Andric InputObjectsWithLifetime.insert(Mem);
1209*b5893f02SDimitry Andric II->eraseFromParent();
1210*b5893f02SDimitry Andric }
1211*b5893f02SDimitry Andric }
1212*b5893f02SDimitry Andric return InputObjectsWithLifetime;
1213*b5893f02SDimitry Andric }
1214*b5893f02SDimitry Andric
1215*b5893f02SDimitry Andric /// Insert lifetime start/end markers surrounding the call to the new function
1216*b5893f02SDimitry Andric /// for objects defined in the caller.
insertLifetimeMarkersSurroundingCall(Module * M,const SetVector<Value * > & InputObjectsWithLifetime,CallInst * TheCall)1217*b5893f02SDimitry Andric static void insertLifetimeMarkersSurroundingCall(
1218*b5893f02SDimitry Andric Module *M, const SetVector<Value *> &InputObjectsWithLifetime,
1219*b5893f02SDimitry Andric CallInst *TheCall) {
1220*b5893f02SDimitry Andric if (InputObjectsWithLifetime.empty())
1221*b5893f02SDimitry Andric return;
1222*b5893f02SDimitry Andric
1223*b5893f02SDimitry Andric LLVMContext &Ctx = M->getContext();
1224*b5893f02SDimitry Andric auto Int8PtrTy = Type::getInt8PtrTy(Ctx);
1225*b5893f02SDimitry Andric auto NegativeOne = ConstantInt::getSigned(Type::getInt64Ty(Ctx), -1);
1226*b5893f02SDimitry Andric auto LifetimeStartFn = llvm::Intrinsic::getDeclaration(
1227*b5893f02SDimitry Andric M, llvm::Intrinsic::lifetime_start, Int8PtrTy);
1228*b5893f02SDimitry Andric auto LifetimeEndFn = llvm::Intrinsic::getDeclaration(
1229*b5893f02SDimitry Andric M, llvm::Intrinsic::lifetime_end, Int8PtrTy);
1230*b5893f02SDimitry Andric for (Value *Mem : InputObjectsWithLifetime) {
1231*b5893f02SDimitry Andric assert((!isa<Instruction>(Mem) ||
1232*b5893f02SDimitry Andric cast<Instruction>(Mem)->getFunction() == TheCall->getFunction()) &&
1233*b5893f02SDimitry Andric "Input memory not defined in original function");
1234*b5893f02SDimitry Andric Value *MemAsI8Ptr = nullptr;
1235*b5893f02SDimitry Andric if (Mem->getType() == Int8PtrTy)
1236*b5893f02SDimitry Andric MemAsI8Ptr = Mem;
1237*b5893f02SDimitry Andric else
1238*b5893f02SDimitry Andric MemAsI8Ptr =
1239*b5893f02SDimitry Andric CastInst::CreatePointerCast(Mem, Int8PtrTy, "lt.cast", TheCall);
1240*b5893f02SDimitry Andric
1241*b5893f02SDimitry Andric auto StartMarker =
1242*b5893f02SDimitry Andric CallInst::Create(LifetimeStartFn, {NegativeOne, MemAsI8Ptr});
1243*b5893f02SDimitry Andric StartMarker->insertBefore(TheCall);
1244*b5893f02SDimitry Andric auto EndMarker = CallInst::Create(LifetimeEndFn, {NegativeOne, MemAsI8Ptr});
1245*b5893f02SDimitry Andric EndMarker->insertAfter(TheCall);
1246*b5893f02SDimitry Andric }
1247*b5893f02SDimitry Andric }
1248*b5893f02SDimitry Andric
extractCodeRegion()12497ae0e2c9SDimitry Andric Function *CodeExtractor::extractCodeRegion() {
12507ae0e2c9SDimitry Andric if (!isEligible())
125191bc56edSDimitry Andric return nullptr;
1252f22ef01cSRoman Divacky
1253f22ef01cSRoman Divacky // Assumption: this is a single-entry code region, and the header is the first
1254f22ef01cSRoman Divacky // block in the region.
12557ae0e2c9SDimitry Andric BasicBlock *header = *Blocks.begin();
12562cab237bSDimitry Andric Function *oldFunction = header->getParent();
12572cab237bSDimitry Andric
12582cab237bSDimitry Andric // For functions with varargs, check that varargs handling is only done in the
12592cab237bSDimitry Andric // outlined function, i.e vastart and vaend are only used in outlined blocks.
12602cab237bSDimitry Andric if (AllowVarArgs && oldFunction->getFunctionType()->isVarArg()) {
12612cab237bSDimitry Andric auto containsVarArgIntrinsic = [](Instruction &I) {
12622cab237bSDimitry Andric if (const CallInst *CI = dyn_cast<CallInst>(&I))
12632cab237bSDimitry Andric if (const Function *F = CI->getCalledFunction())
12642cab237bSDimitry Andric return F->getIntrinsicID() == Intrinsic::vastart ||
12652cab237bSDimitry Andric F->getIntrinsicID() == Intrinsic::vaend;
12662cab237bSDimitry Andric return false;
12672cab237bSDimitry Andric };
12682cab237bSDimitry Andric
12692cab237bSDimitry Andric for (auto &BB : *oldFunction) {
12702cab237bSDimitry Andric if (Blocks.count(&BB))
12712cab237bSDimitry Andric continue;
12722cab237bSDimitry Andric if (llvm::any_of(BB, containsVarArgIntrinsic))
12732cab237bSDimitry Andric return nullptr;
12742cab237bSDimitry Andric }
12752cab237bSDimitry Andric }
12762cab237bSDimitry Andric ValueSet inputs, outputs, SinkingCands, HoistingCands;
12772cab237bSDimitry Andric BasicBlock *CommonExit = nullptr;
1278f22ef01cSRoman Divacky
1279d88c1a5aSDimitry Andric // Calculate the entry frequency of the new function before we change the root
1280d88c1a5aSDimitry Andric // block.
1281d88c1a5aSDimitry Andric BlockFrequency EntryFreq;
1282d88c1a5aSDimitry Andric if (BFI) {
1283d88c1a5aSDimitry Andric assert(BPI && "Both BPI and BFI are required to preserve profile info");
1284d88c1a5aSDimitry Andric for (BasicBlock *Pred : predecessors(header)) {
1285d88c1a5aSDimitry Andric if (Blocks.count(Pred))
1286d88c1a5aSDimitry Andric continue;
1287d88c1a5aSDimitry Andric EntryFreq +=
1288d88c1a5aSDimitry Andric BFI->getBlockFreq(Pred) * BPI->getEdgeProbability(Pred, header);
1289d88c1a5aSDimitry Andric }
1290d88c1a5aSDimitry Andric }
1291d88c1a5aSDimitry Andric
1292f22ef01cSRoman Divacky // If we have any return instructions in the region, split those blocks so
1293f22ef01cSRoman Divacky // that the return is not in the region.
1294f22ef01cSRoman Divacky splitReturnBlocks();
1295f22ef01cSRoman Divacky
1296*b5893f02SDimitry Andric // Calculate the exit blocks for the extracted region and the total exit
1297*b5893f02SDimitry Andric // weights for each of those blocks.
1298*b5893f02SDimitry Andric DenseMap<BasicBlock *, BlockFrequency> ExitWeights;
1299*b5893f02SDimitry Andric SmallPtrSet<BasicBlock *, 1> ExitBlocks;
1300*b5893f02SDimitry Andric for (BasicBlock *Block : Blocks) {
1301*b5893f02SDimitry Andric for (succ_iterator SI = succ_begin(Block), SE = succ_end(Block); SI != SE;
1302*b5893f02SDimitry Andric ++SI) {
1303*b5893f02SDimitry Andric if (!Blocks.count(*SI)) {
1304*b5893f02SDimitry Andric // Update the branch weight for this successor.
1305*b5893f02SDimitry Andric if (BFI) {
1306*b5893f02SDimitry Andric BlockFrequency &BF = ExitWeights[*SI];
1307*b5893f02SDimitry Andric BF += BFI->getBlockFreq(Block) * BPI->getEdgeProbability(Block, *SI);
1308*b5893f02SDimitry Andric }
1309*b5893f02SDimitry Andric ExitBlocks.insert(*SI);
1310*b5893f02SDimitry Andric }
1311*b5893f02SDimitry Andric }
1312*b5893f02SDimitry Andric }
1313*b5893f02SDimitry Andric NumExitBlocks = ExitBlocks.size();
1314*b5893f02SDimitry Andric
1315*b5893f02SDimitry Andric // If we have to split PHI nodes of the entry or exit blocks, do so now.
1316*b5893f02SDimitry Andric severSplitPHINodesOfEntry(header);
1317*b5893f02SDimitry Andric severSplitPHINodesOfExits(ExitBlocks);
1318*b5893f02SDimitry Andric
1319f22ef01cSRoman Divacky // This takes place of the original loop
1320f22ef01cSRoman Divacky BasicBlock *codeReplacer = BasicBlock::Create(header->getContext(),
1321f22ef01cSRoman Divacky "codeRepl", oldFunction,
1322f22ef01cSRoman Divacky header);
1323f22ef01cSRoman Divacky
1324f22ef01cSRoman Divacky // The new function needs a root node because other nodes can branch to the
1325f22ef01cSRoman Divacky // head of the region, but the entry node of a function cannot have preds.
1326f22ef01cSRoman Divacky BasicBlock *newFuncRoot = BasicBlock::Create(header->getContext(),
1327f22ef01cSRoman Divacky "newFuncRoot");
13282cab237bSDimitry Andric auto *BranchI = BranchInst::Create(header);
13292cab237bSDimitry Andric // If the original function has debug info, we have to add a debug location
13302cab237bSDimitry Andric // to the new branch instruction from the artificial entry block.
13312cab237bSDimitry Andric // We use the debug location of the first instruction in the extracted
13322cab237bSDimitry Andric // blocks, as there is no other equivalent line in the source code.
13332cab237bSDimitry Andric if (oldFunction->getSubprogram()) {
13342cab237bSDimitry Andric any_of(Blocks, [&BranchI](const BasicBlock *BB) {
13352cab237bSDimitry Andric return any_of(*BB, [&BranchI](const Instruction &I) {
13362cab237bSDimitry Andric if (!I.getDebugLoc())
13372cab237bSDimitry Andric return false;
13382cab237bSDimitry Andric BranchI->setDebugLoc(I.getDebugLoc());
13392cab237bSDimitry Andric return true;
13402cab237bSDimitry Andric });
13412cab237bSDimitry Andric });
13422cab237bSDimitry Andric }
13432cab237bSDimitry Andric newFuncRoot->getInstList().push_back(BranchI);
1344f22ef01cSRoman Divacky
134524d58133SDimitry Andric findAllocas(SinkingCands, HoistingCands, CommonExit);
134624d58133SDimitry Andric assert(HoistingCands.empty() || CommonExit);
1347f9448bf3SDimitry Andric
1348f22ef01cSRoman Divacky // Find inputs to, outputs from the code region.
1349f9448bf3SDimitry Andric findInputsOutputs(inputs, outputs, SinkingCands);
1350f9448bf3SDimitry Andric
1351f9448bf3SDimitry Andric // Now sink all instructions which only have non-phi uses inside the region
1352f9448bf3SDimitry Andric for (auto *II : SinkingCands)
1353f9448bf3SDimitry Andric cast<Instruction>(II)->moveBefore(*newFuncRoot,
1354f9448bf3SDimitry Andric newFuncRoot->getFirstInsertionPt());
1355f22ef01cSRoman Divacky
135624d58133SDimitry Andric if (!HoistingCands.empty()) {
135724d58133SDimitry Andric auto *HoistToBlock = findOrCreateBlockForHoisting(CommonExit);
135824d58133SDimitry Andric Instruction *TI = HoistToBlock->getTerminator();
135924d58133SDimitry Andric for (auto *II : HoistingCands)
136024d58133SDimitry Andric cast<Instruction>(II)->moveBefore(TI);
136124d58133SDimitry Andric }
136224d58133SDimitry Andric
1363*b5893f02SDimitry Andric // Collect objects which are inputs to the extraction region and also
1364*b5893f02SDimitry Andric // referenced by lifetime start/end markers within it. The effects of these
1365*b5893f02SDimitry Andric // markers must be replicated in the calling function to prevent the stack
1366*b5893f02SDimitry Andric // coloring pass from merging slots which store input objects.
1367*b5893f02SDimitry Andric ValueSet InputObjectsWithLifetime =
1368*b5893f02SDimitry Andric eraseLifetimeMarkersOnInputs(Blocks, SinkingCands);
13697ae0e2c9SDimitry Andric
1370f22ef01cSRoman Divacky // Construct new function based on inputs/outputs & add allocas for all defs.
1371*b5893f02SDimitry Andric Function *newFunction =
1372*b5893f02SDimitry Andric constructFunction(inputs, outputs, header, newFuncRoot, codeReplacer,
1373*b5893f02SDimitry Andric oldFunction, oldFunction->getParent());
1374f22ef01cSRoman Divacky
1375d88c1a5aSDimitry Andric // Update the entry count of the function.
1376d88c1a5aSDimitry Andric if (BFI) {
13774ba319b5SDimitry Andric auto Count = BFI->getProfileCountFromFreq(EntryFreq.getFrequency());
13784ba319b5SDimitry Andric if (Count.hasValue())
13794ba319b5SDimitry Andric newFunction->setEntryCount(
13804ba319b5SDimitry Andric ProfileCount(Count.getValue(), Function::PCT_Real)); // FIXME
1381d88c1a5aSDimitry Andric BFI->setBlockFreq(codeReplacer, EntryFreq.getFrequency());
1382d88c1a5aSDimitry Andric }
1383d88c1a5aSDimitry Andric
1384*b5893f02SDimitry Andric CallInst *TheCall =
1385f22ef01cSRoman Divacky emitCallAndSwitchStatement(newFunction, codeReplacer, inputs, outputs);
1386f22ef01cSRoman Divacky
1387f22ef01cSRoman Divacky moveCodeToFunction(newFunction);
1388f22ef01cSRoman Divacky
1389*b5893f02SDimitry Andric // Replicate the effects of any lifetime start/end markers which referenced
1390*b5893f02SDimitry Andric // input objects in the extraction region by placing markers around the call.
1391*b5893f02SDimitry Andric insertLifetimeMarkersSurroundingCall(oldFunction->getParent(),
1392*b5893f02SDimitry Andric InputObjectsWithLifetime, TheCall);
1393*b5893f02SDimitry Andric
13944ba319b5SDimitry Andric // Propagate personality info to the new function if there is one.
13954ba319b5SDimitry Andric if (oldFunction->hasPersonalityFn())
13964ba319b5SDimitry Andric newFunction->setPersonalityFn(oldFunction->getPersonalityFn());
13974ba319b5SDimitry Andric
1398d88c1a5aSDimitry Andric // Update the branch weights for the exit block.
1399d88c1a5aSDimitry Andric if (BFI && NumExitBlocks > 1)
1400d88c1a5aSDimitry Andric calculateNewCallTerminatorWeights(codeReplacer, ExitWeights, BPI);
1401d88c1a5aSDimitry Andric
1402*b5893f02SDimitry Andric // Loop over all of the PHI nodes in the header and exit blocks, and change
1403*b5893f02SDimitry Andric // any references to the old incoming edge to be the new incoming edge.
1404f22ef01cSRoman Divacky for (BasicBlock::iterator I = header->begin(); isa<PHINode>(I); ++I) {
1405f22ef01cSRoman Divacky PHINode *PN = cast<PHINode>(I);
1406f22ef01cSRoman Divacky for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
14077ae0e2c9SDimitry Andric if (!Blocks.count(PN->getIncomingBlock(i)))
1408f22ef01cSRoman Divacky PN->setIncomingBlock(i, newFuncRoot);
1409f22ef01cSRoman Divacky }
1410f22ef01cSRoman Divacky
1411*b5893f02SDimitry Andric for (BasicBlock *ExitBB : ExitBlocks)
1412*b5893f02SDimitry Andric for (PHINode &PN : ExitBB->phis()) {
1413*b5893f02SDimitry Andric Value *IncomingCodeReplacerVal = nullptr;
1414*b5893f02SDimitry Andric for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1415*b5893f02SDimitry Andric // Ignore incoming values from outside of the extracted region.
1416*b5893f02SDimitry Andric if (!Blocks.count(PN.getIncomingBlock(i)))
1417*b5893f02SDimitry Andric continue;
1418*b5893f02SDimitry Andric
1419*b5893f02SDimitry Andric // Ensure that there is only one incoming value from codeReplacer.
1420*b5893f02SDimitry Andric if (!IncomingCodeReplacerVal) {
1421*b5893f02SDimitry Andric PN.setIncomingBlock(i, codeReplacer);
1422*b5893f02SDimitry Andric IncomingCodeReplacerVal = PN.getIncomingValue(i);
1423*b5893f02SDimitry Andric } else
1424*b5893f02SDimitry Andric assert(IncomingCodeReplacerVal == PN.getIncomingValue(i) &&
1425*b5893f02SDimitry Andric "PHI has two incompatbile incoming values from codeRepl");
1426f22ef01cSRoman Divacky }
1427f22ef01cSRoman Divacky }
1428f22ef01cSRoman Divacky
1429*b5893f02SDimitry Andric // Erase debug info intrinsics. Variable updates within the new function are
1430*b5893f02SDimitry Andric // invisible to debuggers. This could be improved by defining a DISubprogram
1431*b5893f02SDimitry Andric // for the new function.
1432*b5893f02SDimitry Andric for (BasicBlock &BB : *newFunction) {
1433*b5893f02SDimitry Andric auto BlockIt = BB.begin();
1434*b5893f02SDimitry Andric // Remove debug info intrinsics from the new function.
1435*b5893f02SDimitry Andric while (BlockIt != BB.end()) {
1436*b5893f02SDimitry Andric Instruction *Inst = &*BlockIt;
1437*b5893f02SDimitry Andric ++BlockIt;
1438*b5893f02SDimitry Andric if (isa<DbgInfoIntrinsic>(Inst))
1439*b5893f02SDimitry Andric Inst->eraseFromParent();
1440*b5893f02SDimitry Andric }
1441*b5893f02SDimitry Andric // Remove debug info intrinsics which refer to values in the new function
1442*b5893f02SDimitry Andric // from the old function.
1443*b5893f02SDimitry Andric SmallVector<DbgVariableIntrinsic *, 4> DbgUsers;
1444*b5893f02SDimitry Andric for (Instruction &I : BB)
1445*b5893f02SDimitry Andric findDbgUsers(DbgUsers, &I);
1446*b5893f02SDimitry Andric for (DbgVariableIntrinsic *DVI : DbgUsers)
1447*b5893f02SDimitry Andric DVI->eraseFromParent();
1448*b5893f02SDimitry Andric }
1449*b5893f02SDimitry Andric
1450*b5893f02SDimitry Andric // Mark the new function `noreturn` if applicable. Terminators which resume
1451*b5893f02SDimitry Andric // exception propagation are treated as returning instructions. This is to
1452*b5893f02SDimitry Andric // avoid inserting traps after calls to outlined functions which unwind.
1453*b5893f02SDimitry Andric bool doesNotReturn = none_of(*newFunction, [](const BasicBlock &BB) {
1454*b5893f02SDimitry Andric const Instruction *Term = BB.getTerminator();
1455*b5893f02SDimitry Andric return isa<ReturnInst>(Term) || isa<ResumeInst>(Term);
1456*b5893f02SDimitry Andric });
1457*b5893f02SDimitry Andric if (doesNotReturn)
1458*b5893f02SDimitry Andric newFunction->setDoesNotReturn();
1459*b5893f02SDimitry Andric
1460*b5893f02SDimitry Andric LLVM_DEBUG(if (verifyFunction(*newFunction, &errs())) {
1461*b5893f02SDimitry Andric newFunction->dump();
1462*b5893f02SDimitry Andric report_fatal_error("verification of newFunction failed!");
1463*b5893f02SDimitry Andric });
1464*b5893f02SDimitry Andric LLVM_DEBUG(if (verifyFunction(*oldFunction))
1465*b5893f02SDimitry Andric report_fatal_error("verification of oldFunction failed!"));
1466f22ef01cSRoman Divacky return newFunction;
1467f22ef01cSRoman Divacky }
1468