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"
17139f7f9bSDimitry Andric #include "llvm/ADT/STLExtras.h"
1891bc56edSDimitry Andric #include "llvm/ADT/SetVector.h"
19139f7f9bSDimitry Andric #include "llvm/ADT/StringExtras.h"
20d88c1a5aSDimitry Andric #include "llvm/Analysis/BlockFrequencyInfo.h"
21d88c1a5aSDimitry Andric #include "llvm/Analysis/BlockFrequencyInfoImpl.h"
22d88c1a5aSDimitry Andric #include "llvm/Analysis/BranchProbabilityInfo.h"
23f22ef01cSRoman Divacky #include "llvm/Analysis/LoopInfo.h"
247ae0e2c9SDimitry Andric #include "llvm/Analysis/RegionInfo.h"
257ae0e2c9SDimitry Andric #include "llvm/Analysis/RegionIterator.h"
26139f7f9bSDimitry Andric #include "llvm/IR/Constants.h"
27139f7f9bSDimitry Andric #include "llvm/IR/DerivedTypes.h"
2891bc56edSDimitry Andric #include "llvm/IR/Dominators.h"
29139f7f9bSDimitry Andric #include "llvm/IR/Instructions.h"
30f9448bf3SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
31139f7f9bSDimitry Andric #include "llvm/IR/Intrinsics.h"
32139f7f9bSDimitry Andric #include "llvm/IR/LLVMContext.h"
33d88c1a5aSDimitry Andric #include "llvm/IR/MDBuilder.h"
34139f7f9bSDimitry Andric #include "llvm/IR/Module.h"
3591bc56edSDimitry Andric #include "llvm/IR/Verifier.h"
36139f7f9bSDimitry Andric #include "llvm/Pass.h"
37d88c1a5aSDimitry Andric #include "llvm/Support/BlockFrequency.h"
38f22ef01cSRoman Divacky #include "llvm/Support/CommandLine.h"
39f22ef01cSRoman Divacky #include "llvm/Support/Debug.h"
40f22ef01cSRoman Divacky #include "llvm/Support/ErrorHandling.h"
41f22ef01cSRoman Divacky #include "llvm/Support/raw_ostream.h"
42139f7f9bSDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h"
43f22ef01cSRoman Divacky #include <algorithm>
44f22ef01cSRoman Divacky #include <set>
45f22ef01cSRoman Divacky using namespace llvm;
46f22ef01cSRoman Divacky 
4791bc56edSDimitry Andric #define DEBUG_TYPE "code-extractor"
4891bc56edSDimitry Andric 
49f22ef01cSRoman Divacky // Provide a command-line option to aggregate function arguments into a struct
50f22ef01cSRoman Divacky // for functions produced by the code extractor. This is useful when converting
51f22ef01cSRoman Divacky // extracted functions to pthread-based code, as only one argument (void*) can
52f22ef01cSRoman Divacky // be passed in to pthread_create().
53f22ef01cSRoman Divacky static cl::opt<bool>
54f22ef01cSRoman Divacky AggregateArgsOpt("aggregate-extracted-args", cl::Hidden,
55f22ef01cSRoman Divacky                  cl::desc("Aggregate arguments to code-extracted functions"));
56f22ef01cSRoman Divacky 
577ae0e2c9SDimitry Andric /// \brief Test whether a block is valid for extraction.
58d88c1a5aSDimitry Andric bool CodeExtractor::isBlockValidForExtraction(const BasicBlock &BB) {
597ae0e2c9SDimitry Andric   // Landing pads must be in the function where they were inserted for cleanup.
607d523365SDimitry Andric   if (BB.isEHPad())
617ae0e2c9SDimitry Andric     return false;
62f22ef01cSRoman Divacky 
637ae0e2c9SDimitry Andric   // Don't hoist code containing allocas, invokes, or vastarts.
647ae0e2c9SDimitry Andric   for (BasicBlock::const_iterator I = BB.begin(), E = BB.end(); I != E; ++I) {
657ae0e2c9SDimitry Andric     if (isa<AllocaInst>(I) || isa<InvokeInst>(I))
667ae0e2c9SDimitry Andric       return false;
677ae0e2c9SDimitry Andric     if (const CallInst *CI = dyn_cast<CallInst>(I))
687ae0e2c9SDimitry Andric       if (const Function *F = CI->getCalledFunction())
697ae0e2c9SDimitry Andric         if (F->getIntrinsicID() == Intrinsic::vastart)
707ae0e2c9SDimitry Andric           return false;
717ae0e2c9SDimitry Andric   }
72f22ef01cSRoman Divacky 
737ae0e2c9SDimitry Andric   return true;
747ae0e2c9SDimitry Andric }
75f22ef01cSRoman Divacky 
767ae0e2c9SDimitry Andric /// \brief Build a set of blocks to extract if the input blocks are viable.
7751690af2SDimitry Andric static SetVector<BasicBlock *>
7851690af2SDimitry Andric buildExtractionBlockSet(ArrayRef<BasicBlock *> BBs, DominatorTree *DT) {
7951690af2SDimitry Andric   assert(!BBs.empty() && "The set of blocks to extract must be non-empty");
807ae0e2c9SDimitry Andric   SetVector<BasicBlock *> Result;
817ae0e2c9SDimitry Andric 
827ae0e2c9SDimitry Andric   // Loop over the blocks, adding them to our set-vector, and aborting with an
837ae0e2c9SDimitry Andric   // empty set if we encounter invalid blocks.
8451690af2SDimitry Andric   for (BasicBlock *BB : BBs) {
857ae0e2c9SDimitry Andric 
8651690af2SDimitry Andric     // If this block is dead, don't process it.
8751690af2SDimitry Andric     if (DT && !DT->isReachableFromEntry(BB))
8851690af2SDimitry Andric       continue;
8951690af2SDimitry Andric 
9051690af2SDimitry Andric     if (!Result.insert(BB))
9151690af2SDimitry Andric       llvm_unreachable("Repeated basic blocks in extraction input");
9251690af2SDimitry Andric     if (!CodeExtractor::isBlockValidForExtraction(*BB)) {
937ae0e2c9SDimitry Andric       Result.clear();
947ae0e2c9SDimitry Andric       return Result;
957ae0e2c9SDimitry Andric     }
9651690af2SDimitry Andric   }
977ae0e2c9SDimitry Andric 
987ae0e2c9SDimitry Andric #ifndef NDEBUG
9991bc56edSDimitry Andric   for (SetVector<BasicBlock *>::iterator I = std::next(Result.begin()),
1007ae0e2c9SDimitry Andric                                          E = Result.end();
1017ae0e2c9SDimitry Andric        I != E; ++I)
1027ae0e2c9SDimitry Andric     for (pred_iterator PI = pred_begin(*I), PE = pred_end(*I);
1037ae0e2c9SDimitry Andric          PI != PE; ++PI)
1047ae0e2c9SDimitry Andric       assert(Result.count(*PI) &&
1057ae0e2c9SDimitry Andric              "No blocks in this region may have entries from outside the region"
1067ae0e2c9SDimitry Andric              " except for the first block!");
1077ae0e2c9SDimitry Andric #endif
1087ae0e2c9SDimitry Andric 
1097ae0e2c9SDimitry Andric   return Result;
1107ae0e2c9SDimitry Andric }
1117ae0e2c9SDimitry Andric 
1127ae0e2c9SDimitry Andric CodeExtractor::CodeExtractor(ArrayRef<BasicBlock *> BBs, DominatorTree *DT,
113d88c1a5aSDimitry Andric                              bool AggregateArgs, BlockFrequencyInfo *BFI,
114d88c1a5aSDimitry Andric                              BranchProbabilityInfo *BPI)
115d88c1a5aSDimitry Andric     : DT(DT), AggregateArgs(AggregateArgs || AggregateArgsOpt), BFI(BFI),
11651690af2SDimitry Andric       BPI(BPI), Blocks(buildExtractionBlockSet(BBs, DT)), NumExitBlocks(~0U) {}
1177ae0e2c9SDimitry Andric 
118d88c1a5aSDimitry Andric CodeExtractor::CodeExtractor(DominatorTree &DT, Loop &L, bool AggregateArgs,
119d88c1a5aSDimitry Andric                              BlockFrequencyInfo *BFI,
120d88c1a5aSDimitry Andric                              BranchProbabilityInfo *BPI)
121d88c1a5aSDimitry Andric     : DT(&DT), AggregateArgs(AggregateArgs || AggregateArgsOpt), BFI(BFI),
12251690af2SDimitry Andric       BPI(BPI), Blocks(buildExtractionBlockSet(L.getBlocks(), &DT)),
123d88c1a5aSDimitry Andric       NumExitBlocks(~0U) {}
1247ae0e2c9SDimitry Andric 
125f22ef01cSRoman Divacky /// definedInRegion - Return true if the specified value is defined in the
126f22ef01cSRoman Divacky /// extracted region.
1277ae0e2c9SDimitry Andric static bool definedInRegion(const SetVector<BasicBlock *> &Blocks, Value *V) {
128f22ef01cSRoman Divacky   if (Instruction *I = dyn_cast<Instruction>(V))
1297ae0e2c9SDimitry Andric     if (Blocks.count(I->getParent()))
130f22ef01cSRoman Divacky       return true;
131f22ef01cSRoman Divacky   return false;
132f22ef01cSRoman Divacky }
133f22ef01cSRoman Divacky 
134f22ef01cSRoman Divacky /// definedInCaller - Return true if the specified value is defined in the
135f22ef01cSRoman Divacky /// function being code extracted, but not in the region being extracted.
136f22ef01cSRoman Divacky /// These values must be passed in as live-ins to the function.
1377ae0e2c9SDimitry Andric static bool definedInCaller(const SetVector<BasicBlock *> &Blocks, Value *V) {
138f22ef01cSRoman Divacky   if (isa<Argument>(V)) return true;
139f22ef01cSRoman Divacky   if (Instruction *I = dyn_cast<Instruction>(V))
1407ae0e2c9SDimitry Andric     if (!Blocks.count(I->getParent()))
141f22ef01cSRoman Divacky       return true;
142f22ef01cSRoman Divacky   return false;
143f22ef01cSRoman Divacky }
144f22ef01cSRoman Divacky 
145f9448bf3SDimitry Andric void CodeExtractor::findAllocas(ValueSet &SinkCands) const {
146f9448bf3SDimitry Andric   Function *Func = (*Blocks.begin())->getParent();
147f9448bf3SDimitry Andric   for (BasicBlock &BB : *Func) {
148f9448bf3SDimitry Andric     if (Blocks.count(&BB))
149f9448bf3SDimitry Andric       continue;
150f9448bf3SDimitry Andric     for (Instruction &II : BB) {
151f9448bf3SDimitry Andric       auto *AI = dyn_cast<AllocaInst>(&II);
152f9448bf3SDimitry Andric       if (!AI)
153f9448bf3SDimitry Andric         continue;
154f9448bf3SDimitry Andric 
155f9448bf3SDimitry Andric       // Returns true if matching life time markers are found within
156f9448bf3SDimitry Andric       // the outlined region.
157f9448bf3SDimitry Andric       auto GetLifeTimeMarkers = [&](Instruction *Addr) {
158f9448bf3SDimitry Andric         Instruction *LifeStart = nullptr, *LifeEnd = nullptr;
159f9448bf3SDimitry Andric         for (User *U : Addr->users()) {
160f9448bf3SDimitry Andric           if (!definedInRegion(Blocks, U))
161f9448bf3SDimitry Andric             return false;
162f9448bf3SDimitry Andric 
163f9448bf3SDimitry Andric           IntrinsicInst *IntrInst = dyn_cast<IntrinsicInst>(U);
164f9448bf3SDimitry Andric           if (IntrInst) {
165f9448bf3SDimitry Andric             if (IntrInst->getIntrinsicID() == Intrinsic::lifetime_start)
166f9448bf3SDimitry Andric               LifeStart = IntrInst;
167f9448bf3SDimitry Andric             if (IntrInst->getIntrinsicID() == Intrinsic::lifetime_end)
168f9448bf3SDimitry Andric               LifeEnd = IntrInst;
169f9448bf3SDimitry Andric           }
170f9448bf3SDimitry Andric         }
171f9448bf3SDimitry Andric         return LifeStart && LifeEnd;
172f9448bf3SDimitry Andric       };
173f9448bf3SDimitry Andric 
174f9448bf3SDimitry Andric       if (GetLifeTimeMarkers(AI)) {
175f9448bf3SDimitry Andric         SinkCands.insert(AI);
176f9448bf3SDimitry Andric         continue;
177f9448bf3SDimitry Andric       }
178f9448bf3SDimitry Andric 
179f9448bf3SDimitry Andric       // Follow the bitcast:
180f9448bf3SDimitry Andric       Instruction *MarkerAddr = nullptr;
181f9448bf3SDimitry Andric       for (User *U : AI->users()) {
182f9448bf3SDimitry Andric         if (U->stripPointerCasts() == AI) {
183f9448bf3SDimitry Andric           Instruction *Bitcast = cast<Instruction>(U);
184f9448bf3SDimitry Andric           if (GetLifeTimeMarkers(Bitcast)) {
185f9448bf3SDimitry Andric             MarkerAddr = Bitcast;
186f9448bf3SDimitry Andric             continue;
187f9448bf3SDimitry Andric           }
188f9448bf3SDimitry Andric         }
189f9448bf3SDimitry Andric         if (!definedInRegion(Blocks, U)) {
190f9448bf3SDimitry Andric           MarkerAddr = nullptr;
191f9448bf3SDimitry Andric           break;
192f9448bf3SDimitry Andric         }
193f9448bf3SDimitry Andric       }
194f9448bf3SDimitry Andric       if (MarkerAddr) {
195f9448bf3SDimitry Andric         if (!definedInRegion(Blocks, MarkerAddr))
196f9448bf3SDimitry Andric           SinkCands.insert(MarkerAddr);
197f9448bf3SDimitry Andric         SinkCands.insert(AI);
198f9448bf3SDimitry Andric       }
199f9448bf3SDimitry Andric     }
200f9448bf3SDimitry Andric   }
201f9448bf3SDimitry Andric }
202f9448bf3SDimitry Andric 
203f9448bf3SDimitry Andric void CodeExtractor::findInputsOutputs(ValueSet &Inputs, ValueSet &Outputs,
204f9448bf3SDimitry Andric                                       const ValueSet &SinkCands) const {
205f9448bf3SDimitry Andric 
2063ca95b02SDimitry Andric   for (BasicBlock *BB : Blocks) {
2077ae0e2c9SDimitry Andric     // If a used value is defined outside the region, it's an input.  If an
2087ae0e2c9SDimitry Andric     // instruction is used outside the region, it's an output.
2093ca95b02SDimitry Andric     for (Instruction &II : *BB) {
2103ca95b02SDimitry Andric       for (User::op_iterator OI = II.op_begin(), OE = II.op_end(); OI != OE;
211f9448bf3SDimitry Andric            ++OI) {
212f9448bf3SDimitry Andric         Value *V = *OI;
213f9448bf3SDimitry Andric         if (!SinkCands.count(V) && definedInCaller(Blocks, V))
214f9448bf3SDimitry Andric           Inputs.insert(V);
215f9448bf3SDimitry Andric       }
216f22ef01cSRoman Divacky 
2173ca95b02SDimitry Andric       for (User *U : II.users())
21891bc56edSDimitry Andric         if (!definedInRegion(Blocks, U)) {
2193ca95b02SDimitry Andric           Outputs.insert(&II);
2207ae0e2c9SDimitry Andric           break;
2217ae0e2c9SDimitry Andric         }
2227ae0e2c9SDimitry Andric     }
2237ae0e2c9SDimitry Andric   }
224f22ef01cSRoman Divacky }
225f22ef01cSRoman Divacky 
226f22ef01cSRoman Divacky /// severSplitPHINodes - If a PHI node has multiple inputs from outside of the
227f22ef01cSRoman Divacky /// region, we need to split the entry block of the region so that the PHI node
228f22ef01cSRoman Divacky /// is easier to deal with.
229f22ef01cSRoman Divacky void CodeExtractor::severSplitPHINodes(BasicBlock *&Header) {
2303b0f4066SDimitry Andric   unsigned NumPredsFromRegion = 0;
231f22ef01cSRoman Divacky   unsigned NumPredsOutsideRegion = 0;
232f22ef01cSRoman Divacky 
233f22ef01cSRoman Divacky   if (Header != &Header->getParent()->getEntryBlock()) {
234f22ef01cSRoman Divacky     PHINode *PN = dyn_cast<PHINode>(Header->begin());
235f22ef01cSRoman Divacky     if (!PN) return;  // No PHI nodes.
236f22ef01cSRoman Divacky 
237f22ef01cSRoman Divacky     // If the header node contains any PHI nodes, check to see if there is more
238f22ef01cSRoman Divacky     // than one entry from outside the region.  If so, we need to sever the
239f22ef01cSRoman Divacky     // header block into two.
240f22ef01cSRoman Divacky     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2417ae0e2c9SDimitry Andric       if (Blocks.count(PN->getIncomingBlock(i)))
2423b0f4066SDimitry Andric         ++NumPredsFromRegion;
243f22ef01cSRoman Divacky       else
244f22ef01cSRoman Divacky         ++NumPredsOutsideRegion;
245f22ef01cSRoman Divacky 
246f22ef01cSRoman Divacky     // If there is one (or fewer) predecessor from outside the region, we don't
247f22ef01cSRoman Divacky     // need to do anything special.
248f22ef01cSRoman Divacky     if (NumPredsOutsideRegion <= 1) return;
249f22ef01cSRoman Divacky   }
250f22ef01cSRoman Divacky 
251f22ef01cSRoman Divacky   // Otherwise, we need to split the header block into two pieces: one
252f22ef01cSRoman Divacky   // containing PHI nodes merging values from outside of the region, and a
253f22ef01cSRoman Divacky   // second that contains all of the code for the block and merges back any
254f22ef01cSRoman Divacky   // incoming values from inside of the region.
25551690af2SDimitry Andric   BasicBlock *NewBB = llvm::SplitBlock(Header, Header->getFirstNonPHI(), DT);
256f22ef01cSRoman Divacky 
257f22ef01cSRoman Divacky   // We only want to code extract the second block now, and it becomes the new
258f22ef01cSRoman Divacky   // header of the region.
259f22ef01cSRoman Divacky   BasicBlock *OldPred = Header;
2607ae0e2c9SDimitry Andric   Blocks.remove(OldPred);
2617ae0e2c9SDimitry Andric   Blocks.insert(NewBB);
262f22ef01cSRoman Divacky   Header = NewBB;
263f22ef01cSRoman Divacky 
264f22ef01cSRoman Divacky   // Okay, now we need to adjust the PHI nodes and any branches from within the
265f22ef01cSRoman Divacky   // region to go to the new header block instead of the old header block.
2663b0f4066SDimitry Andric   if (NumPredsFromRegion) {
267f22ef01cSRoman Divacky     PHINode *PN = cast<PHINode>(OldPred->begin());
268f22ef01cSRoman Divacky     // Loop over all of the predecessors of OldPred that are in the region,
269f22ef01cSRoman Divacky     // changing them to branch to NewBB instead.
270f22ef01cSRoman Divacky     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2717ae0e2c9SDimitry Andric       if (Blocks.count(PN->getIncomingBlock(i))) {
272f22ef01cSRoman Divacky         TerminatorInst *TI = PN->getIncomingBlock(i)->getTerminator();
273f22ef01cSRoman Divacky         TI->replaceUsesOfWith(OldPred, NewBB);
274f22ef01cSRoman Divacky       }
275f22ef01cSRoman Divacky 
2763b0f4066SDimitry Andric     // Okay, everything within the region is now branching to the right block, we
277f22ef01cSRoman Divacky     // just have to update the PHI nodes now, inserting PHI nodes into NewBB.
27851690af2SDimitry Andric     BasicBlock::iterator AfterPHIs;
279f22ef01cSRoman Divacky     for (AfterPHIs = OldPred->begin(); isa<PHINode>(AfterPHIs); ++AfterPHIs) {
280f22ef01cSRoman Divacky       PHINode *PN = cast<PHINode>(AfterPHIs);
281f22ef01cSRoman Divacky       // Create a new PHI node in the new region, which has an incoming value
282f22ef01cSRoman Divacky       // from OldPred of PN.
2833b0f4066SDimitry Andric       PHINode *NewPN = PHINode::Create(PN->getType(), 1 + NumPredsFromRegion,
2847d523365SDimitry Andric                                        PN->getName() + ".ce", &NewBB->front());
28551690af2SDimitry Andric       PN->replaceAllUsesWith(NewPN);
286f22ef01cSRoman Divacky       NewPN->addIncoming(PN, OldPred);
287f22ef01cSRoman Divacky 
288f22ef01cSRoman Divacky       // Loop over all of the incoming value in PN, moving them to NewPN if they
289f22ef01cSRoman Divacky       // are from the extracted region.
290f22ef01cSRoman Divacky       for (unsigned i = 0; i != PN->getNumIncomingValues(); ++i) {
2917ae0e2c9SDimitry Andric         if (Blocks.count(PN->getIncomingBlock(i))) {
292f22ef01cSRoman Divacky           NewPN->addIncoming(PN->getIncomingValue(i), PN->getIncomingBlock(i));
293f22ef01cSRoman Divacky           PN->removeIncomingValue(i);
294f22ef01cSRoman Divacky           --i;
295f22ef01cSRoman Divacky         }
296f22ef01cSRoman Divacky       }
297f22ef01cSRoman Divacky     }
298f22ef01cSRoman Divacky   }
299f22ef01cSRoman Divacky }
300f22ef01cSRoman Divacky 
301f22ef01cSRoman Divacky void CodeExtractor::splitReturnBlocks() {
3023ca95b02SDimitry Andric   for (BasicBlock *Block : Blocks)
3033ca95b02SDimitry Andric     if (ReturnInst *RI = dyn_cast<ReturnInst>(Block->getTerminator())) {
3047d523365SDimitry Andric       BasicBlock *New =
3053ca95b02SDimitry Andric           Block->splitBasicBlock(RI->getIterator(), Block->getName() + ".ret");
306f22ef01cSRoman Divacky       if (DT) {
3072754fe60SDimitry Andric         // Old dominates New. New node dominates all other nodes dominated
308f22ef01cSRoman Divacky         // by Old.
3093ca95b02SDimitry Andric         DomTreeNode *OldNode = DT->getNode(Block);
3103ca95b02SDimitry Andric         SmallVector<DomTreeNode *, 8> Children(OldNode->begin(),
3113ca95b02SDimitry Andric                                                OldNode->end());
312f22ef01cSRoman Divacky 
3133ca95b02SDimitry Andric         DomTreeNode *NewNode = DT->addNewBlock(New, Block);
314f22ef01cSRoman Divacky 
3153ca95b02SDimitry Andric         for (DomTreeNode *I : Children)
3163ca95b02SDimitry Andric           DT->changeImmediateDominator(I, NewNode);
317f22ef01cSRoman Divacky       }
318f22ef01cSRoman Divacky     }
319f22ef01cSRoman Divacky }
320f22ef01cSRoman Divacky 
321f22ef01cSRoman Divacky /// constructFunction - make a function based on inputs and outputs, as follows:
322f22ef01cSRoman Divacky /// f(in0, ..., inN, out0, ..., outN)
323f22ef01cSRoman Divacky ///
3247ae0e2c9SDimitry Andric Function *CodeExtractor::constructFunction(const ValueSet &inputs,
3257ae0e2c9SDimitry Andric                                            const ValueSet &outputs,
326f22ef01cSRoman Divacky                                            BasicBlock *header,
327f22ef01cSRoman Divacky                                            BasicBlock *newRootNode,
328f22ef01cSRoman Divacky                                            BasicBlock *newHeader,
329f22ef01cSRoman Divacky                                            Function *oldFunction,
330f22ef01cSRoman Divacky                                            Module *M) {
331f22ef01cSRoman Divacky   DEBUG(dbgs() << "inputs: " << inputs.size() << "\n");
332f22ef01cSRoman Divacky   DEBUG(dbgs() << "outputs: " << outputs.size() << "\n");
333f22ef01cSRoman Divacky 
334f22ef01cSRoman Divacky   // This function returns unsigned, outputs will go back by reference.
335f22ef01cSRoman Divacky   switch (NumExitBlocks) {
336f22ef01cSRoman Divacky   case 0:
337f22ef01cSRoman Divacky   case 1: RetTy = Type::getVoidTy(header->getContext()); break;
338f22ef01cSRoman Divacky   case 2: RetTy = Type::getInt1Ty(header->getContext()); break;
339f22ef01cSRoman Divacky   default: RetTy = Type::getInt16Ty(header->getContext()); break;
340f22ef01cSRoman Divacky   }
341f22ef01cSRoman Divacky 
34217a519f9SDimitry Andric   std::vector<Type*> paramTy;
343f22ef01cSRoman Divacky 
344f22ef01cSRoman Divacky   // Add the types of the input values to the function's argument list
3453ca95b02SDimitry Andric   for (Value *value : inputs) {
346f22ef01cSRoman Divacky     DEBUG(dbgs() << "value used in func: " << *value << "\n");
347f22ef01cSRoman Divacky     paramTy.push_back(value->getType());
348f22ef01cSRoman Divacky   }
349f22ef01cSRoman Divacky 
350f22ef01cSRoman Divacky   // Add the types of the output values to the function's argument list.
3513ca95b02SDimitry Andric   for (Value *output : outputs) {
3523ca95b02SDimitry Andric     DEBUG(dbgs() << "instr used in func: " << *output << "\n");
353f22ef01cSRoman Divacky     if (AggregateArgs)
3543ca95b02SDimitry Andric       paramTy.push_back(output->getType());
355f22ef01cSRoman Divacky     else
3563ca95b02SDimitry Andric       paramTy.push_back(PointerType::getUnqual(output->getType()));
357f22ef01cSRoman Divacky   }
358f22ef01cSRoman Divacky 
3593ca95b02SDimitry Andric   DEBUG({
3603ca95b02SDimitry Andric     dbgs() << "Function type: " << *RetTy << " f(";
3613ca95b02SDimitry Andric     for (Type *i : paramTy)
3623ca95b02SDimitry Andric       dbgs() << *i << ", ";
3633ca95b02SDimitry Andric     dbgs() << ")\n";
3643ca95b02SDimitry Andric   });
365f22ef01cSRoman Divacky 
366ff0cc061SDimitry Andric   StructType *StructTy;
367f22ef01cSRoman Divacky   if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
368ff0cc061SDimitry Andric     StructTy = StructType::get(M->getContext(), paramTy);
369f22ef01cSRoman Divacky     paramTy.clear();
370ff0cc061SDimitry Andric     paramTy.push_back(PointerType::getUnqual(StructTy));
371f22ef01cSRoman Divacky   }
3726122f3e6SDimitry Andric   FunctionType *funcType =
373f22ef01cSRoman Divacky                   FunctionType::get(RetTy, paramTy, false);
374f22ef01cSRoman Divacky 
375f22ef01cSRoman Divacky   // Create the new function
376f22ef01cSRoman Divacky   Function *newFunction = Function::Create(funcType,
377f22ef01cSRoman Divacky                                            GlobalValue::InternalLinkage,
378f22ef01cSRoman Divacky                                            oldFunction->getName() + "_" +
379f22ef01cSRoman Divacky                                            header->getName(), M);
380f22ef01cSRoman Divacky   // If the old function is no-throw, so is the new one.
381f22ef01cSRoman Divacky   if (oldFunction->doesNotThrow())
3823861d79fSDimitry Andric     newFunction->setDoesNotThrow();
383f22ef01cSRoman Divacky 
384d88c1a5aSDimitry Andric   // Inherit the uwtable attribute if we need to.
385d88c1a5aSDimitry Andric   if (oldFunction->hasUWTable())
386d88c1a5aSDimitry Andric     newFunction->setHasUWTable();
387d88c1a5aSDimitry Andric 
388d88c1a5aSDimitry Andric   // Inherit all of the target dependent attributes.
389d88c1a5aSDimitry Andric   //  (e.g. If the extracted region contains a call to an x86.sse
390d88c1a5aSDimitry Andric   //  instruction we need to make sure that the extracted region has the
391d88c1a5aSDimitry Andric   //  "target-features" attribute allowing it to be lowered.
392d88c1a5aSDimitry Andric   // FIXME: This should be changed to check to see if a specific
393d88c1a5aSDimitry Andric   //           attribute can not be inherited.
3947a7e6055SDimitry Andric   AttrBuilder AB(oldFunction->getAttributes().getFnAttributes());
3957a7e6055SDimitry Andric   for (const auto &Attr : AB.td_attrs())
396d88c1a5aSDimitry Andric     newFunction->addFnAttr(Attr.first, Attr.second);
397d88c1a5aSDimitry Andric 
398f22ef01cSRoman Divacky   newFunction->getBasicBlockList().push_back(newRootNode);
399f22ef01cSRoman Divacky 
400f22ef01cSRoman Divacky   // Create an iterator to name all of the arguments we inserted.
401f22ef01cSRoman Divacky   Function::arg_iterator AI = newFunction->arg_begin();
402f22ef01cSRoman Divacky 
403f22ef01cSRoman Divacky   // Rewrite all users of the inputs in the extracted region to use the
404f22ef01cSRoman Divacky   // arguments (or appropriate addressing into struct) instead.
405f22ef01cSRoman Divacky   for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
406f22ef01cSRoman Divacky     Value *RewriteVal;
407f22ef01cSRoman Divacky     if (AggregateArgs) {
408f22ef01cSRoman Divacky       Value *Idx[2];
409f22ef01cSRoman Divacky       Idx[0] = Constant::getNullValue(Type::getInt32Ty(header->getContext()));
410f22ef01cSRoman Divacky       Idx[1] = ConstantInt::get(Type::getInt32Ty(header->getContext()), i);
411f22ef01cSRoman Divacky       TerminatorInst *TI = newFunction->begin()->getTerminator();
412ff0cc061SDimitry Andric       GetElementPtrInst *GEP = GetElementPtrInst::Create(
4137d523365SDimitry Andric           StructTy, &*AI, Idx, "gep_" + inputs[i]->getName(), TI);
414f22ef01cSRoman Divacky       RewriteVal = new LoadInst(GEP, "loadgep_" + inputs[i]->getName(), TI);
415f22ef01cSRoman Divacky     } else
4167d523365SDimitry Andric       RewriteVal = &*AI++;
417f22ef01cSRoman Divacky 
41891bc56edSDimitry Andric     std::vector<User*> Users(inputs[i]->user_begin(), inputs[i]->user_end());
4193ca95b02SDimitry Andric     for (User *use : Users)
4203ca95b02SDimitry Andric       if (Instruction *inst = dyn_cast<Instruction>(use))
4217ae0e2c9SDimitry Andric         if (Blocks.count(inst->getParent()))
422f22ef01cSRoman Divacky           inst->replaceUsesOfWith(inputs[i], RewriteVal);
423f22ef01cSRoman Divacky   }
424f22ef01cSRoman Divacky 
425f22ef01cSRoman Divacky   // Set names for input and output arguments.
426f22ef01cSRoman Divacky   if (!AggregateArgs) {
427f22ef01cSRoman Divacky     AI = newFunction->arg_begin();
428f22ef01cSRoman Divacky     for (unsigned i = 0, e = inputs.size(); i != e; ++i, ++AI)
429f22ef01cSRoman Divacky       AI->setName(inputs[i]->getName());
430f22ef01cSRoman Divacky     for (unsigned i = 0, e = outputs.size(); i != e; ++i, ++AI)
431f22ef01cSRoman Divacky       AI->setName(outputs[i]->getName()+".out");
432f22ef01cSRoman Divacky   }
433f22ef01cSRoman Divacky 
434f22ef01cSRoman Divacky   // Rewrite branches to basic blocks outside of the loop to new dummy blocks
435f22ef01cSRoman Divacky   // within the new function. This must be done before we lose track of which
436f22ef01cSRoman Divacky   // blocks were originally in the code region.
43791bc56edSDimitry Andric   std::vector<User*> Users(header->user_begin(), header->user_end());
438f22ef01cSRoman Divacky   for (unsigned i = 0, e = Users.size(); i != e; ++i)
439f22ef01cSRoman Divacky     // The BasicBlock which contains the branch is not in the region
440f22ef01cSRoman Divacky     // modify the branch target to a new block
441f22ef01cSRoman Divacky     if (TerminatorInst *TI = dyn_cast<TerminatorInst>(Users[i]))
4427ae0e2c9SDimitry Andric       if (!Blocks.count(TI->getParent()) &&
443f22ef01cSRoman Divacky           TI->getParent()->getParent() == oldFunction)
444f22ef01cSRoman Divacky         TI->replaceUsesOfWith(header, newHeader);
445f22ef01cSRoman Divacky 
446f22ef01cSRoman Divacky   return newFunction;
447f22ef01cSRoman Divacky }
448f22ef01cSRoman Divacky 
449f22ef01cSRoman Divacky /// FindPhiPredForUseInBlock - Given a value and a basic block, find a PHI
450f22ef01cSRoman Divacky /// that uses the value within the basic block, and return the predecessor
451f22ef01cSRoman Divacky /// block associated with that use, or return 0 if none is found.
452f22ef01cSRoman Divacky static BasicBlock* FindPhiPredForUseInBlock(Value* Used, BasicBlock* BB) {
45391bc56edSDimitry Andric   for (Use &U : Used->uses()) {
45491bc56edSDimitry Andric      PHINode *P = dyn_cast<PHINode>(U.getUser());
455f22ef01cSRoman Divacky      if (P && P->getParent() == BB)
45691bc56edSDimitry Andric        return P->getIncomingBlock(U);
457f22ef01cSRoman Divacky   }
458f22ef01cSRoman Divacky 
45991bc56edSDimitry Andric   return nullptr;
460f22ef01cSRoman Divacky }
461f22ef01cSRoman Divacky 
462f22ef01cSRoman Divacky /// emitCallAndSwitchStatement - This method sets up the caller side by adding
463f22ef01cSRoman Divacky /// the call instruction, splitting any PHI nodes in the header block as
464f22ef01cSRoman Divacky /// necessary.
465f22ef01cSRoman Divacky void CodeExtractor::
466f22ef01cSRoman Divacky emitCallAndSwitchStatement(Function *newFunction, BasicBlock *codeReplacer,
4677ae0e2c9SDimitry Andric                            ValueSet &inputs, ValueSet &outputs) {
468f22ef01cSRoman Divacky   // Emit a call to the new function, passing in: *pointer to struct (if
469f22ef01cSRoman Divacky   // aggregating parameters), or plan inputs and allocated memory for outputs
470f22ef01cSRoman Divacky   std::vector<Value*> params, StructValues, ReloadOutputs, Reloads;
471f22ef01cSRoman Divacky 
4727a7e6055SDimitry Andric   Module *M = newFunction->getParent();
4737a7e6055SDimitry Andric   LLVMContext &Context = M->getContext();
4747a7e6055SDimitry Andric   const DataLayout &DL = M->getDataLayout();
475f22ef01cSRoman Divacky 
476f22ef01cSRoman Divacky   // Add inputs as params, or to be filled into the struct
4773ca95b02SDimitry Andric   for (Value *input : inputs)
478f22ef01cSRoman Divacky     if (AggregateArgs)
4793ca95b02SDimitry Andric       StructValues.push_back(input);
480f22ef01cSRoman Divacky     else
4813ca95b02SDimitry Andric       params.push_back(input);
482f22ef01cSRoman Divacky 
483f22ef01cSRoman Divacky   // Create allocas for the outputs
4843ca95b02SDimitry Andric   for (Value *output : outputs) {
485f22ef01cSRoman Divacky     if (AggregateArgs) {
4863ca95b02SDimitry Andric       StructValues.push_back(output);
487f22ef01cSRoman Divacky     } else {
488f22ef01cSRoman Divacky       AllocaInst *alloca =
4897a7e6055SDimitry Andric         new AllocaInst(output->getType(), DL.getAllocaAddrSpace(),
4907a7e6055SDimitry Andric                        nullptr, output->getName() + ".loc",
4917d523365SDimitry Andric                        &codeReplacer->getParent()->front().front());
492f22ef01cSRoman Divacky       ReloadOutputs.push_back(alloca);
493f22ef01cSRoman Divacky       params.push_back(alloca);
494f22ef01cSRoman Divacky     }
495f22ef01cSRoman Divacky   }
496f22ef01cSRoman Divacky 
497ff0cc061SDimitry Andric   StructType *StructArgTy = nullptr;
49891bc56edSDimitry Andric   AllocaInst *Struct = nullptr;
499f22ef01cSRoman Divacky   if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
50017a519f9SDimitry Andric     std::vector<Type*> ArgTypes;
5017ae0e2c9SDimitry Andric     for (ValueSet::iterator v = StructValues.begin(),
502f22ef01cSRoman Divacky            ve = StructValues.end(); v != ve; ++v)
503f22ef01cSRoman Divacky       ArgTypes.push_back((*v)->getType());
504f22ef01cSRoman Divacky 
505f22ef01cSRoman Divacky     // Allocate a struct at the beginning of this function
506ff0cc061SDimitry Andric     StructArgTy = StructType::get(newFunction->getContext(), ArgTypes);
5077a7e6055SDimitry Andric     Struct = new AllocaInst(StructArgTy, DL.getAllocaAddrSpace(), nullptr,
5087a7e6055SDimitry Andric                             "structArg",
5097d523365SDimitry Andric                             &codeReplacer->getParent()->front().front());
510f22ef01cSRoman Divacky     params.push_back(Struct);
511f22ef01cSRoman Divacky 
512f22ef01cSRoman Divacky     for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
513f22ef01cSRoman Divacky       Value *Idx[2];
514f22ef01cSRoman Divacky       Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
515f22ef01cSRoman Divacky       Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), i);
516ff0cc061SDimitry Andric       GetElementPtrInst *GEP = GetElementPtrInst::Create(
517ff0cc061SDimitry Andric           StructArgTy, Struct, Idx, "gep_" + StructValues[i]->getName());
518f22ef01cSRoman Divacky       codeReplacer->getInstList().push_back(GEP);
519f22ef01cSRoman Divacky       StoreInst *SI = new StoreInst(StructValues[i], GEP);
520f22ef01cSRoman Divacky       codeReplacer->getInstList().push_back(SI);
521f22ef01cSRoman Divacky     }
522f22ef01cSRoman Divacky   }
523f22ef01cSRoman Divacky 
524f22ef01cSRoman Divacky   // Emit the call to the function
52517a519f9SDimitry Andric   CallInst *call = CallInst::Create(newFunction, params,
526f22ef01cSRoman Divacky                                     NumExitBlocks > 1 ? "targetBlock" : "");
527f22ef01cSRoman Divacky   codeReplacer->getInstList().push_back(call);
528f22ef01cSRoman Divacky 
529f22ef01cSRoman Divacky   Function::arg_iterator OutputArgBegin = newFunction->arg_begin();
530f22ef01cSRoman Divacky   unsigned FirstOut = inputs.size();
531f22ef01cSRoman Divacky   if (!AggregateArgs)
532f22ef01cSRoman Divacky     std::advance(OutputArgBegin, inputs.size());
533f22ef01cSRoman Divacky 
534f22ef01cSRoman Divacky   // Reload the outputs passed in by reference
535f22ef01cSRoman Divacky   for (unsigned i = 0, e = outputs.size(); i != e; ++i) {
53691bc56edSDimitry Andric     Value *Output = nullptr;
537f22ef01cSRoman Divacky     if (AggregateArgs) {
538f22ef01cSRoman Divacky       Value *Idx[2];
539f22ef01cSRoman Divacky       Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
540f22ef01cSRoman Divacky       Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), FirstOut + i);
541ff0cc061SDimitry Andric       GetElementPtrInst *GEP = GetElementPtrInst::Create(
542ff0cc061SDimitry Andric           StructArgTy, Struct, Idx, "gep_reload_" + outputs[i]->getName());
543f22ef01cSRoman Divacky       codeReplacer->getInstList().push_back(GEP);
544f22ef01cSRoman Divacky       Output = GEP;
545f22ef01cSRoman Divacky     } else {
546f22ef01cSRoman Divacky       Output = ReloadOutputs[i];
547f22ef01cSRoman Divacky     }
548f22ef01cSRoman Divacky     LoadInst *load = new LoadInst(Output, outputs[i]->getName()+".reload");
549f22ef01cSRoman Divacky     Reloads.push_back(load);
550f22ef01cSRoman Divacky     codeReplacer->getInstList().push_back(load);
55191bc56edSDimitry Andric     std::vector<User*> Users(outputs[i]->user_begin(), outputs[i]->user_end());
552f22ef01cSRoman Divacky     for (unsigned u = 0, e = Users.size(); u != e; ++u) {
553f22ef01cSRoman Divacky       Instruction *inst = cast<Instruction>(Users[u]);
5547ae0e2c9SDimitry Andric       if (!Blocks.count(inst->getParent()))
555f22ef01cSRoman Divacky         inst->replaceUsesOfWith(outputs[i], load);
556f22ef01cSRoman Divacky     }
557f22ef01cSRoman Divacky   }
558f22ef01cSRoman Divacky 
559f22ef01cSRoman Divacky   // Now we can emit a switch statement using the call as a value.
560f22ef01cSRoman Divacky   SwitchInst *TheSwitch =
561f22ef01cSRoman Divacky       SwitchInst::Create(Constant::getNullValue(Type::getInt16Ty(Context)),
562f22ef01cSRoman Divacky                          codeReplacer, 0, codeReplacer);
563f22ef01cSRoman Divacky 
564f22ef01cSRoman Divacky   // Since there may be multiple exits from the original region, make the new
565f22ef01cSRoman Divacky   // function return an unsigned, switch on that number.  This loop iterates
566f22ef01cSRoman Divacky   // over all of the blocks in the extracted region, updating any terminator
567f22ef01cSRoman Divacky   // instructions in the to-be-extracted region that branch to blocks that are
568f22ef01cSRoman Divacky   // not in the region to be extracted.
569f22ef01cSRoman Divacky   std::map<BasicBlock*, BasicBlock*> ExitBlockMap;
570f22ef01cSRoman Divacky 
571f22ef01cSRoman Divacky   unsigned switchVal = 0;
5723ca95b02SDimitry Andric   for (BasicBlock *Block : Blocks) {
5733ca95b02SDimitry Andric     TerminatorInst *TI = Block->getTerminator();
574f22ef01cSRoman Divacky     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
5757ae0e2c9SDimitry Andric       if (!Blocks.count(TI->getSuccessor(i))) {
576f22ef01cSRoman Divacky         BasicBlock *OldTarget = TI->getSuccessor(i);
577f22ef01cSRoman Divacky         // add a new basic block which returns the appropriate value
578f22ef01cSRoman Divacky         BasicBlock *&NewTarget = ExitBlockMap[OldTarget];
579f22ef01cSRoman Divacky         if (!NewTarget) {
580f22ef01cSRoman Divacky           // If we don't already have an exit stub for this non-extracted
581f22ef01cSRoman Divacky           // destination, create one now!
582f22ef01cSRoman Divacky           NewTarget = BasicBlock::Create(Context,
583f22ef01cSRoman Divacky                                          OldTarget->getName() + ".exitStub",
584f22ef01cSRoman Divacky                                          newFunction);
585f22ef01cSRoman Divacky           unsigned SuccNum = switchVal++;
586f22ef01cSRoman Divacky 
58791bc56edSDimitry Andric           Value *brVal = nullptr;
588f22ef01cSRoman Divacky           switch (NumExitBlocks) {
589f22ef01cSRoman Divacky           case 0:
590f22ef01cSRoman Divacky           case 1: break;  // No value needed.
591f22ef01cSRoman Divacky           case 2:         // Conditional branch, return a bool
592f22ef01cSRoman Divacky             brVal = ConstantInt::get(Type::getInt1Ty(Context), !SuccNum);
593f22ef01cSRoman Divacky             break;
594f22ef01cSRoman Divacky           default:
595f22ef01cSRoman Divacky             brVal = ConstantInt::get(Type::getInt16Ty(Context), SuccNum);
596f22ef01cSRoman Divacky             break;
597f22ef01cSRoman Divacky           }
598f22ef01cSRoman Divacky 
599f22ef01cSRoman Divacky           ReturnInst *NTRet = ReturnInst::Create(Context, brVal, NewTarget);
600f22ef01cSRoman Divacky 
601f22ef01cSRoman Divacky           // Update the switch instruction.
602f22ef01cSRoman Divacky           TheSwitch->addCase(ConstantInt::get(Type::getInt16Ty(Context),
603f22ef01cSRoman Divacky                                               SuccNum),
604f22ef01cSRoman Divacky                              OldTarget);
605f22ef01cSRoman Divacky 
606f22ef01cSRoman Divacky           // Restore values just before we exit
607f22ef01cSRoman Divacky           Function::arg_iterator OAI = OutputArgBegin;
608f22ef01cSRoman Divacky           for (unsigned out = 0, e = outputs.size(); out != e; ++out) {
609f22ef01cSRoman Divacky             // For an invoke, the normal destination is the only one that is
610f22ef01cSRoman Divacky             // dominated by the result of the invocation
611f22ef01cSRoman Divacky             BasicBlock *DefBlock = cast<Instruction>(outputs[out])->getParent();
612f22ef01cSRoman Divacky 
613f22ef01cSRoman Divacky             bool DominatesDef = true;
614f22ef01cSRoman Divacky 
6157d523365SDimitry Andric             BasicBlock *NormalDest = nullptr;
6167d523365SDimitry Andric             if (auto *Invoke = dyn_cast<InvokeInst>(outputs[out]))
6177d523365SDimitry Andric               NormalDest = Invoke->getNormalDest();
6187d523365SDimitry Andric 
6197d523365SDimitry Andric             if (NormalDest) {
6207d523365SDimitry Andric               DefBlock = NormalDest;
621f22ef01cSRoman Divacky 
622f22ef01cSRoman Divacky               // Make sure we are looking at the original successor block, not
623f22ef01cSRoman Divacky               // at a newly inserted exit block, which won't be in the dominator
624f22ef01cSRoman Divacky               // info.
6253ca95b02SDimitry Andric               for (const auto &I : ExitBlockMap)
6263ca95b02SDimitry Andric                 if (DefBlock == I.second) {
6273ca95b02SDimitry Andric                   DefBlock = I.first;
628f22ef01cSRoman Divacky                   break;
629f22ef01cSRoman Divacky                 }
630f22ef01cSRoman Divacky 
631f22ef01cSRoman Divacky               // In the extract block case, if the block we are extracting ends
632f22ef01cSRoman Divacky               // with an invoke instruction, make sure that we don't emit a
633f22ef01cSRoman Divacky               // store of the invoke value for the unwind block.
634f22ef01cSRoman Divacky               if (!DT && DefBlock != OldTarget)
635f22ef01cSRoman Divacky                 DominatesDef = false;
636f22ef01cSRoman Divacky             }
637f22ef01cSRoman Divacky 
638f22ef01cSRoman Divacky             if (DT) {
639f22ef01cSRoman Divacky               DominatesDef = DT->dominates(DefBlock, OldTarget);
640f22ef01cSRoman Divacky 
641f22ef01cSRoman Divacky               // If the output value is used by a phi in the target block,
642f22ef01cSRoman Divacky               // then we need to test for dominance of the phi's predecessor
643f22ef01cSRoman Divacky               // instead.  Unfortunately, this a little complicated since we
644f22ef01cSRoman Divacky               // have already rewritten uses of the value to uses of the reload.
645f22ef01cSRoman Divacky               BasicBlock* pred = FindPhiPredForUseInBlock(Reloads[out],
646f22ef01cSRoman Divacky                                                           OldTarget);
647f22ef01cSRoman Divacky               if (pred && DT && DT->dominates(DefBlock, pred))
648f22ef01cSRoman Divacky                 DominatesDef = true;
649f22ef01cSRoman Divacky             }
650f22ef01cSRoman Divacky 
651f22ef01cSRoman Divacky             if (DominatesDef) {
652f22ef01cSRoman Divacky               if (AggregateArgs) {
653f22ef01cSRoman Divacky                 Value *Idx[2];
654f22ef01cSRoman Divacky                 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
655f22ef01cSRoman Divacky                 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context),
656f22ef01cSRoman Divacky                                           FirstOut+out);
657ff0cc061SDimitry Andric                 GetElementPtrInst *GEP = GetElementPtrInst::Create(
6587d523365SDimitry Andric                     StructArgTy, &*OAI, Idx, "gep_" + outputs[out]->getName(),
659f22ef01cSRoman Divacky                     NTRet);
660f22ef01cSRoman Divacky                 new StoreInst(outputs[out], GEP, NTRet);
661f22ef01cSRoman Divacky               } else {
6627d523365SDimitry Andric                 new StoreInst(outputs[out], &*OAI, NTRet);
663f22ef01cSRoman Divacky               }
664f22ef01cSRoman Divacky             }
665f22ef01cSRoman Divacky             // Advance output iterator even if we don't emit a store
666f22ef01cSRoman Divacky             if (!AggregateArgs) ++OAI;
667f22ef01cSRoman Divacky           }
668f22ef01cSRoman Divacky         }
669f22ef01cSRoman Divacky 
670f22ef01cSRoman Divacky         // rewrite the original branch instruction with this new target
671f22ef01cSRoman Divacky         TI->setSuccessor(i, NewTarget);
672f22ef01cSRoman Divacky       }
673f22ef01cSRoman Divacky   }
674f22ef01cSRoman Divacky 
675f22ef01cSRoman Divacky   // Now that we've done the deed, simplify the switch instruction.
6766122f3e6SDimitry Andric   Type *OldFnRetTy = TheSwitch->getParent()->getParent()->getReturnType();
677f22ef01cSRoman Divacky   switch (NumExitBlocks) {
678f22ef01cSRoman Divacky   case 0:
679f22ef01cSRoman Divacky     // There are no successors (the block containing the switch itself), which
680f22ef01cSRoman Divacky     // means that previously this was the last part of the function, and hence
681f22ef01cSRoman Divacky     // this should be rewritten as a `ret'
682f22ef01cSRoman Divacky 
683f22ef01cSRoman Divacky     // Check if the function should return a value
684f22ef01cSRoman Divacky     if (OldFnRetTy->isVoidTy()) {
68591bc56edSDimitry Andric       ReturnInst::Create(Context, nullptr, TheSwitch);  // Return void
686f22ef01cSRoman Divacky     } else if (OldFnRetTy == TheSwitch->getCondition()->getType()) {
687f22ef01cSRoman Divacky       // return what we have
688f22ef01cSRoman Divacky       ReturnInst::Create(Context, TheSwitch->getCondition(), TheSwitch);
689f22ef01cSRoman Divacky     } else {
690f22ef01cSRoman Divacky       // Otherwise we must have code extracted an unwind or something, just
691f22ef01cSRoman Divacky       // return whatever we want.
692f22ef01cSRoman Divacky       ReturnInst::Create(Context,
693f22ef01cSRoman Divacky                          Constant::getNullValue(OldFnRetTy), TheSwitch);
694f22ef01cSRoman Divacky     }
695f22ef01cSRoman Divacky 
696f22ef01cSRoman Divacky     TheSwitch->eraseFromParent();
697f22ef01cSRoman Divacky     break;
698f22ef01cSRoman Divacky   case 1:
699f22ef01cSRoman Divacky     // Only a single destination, change the switch into an unconditional
700f22ef01cSRoman Divacky     // branch.
701f22ef01cSRoman Divacky     BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch);
702f22ef01cSRoman Divacky     TheSwitch->eraseFromParent();
703f22ef01cSRoman Divacky     break;
704f22ef01cSRoman Divacky   case 2:
705f22ef01cSRoman Divacky     BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch->getSuccessor(2),
706f22ef01cSRoman Divacky                        call, TheSwitch);
707f22ef01cSRoman Divacky     TheSwitch->eraseFromParent();
708f22ef01cSRoman Divacky     break;
709f22ef01cSRoman Divacky   default:
710f22ef01cSRoman Divacky     // Otherwise, make the default destination of the switch instruction be one
711f22ef01cSRoman Divacky     // of the other successors.
712dff0c46cSDimitry Andric     TheSwitch->setCondition(call);
713dff0c46cSDimitry Andric     TheSwitch->setDefaultDest(TheSwitch->getSuccessor(NumExitBlocks));
714dff0c46cSDimitry Andric     // Remove redundant case
715f785676fSDimitry Andric     TheSwitch->removeCase(SwitchInst::CaseIt(TheSwitch, NumExitBlocks-1));
716f22ef01cSRoman Divacky     break;
717f22ef01cSRoman Divacky   }
718f22ef01cSRoman Divacky }
719f22ef01cSRoman Divacky 
720f22ef01cSRoman Divacky void CodeExtractor::moveCodeToFunction(Function *newFunction) {
7217ae0e2c9SDimitry Andric   Function *oldFunc = (*Blocks.begin())->getParent();
722f22ef01cSRoman Divacky   Function::BasicBlockListType &oldBlocks = oldFunc->getBasicBlockList();
723f22ef01cSRoman Divacky   Function::BasicBlockListType &newBlocks = newFunction->getBasicBlockList();
724f22ef01cSRoman Divacky 
7253ca95b02SDimitry Andric   for (BasicBlock *Block : Blocks) {
726f22ef01cSRoman Divacky     // Delete the basic block from the old function, and the list of blocks
7273ca95b02SDimitry Andric     oldBlocks.remove(Block);
728f22ef01cSRoman Divacky 
729f22ef01cSRoman Divacky     // Insert this basic block into the new function
7303ca95b02SDimitry Andric     newBlocks.push_back(Block);
731f22ef01cSRoman Divacky   }
732f22ef01cSRoman Divacky }
733f22ef01cSRoman Divacky 
734d88c1a5aSDimitry Andric void CodeExtractor::calculateNewCallTerminatorWeights(
735d88c1a5aSDimitry Andric     BasicBlock *CodeReplacer,
736d88c1a5aSDimitry Andric     DenseMap<BasicBlock *, BlockFrequency> &ExitWeights,
737d88c1a5aSDimitry Andric     BranchProbabilityInfo *BPI) {
738d88c1a5aSDimitry Andric   typedef BlockFrequencyInfoImplBase::Distribution Distribution;
739d88c1a5aSDimitry Andric   typedef BlockFrequencyInfoImplBase::BlockNode BlockNode;
740d88c1a5aSDimitry Andric 
741d88c1a5aSDimitry Andric   // Update the branch weights for the exit block.
742d88c1a5aSDimitry Andric   TerminatorInst *TI = CodeReplacer->getTerminator();
743d88c1a5aSDimitry Andric   SmallVector<unsigned, 8> BranchWeights(TI->getNumSuccessors(), 0);
744d88c1a5aSDimitry Andric 
745d88c1a5aSDimitry Andric   // Block Frequency distribution with dummy node.
746d88c1a5aSDimitry Andric   Distribution BranchDist;
747d88c1a5aSDimitry Andric 
748d88c1a5aSDimitry Andric   // Add each of the frequencies of the successors.
749d88c1a5aSDimitry Andric   for (unsigned i = 0, e = TI->getNumSuccessors(); i < e; ++i) {
750d88c1a5aSDimitry Andric     BlockNode ExitNode(i);
751d88c1a5aSDimitry Andric     uint64_t ExitFreq = ExitWeights[TI->getSuccessor(i)].getFrequency();
752d88c1a5aSDimitry Andric     if (ExitFreq != 0)
753d88c1a5aSDimitry Andric       BranchDist.addExit(ExitNode, ExitFreq);
754d88c1a5aSDimitry Andric     else
755d88c1a5aSDimitry Andric       BPI->setEdgeProbability(CodeReplacer, i, BranchProbability::getZero());
756d88c1a5aSDimitry Andric   }
757d88c1a5aSDimitry Andric 
758d88c1a5aSDimitry Andric   // Check for no total weight.
759d88c1a5aSDimitry Andric   if (BranchDist.Total == 0)
760d88c1a5aSDimitry Andric     return;
761d88c1a5aSDimitry Andric 
762d88c1a5aSDimitry Andric   // Normalize the distribution so that they can fit in unsigned.
763d88c1a5aSDimitry Andric   BranchDist.normalize();
764d88c1a5aSDimitry Andric 
765d88c1a5aSDimitry Andric   // Create normalized branch weights and set the metadata.
766d88c1a5aSDimitry Andric   for (unsigned I = 0, E = BranchDist.Weights.size(); I < E; ++I) {
767d88c1a5aSDimitry Andric     const auto &Weight = BranchDist.Weights[I];
768d88c1a5aSDimitry Andric 
769d88c1a5aSDimitry Andric     // Get the weight and update the current BFI.
770d88c1a5aSDimitry Andric     BranchWeights[Weight.TargetNode.Index] = Weight.Amount;
771d88c1a5aSDimitry Andric     BranchProbability BP(Weight.Amount, BranchDist.Total);
772d88c1a5aSDimitry Andric     BPI->setEdgeProbability(CodeReplacer, Weight.TargetNode.Index, BP);
773d88c1a5aSDimitry Andric   }
774d88c1a5aSDimitry Andric   TI->setMetadata(
775d88c1a5aSDimitry Andric       LLVMContext::MD_prof,
776d88c1a5aSDimitry Andric       MDBuilder(TI->getContext()).createBranchWeights(BranchWeights));
777d88c1a5aSDimitry Andric }
778d88c1a5aSDimitry Andric 
7797ae0e2c9SDimitry Andric Function *CodeExtractor::extractCodeRegion() {
7807ae0e2c9SDimitry Andric   if (!isEligible())
78191bc56edSDimitry Andric     return nullptr;
782f22ef01cSRoman Divacky 
783f9448bf3SDimitry Andric   ValueSet inputs, outputs, SinkingCands;
784f22ef01cSRoman Divacky 
785f22ef01cSRoman Divacky   // Assumption: this is a single-entry code region, and the header is the first
786f22ef01cSRoman Divacky   // block in the region.
7877ae0e2c9SDimitry Andric   BasicBlock *header = *Blocks.begin();
788f22ef01cSRoman Divacky 
789d88c1a5aSDimitry Andric   // Calculate the entry frequency of the new function before we change the root
790d88c1a5aSDimitry Andric   //   block.
791d88c1a5aSDimitry Andric   BlockFrequency EntryFreq;
792d88c1a5aSDimitry Andric   if (BFI) {
793d88c1a5aSDimitry Andric     assert(BPI && "Both BPI and BFI are required to preserve profile info");
794d88c1a5aSDimitry Andric     for (BasicBlock *Pred : predecessors(header)) {
795d88c1a5aSDimitry Andric       if (Blocks.count(Pred))
796d88c1a5aSDimitry Andric         continue;
797d88c1a5aSDimitry Andric       EntryFreq +=
798d88c1a5aSDimitry Andric           BFI->getBlockFreq(Pred) * BPI->getEdgeProbability(Pred, header);
799d88c1a5aSDimitry Andric     }
800d88c1a5aSDimitry Andric   }
801d88c1a5aSDimitry Andric 
802f22ef01cSRoman Divacky   // If we have to split PHI nodes or the entry block, do so now.
803f22ef01cSRoman Divacky   severSplitPHINodes(header);
804f22ef01cSRoman Divacky 
805f22ef01cSRoman Divacky   // If we have any return instructions in the region, split those blocks so
806f22ef01cSRoman Divacky   // that the return is not in the region.
807f22ef01cSRoman Divacky   splitReturnBlocks();
808f22ef01cSRoman Divacky 
809f22ef01cSRoman Divacky   Function *oldFunction = header->getParent();
810f22ef01cSRoman Divacky 
811f22ef01cSRoman Divacky   // This takes place of the original loop
812f22ef01cSRoman Divacky   BasicBlock *codeReplacer = BasicBlock::Create(header->getContext(),
813f22ef01cSRoman Divacky                                                 "codeRepl", oldFunction,
814f22ef01cSRoman Divacky                                                 header);
815f22ef01cSRoman Divacky 
816f22ef01cSRoman Divacky   // The new function needs a root node because other nodes can branch to the
817f22ef01cSRoman Divacky   // head of the region, but the entry node of a function cannot have preds.
818f22ef01cSRoman Divacky   BasicBlock *newFuncRoot = BasicBlock::Create(header->getContext(),
819f22ef01cSRoman Divacky                                                "newFuncRoot");
820f22ef01cSRoman Divacky   newFuncRoot->getInstList().push_back(BranchInst::Create(header));
821f22ef01cSRoman Divacky 
822f9448bf3SDimitry Andric   findAllocas(SinkingCands);
823f9448bf3SDimitry Andric 
824f22ef01cSRoman Divacky   // Find inputs to, outputs from the code region.
825f9448bf3SDimitry Andric   findInputsOutputs(inputs, outputs, SinkingCands);
826f9448bf3SDimitry Andric 
827f9448bf3SDimitry Andric   // Now sink all instructions which only have non-phi uses inside the region
828f9448bf3SDimitry Andric   for (auto *II : SinkingCands)
829f9448bf3SDimitry Andric     cast<Instruction>(II)->moveBefore(*newFuncRoot,
830f9448bf3SDimitry Andric                                       newFuncRoot->getFirstInsertionPt());
831f22ef01cSRoman Divacky 
832d88c1a5aSDimitry Andric   // Calculate the exit blocks for the extracted region and the total exit
833d88c1a5aSDimitry Andric   //  weights for each of those blocks.
834d88c1a5aSDimitry Andric   DenseMap<BasicBlock *, BlockFrequency> ExitWeights;
8357ae0e2c9SDimitry Andric   SmallPtrSet<BasicBlock *, 1> ExitBlocks;
836d88c1a5aSDimitry Andric   for (BasicBlock *Block : Blocks) {
8373ca95b02SDimitry Andric     for (succ_iterator SI = succ_begin(Block), SE = succ_end(Block); SI != SE;
838d88c1a5aSDimitry Andric          ++SI) {
839d88c1a5aSDimitry Andric       if (!Blocks.count(*SI)) {
840d88c1a5aSDimitry Andric         // Update the branch weight for this successor.
841d88c1a5aSDimitry Andric         if (BFI) {
842d88c1a5aSDimitry Andric           BlockFrequency &BF = ExitWeights[*SI];
843d88c1a5aSDimitry Andric           BF += BFI->getBlockFreq(Block) * BPI->getEdgeProbability(Block, *SI);
844d88c1a5aSDimitry Andric         }
8457ae0e2c9SDimitry Andric         ExitBlocks.insert(*SI);
846d88c1a5aSDimitry Andric       }
847d88c1a5aSDimitry Andric     }
848d88c1a5aSDimitry Andric   }
8497ae0e2c9SDimitry Andric   NumExitBlocks = ExitBlocks.size();
8507ae0e2c9SDimitry Andric 
851f22ef01cSRoman Divacky   // Construct new function based on inputs/outputs & add allocas for all defs.
852f22ef01cSRoman Divacky   Function *newFunction = constructFunction(inputs, outputs, header,
853f22ef01cSRoman Divacky                                             newFuncRoot,
854f22ef01cSRoman Divacky                                             codeReplacer, oldFunction,
855f22ef01cSRoman Divacky                                             oldFunction->getParent());
856f22ef01cSRoman Divacky 
857d88c1a5aSDimitry Andric   // Update the entry count of the function.
858d88c1a5aSDimitry Andric   if (BFI) {
859d88c1a5aSDimitry Andric     Optional<uint64_t> EntryCount =
860d88c1a5aSDimitry Andric         BFI->getProfileCountFromFreq(EntryFreq.getFrequency());
861d88c1a5aSDimitry Andric     if (EntryCount.hasValue())
862d88c1a5aSDimitry Andric       newFunction->setEntryCount(EntryCount.getValue());
863d88c1a5aSDimitry Andric     BFI->setBlockFreq(codeReplacer, EntryFreq.getFrequency());
864d88c1a5aSDimitry Andric   }
865d88c1a5aSDimitry Andric 
866f22ef01cSRoman Divacky   emitCallAndSwitchStatement(newFunction, codeReplacer, inputs, outputs);
867f22ef01cSRoman Divacky 
868f22ef01cSRoman Divacky   moveCodeToFunction(newFunction);
869f22ef01cSRoman Divacky 
870d88c1a5aSDimitry Andric   // Update the branch weights for the exit block.
871d88c1a5aSDimitry Andric   if (BFI && NumExitBlocks > 1)
872d88c1a5aSDimitry Andric     calculateNewCallTerminatorWeights(codeReplacer, ExitWeights, BPI);
873d88c1a5aSDimitry Andric 
874f22ef01cSRoman Divacky   // Loop over all of the PHI nodes in the header block, and change any
875f22ef01cSRoman Divacky   // references to the old incoming edge to be the new incoming edge.
876f22ef01cSRoman Divacky   for (BasicBlock::iterator I = header->begin(); isa<PHINode>(I); ++I) {
877f22ef01cSRoman Divacky     PHINode *PN = cast<PHINode>(I);
878f22ef01cSRoman Divacky     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8797ae0e2c9SDimitry Andric       if (!Blocks.count(PN->getIncomingBlock(i)))
880f22ef01cSRoman Divacky         PN->setIncomingBlock(i, newFuncRoot);
881f22ef01cSRoman Divacky   }
882f22ef01cSRoman Divacky 
883f22ef01cSRoman Divacky   // Look at all successors of the codeReplacer block.  If any of these blocks
884f22ef01cSRoman Divacky   // had PHI nodes in them, we need to update the "from" block to be the code
885f22ef01cSRoman Divacky   // replacer, not the original block in the extracted region.
886f22ef01cSRoman Divacky   std::vector<BasicBlock*> Succs(succ_begin(codeReplacer),
887f22ef01cSRoman Divacky                                  succ_end(codeReplacer));
888f22ef01cSRoman Divacky   for (unsigned i = 0, e = Succs.size(); i != e; ++i)
889f22ef01cSRoman Divacky     for (BasicBlock::iterator I = Succs[i]->begin(); isa<PHINode>(I); ++I) {
890f22ef01cSRoman Divacky       PHINode *PN = cast<PHINode>(I);
891f22ef01cSRoman Divacky       std::set<BasicBlock*> ProcessedPreds;
892f22ef01cSRoman Divacky       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8937ae0e2c9SDimitry Andric         if (Blocks.count(PN->getIncomingBlock(i))) {
894f22ef01cSRoman Divacky           if (ProcessedPreds.insert(PN->getIncomingBlock(i)).second)
895f22ef01cSRoman Divacky             PN->setIncomingBlock(i, codeReplacer);
896f22ef01cSRoman Divacky           else {
897f22ef01cSRoman Divacky             // There were multiple entries in the PHI for this block, now there
898f22ef01cSRoman Divacky             // is only one, so remove the duplicated entries.
899f22ef01cSRoman Divacky             PN->removeIncomingValue(i, false);
900f22ef01cSRoman Divacky             --i; --e;
901f22ef01cSRoman Divacky           }
902f22ef01cSRoman Divacky         }
903f22ef01cSRoman Divacky     }
904f22ef01cSRoman Divacky 
905f22ef01cSRoman Divacky   //cerr << "NEW FUNCTION: " << *newFunction;
906f22ef01cSRoman Divacky   //  verifyFunction(*newFunction);
907f22ef01cSRoman Divacky 
908f22ef01cSRoman Divacky   //  cerr << "OLD FUNCTION: " << *oldFunction;
909f22ef01cSRoman Divacky   //  verifyFunction(*oldFunction);
910f22ef01cSRoman Divacky 
911f22ef01cSRoman Divacky   DEBUG(if (verifyFunction(*newFunction))
912f22ef01cSRoman Divacky         report_fatal_error("verifyFunction failed!"));
913f22ef01cSRoman Divacky   return newFunction;
914f22ef01cSRoman Divacky }
915