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" 20f22ef01cSRoman Divacky #include "llvm/Analysis/LoopInfo.h" 217ae0e2c9SDimitry Andric #include "llvm/Analysis/RegionInfo.h" 227ae0e2c9SDimitry Andric #include "llvm/Analysis/RegionIterator.h" 23139f7f9bSDimitry Andric #include "llvm/IR/Constants.h" 24139f7f9bSDimitry Andric #include "llvm/IR/DerivedTypes.h" 2591bc56edSDimitry Andric #include "llvm/IR/Dominators.h" 26139f7f9bSDimitry Andric #include "llvm/IR/Instructions.h" 27139f7f9bSDimitry Andric #include "llvm/IR/Intrinsics.h" 28139f7f9bSDimitry Andric #include "llvm/IR/LLVMContext.h" 29139f7f9bSDimitry Andric #include "llvm/IR/Module.h" 3091bc56edSDimitry Andric #include "llvm/IR/Verifier.h" 31139f7f9bSDimitry Andric #include "llvm/Pass.h" 32f22ef01cSRoman Divacky #include "llvm/Support/CommandLine.h" 33f22ef01cSRoman Divacky #include "llvm/Support/Debug.h" 34f22ef01cSRoman Divacky #include "llvm/Support/ErrorHandling.h" 35f22ef01cSRoman Divacky #include "llvm/Support/raw_ostream.h" 36139f7f9bSDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h" 37f22ef01cSRoman Divacky #include <algorithm> 38f22ef01cSRoman Divacky #include <set> 39f22ef01cSRoman Divacky using namespace llvm; 40f22ef01cSRoman Divacky 4191bc56edSDimitry Andric #define DEBUG_TYPE "code-extractor" 4291bc56edSDimitry Andric 43f22ef01cSRoman Divacky // Provide a command-line option to aggregate function arguments into a struct 44f22ef01cSRoman Divacky // for functions produced by the code extractor. This is useful when converting 45f22ef01cSRoman Divacky // extracted functions to pthread-based code, as only one argument (void*) can 46f22ef01cSRoman Divacky // be passed in to pthread_create(). 47f22ef01cSRoman Divacky static cl::opt<bool> 48f22ef01cSRoman Divacky AggregateArgsOpt("aggregate-extracted-args", cl::Hidden, 49f22ef01cSRoman Divacky cl::desc("Aggregate arguments to code-extracted functions")); 50f22ef01cSRoman Divacky 517ae0e2c9SDimitry Andric /// \brief Test whether a block is valid for extraction. 527ae0e2c9SDimitry Andric static bool isBlockValidForExtraction(const BasicBlock &BB) { 537ae0e2c9SDimitry Andric // Landing pads must be in the function where they were inserted for cleanup. 547ae0e2c9SDimitry Andric if (BB.isLandingPad()) 557ae0e2c9SDimitry Andric return false; 56f22ef01cSRoman Divacky 577ae0e2c9SDimitry Andric // Don't hoist code containing allocas, invokes, or vastarts. 587ae0e2c9SDimitry Andric for (BasicBlock::const_iterator I = BB.begin(), E = BB.end(); I != E; ++I) { 597ae0e2c9SDimitry Andric if (isa<AllocaInst>(I) || isa<InvokeInst>(I)) 607ae0e2c9SDimitry Andric return false; 617ae0e2c9SDimitry Andric if (const CallInst *CI = dyn_cast<CallInst>(I)) 627ae0e2c9SDimitry Andric if (const Function *F = CI->getCalledFunction()) 637ae0e2c9SDimitry Andric if (F->getIntrinsicID() == Intrinsic::vastart) 647ae0e2c9SDimitry Andric return false; 657ae0e2c9SDimitry Andric } 66f22ef01cSRoman Divacky 677ae0e2c9SDimitry Andric return true; 687ae0e2c9SDimitry Andric } 69f22ef01cSRoman Divacky 707ae0e2c9SDimitry Andric /// \brief Build a set of blocks to extract if the input blocks are viable. 717ae0e2c9SDimitry Andric template <typename IteratorT> 727ae0e2c9SDimitry Andric static SetVector<BasicBlock *> buildExtractionBlockSet(IteratorT BBBegin, 737ae0e2c9SDimitry Andric IteratorT BBEnd) { 747ae0e2c9SDimitry Andric SetVector<BasicBlock *> Result; 757ae0e2c9SDimitry Andric 767ae0e2c9SDimitry Andric assert(BBBegin != BBEnd); 777ae0e2c9SDimitry Andric 787ae0e2c9SDimitry Andric // Loop over the blocks, adding them to our set-vector, and aborting with an 797ae0e2c9SDimitry Andric // empty set if we encounter invalid blocks. 807ae0e2c9SDimitry Andric for (IteratorT I = BBBegin, E = BBEnd; I != E; ++I) { 817ae0e2c9SDimitry Andric if (!Result.insert(*I)) 827ae0e2c9SDimitry Andric llvm_unreachable("Repeated basic blocks in extraction input"); 837ae0e2c9SDimitry Andric 847ae0e2c9SDimitry Andric if (!isBlockValidForExtraction(**I)) { 857ae0e2c9SDimitry Andric Result.clear(); 867ae0e2c9SDimitry Andric return Result; 877ae0e2c9SDimitry Andric } 887ae0e2c9SDimitry Andric } 897ae0e2c9SDimitry Andric 907ae0e2c9SDimitry Andric #ifndef NDEBUG 9191bc56edSDimitry Andric for (SetVector<BasicBlock *>::iterator I = std::next(Result.begin()), 927ae0e2c9SDimitry Andric E = Result.end(); 937ae0e2c9SDimitry Andric I != E; ++I) 947ae0e2c9SDimitry Andric for (pred_iterator PI = pred_begin(*I), PE = pred_end(*I); 957ae0e2c9SDimitry Andric PI != PE; ++PI) 967ae0e2c9SDimitry Andric assert(Result.count(*PI) && 977ae0e2c9SDimitry Andric "No blocks in this region may have entries from outside the region" 987ae0e2c9SDimitry Andric " except for the first block!"); 997ae0e2c9SDimitry Andric #endif 1007ae0e2c9SDimitry Andric 1017ae0e2c9SDimitry Andric return Result; 1027ae0e2c9SDimitry Andric } 1037ae0e2c9SDimitry Andric 1047ae0e2c9SDimitry Andric /// \brief Helper to call buildExtractionBlockSet with an ArrayRef. 1057ae0e2c9SDimitry Andric static SetVector<BasicBlock *> 1067ae0e2c9SDimitry Andric buildExtractionBlockSet(ArrayRef<BasicBlock *> BBs) { 1077ae0e2c9SDimitry Andric return buildExtractionBlockSet(BBs.begin(), BBs.end()); 1087ae0e2c9SDimitry Andric } 1097ae0e2c9SDimitry Andric 1107ae0e2c9SDimitry Andric /// \brief Helper to call buildExtractionBlockSet with a RegionNode. 1117ae0e2c9SDimitry Andric static SetVector<BasicBlock *> 1127ae0e2c9SDimitry Andric buildExtractionBlockSet(const RegionNode &RN) { 1137ae0e2c9SDimitry Andric if (!RN.isSubRegion()) 1147ae0e2c9SDimitry Andric // Just a single BasicBlock. 1157ae0e2c9SDimitry Andric return buildExtractionBlockSet(RN.getNodeAs<BasicBlock>()); 1167ae0e2c9SDimitry Andric 1177ae0e2c9SDimitry Andric const Region &R = *RN.getNodeAs<Region>(); 1187ae0e2c9SDimitry Andric 1197ae0e2c9SDimitry Andric return buildExtractionBlockSet(R.block_begin(), R.block_end()); 1207ae0e2c9SDimitry Andric } 1217ae0e2c9SDimitry Andric 1227ae0e2c9SDimitry Andric CodeExtractor::CodeExtractor(BasicBlock *BB, bool AggregateArgs) 12391bc56edSDimitry Andric : DT(nullptr), AggregateArgs(AggregateArgs||AggregateArgsOpt), 1247ae0e2c9SDimitry Andric Blocks(buildExtractionBlockSet(BB)), NumExitBlocks(~0U) {} 1257ae0e2c9SDimitry Andric 1267ae0e2c9SDimitry Andric CodeExtractor::CodeExtractor(ArrayRef<BasicBlock *> BBs, DominatorTree *DT, 1277ae0e2c9SDimitry Andric bool AggregateArgs) 1287ae0e2c9SDimitry Andric : DT(DT), AggregateArgs(AggregateArgs||AggregateArgsOpt), 1297ae0e2c9SDimitry Andric Blocks(buildExtractionBlockSet(BBs)), NumExitBlocks(~0U) {} 1307ae0e2c9SDimitry Andric 1317ae0e2c9SDimitry Andric CodeExtractor::CodeExtractor(DominatorTree &DT, Loop &L, bool AggregateArgs) 1327ae0e2c9SDimitry Andric : DT(&DT), AggregateArgs(AggregateArgs||AggregateArgsOpt), 1337ae0e2c9SDimitry Andric Blocks(buildExtractionBlockSet(L.getBlocks())), NumExitBlocks(~0U) {} 1347ae0e2c9SDimitry Andric 1357ae0e2c9SDimitry Andric CodeExtractor::CodeExtractor(DominatorTree &DT, const RegionNode &RN, 1367ae0e2c9SDimitry Andric bool AggregateArgs) 1377ae0e2c9SDimitry Andric : DT(&DT), AggregateArgs(AggregateArgs||AggregateArgsOpt), 1387ae0e2c9SDimitry Andric Blocks(buildExtractionBlockSet(RN)), NumExitBlocks(~0U) {} 1397ae0e2c9SDimitry Andric 140f22ef01cSRoman Divacky /// definedInRegion - Return true if the specified value is defined in the 141f22ef01cSRoman Divacky /// extracted region. 1427ae0e2c9SDimitry Andric static bool definedInRegion(const SetVector<BasicBlock *> &Blocks, Value *V) { 143f22ef01cSRoman Divacky if (Instruction *I = dyn_cast<Instruction>(V)) 1447ae0e2c9SDimitry Andric if (Blocks.count(I->getParent())) 145f22ef01cSRoman Divacky return true; 146f22ef01cSRoman Divacky return false; 147f22ef01cSRoman Divacky } 148f22ef01cSRoman Divacky 149f22ef01cSRoman Divacky /// definedInCaller - Return true if the specified value is defined in the 150f22ef01cSRoman Divacky /// function being code extracted, but not in the region being extracted. 151f22ef01cSRoman Divacky /// These values must be passed in as live-ins to the function. 1527ae0e2c9SDimitry Andric static bool definedInCaller(const SetVector<BasicBlock *> &Blocks, Value *V) { 153f22ef01cSRoman Divacky if (isa<Argument>(V)) return true; 154f22ef01cSRoman Divacky if (Instruction *I = dyn_cast<Instruction>(V)) 1557ae0e2c9SDimitry Andric if (!Blocks.count(I->getParent())) 156f22ef01cSRoman Divacky return true; 157f22ef01cSRoman Divacky return false; 158f22ef01cSRoman Divacky } 159f22ef01cSRoman Divacky 1607ae0e2c9SDimitry Andric void CodeExtractor::findInputsOutputs(ValueSet &Inputs, 1617ae0e2c9SDimitry Andric ValueSet &Outputs) const { 1627ae0e2c9SDimitry Andric for (SetVector<BasicBlock *>::const_iterator I = Blocks.begin(), 1637ae0e2c9SDimitry Andric E = Blocks.end(); 1647ae0e2c9SDimitry Andric I != E; ++I) { 1657ae0e2c9SDimitry Andric BasicBlock *BB = *I; 166f22ef01cSRoman Divacky 1677ae0e2c9SDimitry Andric // If a used value is defined outside the region, it's an input. If an 1687ae0e2c9SDimitry Andric // instruction is used outside the region, it's an output. 1697ae0e2c9SDimitry Andric for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); 1707ae0e2c9SDimitry Andric II != IE; ++II) { 1717ae0e2c9SDimitry Andric for (User::op_iterator OI = II->op_begin(), OE = II->op_end(); 1727ae0e2c9SDimitry Andric OI != OE; ++OI) 1737ae0e2c9SDimitry Andric if (definedInCaller(Blocks, *OI)) 1747ae0e2c9SDimitry Andric Inputs.insert(*OI); 175f22ef01cSRoman Divacky 17691bc56edSDimitry Andric for (User *U : II->users()) 17791bc56edSDimitry Andric if (!definedInRegion(Blocks, U)) { 1787ae0e2c9SDimitry Andric Outputs.insert(II); 1797ae0e2c9SDimitry Andric break; 1807ae0e2c9SDimitry Andric } 1817ae0e2c9SDimitry Andric } 1827ae0e2c9SDimitry Andric } 183f22ef01cSRoman Divacky } 184f22ef01cSRoman Divacky 185f22ef01cSRoman Divacky /// severSplitPHINodes - If a PHI node has multiple inputs from outside of the 186f22ef01cSRoman Divacky /// region, we need to split the entry block of the region so that the PHI node 187f22ef01cSRoman Divacky /// is easier to deal with. 188f22ef01cSRoman Divacky void CodeExtractor::severSplitPHINodes(BasicBlock *&Header) { 1893b0f4066SDimitry Andric unsigned NumPredsFromRegion = 0; 190f22ef01cSRoman Divacky unsigned NumPredsOutsideRegion = 0; 191f22ef01cSRoman Divacky 192f22ef01cSRoman Divacky if (Header != &Header->getParent()->getEntryBlock()) { 193f22ef01cSRoman Divacky PHINode *PN = dyn_cast<PHINode>(Header->begin()); 194f22ef01cSRoman Divacky if (!PN) return; // No PHI nodes. 195f22ef01cSRoman Divacky 196f22ef01cSRoman Divacky // If the header node contains any PHI nodes, check to see if there is more 197f22ef01cSRoman Divacky // than one entry from outside the region. If so, we need to sever the 198f22ef01cSRoman Divacky // header block into two. 199f22ef01cSRoman Divacky for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 2007ae0e2c9SDimitry Andric if (Blocks.count(PN->getIncomingBlock(i))) 2013b0f4066SDimitry Andric ++NumPredsFromRegion; 202f22ef01cSRoman Divacky else 203f22ef01cSRoman Divacky ++NumPredsOutsideRegion; 204f22ef01cSRoman Divacky 205f22ef01cSRoman Divacky // If there is one (or fewer) predecessor from outside the region, we don't 206f22ef01cSRoman Divacky // need to do anything special. 207f22ef01cSRoman Divacky if (NumPredsOutsideRegion <= 1) return; 208f22ef01cSRoman Divacky } 209f22ef01cSRoman Divacky 210f22ef01cSRoman Divacky // Otherwise, we need to split the header block into two pieces: one 211f22ef01cSRoman Divacky // containing PHI nodes merging values from outside of the region, and a 212f22ef01cSRoman Divacky // second that contains all of the code for the block and merges back any 213f22ef01cSRoman Divacky // incoming values from inside of the region. 214f22ef01cSRoman Divacky BasicBlock::iterator AfterPHIs = Header->getFirstNonPHI(); 215f22ef01cSRoman Divacky BasicBlock *NewBB = Header->splitBasicBlock(AfterPHIs, 216f22ef01cSRoman Divacky Header->getName()+".ce"); 217f22ef01cSRoman Divacky 218f22ef01cSRoman Divacky // We only want to code extract the second block now, and it becomes the new 219f22ef01cSRoman Divacky // header of the region. 220f22ef01cSRoman Divacky BasicBlock *OldPred = Header; 2217ae0e2c9SDimitry Andric Blocks.remove(OldPred); 2227ae0e2c9SDimitry Andric Blocks.insert(NewBB); 223f22ef01cSRoman Divacky Header = NewBB; 224f22ef01cSRoman Divacky 225f22ef01cSRoman Divacky // Okay, update dominator sets. The blocks that dominate the new one are the 226f22ef01cSRoman Divacky // blocks that dominate TIBB plus the new block itself. 227f22ef01cSRoman Divacky if (DT) 228f22ef01cSRoman Divacky DT->splitBlock(NewBB); 229f22ef01cSRoman Divacky 230f22ef01cSRoman Divacky // Okay, now we need to adjust the PHI nodes and any branches from within the 231f22ef01cSRoman Divacky // region to go to the new header block instead of the old header block. 2323b0f4066SDimitry Andric if (NumPredsFromRegion) { 233f22ef01cSRoman Divacky PHINode *PN = cast<PHINode>(OldPred->begin()); 234f22ef01cSRoman Divacky // Loop over all of the predecessors of OldPred that are in the region, 235f22ef01cSRoman Divacky // changing them to branch to NewBB instead. 236f22ef01cSRoman Divacky for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 2377ae0e2c9SDimitry Andric if (Blocks.count(PN->getIncomingBlock(i))) { 238f22ef01cSRoman Divacky TerminatorInst *TI = PN->getIncomingBlock(i)->getTerminator(); 239f22ef01cSRoman Divacky TI->replaceUsesOfWith(OldPred, NewBB); 240f22ef01cSRoman Divacky } 241f22ef01cSRoman Divacky 2423b0f4066SDimitry Andric // Okay, everything within the region is now branching to the right block, we 243f22ef01cSRoman Divacky // just have to update the PHI nodes now, inserting PHI nodes into NewBB. 244f22ef01cSRoman Divacky for (AfterPHIs = OldPred->begin(); isa<PHINode>(AfterPHIs); ++AfterPHIs) { 245f22ef01cSRoman Divacky PHINode *PN = cast<PHINode>(AfterPHIs); 246f22ef01cSRoman Divacky // Create a new PHI node in the new region, which has an incoming value 247f22ef01cSRoman Divacky // from OldPred of PN. 2483b0f4066SDimitry Andric PHINode *NewPN = PHINode::Create(PN->getType(), 1 + NumPredsFromRegion, 2493b0f4066SDimitry Andric PN->getName()+".ce", NewBB->begin()); 250f22ef01cSRoman Divacky NewPN->addIncoming(PN, OldPred); 251f22ef01cSRoman Divacky 252f22ef01cSRoman Divacky // Loop over all of the incoming value in PN, moving them to NewPN if they 253f22ef01cSRoman Divacky // are from the extracted region. 254f22ef01cSRoman Divacky for (unsigned i = 0; i != PN->getNumIncomingValues(); ++i) { 2557ae0e2c9SDimitry Andric if (Blocks.count(PN->getIncomingBlock(i))) { 256f22ef01cSRoman Divacky NewPN->addIncoming(PN->getIncomingValue(i), PN->getIncomingBlock(i)); 257f22ef01cSRoman Divacky PN->removeIncomingValue(i); 258f22ef01cSRoman Divacky --i; 259f22ef01cSRoman Divacky } 260f22ef01cSRoman Divacky } 261f22ef01cSRoman Divacky } 262f22ef01cSRoman Divacky } 263f22ef01cSRoman Divacky } 264f22ef01cSRoman Divacky 265f22ef01cSRoman Divacky void CodeExtractor::splitReturnBlocks() { 2667ae0e2c9SDimitry Andric for (SetVector<BasicBlock *>::iterator I = Blocks.begin(), E = Blocks.end(); 2677ae0e2c9SDimitry Andric I != E; ++I) 268f22ef01cSRoman Divacky if (ReturnInst *RI = dyn_cast<ReturnInst>((*I)->getTerminator())) { 269f22ef01cSRoman Divacky BasicBlock *New = (*I)->splitBasicBlock(RI, (*I)->getName()+".ret"); 270f22ef01cSRoman Divacky if (DT) { 2712754fe60SDimitry Andric // Old dominates New. New node dominates all other nodes dominated 272f22ef01cSRoman Divacky // by Old. 273f22ef01cSRoman Divacky DomTreeNode *OldNode = DT->getNode(*I); 274f22ef01cSRoman Divacky SmallVector<DomTreeNode*, 8> Children; 275f22ef01cSRoman Divacky for (DomTreeNode::iterator DI = OldNode->begin(), DE = OldNode->end(); 276f22ef01cSRoman Divacky DI != DE; ++DI) 277f22ef01cSRoman Divacky Children.push_back(*DI); 278f22ef01cSRoman Divacky 279f22ef01cSRoman Divacky DomTreeNode *NewNode = DT->addNewBlock(New, *I); 280f22ef01cSRoman Divacky 281f785676fSDimitry Andric for (SmallVectorImpl<DomTreeNode *>::iterator I = Children.begin(), 282f22ef01cSRoman Divacky E = Children.end(); I != E; ++I) 283f22ef01cSRoman Divacky DT->changeImmediateDominator(*I, NewNode); 284f22ef01cSRoman Divacky } 285f22ef01cSRoman Divacky } 286f22ef01cSRoman Divacky } 287f22ef01cSRoman Divacky 288f22ef01cSRoman Divacky /// constructFunction - make a function based on inputs and outputs, as follows: 289f22ef01cSRoman Divacky /// f(in0, ..., inN, out0, ..., outN) 290f22ef01cSRoman Divacky /// 2917ae0e2c9SDimitry Andric Function *CodeExtractor::constructFunction(const ValueSet &inputs, 2927ae0e2c9SDimitry Andric const ValueSet &outputs, 293f22ef01cSRoman Divacky BasicBlock *header, 294f22ef01cSRoman Divacky BasicBlock *newRootNode, 295f22ef01cSRoman Divacky BasicBlock *newHeader, 296f22ef01cSRoman Divacky Function *oldFunction, 297f22ef01cSRoman Divacky Module *M) { 298f22ef01cSRoman Divacky DEBUG(dbgs() << "inputs: " << inputs.size() << "\n"); 299f22ef01cSRoman Divacky DEBUG(dbgs() << "outputs: " << outputs.size() << "\n"); 300f22ef01cSRoman Divacky 301f22ef01cSRoman Divacky // This function returns unsigned, outputs will go back by reference. 302f22ef01cSRoman Divacky switch (NumExitBlocks) { 303f22ef01cSRoman Divacky case 0: 304f22ef01cSRoman Divacky case 1: RetTy = Type::getVoidTy(header->getContext()); break; 305f22ef01cSRoman Divacky case 2: RetTy = Type::getInt1Ty(header->getContext()); break; 306f22ef01cSRoman Divacky default: RetTy = Type::getInt16Ty(header->getContext()); break; 307f22ef01cSRoman Divacky } 308f22ef01cSRoman Divacky 30917a519f9SDimitry Andric std::vector<Type*> paramTy; 310f22ef01cSRoman Divacky 311f22ef01cSRoman Divacky // Add the types of the input values to the function's argument list 3127ae0e2c9SDimitry Andric for (ValueSet::const_iterator i = inputs.begin(), e = inputs.end(); 3137ae0e2c9SDimitry Andric i != e; ++i) { 314f22ef01cSRoman Divacky const Value *value = *i; 315f22ef01cSRoman Divacky DEBUG(dbgs() << "value used in func: " << *value << "\n"); 316f22ef01cSRoman Divacky paramTy.push_back(value->getType()); 317f22ef01cSRoman Divacky } 318f22ef01cSRoman Divacky 319f22ef01cSRoman Divacky // Add the types of the output values to the function's argument list. 3207ae0e2c9SDimitry Andric for (ValueSet::const_iterator I = outputs.begin(), E = outputs.end(); 321f22ef01cSRoman Divacky I != E; ++I) { 322f22ef01cSRoman Divacky DEBUG(dbgs() << "instr used in func: " << **I << "\n"); 323f22ef01cSRoman Divacky if (AggregateArgs) 324f22ef01cSRoman Divacky paramTy.push_back((*I)->getType()); 325f22ef01cSRoman Divacky else 326f22ef01cSRoman Divacky paramTy.push_back(PointerType::getUnqual((*I)->getType())); 327f22ef01cSRoman Divacky } 328f22ef01cSRoman Divacky 329f22ef01cSRoman Divacky DEBUG(dbgs() << "Function type: " << *RetTy << " f("); 33017a519f9SDimitry Andric for (std::vector<Type*>::iterator i = paramTy.begin(), 331f22ef01cSRoman Divacky e = paramTy.end(); i != e; ++i) 332f22ef01cSRoman Divacky DEBUG(dbgs() << **i << ", "); 333f22ef01cSRoman Divacky DEBUG(dbgs() << ")\n"); 334f22ef01cSRoman Divacky 335f22ef01cSRoman Divacky if (AggregateArgs && (inputs.size() + outputs.size() > 0)) { 336f22ef01cSRoman Divacky PointerType *StructPtr = 337f22ef01cSRoman Divacky PointerType::getUnqual(StructType::get(M->getContext(), paramTy)); 338f22ef01cSRoman Divacky paramTy.clear(); 339f22ef01cSRoman Divacky paramTy.push_back(StructPtr); 340f22ef01cSRoman Divacky } 3416122f3e6SDimitry Andric FunctionType *funcType = 342f22ef01cSRoman Divacky FunctionType::get(RetTy, paramTy, false); 343f22ef01cSRoman Divacky 344f22ef01cSRoman Divacky // Create the new function 345f22ef01cSRoman Divacky Function *newFunction = Function::Create(funcType, 346f22ef01cSRoman Divacky GlobalValue::InternalLinkage, 347f22ef01cSRoman Divacky oldFunction->getName() + "_" + 348f22ef01cSRoman Divacky header->getName(), M); 349f22ef01cSRoman Divacky // If the old function is no-throw, so is the new one. 350f22ef01cSRoman Divacky if (oldFunction->doesNotThrow()) 3513861d79fSDimitry Andric newFunction->setDoesNotThrow(); 352f22ef01cSRoman Divacky 353f22ef01cSRoman Divacky newFunction->getBasicBlockList().push_back(newRootNode); 354f22ef01cSRoman Divacky 355f22ef01cSRoman Divacky // Create an iterator to name all of the arguments we inserted. 356f22ef01cSRoman Divacky Function::arg_iterator AI = newFunction->arg_begin(); 357f22ef01cSRoman Divacky 358f22ef01cSRoman Divacky // Rewrite all users of the inputs in the extracted region to use the 359f22ef01cSRoman Divacky // arguments (or appropriate addressing into struct) instead. 360f22ef01cSRoman Divacky for (unsigned i = 0, e = inputs.size(); i != e; ++i) { 361f22ef01cSRoman Divacky Value *RewriteVal; 362f22ef01cSRoman Divacky if (AggregateArgs) { 363f22ef01cSRoman Divacky Value *Idx[2]; 364f22ef01cSRoman Divacky Idx[0] = Constant::getNullValue(Type::getInt32Ty(header->getContext())); 365f22ef01cSRoman Divacky Idx[1] = ConstantInt::get(Type::getInt32Ty(header->getContext()), i); 366f22ef01cSRoman Divacky TerminatorInst *TI = newFunction->begin()->getTerminator(); 367f22ef01cSRoman Divacky GetElementPtrInst *GEP = 3686122f3e6SDimitry Andric GetElementPtrInst::Create(AI, Idx, "gep_" + inputs[i]->getName(), TI); 369f22ef01cSRoman Divacky RewriteVal = new LoadInst(GEP, "loadgep_" + inputs[i]->getName(), TI); 370f22ef01cSRoman Divacky } else 371f22ef01cSRoman Divacky RewriteVal = AI++; 372f22ef01cSRoman Divacky 37391bc56edSDimitry Andric std::vector<User*> Users(inputs[i]->user_begin(), inputs[i]->user_end()); 374f22ef01cSRoman Divacky for (std::vector<User*>::iterator use = Users.begin(), useE = Users.end(); 375f22ef01cSRoman Divacky use != useE; ++use) 376f22ef01cSRoman Divacky if (Instruction* inst = dyn_cast<Instruction>(*use)) 3777ae0e2c9SDimitry Andric if (Blocks.count(inst->getParent())) 378f22ef01cSRoman Divacky inst->replaceUsesOfWith(inputs[i], RewriteVal); 379f22ef01cSRoman Divacky } 380f22ef01cSRoman Divacky 381f22ef01cSRoman Divacky // Set names for input and output arguments. 382f22ef01cSRoman Divacky if (!AggregateArgs) { 383f22ef01cSRoman Divacky AI = newFunction->arg_begin(); 384f22ef01cSRoman Divacky for (unsigned i = 0, e = inputs.size(); i != e; ++i, ++AI) 385f22ef01cSRoman Divacky AI->setName(inputs[i]->getName()); 386f22ef01cSRoman Divacky for (unsigned i = 0, e = outputs.size(); i != e; ++i, ++AI) 387f22ef01cSRoman Divacky AI->setName(outputs[i]->getName()+".out"); 388f22ef01cSRoman Divacky } 389f22ef01cSRoman Divacky 390f22ef01cSRoman Divacky // Rewrite branches to basic blocks outside of the loop to new dummy blocks 391f22ef01cSRoman Divacky // within the new function. This must be done before we lose track of which 392f22ef01cSRoman Divacky // blocks were originally in the code region. 39391bc56edSDimitry Andric std::vector<User*> Users(header->user_begin(), header->user_end()); 394f22ef01cSRoman Divacky for (unsigned i = 0, e = Users.size(); i != e; ++i) 395f22ef01cSRoman Divacky // The BasicBlock which contains the branch is not in the region 396f22ef01cSRoman Divacky // modify the branch target to a new block 397f22ef01cSRoman Divacky if (TerminatorInst *TI = dyn_cast<TerminatorInst>(Users[i])) 3987ae0e2c9SDimitry Andric if (!Blocks.count(TI->getParent()) && 399f22ef01cSRoman Divacky TI->getParent()->getParent() == oldFunction) 400f22ef01cSRoman Divacky TI->replaceUsesOfWith(header, newHeader); 401f22ef01cSRoman Divacky 402f22ef01cSRoman Divacky return newFunction; 403f22ef01cSRoman Divacky } 404f22ef01cSRoman Divacky 405f22ef01cSRoman Divacky /// FindPhiPredForUseInBlock - Given a value and a basic block, find a PHI 406f22ef01cSRoman Divacky /// that uses the value within the basic block, and return the predecessor 407f22ef01cSRoman Divacky /// block associated with that use, or return 0 if none is found. 408f22ef01cSRoman Divacky static BasicBlock* FindPhiPredForUseInBlock(Value* Used, BasicBlock* BB) { 40991bc56edSDimitry Andric for (Use &U : Used->uses()) { 41091bc56edSDimitry Andric PHINode *P = dyn_cast<PHINode>(U.getUser()); 411f22ef01cSRoman Divacky if (P && P->getParent() == BB) 41291bc56edSDimitry Andric return P->getIncomingBlock(U); 413f22ef01cSRoman Divacky } 414f22ef01cSRoman Divacky 41591bc56edSDimitry Andric return nullptr; 416f22ef01cSRoman Divacky } 417f22ef01cSRoman Divacky 418f22ef01cSRoman Divacky /// emitCallAndSwitchStatement - This method sets up the caller side by adding 419f22ef01cSRoman Divacky /// the call instruction, splitting any PHI nodes in the header block as 420f22ef01cSRoman Divacky /// necessary. 421f22ef01cSRoman Divacky void CodeExtractor:: 422f22ef01cSRoman Divacky emitCallAndSwitchStatement(Function *newFunction, BasicBlock *codeReplacer, 4237ae0e2c9SDimitry Andric ValueSet &inputs, ValueSet &outputs) { 424f22ef01cSRoman Divacky // Emit a call to the new function, passing in: *pointer to struct (if 425f22ef01cSRoman Divacky // aggregating parameters), or plan inputs and allocated memory for outputs 426f22ef01cSRoman Divacky std::vector<Value*> params, StructValues, ReloadOutputs, Reloads; 427f22ef01cSRoman Divacky 428f22ef01cSRoman Divacky LLVMContext &Context = newFunction->getContext(); 429f22ef01cSRoman Divacky 430f22ef01cSRoman Divacky // Add inputs as params, or to be filled into the struct 4317ae0e2c9SDimitry Andric for (ValueSet::iterator i = inputs.begin(), e = inputs.end(); i != e; ++i) 432f22ef01cSRoman Divacky if (AggregateArgs) 433f22ef01cSRoman Divacky StructValues.push_back(*i); 434f22ef01cSRoman Divacky else 435f22ef01cSRoman Divacky params.push_back(*i); 436f22ef01cSRoman Divacky 437f22ef01cSRoman Divacky // Create allocas for the outputs 4387ae0e2c9SDimitry Andric for (ValueSet::iterator i = outputs.begin(), e = outputs.end(); i != e; ++i) { 439f22ef01cSRoman Divacky if (AggregateArgs) { 440f22ef01cSRoman Divacky StructValues.push_back(*i); 441f22ef01cSRoman Divacky } else { 442f22ef01cSRoman Divacky AllocaInst *alloca = 44391bc56edSDimitry Andric new AllocaInst((*i)->getType(), nullptr, (*i)->getName()+".loc", 444f22ef01cSRoman Divacky codeReplacer->getParent()->begin()->begin()); 445f22ef01cSRoman Divacky ReloadOutputs.push_back(alloca); 446f22ef01cSRoman Divacky params.push_back(alloca); 447f22ef01cSRoman Divacky } 448f22ef01cSRoman Divacky } 449f22ef01cSRoman Divacky 45091bc56edSDimitry Andric AllocaInst *Struct = nullptr; 451f22ef01cSRoman Divacky if (AggregateArgs && (inputs.size() + outputs.size() > 0)) { 45217a519f9SDimitry Andric std::vector<Type*> ArgTypes; 4537ae0e2c9SDimitry Andric for (ValueSet::iterator v = StructValues.begin(), 454f22ef01cSRoman Divacky ve = StructValues.end(); v != ve; ++v) 455f22ef01cSRoman Divacky ArgTypes.push_back((*v)->getType()); 456f22ef01cSRoman Divacky 457f22ef01cSRoman Divacky // Allocate a struct at the beginning of this function 458f22ef01cSRoman Divacky Type *StructArgTy = StructType::get(newFunction->getContext(), ArgTypes); 459f22ef01cSRoman Divacky Struct = 46091bc56edSDimitry Andric new AllocaInst(StructArgTy, nullptr, "structArg", 461f22ef01cSRoman Divacky codeReplacer->getParent()->begin()->begin()); 462f22ef01cSRoman Divacky params.push_back(Struct); 463f22ef01cSRoman Divacky 464f22ef01cSRoman Divacky for (unsigned i = 0, e = inputs.size(); i != e; ++i) { 465f22ef01cSRoman Divacky Value *Idx[2]; 466f22ef01cSRoman Divacky Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context)); 467f22ef01cSRoman Divacky Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), i); 468f22ef01cSRoman Divacky GetElementPtrInst *GEP = 4696122f3e6SDimitry Andric GetElementPtrInst::Create(Struct, Idx, 470f22ef01cSRoman Divacky "gep_" + StructValues[i]->getName()); 471f22ef01cSRoman Divacky codeReplacer->getInstList().push_back(GEP); 472f22ef01cSRoman Divacky StoreInst *SI = new StoreInst(StructValues[i], GEP); 473f22ef01cSRoman Divacky codeReplacer->getInstList().push_back(SI); 474f22ef01cSRoman Divacky } 475f22ef01cSRoman Divacky } 476f22ef01cSRoman Divacky 477f22ef01cSRoman Divacky // Emit the call to the function 47817a519f9SDimitry Andric CallInst *call = CallInst::Create(newFunction, params, 479f22ef01cSRoman Divacky NumExitBlocks > 1 ? "targetBlock" : ""); 480f22ef01cSRoman Divacky codeReplacer->getInstList().push_back(call); 481f22ef01cSRoman Divacky 482f22ef01cSRoman Divacky Function::arg_iterator OutputArgBegin = newFunction->arg_begin(); 483f22ef01cSRoman Divacky unsigned FirstOut = inputs.size(); 484f22ef01cSRoman Divacky if (!AggregateArgs) 485f22ef01cSRoman Divacky std::advance(OutputArgBegin, inputs.size()); 486f22ef01cSRoman Divacky 487f22ef01cSRoman Divacky // Reload the outputs passed in by reference 488f22ef01cSRoman Divacky for (unsigned i = 0, e = outputs.size(); i != e; ++i) { 48991bc56edSDimitry Andric Value *Output = nullptr; 490f22ef01cSRoman Divacky if (AggregateArgs) { 491f22ef01cSRoman Divacky Value *Idx[2]; 492f22ef01cSRoman Divacky Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context)); 493f22ef01cSRoman Divacky Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), FirstOut + i); 494f22ef01cSRoman Divacky GetElementPtrInst *GEP 4956122f3e6SDimitry Andric = GetElementPtrInst::Create(Struct, Idx, 496f22ef01cSRoman Divacky "gep_reload_" + outputs[i]->getName()); 497f22ef01cSRoman Divacky codeReplacer->getInstList().push_back(GEP); 498f22ef01cSRoman Divacky Output = GEP; 499f22ef01cSRoman Divacky } else { 500f22ef01cSRoman Divacky Output = ReloadOutputs[i]; 501f22ef01cSRoman Divacky } 502f22ef01cSRoman Divacky LoadInst *load = new LoadInst(Output, outputs[i]->getName()+".reload"); 503f22ef01cSRoman Divacky Reloads.push_back(load); 504f22ef01cSRoman Divacky codeReplacer->getInstList().push_back(load); 50591bc56edSDimitry Andric std::vector<User*> Users(outputs[i]->user_begin(), outputs[i]->user_end()); 506f22ef01cSRoman Divacky for (unsigned u = 0, e = Users.size(); u != e; ++u) { 507f22ef01cSRoman Divacky Instruction *inst = cast<Instruction>(Users[u]); 5087ae0e2c9SDimitry Andric if (!Blocks.count(inst->getParent())) 509f22ef01cSRoman Divacky inst->replaceUsesOfWith(outputs[i], load); 510f22ef01cSRoman Divacky } 511f22ef01cSRoman Divacky } 512f22ef01cSRoman Divacky 513f22ef01cSRoman Divacky // Now we can emit a switch statement using the call as a value. 514f22ef01cSRoman Divacky SwitchInst *TheSwitch = 515f22ef01cSRoman Divacky SwitchInst::Create(Constant::getNullValue(Type::getInt16Ty(Context)), 516f22ef01cSRoman Divacky codeReplacer, 0, codeReplacer); 517f22ef01cSRoman Divacky 518f22ef01cSRoman Divacky // Since there may be multiple exits from the original region, make the new 519f22ef01cSRoman Divacky // function return an unsigned, switch on that number. This loop iterates 520f22ef01cSRoman Divacky // over all of the blocks in the extracted region, updating any terminator 521f22ef01cSRoman Divacky // instructions in the to-be-extracted region that branch to blocks that are 522f22ef01cSRoman Divacky // not in the region to be extracted. 523f22ef01cSRoman Divacky std::map<BasicBlock*, BasicBlock*> ExitBlockMap; 524f22ef01cSRoman Divacky 525f22ef01cSRoman Divacky unsigned switchVal = 0; 5267ae0e2c9SDimitry Andric for (SetVector<BasicBlock*>::const_iterator i = Blocks.begin(), 5277ae0e2c9SDimitry Andric e = Blocks.end(); i != e; ++i) { 528f22ef01cSRoman Divacky TerminatorInst *TI = (*i)->getTerminator(); 529f22ef01cSRoman Divacky for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) 5307ae0e2c9SDimitry Andric if (!Blocks.count(TI->getSuccessor(i))) { 531f22ef01cSRoman Divacky BasicBlock *OldTarget = TI->getSuccessor(i); 532f22ef01cSRoman Divacky // add a new basic block which returns the appropriate value 533f22ef01cSRoman Divacky BasicBlock *&NewTarget = ExitBlockMap[OldTarget]; 534f22ef01cSRoman Divacky if (!NewTarget) { 535f22ef01cSRoman Divacky // If we don't already have an exit stub for this non-extracted 536f22ef01cSRoman Divacky // destination, create one now! 537f22ef01cSRoman Divacky NewTarget = BasicBlock::Create(Context, 538f22ef01cSRoman Divacky OldTarget->getName() + ".exitStub", 539f22ef01cSRoman Divacky newFunction); 540f22ef01cSRoman Divacky unsigned SuccNum = switchVal++; 541f22ef01cSRoman Divacky 54291bc56edSDimitry Andric Value *brVal = nullptr; 543f22ef01cSRoman Divacky switch (NumExitBlocks) { 544f22ef01cSRoman Divacky case 0: 545f22ef01cSRoman Divacky case 1: break; // No value needed. 546f22ef01cSRoman Divacky case 2: // Conditional branch, return a bool 547f22ef01cSRoman Divacky brVal = ConstantInt::get(Type::getInt1Ty(Context), !SuccNum); 548f22ef01cSRoman Divacky break; 549f22ef01cSRoman Divacky default: 550f22ef01cSRoman Divacky brVal = ConstantInt::get(Type::getInt16Ty(Context), SuccNum); 551f22ef01cSRoman Divacky break; 552f22ef01cSRoman Divacky } 553f22ef01cSRoman Divacky 554f22ef01cSRoman Divacky ReturnInst *NTRet = ReturnInst::Create(Context, brVal, NewTarget); 555f22ef01cSRoman Divacky 556f22ef01cSRoman Divacky // Update the switch instruction. 557f22ef01cSRoman Divacky TheSwitch->addCase(ConstantInt::get(Type::getInt16Ty(Context), 558f22ef01cSRoman Divacky SuccNum), 559f22ef01cSRoman Divacky OldTarget); 560f22ef01cSRoman Divacky 561f22ef01cSRoman Divacky // Restore values just before we exit 562f22ef01cSRoman Divacky Function::arg_iterator OAI = OutputArgBegin; 563f22ef01cSRoman Divacky for (unsigned out = 0, e = outputs.size(); out != e; ++out) { 564f22ef01cSRoman Divacky // For an invoke, the normal destination is the only one that is 565f22ef01cSRoman Divacky // dominated by the result of the invocation 566f22ef01cSRoman Divacky BasicBlock *DefBlock = cast<Instruction>(outputs[out])->getParent(); 567f22ef01cSRoman Divacky 568f22ef01cSRoman Divacky bool DominatesDef = true; 569f22ef01cSRoman Divacky 570f22ef01cSRoman Divacky if (InvokeInst *Invoke = dyn_cast<InvokeInst>(outputs[out])) { 571f22ef01cSRoman Divacky DefBlock = Invoke->getNormalDest(); 572f22ef01cSRoman Divacky 573f22ef01cSRoman Divacky // Make sure we are looking at the original successor block, not 574f22ef01cSRoman Divacky // at a newly inserted exit block, which won't be in the dominator 575f22ef01cSRoman Divacky // info. 576f22ef01cSRoman Divacky for (std::map<BasicBlock*, BasicBlock*>::iterator I = 577f22ef01cSRoman Divacky ExitBlockMap.begin(), E = ExitBlockMap.end(); I != E; ++I) 578f22ef01cSRoman Divacky if (DefBlock == I->second) { 579f22ef01cSRoman Divacky DefBlock = I->first; 580f22ef01cSRoman Divacky break; 581f22ef01cSRoman Divacky } 582f22ef01cSRoman Divacky 583f22ef01cSRoman Divacky // In the extract block case, if the block we are extracting ends 584f22ef01cSRoman Divacky // with an invoke instruction, make sure that we don't emit a 585f22ef01cSRoman Divacky // store of the invoke value for the unwind block. 586f22ef01cSRoman Divacky if (!DT && DefBlock != OldTarget) 587f22ef01cSRoman Divacky DominatesDef = false; 588f22ef01cSRoman Divacky } 589f22ef01cSRoman Divacky 590f22ef01cSRoman Divacky if (DT) { 591f22ef01cSRoman Divacky DominatesDef = DT->dominates(DefBlock, OldTarget); 592f22ef01cSRoman Divacky 593f22ef01cSRoman Divacky // If the output value is used by a phi in the target block, 594f22ef01cSRoman Divacky // then we need to test for dominance of the phi's predecessor 595f22ef01cSRoman Divacky // instead. Unfortunately, this a little complicated since we 596f22ef01cSRoman Divacky // have already rewritten uses of the value to uses of the reload. 597f22ef01cSRoman Divacky BasicBlock* pred = FindPhiPredForUseInBlock(Reloads[out], 598f22ef01cSRoman Divacky OldTarget); 599f22ef01cSRoman Divacky if (pred && DT && DT->dominates(DefBlock, pred)) 600f22ef01cSRoman Divacky DominatesDef = true; 601f22ef01cSRoman Divacky } 602f22ef01cSRoman Divacky 603f22ef01cSRoman Divacky if (DominatesDef) { 604f22ef01cSRoman Divacky if (AggregateArgs) { 605f22ef01cSRoman Divacky Value *Idx[2]; 606f22ef01cSRoman Divacky Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context)); 607f22ef01cSRoman Divacky Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), 608f22ef01cSRoman Divacky FirstOut+out); 609f22ef01cSRoman Divacky GetElementPtrInst *GEP = 6106122f3e6SDimitry Andric GetElementPtrInst::Create(OAI, Idx, 611f22ef01cSRoman Divacky "gep_" + outputs[out]->getName(), 612f22ef01cSRoman Divacky NTRet); 613f22ef01cSRoman Divacky new StoreInst(outputs[out], GEP, NTRet); 614f22ef01cSRoman Divacky } else { 615f22ef01cSRoman Divacky new StoreInst(outputs[out], OAI, NTRet); 616f22ef01cSRoman Divacky } 617f22ef01cSRoman Divacky } 618f22ef01cSRoman Divacky // Advance output iterator even if we don't emit a store 619f22ef01cSRoman Divacky if (!AggregateArgs) ++OAI; 620f22ef01cSRoman Divacky } 621f22ef01cSRoman Divacky } 622f22ef01cSRoman Divacky 623f22ef01cSRoman Divacky // rewrite the original branch instruction with this new target 624f22ef01cSRoman Divacky TI->setSuccessor(i, NewTarget); 625f22ef01cSRoman Divacky } 626f22ef01cSRoman Divacky } 627f22ef01cSRoman Divacky 628f22ef01cSRoman Divacky // Now that we've done the deed, simplify the switch instruction. 6296122f3e6SDimitry Andric Type *OldFnRetTy = TheSwitch->getParent()->getParent()->getReturnType(); 630f22ef01cSRoman Divacky switch (NumExitBlocks) { 631f22ef01cSRoman Divacky case 0: 632f22ef01cSRoman Divacky // There are no successors (the block containing the switch itself), which 633f22ef01cSRoman Divacky // means that previously this was the last part of the function, and hence 634f22ef01cSRoman Divacky // this should be rewritten as a `ret' 635f22ef01cSRoman Divacky 636f22ef01cSRoman Divacky // Check if the function should return a value 637f22ef01cSRoman Divacky if (OldFnRetTy->isVoidTy()) { 63891bc56edSDimitry Andric ReturnInst::Create(Context, nullptr, TheSwitch); // Return void 639f22ef01cSRoman Divacky } else if (OldFnRetTy == TheSwitch->getCondition()->getType()) { 640f22ef01cSRoman Divacky // return what we have 641f22ef01cSRoman Divacky ReturnInst::Create(Context, TheSwitch->getCondition(), TheSwitch); 642f22ef01cSRoman Divacky } else { 643f22ef01cSRoman Divacky // Otherwise we must have code extracted an unwind or something, just 644f22ef01cSRoman Divacky // return whatever we want. 645f22ef01cSRoman Divacky ReturnInst::Create(Context, 646f22ef01cSRoman Divacky Constant::getNullValue(OldFnRetTy), TheSwitch); 647f22ef01cSRoman Divacky } 648f22ef01cSRoman Divacky 649f22ef01cSRoman Divacky TheSwitch->eraseFromParent(); 650f22ef01cSRoman Divacky break; 651f22ef01cSRoman Divacky case 1: 652f22ef01cSRoman Divacky // Only a single destination, change the switch into an unconditional 653f22ef01cSRoman Divacky // branch. 654f22ef01cSRoman Divacky BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch); 655f22ef01cSRoman Divacky TheSwitch->eraseFromParent(); 656f22ef01cSRoman Divacky break; 657f22ef01cSRoman Divacky case 2: 658f22ef01cSRoman Divacky BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch->getSuccessor(2), 659f22ef01cSRoman Divacky call, TheSwitch); 660f22ef01cSRoman Divacky TheSwitch->eraseFromParent(); 661f22ef01cSRoman Divacky break; 662f22ef01cSRoman Divacky default: 663f22ef01cSRoman Divacky // Otherwise, make the default destination of the switch instruction be one 664f22ef01cSRoman Divacky // of the other successors. 665dff0c46cSDimitry Andric TheSwitch->setCondition(call); 666dff0c46cSDimitry Andric TheSwitch->setDefaultDest(TheSwitch->getSuccessor(NumExitBlocks)); 667dff0c46cSDimitry Andric // Remove redundant case 668f785676fSDimitry Andric TheSwitch->removeCase(SwitchInst::CaseIt(TheSwitch, NumExitBlocks-1)); 669f22ef01cSRoman Divacky break; 670f22ef01cSRoman Divacky } 671f22ef01cSRoman Divacky } 672f22ef01cSRoman Divacky 673f22ef01cSRoman Divacky void CodeExtractor::moveCodeToFunction(Function *newFunction) { 6747ae0e2c9SDimitry Andric Function *oldFunc = (*Blocks.begin())->getParent(); 675f22ef01cSRoman Divacky Function::BasicBlockListType &oldBlocks = oldFunc->getBasicBlockList(); 676f22ef01cSRoman Divacky Function::BasicBlockListType &newBlocks = newFunction->getBasicBlockList(); 677f22ef01cSRoman Divacky 6787ae0e2c9SDimitry Andric for (SetVector<BasicBlock*>::const_iterator i = Blocks.begin(), 6797ae0e2c9SDimitry Andric e = Blocks.end(); i != e; ++i) { 680f22ef01cSRoman Divacky // Delete the basic block from the old function, and the list of blocks 681f22ef01cSRoman Divacky oldBlocks.remove(*i); 682f22ef01cSRoman Divacky 683f22ef01cSRoman Divacky // Insert this basic block into the new function 684f22ef01cSRoman Divacky newBlocks.push_back(*i); 685f22ef01cSRoman Divacky } 686f22ef01cSRoman Divacky } 687f22ef01cSRoman Divacky 6887ae0e2c9SDimitry Andric Function *CodeExtractor::extractCodeRegion() { 6897ae0e2c9SDimitry Andric if (!isEligible()) 69091bc56edSDimitry Andric return nullptr; 691f22ef01cSRoman Divacky 6927ae0e2c9SDimitry Andric ValueSet inputs, outputs; 693f22ef01cSRoman Divacky 694f22ef01cSRoman Divacky // Assumption: this is a single-entry code region, and the header is the first 695f22ef01cSRoman Divacky // block in the region. 6967ae0e2c9SDimitry Andric BasicBlock *header = *Blocks.begin(); 697f22ef01cSRoman Divacky 698f22ef01cSRoman Divacky // If we have to split PHI nodes or the entry block, do so now. 699f22ef01cSRoman Divacky severSplitPHINodes(header); 700f22ef01cSRoman Divacky 701f22ef01cSRoman Divacky // If we have any return instructions in the region, split those blocks so 702f22ef01cSRoman Divacky // that the return is not in the region. 703f22ef01cSRoman Divacky splitReturnBlocks(); 704f22ef01cSRoman Divacky 705f22ef01cSRoman Divacky Function *oldFunction = header->getParent(); 706f22ef01cSRoman Divacky 707f22ef01cSRoman Divacky // This takes place of the original loop 708f22ef01cSRoman Divacky BasicBlock *codeReplacer = BasicBlock::Create(header->getContext(), 709f22ef01cSRoman Divacky "codeRepl", oldFunction, 710f22ef01cSRoman Divacky header); 711f22ef01cSRoman Divacky 712f22ef01cSRoman Divacky // The new function needs a root node because other nodes can branch to the 713f22ef01cSRoman Divacky // head of the region, but the entry node of a function cannot have preds. 714f22ef01cSRoman Divacky BasicBlock *newFuncRoot = BasicBlock::Create(header->getContext(), 715f22ef01cSRoman Divacky "newFuncRoot"); 716f22ef01cSRoman Divacky newFuncRoot->getInstList().push_back(BranchInst::Create(header)); 717f22ef01cSRoman Divacky 718f22ef01cSRoman Divacky // Find inputs to, outputs from the code region. 719f22ef01cSRoman Divacky findInputsOutputs(inputs, outputs); 720f22ef01cSRoman Divacky 7217ae0e2c9SDimitry Andric SmallPtrSet<BasicBlock *, 1> ExitBlocks; 7227ae0e2c9SDimitry Andric for (SetVector<BasicBlock *>::iterator I = Blocks.begin(), E = Blocks.end(); 7237ae0e2c9SDimitry Andric I != E; ++I) 7247ae0e2c9SDimitry Andric for (succ_iterator SI = succ_begin(*I), SE = succ_end(*I); SI != SE; ++SI) 7257ae0e2c9SDimitry Andric if (!Blocks.count(*SI)) 7267ae0e2c9SDimitry Andric ExitBlocks.insert(*SI); 7277ae0e2c9SDimitry Andric NumExitBlocks = ExitBlocks.size(); 7287ae0e2c9SDimitry Andric 729f22ef01cSRoman Divacky // Construct new function based on inputs/outputs & add allocas for all defs. 730f22ef01cSRoman Divacky Function *newFunction = constructFunction(inputs, outputs, header, 731f22ef01cSRoman Divacky newFuncRoot, 732f22ef01cSRoman Divacky codeReplacer, oldFunction, 733f22ef01cSRoman Divacky oldFunction->getParent()); 734f22ef01cSRoman Divacky 735f22ef01cSRoman Divacky emitCallAndSwitchStatement(newFunction, codeReplacer, inputs, outputs); 736f22ef01cSRoman Divacky 737f22ef01cSRoman Divacky moveCodeToFunction(newFunction); 738f22ef01cSRoman Divacky 739f22ef01cSRoman Divacky // Loop over all of the PHI nodes in the header block, and change any 740f22ef01cSRoman Divacky // references to the old incoming edge to be the new incoming edge. 741f22ef01cSRoman Divacky for (BasicBlock::iterator I = header->begin(); isa<PHINode>(I); ++I) { 742f22ef01cSRoman Divacky PHINode *PN = cast<PHINode>(I); 743f22ef01cSRoman Divacky for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 7447ae0e2c9SDimitry Andric if (!Blocks.count(PN->getIncomingBlock(i))) 745f22ef01cSRoman Divacky PN->setIncomingBlock(i, newFuncRoot); 746f22ef01cSRoman Divacky } 747f22ef01cSRoman Divacky 748f22ef01cSRoman Divacky // Look at all successors of the codeReplacer block. If any of these blocks 749f22ef01cSRoman Divacky // had PHI nodes in them, we need to update the "from" block to be the code 750f22ef01cSRoman Divacky // replacer, not the original block in the extracted region. 751f22ef01cSRoman Divacky std::vector<BasicBlock*> Succs(succ_begin(codeReplacer), 752f22ef01cSRoman Divacky succ_end(codeReplacer)); 753f22ef01cSRoman Divacky for (unsigned i = 0, e = Succs.size(); i != e; ++i) 754f22ef01cSRoman Divacky for (BasicBlock::iterator I = Succs[i]->begin(); isa<PHINode>(I); ++I) { 755f22ef01cSRoman Divacky PHINode *PN = cast<PHINode>(I); 756f22ef01cSRoman Divacky std::set<BasicBlock*> ProcessedPreds; 757f22ef01cSRoman Divacky for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 7587ae0e2c9SDimitry Andric if (Blocks.count(PN->getIncomingBlock(i))) { 759f22ef01cSRoman Divacky if (ProcessedPreds.insert(PN->getIncomingBlock(i)).second) 760f22ef01cSRoman Divacky PN->setIncomingBlock(i, codeReplacer); 761f22ef01cSRoman Divacky else { 762f22ef01cSRoman Divacky // There were multiple entries in the PHI for this block, now there 763f22ef01cSRoman Divacky // is only one, so remove the duplicated entries. 764f22ef01cSRoman Divacky PN->removeIncomingValue(i, false); 765f22ef01cSRoman Divacky --i; --e; 766f22ef01cSRoman Divacky } 767f22ef01cSRoman Divacky } 768f22ef01cSRoman Divacky } 769f22ef01cSRoman Divacky 770f22ef01cSRoman Divacky //cerr << "NEW FUNCTION: " << *newFunction; 771f22ef01cSRoman Divacky // verifyFunction(*newFunction); 772f22ef01cSRoman Divacky 773f22ef01cSRoman Divacky // cerr << "OLD FUNCTION: " << *oldFunction; 774f22ef01cSRoman Divacky // verifyFunction(*oldFunction); 775f22ef01cSRoman Divacky 776f22ef01cSRoman Divacky DEBUG(if (verifyFunction(*newFunction)) 777f22ef01cSRoman Divacky report_fatal_error("verifyFunction failed!")); 778f22ef01cSRoman Divacky return newFunction; 779f22ef01cSRoman Divacky } 780