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 
16f22ef01cSRoman Divacky #include "llvm/Transforms/Utils/FunctionUtils.h"
17f22ef01cSRoman Divacky #include "llvm/Constants.h"
18f22ef01cSRoman Divacky #include "llvm/DerivedTypes.h"
19f22ef01cSRoman Divacky #include "llvm/Instructions.h"
20f22ef01cSRoman Divacky #include "llvm/Intrinsics.h"
21f22ef01cSRoman Divacky #include "llvm/LLVMContext.h"
22f22ef01cSRoman Divacky #include "llvm/Module.h"
23f22ef01cSRoman Divacky #include "llvm/Pass.h"
24f22ef01cSRoman Divacky #include "llvm/Analysis/Dominators.h"
25f22ef01cSRoman Divacky #include "llvm/Analysis/LoopInfo.h"
26f22ef01cSRoman Divacky #include "llvm/Analysis/Verifier.h"
27f22ef01cSRoman Divacky #include "llvm/Transforms/Utils/BasicBlockUtils.h"
28f22ef01cSRoman Divacky #include "llvm/Support/CommandLine.h"
29f22ef01cSRoman Divacky #include "llvm/Support/Debug.h"
30f22ef01cSRoman Divacky #include "llvm/Support/ErrorHandling.h"
31f22ef01cSRoman Divacky #include "llvm/Support/raw_ostream.h"
32f22ef01cSRoman Divacky #include "llvm/ADT/SetVector.h"
33f22ef01cSRoman Divacky #include "llvm/ADT/StringExtras.h"
34f22ef01cSRoman Divacky #include <algorithm>
35f22ef01cSRoman Divacky #include <set>
36f22ef01cSRoman Divacky using namespace llvm;
37f22ef01cSRoman Divacky 
38f22ef01cSRoman Divacky // Provide a command-line option to aggregate function arguments into a struct
39f22ef01cSRoman Divacky // for functions produced by the code extractor. This is useful when converting
40f22ef01cSRoman Divacky // extracted functions to pthread-based code, as only one argument (void*) can
41f22ef01cSRoman Divacky // be passed in to pthread_create().
42f22ef01cSRoman Divacky static cl::opt<bool>
43f22ef01cSRoman Divacky AggregateArgsOpt("aggregate-extracted-args", cl::Hidden,
44f22ef01cSRoman Divacky                  cl::desc("Aggregate arguments to code-extracted functions"));
45f22ef01cSRoman Divacky 
46f22ef01cSRoman Divacky namespace {
47f22ef01cSRoman Divacky   class CodeExtractor {
48f22ef01cSRoman Divacky     typedef SetVector<Value*> Values;
49f22ef01cSRoman Divacky     SetVector<BasicBlock*> BlocksToExtract;
50f22ef01cSRoman Divacky     DominatorTree* DT;
51f22ef01cSRoman Divacky     bool AggregateArgs;
52f22ef01cSRoman Divacky     unsigned NumExitBlocks;
53f22ef01cSRoman Divacky     const Type *RetTy;
54f22ef01cSRoman Divacky   public:
55f22ef01cSRoman Divacky     CodeExtractor(DominatorTree* dt = 0, bool AggArgs = false)
56f22ef01cSRoman Divacky       : DT(dt), AggregateArgs(AggArgs||AggregateArgsOpt), NumExitBlocks(~0U) {}
57f22ef01cSRoman Divacky 
58f22ef01cSRoman Divacky     Function *ExtractCodeRegion(const std::vector<BasicBlock*> &code);
59f22ef01cSRoman Divacky 
60f22ef01cSRoman Divacky     bool isEligible(const std::vector<BasicBlock*> &code);
61f22ef01cSRoman Divacky 
62f22ef01cSRoman Divacky   private:
63f22ef01cSRoman Divacky     /// definedInRegion - Return true if the specified value is defined in the
64f22ef01cSRoman Divacky     /// extracted region.
65f22ef01cSRoman Divacky     bool definedInRegion(Value *V) const {
66f22ef01cSRoman Divacky       if (Instruction *I = dyn_cast<Instruction>(V))
67f22ef01cSRoman Divacky         if (BlocksToExtract.count(I->getParent()))
68f22ef01cSRoman Divacky           return true;
69f22ef01cSRoman Divacky       return false;
70f22ef01cSRoman Divacky     }
71f22ef01cSRoman Divacky 
72f22ef01cSRoman Divacky     /// definedInCaller - Return true if the specified value is defined in the
73f22ef01cSRoman Divacky     /// function being code extracted, but not in the region being extracted.
74f22ef01cSRoman Divacky     /// These values must be passed in as live-ins to the function.
75f22ef01cSRoman Divacky     bool definedInCaller(Value *V) const {
76f22ef01cSRoman Divacky       if (isa<Argument>(V)) return true;
77f22ef01cSRoman Divacky       if (Instruction *I = dyn_cast<Instruction>(V))
78f22ef01cSRoman Divacky         if (!BlocksToExtract.count(I->getParent()))
79f22ef01cSRoman Divacky           return true;
80f22ef01cSRoman Divacky       return false;
81f22ef01cSRoman Divacky     }
82f22ef01cSRoman Divacky 
83f22ef01cSRoman Divacky     void severSplitPHINodes(BasicBlock *&Header);
84f22ef01cSRoman Divacky     void splitReturnBlocks();
85f22ef01cSRoman Divacky     void findInputsOutputs(Values &inputs, Values &outputs);
86f22ef01cSRoman Divacky 
87f22ef01cSRoman Divacky     Function *constructFunction(const Values &inputs,
88f22ef01cSRoman Divacky                                 const Values &outputs,
89f22ef01cSRoman Divacky                                 BasicBlock *header,
90f22ef01cSRoman Divacky                                 BasicBlock *newRootNode, BasicBlock *newHeader,
91f22ef01cSRoman Divacky                                 Function *oldFunction, Module *M);
92f22ef01cSRoman Divacky 
93f22ef01cSRoman Divacky     void moveCodeToFunction(Function *newFunction);
94f22ef01cSRoman Divacky 
95f22ef01cSRoman Divacky     void emitCallAndSwitchStatement(Function *newFunction,
96f22ef01cSRoman Divacky                                     BasicBlock *newHeader,
97f22ef01cSRoman Divacky                                     Values &inputs,
98f22ef01cSRoman Divacky                                     Values &outputs);
99f22ef01cSRoman Divacky 
100f22ef01cSRoman Divacky   };
101f22ef01cSRoman Divacky }
102f22ef01cSRoman Divacky 
103f22ef01cSRoman Divacky /// severSplitPHINodes - If a PHI node has multiple inputs from outside of the
104f22ef01cSRoman Divacky /// region, we need to split the entry block of the region so that the PHI node
105f22ef01cSRoman Divacky /// is easier to deal with.
106f22ef01cSRoman Divacky void CodeExtractor::severSplitPHINodes(BasicBlock *&Header) {
107f22ef01cSRoman Divacky   bool HasPredsFromRegion = false;
108f22ef01cSRoman Divacky   unsigned NumPredsOutsideRegion = 0;
109f22ef01cSRoman Divacky 
110f22ef01cSRoman Divacky   if (Header != &Header->getParent()->getEntryBlock()) {
111f22ef01cSRoman Divacky     PHINode *PN = dyn_cast<PHINode>(Header->begin());
112f22ef01cSRoman Divacky     if (!PN) return;  // No PHI nodes.
113f22ef01cSRoman Divacky 
114f22ef01cSRoman Divacky     // If the header node contains any PHI nodes, check to see if there is more
115f22ef01cSRoman Divacky     // than one entry from outside the region.  If so, we need to sever the
116f22ef01cSRoman Divacky     // header block into two.
117f22ef01cSRoman Divacky     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
118f22ef01cSRoman Divacky       if (BlocksToExtract.count(PN->getIncomingBlock(i)))
119f22ef01cSRoman Divacky         HasPredsFromRegion = true;
120f22ef01cSRoman Divacky       else
121f22ef01cSRoman Divacky         ++NumPredsOutsideRegion;
122f22ef01cSRoman Divacky 
123f22ef01cSRoman Divacky     // If there is one (or fewer) predecessor from outside the region, we don't
124f22ef01cSRoman Divacky     // need to do anything special.
125f22ef01cSRoman Divacky     if (NumPredsOutsideRegion <= 1) return;
126f22ef01cSRoman Divacky   }
127f22ef01cSRoman Divacky 
128f22ef01cSRoman Divacky   // Otherwise, we need to split the header block into two pieces: one
129f22ef01cSRoman Divacky   // containing PHI nodes merging values from outside of the region, and a
130f22ef01cSRoman Divacky   // second that contains all of the code for the block and merges back any
131f22ef01cSRoman Divacky   // incoming values from inside of the region.
132f22ef01cSRoman Divacky   BasicBlock::iterator AfterPHIs = Header->getFirstNonPHI();
133f22ef01cSRoman Divacky   BasicBlock *NewBB = Header->splitBasicBlock(AfterPHIs,
134f22ef01cSRoman Divacky                                               Header->getName()+".ce");
135f22ef01cSRoman Divacky 
136f22ef01cSRoman Divacky   // We only want to code extract the second block now, and it becomes the new
137f22ef01cSRoman Divacky   // header of the region.
138f22ef01cSRoman Divacky   BasicBlock *OldPred = Header;
139f22ef01cSRoman Divacky   BlocksToExtract.remove(OldPred);
140f22ef01cSRoman Divacky   BlocksToExtract.insert(NewBB);
141f22ef01cSRoman Divacky   Header = NewBB;
142f22ef01cSRoman Divacky 
143f22ef01cSRoman Divacky   // Okay, update dominator sets. The blocks that dominate the new one are the
144f22ef01cSRoman Divacky   // blocks that dominate TIBB plus the new block itself.
145f22ef01cSRoman Divacky   if (DT)
146f22ef01cSRoman Divacky     DT->splitBlock(NewBB);
147f22ef01cSRoman Divacky 
148f22ef01cSRoman Divacky   // Okay, now we need to adjust the PHI nodes and any branches from within the
149f22ef01cSRoman Divacky   // region to go to the new header block instead of the old header block.
150f22ef01cSRoman Divacky   if (HasPredsFromRegion) {
151f22ef01cSRoman Divacky     PHINode *PN = cast<PHINode>(OldPred->begin());
152f22ef01cSRoman Divacky     // Loop over all of the predecessors of OldPred that are in the region,
153f22ef01cSRoman Divacky     // changing them to branch to NewBB instead.
154f22ef01cSRoman Divacky     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
155f22ef01cSRoman Divacky       if (BlocksToExtract.count(PN->getIncomingBlock(i))) {
156f22ef01cSRoman Divacky         TerminatorInst *TI = PN->getIncomingBlock(i)->getTerminator();
157f22ef01cSRoman Divacky         TI->replaceUsesOfWith(OldPred, NewBB);
158f22ef01cSRoman Divacky       }
159f22ef01cSRoman Divacky 
160f22ef01cSRoman Divacky     // Okay, everthing within the region is now branching to the right block, we
161f22ef01cSRoman Divacky     // just have to update the PHI nodes now, inserting PHI nodes into NewBB.
162f22ef01cSRoman Divacky     for (AfterPHIs = OldPred->begin(); isa<PHINode>(AfterPHIs); ++AfterPHIs) {
163f22ef01cSRoman Divacky       PHINode *PN = cast<PHINode>(AfterPHIs);
164f22ef01cSRoman Divacky       // Create a new PHI node in the new region, which has an incoming value
165f22ef01cSRoman Divacky       // from OldPred of PN.
166f22ef01cSRoman Divacky       PHINode *NewPN = PHINode::Create(PN->getType(), PN->getName()+".ce",
167f22ef01cSRoman Divacky                                        NewBB->begin());
168f22ef01cSRoman Divacky       NewPN->addIncoming(PN, OldPred);
169f22ef01cSRoman Divacky 
170f22ef01cSRoman Divacky       // Loop over all of the incoming value in PN, moving them to NewPN if they
171f22ef01cSRoman Divacky       // are from the extracted region.
172f22ef01cSRoman Divacky       for (unsigned i = 0; i != PN->getNumIncomingValues(); ++i) {
173f22ef01cSRoman Divacky         if (BlocksToExtract.count(PN->getIncomingBlock(i))) {
174f22ef01cSRoman Divacky           NewPN->addIncoming(PN->getIncomingValue(i), PN->getIncomingBlock(i));
175f22ef01cSRoman Divacky           PN->removeIncomingValue(i);
176f22ef01cSRoman Divacky           --i;
177f22ef01cSRoman Divacky         }
178f22ef01cSRoman Divacky       }
179f22ef01cSRoman Divacky     }
180f22ef01cSRoman Divacky   }
181f22ef01cSRoman Divacky }
182f22ef01cSRoman Divacky 
183f22ef01cSRoman Divacky void CodeExtractor::splitReturnBlocks() {
184f22ef01cSRoman Divacky   for (SetVector<BasicBlock*>::iterator I = BlocksToExtract.begin(),
185f22ef01cSRoman Divacky          E = BlocksToExtract.end(); I != E; ++I)
186f22ef01cSRoman Divacky     if (ReturnInst *RI = dyn_cast<ReturnInst>((*I)->getTerminator())) {
187f22ef01cSRoman Divacky       BasicBlock *New = (*I)->splitBasicBlock(RI, (*I)->getName()+".ret");
188f22ef01cSRoman Divacky       if (DT) {
189f22ef01cSRoman Divacky         // Old dominates New. New node domiantes all other nodes dominated
190f22ef01cSRoman Divacky         //by Old.
191f22ef01cSRoman Divacky         DomTreeNode *OldNode = DT->getNode(*I);
192f22ef01cSRoman Divacky         SmallVector<DomTreeNode*, 8> Children;
193f22ef01cSRoman Divacky         for (DomTreeNode::iterator DI = OldNode->begin(), DE = OldNode->end();
194f22ef01cSRoman Divacky              DI != DE; ++DI)
195f22ef01cSRoman Divacky           Children.push_back(*DI);
196f22ef01cSRoman Divacky 
197f22ef01cSRoman Divacky         DomTreeNode *NewNode = DT->addNewBlock(New, *I);
198f22ef01cSRoman Divacky 
199f22ef01cSRoman Divacky         for (SmallVector<DomTreeNode*, 8>::iterator I = Children.begin(),
200f22ef01cSRoman Divacky                E = Children.end(); I != E; ++I)
201f22ef01cSRoman Divacky           DT->changeImmediateDominator(*I, NewNode);
202f22ef01cSRoman Divacky       }
203f22ef01cSRoman Divacky     }
204f22ef01cSRoman Divacky }
205f22ef01cSRoman Divacky 
206f22ef01cSRoman Divacky // findInputsOutputs - Find inputs to, outputs from the code region.
207f22ef01cSRoman Divacky //
208f22ef01cSRoman Divacky void CodeExtractor::findInputsOutputs(Values &inputs, Values &outputs) {
209f22ef01cSRoman Divacky   std::set<BasicBlock*> ExitBlocks;
210f22ef01cSRoman Divacky   for (SetVector<BasicBlock*>::const_iterator ci = BlocksToExtract.begin(),
211f22ef01cSRoman Divacky        ce = BlocksToExtract.end(); ci != ce; ++ci) {
212f22ef01cSRoman Divacky     BasicBlock *BB = *ci;
213f22ef01cSRoman Divacky 
214f22ef01cSRoman Divacky     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
215f22ef01cSRoman Divacky       // If a used value is defined outside the region, it's an input.  If an
216f22ef01cSRoman Divacky       // instruction is used outside the region, it's an output.
217f22ef01cSRoman Divacky       for (User::op_iterator O = I->op_begin(), E = I->op_end(); O != E; ++O)
218f22ef01cSRoman Divacky         if (definedInCaller(*O))
219f22ef01cSRoman Divacky           inputs.insert(*O);
220f22ef01cSRoman Divacky 
221f22ef01cSRoman Divacky       // Consider uses of this instruction (outputs).
222f22ef01cSRoman Divacky       for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
223f22ef01cSRoman Divacky            UI != E; ++UI)
224f22ef01cSRoman Divacky         if (!definedInRegion(*UI)) {
225f22ef01cSRoman Divacky           outputs.insert(I);
226f22ef01cSRoman Divacky           break;
227f22ef01cSRoman Divacky         }
228f22ef01cSRoman Divacky     } // for: insts
229f22ef01cSRoman Divacky 
230f22ef01cSRoman Divacky     // Keep track of the exit blocks from the region.
231f22ef01cSRoman Divacky     TerminatorInst *TI = BB->getTerminator();
232f22ef01cSRoman Divacky     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
233f22ef01cSRoman Divacky       if (!BlocksToExtract.count(TI->getSuccessor(i)))
234f22ef01cSRoman Divacky         ExitBlocks.insert(TI->getSuccessor(i));
235f22ef01cSRoman Divacky   } // for: basic blocks
236f22ef01cSRoman Divacky 
237f22ef01cSRoman Divacky   NumExitBlocks = ExitBlocks.size();
238f22ef01cSRoman Divacky }
239f22ef01cSRoman Divacky 
240f22ef01cSRoman Divacky /// constructFunction - make a function based on inputs and outputs, as follows:
241f22ef01cSRoman Divacky /// f(in0, ..., inN, out0, ..., outN)
242f22ef01cSRoman Divacky ///
243f22ef01cSRoman Divacky Function *CodeExtractor::constructFunction(const Values &inputs,
244f22ef01cSRoman Divacky                                            const Values &outputs,
245f22ef01cSRoman Divacky                                            BasicBlock *header,
246f22ef01cSRoman Divacky                                            BasicBlock *newRootNode,
247f22ef01cSRoman Divacky                                            BasicBlock *newHeader,
248f22ef01cSRoman Divacky                                            Function *oldFunction,
249f22ef01cSRoman Divacky                                            Module *M) {
250f22ef01cSRoman Divacky   DEBUG(dbgs() << "inputs: " << inputs.size() << "\n");
251f22ef01cSRoman Divacky   DEBUG(dbgs() << "outputs: " << outputs.size() << "\n");
252f22ef01cSRoman Divacky 
253f22ef01cSRoman Divacky   // This function returns unsigned, outputs will go back by reference.
254f22ef01cSRoman Divacky   switch (NumExitBlocks) {
255f22ef01cSRoman Divacky   case 0:
256f22ef01cSRoman Divacky   case 1: RetTy = Type::getVoidTy(header->getContext()); break;
257f22ef01cSRoman Divacky   case 2: RetTy = Type::getInt1Ty(header->getContext()); break;
258f22ef01cSRoman Divacky   default: RetTy = Type::getInt16Ty(header->getContext()); break;
259f22ef01cSRoman Divacky   }
260f22ef01cSRoman Divacky 
261f22ef01cSRoman Divacky   std::vector<const Type*> paramTy;
262f22ef01cSRoman Divacky 
263f22ef01cSRoman Divacky   // Add the types of the input values to the function's argument list
264f22ef01cSRoman Divacky   for (Values::const_iterator i = inputs.begin(),
265f22ef01cSRoman Divacky          e = inputs.end(); i != e; ++i) {
266f22ef01cSRoman Divacky     const Value *value = *i;
267f22ef01cSRoman Divacky     DEBUG(dbgs() << "value used in func: " << *value << "\n");
268f22ef01cSRoman Divacky     paramTy.push_back(value->getType());
269f22ef01cSRoman Divacky   }
270f22ef01cSRoman Divacky 
271f22ef01cSRoman Divacky   // Add the types of the output values to the function's argument list.
272f22ef01cSRoman Divacky   for (Values::const_iterator I = outputs.begin(), E = outputs.end();
273f22ef01cSRoman Divacky        I != E; ++I) {
274f22ef01cSRoman Divacky     DEBUG(dbgs() << "instr used in func: " << **I << "\n");
275f22ef01cSRoman Divacky     if (AggregateArgs)
276f22ef01cSRoman Divacky       paramTy.push_back((*I)->getType());
277f22ef01cSRoman Divacky     else
278f22ef01cSRoman Divacky       paramTy.push_back(PointerType::getUnqual((*I)->getType()));
279f22ef01cSRoman Divacky   }
280f22ef01cSRoman Divacky 
281f22ef01cSRoman Divacky   DEBUG(dbgs() << "Function type: " << *RetTy << " f(");
282f22ef01cSRoman Divacky   for (std::vector<const Type*>::iterator i = paramTy.begin(),
283f22ef01cSRoman Divacky          e = paramTy.end(); i != e; ++i)
284f22ef01cSRoman Divacky     DEBUG(dbgs() << **i << ", ");
285f22ef01cSRoman Divacky   DEBUG(dbgs() << ")\n");
286f22ef01cSRoman Divacky 
287f22ef01cSRoman Divacky   if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
288f22ef01cSRoman Divacky     PointerType *StructPtr =
289f22ef01cSRoman Divacky            PointerType::getUnqual(StructType::get(M->getContext(), paramTy));
290f22ef01cSRoman Divacky     paramTy.clear();
291f22ef01cSRoman Divacky     paramTy.push_back(StructPtr);
292f22ef01cSRoman Divacky   }
293f22ef01cSRoman Divacky   const FunctionType *funcType =
294f22ef01cSRoman Divacky                   FunctionType::get(RetTy, paramTy, false);
295f22ef01cSRoman Divacky 
296f22ef01cSRoman Divacky   // Create the new function
297f22ef01cSRoman Divacky   Function *newFunction = Function::Create(funcType,
298f22ef01cSRoman Divacky                                            GlobalValue::InternalLinkage,
299f22ef01cSRoman Divacky                                            oldFunction->getName() + "_" +
300f22ef01cSRoman Divacky                                            header->getName(), M);
301f22ef01cSRoman Divacky   // If the old function is no-throw, so is the new one.
302f22ef01cSRoman Divacky   if (oldFunction->doesNotThrow())
303f22ef01cSRoman Divacky     newFunction->setDoesNotThrow(true);
304f22ef01cSRoman Divacky 
305f22ef01cSRoman Divacky   newFunction->getBasicBlockList().push_back(newRootNode);
306f22ef01cSRoman Divacky 
307f22ef01cSRoman Divacky   // Create an iterator to name all of the arguments we inserted.
308f22ef01cSRoman Divacky   Function::arg_iterator AI = newFunction->arg_begin();
309f22ef01cSRoman Divacky 
310f22ef01cSRoman Divacky   // Rewrite all users of the inputs in the extracted region to use the
311f22ef01cSRoman Divacky   // arguments (or appropriate addressing into struct) instead.
312f22ef01cSRoman Divacky   for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
313f22ef01cSRoman Divacky     Value *RewriteVal;
314f22ef01cSRoman Divacky     if (AggregateArgs) {
315f22ef01cSRoman Divacky       Value *Idx[2];
316f22ef01cSRoman Divacky       Idx[0] = Constant::getNullValue(Type::getInt32Ty(header->getContext()));
317f22ef01cSRoman Divacky       Idx[1] = ConstantInt::get(Type::getInt32Ty(header->getContext()), i);
318f22ef01cSRoman Divacky       TerminatorInst *TI = newFunction->begin()->getTerminator();
319f22ef01cSRoman Divacky       GetElementPtrInst *GEP =
320f22ef01cSRoman Divacky         GetElementPtrInst::Create(AI, Idx, Idx+2,
321f22ef01cSRoman Divacky                                   "gep_" + inputs[i]->getName(), TI);
322f22ef01cSRoman Divacky       RewriteVal = new LoadInst(GEP, "loadgep_" + inputs[i]->getName(), TI);
323f22ef01cSRoman Divacky     } else
324f22ef01cSRoman Divacky       RewriteVal = AI++;
325f22ef01cSRoman Divacky 
326f22ef01cSRoman Divacky     std::vector<User*> Users(inputs[i]->use_begin(), inputs[i]->use_end());
327f22ef01cSRoman Divacky     for (std::vector<User*>::iterator use = Users.begin(), useE = Users.end();
328f22ef01cSRoman Divacky          use != useE; ++use)
329f22ef01cSRoman Divacky       if (Instruction* inst = dyn_cast<Instruction>(*use))
330f22ef01cSRoman Divacky         if (BlocksToExtract.count(inst->getParent()))
331f22ef01cSRoman Divacky           inst->replaceUsesOfWith(inputs[i], RewriteVal);
332f22ef01cSRoman Divacky   }
333f22ef01cSRoman Divacky 
334f22ef01cSRoman Divacky   // Set names for input and output arguments.
335f22ef01cSRoman Divacky   if (!AggregateArgs) {
336f22ef01cSRoman Divacky     AI = newFunction->arg_begin();
337f22ef01cSRoman Divacky     for (unsigned i = 0, e = inputs.size(); i != e; ++i, ++AI)
338f22ef01cSRoman Divacky       AI->setName(inputs[i]->getName());
339f22ef01cSRoman Divacky     for (unsigned i = 0, e = outputs.size(); i != e; ++i, ++AI)
340f22ef01cSRoman Divacky       AI->setName(outputs[i]->getName()+".out");
341f22ef01cSRoman Divacky   }
342f22ef01cSRoman Divacky 
343f22ef01cSRoman Divacky   // Rewrite branches to basic blocks outside of the loop to new dummy blocks
344f22ef01cSRoman Divacky   // within the new function. This must be done before we lose track of which
345f22ef01cSRoman Divacky   // blocks were originally in the code region.
346f22ef01cSRoman Divacky   std::vector<User*> Users(header->use_begin(), header->use_end());
347f22ef01cSRoman Divacky   for (unsigned i = 0, e = Users.size(); i != e; ++i)
348f22ef01cSRoman Divacky     // The BasicBlock which contains the branch is not in the region
349f22ef01cSRoman Divacky     // modify the branch target to a new block
350f22ef01cSRoman Divacky     if (TerminatorInst *TI = dyn_cast<TerminatorInst>(Users[i]))
351f22ef01cSRoman Divacky       if (!BlocksToExtract.count(TI->getParent()) &&
352f22ef01cSRoman Divacky           TI->getParent()->getParent() == oldFunction)
353f22ef01cSRoman Divacky         TI->replaceUsesOfWith(header, newHeader);
354f22ef01cSRoman Divacky 
355f22ef01cSRoman Divacky   return newFunction;
356f22ef01cSRoman Divacky }
357f22ef01cSRoman Divacky 
358f22ef01cSRoman Divacky /// FindPhiPredForUseInBlock - Given a value and a basic block, find a PHI
359f22ef01cSRoman Divacky /// that uses the value within the basic block, and return the predecessor
360f22ef01cSRoman Divacky /// block associated with that use, or return 0 if none is found.
361f22ef01cSRoman Divacky static BasicBlock* FindPhiPredForUseInBlock(Value* Used, BasicBlock* BB) {
362f22ef01cSRoman Divacky   for (Value::use_iterator UI = Used->use_begin(),
363f22ef01cSRoman Divacky        UE = Used->use_end(); UI != UE; ++UI) {
364f22ef01cSRoman Divacky      PHINode *P = dyn_cast<PHINode>(*UI);
365f22ef01cSRoman Divacky      if (P && P->getParent() == BB)
366f22ef01cSRoman Divacky        return P->getIncomingBlock(UI);
367f22ef01cSRoman Divacky   }
368f22ef01cSRoman Divacky 
369f22ef01cSRoman Divacky   return 0;
370f22ef01cSRoman Divacky }
371f22ef01cSRoman Divacky 
372f22ef01cSRoman Divacky /// emitCallAndSwitchStatement - This method sets up the caller side by adding
373f22ef01cSRoman Divacky /// the call instruction, splitting any PHI nodes in the header block as
374f22ef01cSRoman Divacky /// necessary.
375f22ef01cSRoman Divacky void CodeExtractor::
376f22ef01cSRoman Divacky emitCallAndSwitchStatement(Function *newFunction, BasicBlock *codeReplacer,
377f22ef01cSRoman Divacky                            Values &inputs, Values &outputs) {
378f22ef01cSRoman Divacky   // Emit a call to the new function, passing in: *pointer to struct (if
379f22ef01cSRoman Divacky   // aggregating parameters), or plan inputs and allocated memory for outputs
380f22ef01cSRoman Divacky   std::vector<Value*> params, StructValues, ReloadOutputs, Reloads;
381f22ef01cSRoman Divacky 
382f22ef01cSRoman Divacky   LLVMContext &Context = newFunction->getContext();
383f22ef01cSRoman Divacky 
384f22ef01cSRoman Divacky   // Add inputs as params, or to be filled into the struct
385f22ef01cSRoman Divacky   for (Values::iterator i = inputs.begin(), e = inputs.end(); i != e; ++i)
386f22ef01cSRoman Divacky     if (AggregateArgs)
387f22ef01cSRoman Divacky       StructValues.push_back(*i);
388f22ef01cSRoman Divacky     else
389f22ef01cSRoman Divacky       params.push_back(*i);
390f22ef01cSRoman Divacky 
391f22ef01cSRoman Divacky   // Create allocas for the outputs
392f22ef01cSRoman Divacky   for (Values::iterator i = outputs.begin(), e = outputs.end(); i != e; ++i) {
393f22ef01cSRoman Divacky     if (AggregateArgs) {
394f22ef01cSRoman Divacky       StructValues.push_back(*i);
395f22ef01cSRoman Divacky     } else {
396f22ef01cSRoman Divacky       AllocaInst *alloca =
397f22ef01cSRoman Divacky         new AllocaInst((*i)->getType(), 0, (*i)->getName()+".loc",
398f22ef01cSRoman Divacky                        codeReplacer->getParent()->begin()->begin());
399f22ef01cSRoman Divacky       ReloadOutputs.push_back(alloca);
400f22ef01cSRoman Divacky       params.push_back(alloca);
401f22ef01cSRoman Divacky     }
402f22ef01cSRoman Divacky   }
403f22ef01cSRoman Divacky 
404f22ef01cSRoman Divacky   AllocaInst *Struct = 0;
405f22ef01cSRoman Divacky   if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
406f22ef01cSRoman Divacky     std::vector<const Type*> ArgTypes;
407f22ef01cSRoman Divacky     for (Values::iterator v = StructValues.begin(),
408f22ef01cSRoman Divacky            ve = StructValues.end(); v != ve; ++v)
409f22ef01cSRoman Divacky       ArgTypes.push_back((*v)->getType());
410f22ef01cSRoman Divacky 
411f22ef01cSRoman Divacky     // Allocate a struct at the beginning of this function
412f22ef01cSRoman Divacky     Type *StructArgTy = StructType::get(newFunction->getContext(), ArgTypes);
413f22ef01cSRoman Divacky     Struct =
414f22ef01cSRoman Divacky       new AllocaInst(StructArgTy, 0, "structArg",
415f22ef01cSRoman Divacky                      codeReplacer->getParent()->begin()->begin());
416f22ef01cSRoman Divacky     params.push_back(Struct);
417f22ef01cSRoman Divacky 
418f22ef01cSRoman Divacky     for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
419f22ef01cSRoman Divacky       Value *Idx[2];
420f22ef01cSRoman Divacky       Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
421f22ef01cSRoman Divacky       Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), i);
422f22ef01cSRoman Divacky       GetElementPtrInst *GEP =
423f22ef01cSRoman Divacky         GetElementPtrInst::Create(Struct, Idx, Idx + 2,
424f22ef01cSRoman Divacky                                   "gep_" + StructValues[i]->getName());
425f22ef01cSRoman Divacky       codeReplacer->getInstList().push_back(GEP);
426f22ef01cSRoman Divacky       StoreInst *SI = new StoreInst(StructValues[i], GEP);
427f22ef01cSRoman Divacky       codeReplacer->getInstList().push_back(SI);
428f22ef01cSRoman Divacky     }
429f22ef01cSRoman Divacky   }
430f22ef01cSRoman Divacky 
431f22ef01cSRoman Divacky   // Emit the call to the function
432f22ef01cSRoman Divacky   CallInst *call = CallInst::Create(newFunction, params.begin(), params.end(),
433f22ef01cSRoman Divacky                                     NumExitBlocks > 1 ? "targetBlock" : "");
434f22ef01cSRoman Divacky   codeReplacer->getInstList().push_back(call);
435f22ef01cSRoman Divacky 
436f22ef01cSRoman Divacky   Function::arg_iterator OutputArgBegin = newFunction->arg_begin();
437f22ef01cSRoman Divacky   unsigned FirstOut = inputs.size();
438f22ef01cSRoman Divacky   if (!AggregateArgs)
439f22ef01cSRoman Divacky     std::advance(OutputArgBegin, inputs.size());
440f22ef01cSRoman Divacky 
441f22ef01cSRoman Divacky   // Reload the outputs passed in by reference
442f22ef01cSRoman Divacky   for (unsigned i = 0, e = outputs.size(); i != e; ++i) {
443f22ef01cSRoman Divacky     Value *Output = 0;
444f22ef01cSRoman Divacky     if (AggregateArgs) {
445f22ef01cSRoman Divacky       Value *Idx[2];
446f22ef01cSRoman Divacky       Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
447f22ef01cSRoman Divacky       Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), FirstOut + i);
448f22ef01cSRoman Divacky       GetElementPtrInst *GEP
449f22ef01cSRoman Divacky         = GetElementPtrInst::Create(Struct, Idx, Idx + 2,
450f22ef01cSRoman Divacky                                     "gep_reload_" + outputs[i]->getName());
451f22ef01cSRoman Divacky       codeReplacer->getInstList().push_back(GEP);
452f22ef01cSRoman Divacky       Output = GEP;
453f22ef01cSRoman Divacky     } else {
454f22ef01cSRoman Divacky       Output = ReloadOutputs[i];
455f22ef01cSRoman Divacky     }
456f22ef01cSRoman Divacky     LoadInst *load = new LoadInst(Output, outputs[i]->getName()+".reload");
457f22ef01cSRoman Divacky     Reloads.push_back(load);
458f22ef01cSRoman Divacky     codeReplacer->getInstList().push_back(load);
459f22ef01cSRoman Divacky     std::vector<User*> Users(outputs[i]->use_begin(), outputs[i]->use_end());
460f22ef01cSRoman Divacky     for (unsigned u = 0, e = Users.size(); u != e; ++u) {
461f22ef01cSRoman Divacky       Instruction *inst = cast<Instruction>(Users[u]);
462f22ef01cSRoman Divacky       if (!BlocksToExtract.count(inst->getParent()))
463f22ef01cSRoman Divacky         inst->replaceUsesOfWith(outputs[i], load);
464f22ef01cSRoman Divacky     }
465f22ef01cSRoman Divacky   }
466f22ef01cSRoman Divacky 
467f22ef01cSRoman Divacky   // Now we can emit a switch statement using the call as a value.
468f22ef01cSRoman Divacky   SwitchInst *TheSwitch =
469f22ef01cSRoman Divacky       SwitchInst::Create(Constant::getNullValue(Type::getInt16Ty(Context)),
470f22ef01cSRoman Divacky                          codeReplacer, 0, codeReplacer);
471f22ef01cSRoman Divacky 
472f22ef01cSRoman Divacky   // Since there may be multiple exits from the original region, make the new
473f22ef01cSRoman Divacky   // function return an unsigned, switch on that number.  This loop iterates
474f22ef01cSRoman Divacky   // over all of the blocks in the extracted region, updating any terminator
475f22ef01cSRoman Divacky   // instructions in the to-be-extracted region that branch to blocks that are
476f22ef01cSRoman Divacky   // not in the region to be extracted.
477f22ef01cSRoman Divacky   std::map<BasicBlock*, BasicBlock*> ExitBlockMap;
478f22ef01cSRoman Divacky 
479f22ef01cSRoman Divacky   unsigned switchVal = 0;
480f22ef01cSRoman Divacky   for (SetVector<BasicBlock*>::const_iterator i = BlocksToExtract.begin(),
481f22ef01cSRoman Divacky          e = BlocksToExtract.end(); i != e; ++i) {
482f22ef01cSRoman Divacky     TerminatorInst *TI = (*i)->getTerminator();
483f22ef01cSRoman Divacky     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
484f22ef01cSRoman Divacky       if (!BlocksToExtract.count(TI->getSuccessor(i))) {
485f22ef01cSRoman Divacky         BasicBlock *OldTarget = TI->getSuccessor(i);
486f22ef01cSRoman Divacky         // add a new basic block which returns the appropriate value
487f22ef01cSRoman Divacky         BasicBlock *&NewTarget = ExitBlockMap[OldTarget];
488f22ef01cSRoman Divacky         if (!NewTarget) {
489f22ef01cSRoman Divacky           // If we don't already have an exit stub for this non-extracted
490f22ef01cSRoman Divacky           // destination, create one now!
491f22ef01cSRoman Divacky           NewTarget = BasicBlock::Create(Context,
492f22ef01cSRoman Divacky                                          OldTarget->getName() + ".exitStub",
493f22ef01cSRoman Divacky                                          newFunction);
494f22ef01cSRoman Divacky           unsigned SuccNum = switchVal++;
495f22ef01cSRoman Divacky 
496f22ef01cSRoman Divacky           Value *brVal = 0;
497f22ef01cSRoman Divacky           switch (NumExitBlocks) {
498f22ef01cSRoman Divacky           case 0:
499f22ef01cSRoman Divacky           case 1: break;  // No value needed.
500f22ef01cSRoman Divacky           case 2:         // Conditional branch, return a bool
501f22ef01cSRoman Divacky             brVal = ConstantInt::get(Type::getInt1Ty(Context), !SuccNum);
502f22ef01cSRoman Divacky             break;
503f22ef01cSRoman Divacky           default:
504f22ef01cSRoman Divacky             brVal = ConstantInt::get(Type::getInt16Ty(Context), SuccNum);
505f22ef01cSRoman Divacky             break;
506f22ef01cSRoman Divacky           }
507f22ef01cSRoman Divacky 
508f22ef01cSRoman Divacky           ReturnInst *NTRet = ReturnInst::Create(Context, brVal, NewTarget);
509f22ef01cSRoman Divacky 
510f22ef01cSRoman Divacky           // Update the switch instruction.
511f22ef01cSRoman Divacky           TheSwitch->addCase(ConstantInt::get(Type::getInt16Ty(Context),
512f22ef01cSRoman Divacky                                               SuccNum),
513f22ef01cSRoman Divacky                              OldTarget);
514f22ef01cSRoman Divacky 
515f22ef01cSRoman Divacky           // Restore values just before we exit
516f22ef01cSRoman Divacky           Function::arg_iterator OAI = OutputArgBegin;
517f22ef01cSRoman Divacky           for (unsigned out = 0, e = outputs.size(); out != e; ++out) {
518f22ef01cSRoman Divacky             // For an invoke, the normal destination is the only one that is
519f22ef01cSRoman Divacky             // dominated by the result of the invocation
520f22ef01cSRoman Divacky             BasicBlock *DefBlock = cast<Instruction>(outputs[out])->getParent();
521f22ef01cSRoman Divacky 
522f22ef01cSRoman Divacky             bool DominatesDef = true;
523f22ef01cSRoman Divacky 
524f22ef01cSRoman Divacky             if (InvokeInst *Invoke = dyn_cast<InvokeInst>(outputs[out])) {
525f22ef01cSRoman Divacky               DefBlock = Invoke->getNormalDest();
526f22ef01cSRoman Divacky 
527f22ef01cSRoman Divacky               // Make sure we are looking at the original successor block, not
528f22ef01cSRoman Divacky               // at a newly inserted exit block, which won't be in the dominator
529f22ef01cSRoman Divacky               // info.
530f22ef01cSRoman Divacky               for (std::map<BasicBlock*, BasicBlock*>::iterator I =
531f22ef01cSRoman Divacky                      ExitBlockMap.begin(), E = ExitBlockMap.end(); I != E; ++I)
532f22ef01cSRoman Divacky                 if (DefBlock == I->second) {
533f22ef01cSRoman Divacky                   DefBlock = I->first;
534f22ef01cSRoman Divacky                   break;
535f22ef01cSRoman Divacky                 }
536f22ef01cSRoman Divacky 
537f22ef01cSRoman Divacky               // In the extract block case, if the block we are extracting ends
538f22ef01cSRoman Divacky               // with an invoke instruction, make sure that we don't emit a
539f22ef01cSRoman Divacky               // store of the invoke value for the unwind block.
540f22ef01cSRoman Divacky               if (!DT && DefBlock != OldTarget)
541f22ef01cSRoman Divacky                 DominatesDef = false;
542f22ef01cSRoman Divacky             }
543f22ef01cSRoman Divacky 
544f22ef01cSRoman Divacky             if (DT) {
545f22ef01cSRoman Divacky               DominatesDef = DT->dominates(DefBlock, OldTarget);
546f22ef01cSRoman Divacky 
547f22ef01cSRoman Divacky               // If the output value is used by a phi in the target block,
548f22ef01cSRoman Divacky               // then we need to test for dominance of the phi's predecessor
549f22ef01cSRoman Divacky               // instead.  Unfortunately, this a little complicated since we
550f22ef01cSRoman Divacky               // have already rewritten uses of the value to uses of the reload.
551f22ef01cSRoman Divacky               BasicBlock* pred = FindPhiPredForUseInBlock(Reloads[out],
552f22ef01cSRoman Divacky                                                           OldTarget);
553f22ef01cSRoman Divacky               if (pred && DT && DT->dominates(DefBlock, pred))
554f22ef01cSRoman Divacky                 DominatesDef = true;
555f22ef01cSRoman Divacky             }
556f22ef01cSRoman Divacky 
557f22ef01cSRoman Divacky             if (DominatesDef) {
558f22ef01cSRoman Divacky               if (AggregateArgs) {
559f22ef01cSRoman Divacky                 Value *Idx[2];
560f22ef01cSRoman Divacky                 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
561f22ef01cSRoman Divacky                 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context),
562f22ef01cSRoman Divacky                                           FirstOut+out);
563f22ef01cSRoman Divacky                 GetElementPtrInst *GEP =
564f22ef01cSRoman Divacky                   GetElementPtrInst::Create(OAI, Idx, Idx + 2,
565f22ef01cSRoman Divacky                                             "gep_" + outputs[out]->getName(),
566f22ef01cSRoman Divacky                                             NTRet);
567f22ef01cSRoman Divacky                 new StoreInst(outputs[out], GEP, NTRet);
568f22ef01cSRoman Divacky               } else {
569f22ef01cSRoman Divacky                 new StoreInst(outputs[out], OAI, NTRet);
570f22ef01cSRoman Divacky               }
571f22ef01cSRoman Divacky             }
572f22ef01cSRoman Divacky             // Advance output iterator even if we don't emit a store
573f22ef01cSRoman Divacky             if (!AggregateArgs) ++OAI;
574f22ef01cSRoman Divacky           }
575f22ef01cSRoman Divacky         }
576f22ef01cSRoman Divacky 
577f22ef01cSRoman Divacky         // rewrite the original branch instruction with this new target
578f22ef01cSRoman Divacky         TI->setSuccessor(i, NewTarget);
579f22ef01cSRoman Divacky       }
580f22ef01cSRoman Divacky   }
581f22ef01cSRoman Divacky 
582f22ef01cSRoman Divacky   // Now that we've done the deed, simplify the switch instruction.
583f22ef01cSRoman Divacky   const Type *OldFnRetTy = TheSwitch->getParent()->getParent()->getReturnType();
584f22ef01cSRoman Divacky   switch (NumExitBlocks) {
585f22ef01cSRoman Divacky   case 0:
586f22ef01cSRoman Divacky     // There are no successors (the block containing the switch itself), which
587f22ef01cSRoman Divacky     // means that previously this was the last part of the function, and hence
588f22ef01cSRoman Divacky     // this should be rewritten as a `ret'
589f22ef01cSRoman Divacky 
590f22ef01cSRoman Divacky     // Check if the function should return a value
591f22ef01cSRoman Divacky     if (OldFnRetTy->isVoidTy()) {
592f22ef01cSRoman Divacky       ReturnInst::Create(Context, 0, TheSwitch);  // Return void
593f22ef01cSRoman Divacky     } else if (OldFnRetTy == TheSwitch->getCondition()->getType()) {
594f22ef01cSRoman Divacky       // return what we have
595f22ef01cSRoman Divacky       ReturnInst::Create(Context, TheSwitch->getCondition(), TheSwitch);
596f22ef01cSRoman Divacky     } else {
597f22ef01cSRoman Divacky       // Otherwise we must have code extracted an unwind or something, just
598f22ef01cSRoman Divacky       // return whatever we want.
599f22ef01cSRoman Divacky       ReturnInst::Create(Context,
600f22ef01cSRoman Divacky                          Constant::getNullValue(OldFnRetTy), TheSwitch);
601f22ef01cSRoman Divacky     }
602f22ef01cSRoman Divacky 
603f22ef01cSRoman Divacky     TheSwitch->eraseFromParent();
604f22ef01cSRoman Divacky     break;
605f22ef01cSRoman Divacky   case 1:
606f22ef01cSRoman Divacky     // Only a single destination, change the switch into an unconditional
607f22ef01cSRoman Divacky     // branch.
608f22ef01cSRoman Divacky     BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch);
609f22ef01cSRoman Divacky     TheSwitch->eraseFromParent();
610f22ef01cSRoman Divacky     break;
611f22ef01cSRoman Divacky   case 2:
612f22ef01cSRoman Divacky     BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch->getSuccessor(2),
613f22ef01cSRoman Divacky                        call, TheSwitch);
614f22ef01cSRoman Divacky     TheSwitch->eraseFromParent();
615f22ef01cSRoman Divacky     break;
616f22ef01cSRoman Divacky   default:
617f22ef01cSRoman Divacky     // Otherwise, make the default destination of the switch instruction be one
618f22ef01cSRoman Divacky     // of the other successors.
619f22ef01cSRoman Divacky     TheSwitch->setOperand(0, call);
620f22ef01cSRoman Divacky     TheSwitch->setSuccessor(0, TheSwitch->getSuccessor(NumExitBlocks));
621f22ef01cSRoman Divacky     TheSwitch->removeCase(NumExitBlocks);  // Remove redundant case
622f22ef01cSRoman Divacky     break;
623f22ef01cSRoman Divacky   }
624f22ef01cSRoman Divacky }
625f22ef01cSRoman Divacky 
626f22ef01cSRoman Divacky void CodeExtractor::moveCodeToFunction(Function *newFunction) {
627f22ef01cSRoman Divacky   Function *oldFunc = (*BlocksToExtract.begin())->getParent();
628f22ef01cSRoman Divacky   Function::BasicBlockListType &oldBlocks = oldFunc->getBasicBlockList();
629f22ef01cSRoman Divacky   Function::BasicBlockListType &newBlocks = newFunction->getBasicBlockList();
630f22ef01cSRoman Divacky 
631f22ef01cSRoman Divacky   for (SetVector<BasicBlock*>::const_iterator i = BlocksToExtract.begin(),
632f22ef01cSRoman Divacky          e = BlocksToExtract.end(); i != e; ++i) {
633f22ef01cSRoman Divacky     // Delete the basic block from the old function, and the list of blocks
634f22ef01cSRoman Divacky     oldBlocks.remove(*i);
635f22ef01cSRoman Divacky 
636f22ef01cSRoman Divacky     // Insert this basic block into the new function
637f22ef01cSRoman Divacky     newBlocks.push_back(*i);
638f22ef01cSRoman Divacky   }
639f22ef01cSRoman Divacky }
640f22ef01cSRoman Divacky 
641f22ef01cSRoman Divacky /// ExtractRegion - Removes a loop from a function, replaces it with a call to
642f22ef01cSRoman Divacky /// new function. Returns pointer to the new function.
643f22ef01cSRoman Divacky ///
644f22ef01cSRoman Divacky /// algorithm:
645f22ef01cSRoman Divacky ///
646f22ef01cSRoman Divacky /// find inputs and outputs for the region
647f22ef01cSRoman Divacky ///
648f22ef01cSRoman Divacky /// for inputs: add to function as args, map input instr* to arg#
649f22ef01cSRoman Divacky /// for outputs: add allocas for scalars,
650f22ef01cSRoman Divacky ///             add to func as args, map output instr* to arg#
651f22ef01cSRoman Divacky ///
652f22ef01cSRoman Divacky /// rewrite func to use argument #s instead of instr*
653f22ef01cSRoman Divacky ///
654f22ef01cSRoman Divacky /// for each scalar output in the function: at every exit, store intermediate
655f22ef01cSRoman Divacky /// computed result back into memory.
656f22ef01cSRoman Divacky ///
657f22ef01cSRoman Divacky Function *CodeExtractor::
658f22ef01cSRoman Divacky ExtractCodeRegion(const std::vector<BasicBlock*> &code) {
659f22ef01cSRoman Divacky   if (!isEligible(code))
660f22ef01cSRoman Divacky     return 0;
661f22ef01cSRoman Divacky 
662f22ef01cSRoman Divacky   // 1) Find inputs, outputs
663f22ef01cSRoman Divacky   // 2) Construct new function
664f22ef01cSRoman Divacky   //  * Add allocas for defs, pass as args by reference
665f22ef01cSRoman Divacky   //  * Pass in uses as args
666f22ef01cSRoman Divacky   // 3) Move code region, add call instr to func
667f22ef01cSRoman Divacky   //
668f22ef01cSRoman Divacky   BlocksToExtract.insert(code.begin(), code.end());
669f22ef01cSRoman Divacky 
670f22ef01cSRoman Divacky   Values inputs, outputs;
671f22ef01cSRoman Divacky 
672f22ef01cSRoman Divacky   // Assumption: this is a single-entry code region, and the header is the first
673f22ef01cSRoman Divacky   // block in the region.
674f22ef01cSRoman Divacky   BasicBlock *header = code[0];
675f22ef01cSRoman Divacky 
676f22ef01cSRoman Divacky   for (unsigned i = 1, e = code.size(); i != e; ++i)
677f22ef01cSRoman Divacky     for (pred_iterator PI = pred_begin(code[i]), E = pred_end(code[i]);
678f22ef01cSRoman Divacky          PI != E; ++PI)
679f22ef01cSRoman Divacky       assert(BlocksToExtract.count(*PI) &&
680f22ef01cSRoman Divacky              "No blocks in this region may have entries from outside the region"
681f22ef01cSRoman Divacky              " except for the first block!");
682f22ef01cSRoman Divacky 
683f22ef01cSRoman Divacky   // If we have to split PHI nodes or the entry block, do so now.
684f22ef01cSRoman Divacky   severSplitPHINodes(header);
685f22ef01cSRoman Divacky 
686f22ef01cSRoman Divacky   // If we have any return instructions in the region, split those blocks so
687f22ef01cSRoman Divacky   // that the return is not in the region.
688f22ef01cSRoman Divacky   splitReturnBlocks();
689f22ef01cSRoman Divacky 
690f22ef01cSRoman Divacky   Function *oldFunction = header->getParent();
691f22ef01cSRoman Divacky 
692f22ef01cSRoman Divacky   // This takes place of the original loop
693f22ef01cSRoman Divacky   BasicBlock *codeReplacer = BasicBlock::Create(header->getContext(),
694f22ef01cSRoman Divacky                                                 "codeRepl", oldFunction,
695f22ef01cSRoman Divacky                                                 header);
696f22ef01cSRoman Divacky 
697f22ef01cSRoman Divacky   // The new function needs a root node because other nodes can branch to the
698f22ef01cSRoman Divacky   // head of the region, but the entry node of a function cannot have preds.
699f22ef01cSRoman Divacky   BasicBlock *newFuncRoot = BasicBlock::Create(header->getContext(),
700f22ef01cSRoman Divacky                                                "newFuncRoot");
701f22ef01cSRoman Divacky   newFuncRoot->getInstList().push_back(BranchInst::Create(header));
702f22ef01cSRoman Divacky 
703f22ef01cSRoman Divacky   // Find inputs to, outputs from the code region.
704f22ef01cSRoman Divacky   findInputsOutputs(inputs, outputs);
705f22ef01cSRoman Divacky 
706f22ef01cSRoman Divacky   // Construct new function based on inputs/outputs & add allocas for all defs.
707f22ef01cSRoman Divacky   Function *newFunction = constructFunction(inputs, outputs, header,
708f22ef01cSRoman Divacky                                             newFuncRoot,
709f22ef01cSRoman Divacky                                             codeReplacer, oldFunction,
710f22ef01cSRoman Divacky                                             oldFunction->getParent());
711f22ef01cSRoman Divacky 
712f22ef01cSRoman Divacky   emitCallAndSwitchStatement(newFunction, codeReplacer, inputs, outputs);
713f22ef01cSRoman Divacky 
714f22ef01cSRoman Divacky   moveCodeToFunction(newFunction);
715f22ef01cSRoman Divacky 
716f22ef01cSRoman Divacky   // Loop over all of the PHI nodes in the header block, and change any
717f22ef01cSRoman Divacky   // references to the old incoming edge to be the new incoming edge.
718f22ef01cSRoman Divacky   for (BasicBlock::iterator I = header->begin(); isa<PHINode>(I); ++I) {
719f22ef01cSRoman Divacky     PHINode *PN = cast<PHINode>(I);
720f22ef01cSRoman Divacky     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
721f22ef01cSRoman Divacky       if (!BlocksToExtract.count(PN->getIncomingBlock(i)))
722f22ef01cSRoman Divacky         PN->setIncomingBlock(i, newFuncRoot);
723f22ef01cSRoman Divacky   }
724f22ef01cSRoman Divacky 
725f22ef01cSRoman Divacky   // Look at all successors of the codeReplacer block.  If any of these blocks
726f22ef01cSRoman Divacky   // had PHI nodes in them, we need to update the "from" block to be the code
727f22ef01cSRoman Divacky   // replacer, not the original block in the extracted region.
728f22ef01cSRoman Divacky   std::vector<BasicBlock*> Succs(succ_begin(codeReplacer),
729f22ef01cSRoman Divacky                                  succ_end(codeReplacer));
730f22ef01cSRoman Divacky   for (unsigned i = 0, e = Succs.size(); i != e; ++i)
731f22ef01cSRoman Divacky     for (BasicBlock::iterator I = Succs[i]->begin(); isa<PHINode>(I); ++I) {
732f22ef01cSRoman Divacky       PHINode *PN = cast<PHINode>(I);
733f22ef01cSRoman Divacky       std::set<BasicBlock*> ProcessedPreds;
734f22ef01cSRoman Divacky       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
735f22ef01cSRoman Divacky         if (BlocksToExtract.count(PN->getIncomingBlock(i))) {
736f22ef01cSRoman Divacky           if (ProcessedPreds.insert(PN->getIncomingBlock(i)).second)
737f22ef01cSRoman Divacky             PN->setIncomingBlock(i, codeReplacer);
738f22ef01cSRoman Divacky           else {
739f22ef01cSRoman Divacky             // There were multiple entries in the PHI for this block, now there
740f22ef01cSRoman Divacky             // is only one, so remove the duplicated entries.
741f22ef01cSRoman Divacky             PN->removeIncomingValue(i, false);
742f22ef01cSRoman Divacky             --i; --e;
743f22ef01cSRoman Divacky           }
744f22ef01cSRoman Divacky         }
745f22ef01cSRoman Divacky     }
746f22ef01cSRoman Divacky 
747f22ef01cSRoman Divacky   //cerr << "NEW FUNCTION: " << *newFunction;
748f22ef01cSRoman Divacky   //  verifyFunction(*newFunction);
749f22ef01cSRoman Divacky 
750f22ef01cSRoman Divacky   //  cerr << "OLD FUNCTION: " << *oldFunction;
751f22ef01cSRoman Divacky   //  verifyFunction(*oldFunction);
752f22ef01cSRoman Divacky 
753f22ef01cSRoman Divacky   DEBUG(if (verifyFunction(*newFunction))
754f22ef01cSRoman Divacky         report_fatal_error("verifyFunction failed!"));
755f22ef01cSRoman Divacky   return newFunction;
756f22ef01cSRoman Divacky }
757f22ef01cSRoman Divacky 
758f22ef01cSRoman Divacky bool CodeExtractor::isEligible(const std::vector<BasicBlock*> &code) {
759f22ef01cSRoman Divacky   // Deny code region if it contains allocas or vastarts.
760f22ef01cSRoman Divacky   for (std::vector<BasicBlock*>::const_iterator BB = code.begin(), e=code.end();
761f22ef01cSRoman Divacky        BB != e; ++BB)
762f22ef01cSRoman Divacky     for (BasicBlock::const_iterator I = (*BB)->begin(), Ie = (*BB)->end();
763f22ef01cSRoman Divacky          I != Ie; ++I)
764f22ef01cSRoman Divacky       if (isa<AllocaInst>(*I))
765f22ef01cSRoman Divacky         return false;
766f22ef01cSRoman Divacky       else if (const CallInst *CI = dyn_cast<CallInst>(I))
767f22ef01cSRoman Divacky         if (const Function *F = CI->getCalledFunction())
768f22ef01cSRoman Divacky           if (F->getIntrinsicID() == Intrinsic::vastart)
769f22ef01cSRoman Divacky             return false;
770f22ef01cSRoman Divacky   return true;
771f22ef01cSRoman Divacky }
772f22ef01cSRoman Divacky 
773f22ef01cSRoman Divacky 
774f22ef01cSRoman Divacky /// ExtractCodeRegion - slurp a sequence of basic blocks into a brand new
775f22ef01cSRoman Divacky /// function
776f22ef01cSRoman Divacky ///
777f22ef01cSRoman Divacky Function* llvm::ExtractCodeRegion(DominatorTree &DT,
778f22ef01cSRoman Divacky                                   const std::vector<BasicBlock*> &code,
779f22ef01cSRoman Divacky                                   bool AggregateArgs) {
780f22ef01cSRoman Divacky   return CodeExtractor(&DT, AggregateArgs).ExtractCodeRegion(code);
781f22ef01cSRoman Divacky }
782f22ef01cSRoman Divacky 
783f22ef01cSRoman Divacky /// ExtractBasicBlock - slurp a natural loop into a brand new function
784f22ef01cSRoman Divacky ///
785f22ef01cSRoman Divacky Function* llvm::ExtractLoop(DominatorTree &DT, Loop *L, bool AggregateArgs) {
786f22ef01cSRoman Divacky   return CodeExtractor(&DT, AggregateArgs).ExtractCodeRegion(L->getBlocks());
787f22ef01cSRoman Divacky }
788f22ef01cSRoman Divacky 
789f22ef01cSRoman Divacky /// ExtractBasicBlock - slurp a basic block into a brand new function
790f22ef01cSRoman Divacky ///
791f22ef01cSRoman Divacky Function* llvm::ExtractBasicBlock(BasicBlock *BB, bool AggregateArgs) {
792f22ef01cSRoman Divacky   std::vector<BasicBlock*> Blocks;
793f22ef01cSRoman Divacky   Blocks.push_back(BB);
794f22ef01cSRoman Divacky   return CodeExtractor(0, AggregateArgs).ExtractCodeRegion(Blocks);
795f22ef01cSRoman Divacky }
796