blob: bc4c5a72383c17daeb687bac58eb2da56eb7540a [file] [log] [blame]
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001//===- CodeExtractor.cpp - Pull code region into a new function -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the interface to tear out a code region, such as an
11// individual loop or a parallel section, into a new function, replacing it with
12// a call to the new function.
13//
14//===----------------------------------------------------------------------===//
15
16#include "llvm/BasicBlock.h"
17#include "llvm/Constants.h"
18#include "llvm/DerivedTypes.h"
19#include "llvm/Instructions.h"
20#include "llvm/Module.h"
21#include "llvm/Pass.h"
22#include "llvm/Analysis/LoopInfo.h"
Chris Lattner36844692004-03-14 03:17:22 +000023#include "llvm/Analysis/Verifier.h"
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000024#include "llvm/Transforms/Utils/BasicBlockUtils.h"
25#include "llvm/Transforms/Utils/FunctionUtils.h"
26#include "Support/Debug.h"
27#include "Support/StringExtras.h"
28#include <algorithm>
Chris Lattner9c431f62004-03-14 22:34:55 +000029#include <set>
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000030using namespace llvm;
31
32namespace {
33
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000034 /// getFunctionArg - Return a pointer to F's ARGNOth argument.
35 ///
36 Argument *getFunctionArg(Function *F, unsigned argno) {
Chris Lattner5b2072e2004-03-14 23:43:24 +000037 Function::aiterator I = F->abegin();
38 std::advance(I, argno);
39 return I;
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000040 }
41
42 struct CodeExtractor {
43 typedef std::vector<Value*> Values;
44 typedef std::vector<std::pair<unsigned, unsigned> > PhiValChangesTy;
45 typedef std::map<PHINode*, PhiValChangesTy> PhiVal2ArgTy;
46 PhiVal2ArgTy PhiVal2Arg;
Chris Lattner9c431f62004-03-14 22:34:55 +000047 std::set<BasicBlock*> BlocksToExtract;
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000048 public:
49 Function *ExtractCodeRegion(const std::vector<BasicBlock*> &code);
50
51 private:
Chris Lattner9c431f62004-03-14 22:34:55 +000052 void findInputsOutputs(Values &inputs, Values &outputs,
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000053 BasicBlock *newHeader,
54 BasicBlock *newRootNode);
55
56 void processPhiNodeInputs(PHINode *Phi,
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000057 Values &inputs,
58 BasicBlock *newHeader,
59 BasicBlock *newRootNode);
60
61 void rewritePhiNodes(Function *F, BasicBlock *newFuncRoot);
62
63 Function *constructFunction(const Values &inputs,
64 const Values &outputs,
65 BasicBlock *newRootNode, BasicBlock *newHeader,
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000066 Function *oldFunction, Module *M);
67
Chris Lattner9c431f62004-03-14 22:34:55 +000068 void moveCodeToFunction(Function *newFunction);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000069
70 void emitCallAndSwitchStatement(Function *newFunction,
71 BasicBlock *newHeader,
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000072 Values &inputs,
73 Values &outputs);
74
75 };
76}
77
78void CodeExtractor::processPhiNodeInputs(PHINode *Phi,
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000079 Values &inputs,
80 BasicBlock *codeReplacer,
Chris Lattnerfb87cde2004-03-15 01:26:44 +000081 BasicBlock *newFuncRoot) {
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000082 // Separate incoming values and BasicBlocks as internal/external. We ignore
83 // the case where both the value and BasicBlock are internal, because we don't
84 // need to do a thing.
85 std::vector<unsigned> EValEBB;
86 std::vector<unsigned> EValIBB;
87 std::vector<unsigned> IValEBB;
88
89 for (unsigned i = 0, e = Phi->getNumIncomingValues(); i != e; ++i) {
90 Value *phiVal = Phi->getIncomingValue(i);
91 if (Instruction *Inst = dyn_cast<Instruction>(phiVal)) {
Chris Lattner9c431f62004-03-14 22:34:55 +000092 if (BlocksToExtract.count(Inst->getParent())) {
93 if (!BlocksToExtract.count(Phi->getIncomingBlock(i)))
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000094 IValEBB.push_back(i);
95 } else {
Chris Lattner9c431f62004-03-14 22:34:55 +000096 if (BlocksToExtract.count(Phi->getIncomingBlock(i)))
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000097 EValIBB.push_back(i);
98 else
99 EValEBB.push_back(i);
100 }
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000101 } else if (Argument *Arg = dyn_cast<Argument>(phiVal)) {
102 // arguments are external
Chris Lattner9c431f62004-03-14 22:34:55 +0000103 if (BlocksToExtract.count(Phi->getIncomingBlock(i)))
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000104 EValIBB.push_back(i);
105 else
106 EValEBB.push_back(i);
107 } else {
Chris Lattnerfb87cde2004-03-15 01:26:44 +0000108 // Globals/Constants are internal, but considered `external' if they are
109 // coming from an external block.
110 if (!BlocksToExtract.count(Phi->getIncomingBlock(i)))
111 EValEBB.push_back(i);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000112 }
113 }
114
Chris Lattnerfb87cde2004-03-15 01:26:44 +0000115 // Both value and block are external. Need to group all of these, have an
116 // external phi, pass the result as an argument, and have THIS phi use that
117 // result.
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000118 if (EValEBB.size() > 0) {
119 if (EValEBB.size() == 1) {
120 // Now if it's coming from the newFuncRoot, it's that funky input
121 unsigned phiIdx = EValEBB[0];
Chris Lattnerfb87cde2004-03-15 01:26:44 +0000122 if (!isa<Constant>(Phi->getIncomingValue(phiIdx))) {
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000123 PhiVal2Arg[Phi].push_back(std::make_pair(phiIdx, inputs.size()));
124 // We can just pass this value in as argument
125 inputs.push_back(Phi->getIncomingValue(phiIdx));
126 }
127 Phi->setIncomingBlock(phiIdx, newFuncRoot);
128 } else {
129 PHINode *externalPhi = new PHINode(Phi->getType(), "extPhi");
130 codeReplacer->getInstList().insert(codeReplacer->begin(), externalPhi);
131 for (std::vector<unsigned>::iterator i = EValEBB.begin(),
Chris Lattnerfb87cde2004-03-15 01:26:44 +0000132 e = EValEBB.end(); i != e; ++i) {
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000133 externalPhi->addIncoming(Phi->getIncomingValue(*i),
134 Phi->getIncomingBlock(*i));
135
136 // We make these values invalid instead of deleting them because that
137 // would shift the indices of other values... The fixPhiNodes should
138 // clean these phi nodes up later.
139 Phi->setIncomingValue(*i, 0);
140 Phi->setIncomingBlock(*i, 0);
141 }
142 PhiVal2Arg[Phi].push_back(std::make_pair(Phi->getNumIncomingValues(),
143 inputs.size()));
144 // We can just pass this value in as argument
145 inputs.push_back(externalPhi);
146 }
147 }
148
Chris Lattnerfb87cde2004-03-15 01:26:44 +0000149 // When the value is external, but block internal... just pass it in as
150 // argument, no change to phi node
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000151 for (std::vector<unsigned>::iterator i = EValIBB.begin(),
Chris Lattnerfb87cde2004-03-15 01:26:44 +0000152 e = EValIBB.end(); i != e; ++i) {
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000153 // rewrite the phi input node to be an argument
154 PhiVal2Arg[Phi].push_back(std::make_pair(*i, inputs.size()));
155 inputs.push_back(Phi->getIncomingValue(*i));
156 }
157
Chris Lattnerfb87cde2004-03-15 01:26:44 +0000158 // Value internal, block external this can happen if we are extracting a part
159 // of a loop.
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000160 for (std::vector<unsigned>::iterator i = IValEBB.begin(),
Chris Lattnerfb87cde2004-03-15 01:26:44 +0000161 e = IValEBB.end(); i != e; ++i) {
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000162 assert(0 && "Cannot (YET) handle internal values via external blocks");
163 }
164}
165
166
Chris Lattner73ab1fa2004-03-15 01:18:23 +0000167void CodeExtractor::findInputsOutputs(Values &inputs, Values &outputs,
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000168 BasicBlock *newHeader,
Chris Lattner73ab1fa2004-03-15 01:18:23 +0000169 BasicBlock *newRootNode) {
Chris Lattner9c431f62004-03-14 22:34:55 +0000170 for (std::set<BasicBlock*>::const_iterator ci = BlocksToExtract.begin(),
171 ce = BlocksToExtract.end(); ci != ce; ++ci) {
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000172 BasicBlock *BB = *ci;
Chris Lattner73ab1fa2004-03-15 01:18:23 +0000173 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
174 // If a used value is defined outside the region, it's an input. If an
175 // instruction is used outside the region, it's an output.
176 if (PHINode *Phi = dyn_cast<PHINode>(I)) {
177 processPhiNodeInputs(Phi, inputs, newHeader, newRootNode);
178 } else {
179 // All other instructions go through the generic input finder
180 // Loop over the operands of each instruction (inputs)
181 for (User::op_iterator op = I->op_begin(), opE = I->op_end();
182 op != opE; ++op)
183 if (Instruction *opI = dyn_cast<Instruction>(*op)) {
184 // Check if definition of this operand is within the loop
Chris Lattnerfb87cde2004-03-15 01:26:44 +0000185 if (!BlocksToExtract.count(opI->getParent()))
Chris Lattner73ab1fa2004-03-15 01:18:23 +0000186 inputs.push_back(opI);
Chris Lattner73ab1fa2004-03-15 01:18:23 +0000187 } else if (isa<Argument>(*op)) {
188 inputs.push_back(*op);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000189 }
Chris Lattner73ab1fa2004-03-15 01:18:23 +0000190 }
191
192 // Consider uses of this instruction (outputs)
193 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
194 UI != E; ++UI)
195 if (!BlocksToExtract.count(cast<Instruction>(*UI)->getParent()))
196 outputs.push_back(*UI);
197 } // for: insts
198 } // for: basic blocks
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000199}
200
201void CodeExtractor::rewritePhiNodes(Function *F,
202 BasicBlock *newFuncRoot) {
203 // Write any changes that were saved before: use function arguments as inputs
204 for (PhiVal2ArgTy::iterator i = PhiVal2Arg.begin(), e = PhiVal2Arg.end();
Chris Lattnerfb87cde2004-03-15 01:26:44 +0000205 i != e; ++i) {
206 PHINode *phi = i->first;
207 PhiValChangesTy &values = i->second;
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000208 for (unsigned cIdx = 0, ce = values.size(); cIdx != ce; ++cIdx)
209 {
210 unsigned phiValueIdx = values[cIdx].first, argNum = values[cIdx].second;
211 if (phiValueIdx < phi->getNumIncomingValues())
212 phi->setIncomingValue(phiValueIdx, getFunctionArg(F, argNum));
213 else
214 phi->addIncoming(getFunctionArg(F, argNum), newFuncRoot);
215 }
216 }
217
218 // Delete any invalid Phi node inputs that were marked as NULL previously
219 for (PhiVal2ArgTy::iterator i = PhiVal2Arg.begin(), e = PhiVal2Arg.end();
Chris Lattnerfb87cde2004-03-15 01:26:44 +0000220 i != e; ++i) {
221 PHINode *phi = i->first;
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000222 for (unsigned idx = 0, end = phi->getNumIncomingValues(); idx != end; ++idx)
223 {
224 if (phi->getIncomingValue(idx) == 0 && phi->getIncomingBlock(idx) == 0) {
225 phi->removeIncomingValue(idx);
226 --idx;
227 --end;
228 }
229 }
230 }
231
232 // We are done with the saved values
233 PhiVal2Arg.clear();
234}
235
236
237/// constructFunction - make a function based on inputs and outputs, as follows:
238/// f(in0, ..., inN, out0, ..., outN)
239///
240Function *CodeExtractor::constructFunction(const Values &inputs,
241 const Values &outputs,
242 BasicBlock *newRootNode,
243 BasicBlock *newHeader,
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000244 Function *oldFunction, Module *M) {
245 DEBUG(std::cerr << "inputs: " << inputs.size() << "\n");
246 DEBUG(std::cerr << "outputs: " << outputs.size() << "\n");
Chris Lattner9c431f62004-03-14 22:34:55 +0000247 BasicBlock *header = *BlocksToExtract.begin();
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000248
249 // This function returns unsigned, outputs will go back by reference.
250 Type *retTy = Type::UShortTy;
251 std::vector<const Type*> paramTy;
252
253 // Add the types of the input values to the function's argument list
254 for (Values::const_iterator i = inputs.begin(),
255 e = inputs.end(); i != e; ++i) {
256 const Value *value = *i;
257 DEBUG(std::cerr << "value used in func: " << value << "\n");
258 paramTy.push_back(value->getType());
259 }
260
261 // Add the types of the output values to the function's argument list, but
262 // make them pointer types for scalars
263 for (Values::const_iterator i = outputs.begin(),
264 e = outputs.end(); i != e; ++i) {
265 const Value *value = *i;
266 DEBUG(std::cerr << "instr used in func: " << value << "\n");
267 const Type *valueType = value->getType();
268 // Convert scalar types into a pointer of that type
269 if (valueType->isPrimitiveType()) {
270 valueType = PointerType::get(valueType);
271 }
272 paramTy.push_back(valueType);
273 }
274
275 DEBUG(std::cerr << "Function type: " << retTy << " f(");
276 for (std::vector<const Type*>::iterator i = paramTy.begin(),
277 e = paramTy.end(); i != e; ++i)
Chris Lattnerfb87cde2004-03-15 01:26:44 +0000278 DEBUG(std::cerr << *i << ", ");
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000279 DEBUG(std::cerr << ")\n");
280
281 const FunctionType *funcType = FunctionType::get(retTy, paramTy, false);
282
283 // Create the new function
284 Function *newFunction = new Function(funcType,
285 GlobalValue::InternalLinkage,
286 oldFunction->getName() + "_code", M);
287 newFunction->getBasicBlockList().push_back(newRootNode);
288
289 for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
290 std::vector<User*> Users(inputs[i]->use_begin(), inputs[i]->use_end());
291 for (std::vector<User*>::iterator use = Users.begin(), useE = Users.end();
Chris Lattner36844692004-03-14 03:17:22 +0000292 use != useE; ++use)
293 if (Instruction* inst = dyn_cast<Instruction>(*use))
Chris Lattner9c431f62004-03-14 22:34:55 +0000294 if (BlocksToExtract.count(inst->getParent()))
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000295 inst->replaceUsesOfWith(inputs[i], getFunctionArg(newFunction, i));
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000296 }
297
298 // Rewrite branches to basic blocks outside of the loop to new dummy blocks
299 // within the new function. This must be done before we lose track of which
300 // blocks were originally in the code region.
301 std::vector<User*> Users(header->use_begin(), header->use_end());
302 for (std::vector<User*>::iterator i = Users.begin(), e = Users.end();
303 i != e; ++i) {
304 if (BranchInst *inst = dyn_cast<BranchInst>(*i)) {
305 BasicBlock *BB = inst->getParent();
Chris Lattner9c431f62004-03-14 22:34:55 +0000306 if (!BlocksToExtract.count(BB) && BB->getParent() == oldFunction) {
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000307 // The BasicBlock which contains the branch is not in the region
308 // modify the branch target to a new block
309 inst->replaceUsesOfWith(header, newHeader);
310 }
311 }
312 }
313
314 return newFunction;
315}
316
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000317void CodeExtractor::moveCodeToFunction(Function *newFunction) {
Chris Lattner9c431f62004-03-14 22:34:55 +0000318 Function *oldFunc = (*BlocksToExtract.begin())->getParent();
Chris Lattner4fca71e2004-03-14 04:01:47 +0000319 Function::BasicBlockListType &oldBlocks = oldFunc->getBasicBlockList();
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000320 Function::BasicBlockListType &newBlocks = newFunction->getBasicBlockList();
Chris Lattner4fca71e2004-03-14 04:01:47 +0000321
Chris Lattner9c431f62004-03-14 22:34:55 +0000322 for (std::set<BasicBlock*>::const_iterator i = BlocksToExtract.begin(),
323 e = BlocksToExtract.end(); i != e; ++i) {
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000324 // Delete the basic block from the old function, and the list of blocks
Chris Lattner9c431f62004-03-14 22:34:55 +0000325 oldBlocks.remove(*i);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000326
327 // Insert this basic block into the new function
Chris Lattner9c431f62004-03-14 22:34:55 +0000328 newBlocks.push_back(*i);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000329 }
330}
331
332void
333CodeExtractor::emitCallAndSwitchStatement(Function *newFunction,
334 BasicBlock *codeReplacer,
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000335 Values &inputs,
336 Values &outputs)
337{
338 // Emit a call to the new function, passing allocated memory for outputs and
339 // just plain inputs for non-scalars
Chris Lattner5b2072e2004-03-14 23:43:24 +0000340 std::vector<Value*> params(inputs);
341
342 for (Values::const_iterator i = outputs.begin(), e = outputs.end(); i != e;
343 ++i) {
344 Value *Output = *i;
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000345 // Create allocas for scalar outputs
Chris Lattner5b2072e2004-03-14 23:43:24 +0000346 if (Output->getType()->isPrimitiveType()) {
347 AllocaInst *alloca =
348 new AllocaInst((*i)->getType(), 0, Output->getName()+".loc",
349 codeReplacer->getParent()->begin()->begin());
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000350 params.push_back(alloca);
351
Chris Lattner5b2072e2004-03-14 23:43:24 +0000352 LoadInst *load = new LoadInst(alloca, Output->getName()+".reload");
353 codeReplacer->getInstList().push_back(load);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000354 std::vector<User*> Users((*i)->use_begin(), (*i)->use_end());
355 for (std::vector<User*>::iterator use = Users.begin(), useE =Users.end();
356 use != useE; ++use) {
357 if (Instruction* inst = dyn_cast<Instruction>(*use)) {
Chris Lattner5b2072e2004-03-14 23:43:24 +0000358 if (!BlocksToExtract.count(inst->getParent()))
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000359 inst->replaceUsesOfWith(*i, load);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000360 }
361 }
362 } else {
363 params.push_back(*i);
364 }
365 }
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000366
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000367 CallInst *call = new CallInst(newFunction, params, "targetBlock");
Chris Lattner5b2072e2004-03-14 23:43:24 +0000368 codeReplacer->getInstList().push_front(call);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000369
370 // Now we can emit a switch statement using the call as a value.
Chris Lattner5b2072e2004-03-14 23:43:24 +0000371 SwitchInst *TheSwitch = new SwitchInst(call, codeReplacer, codeReplacer);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000372
373 // Since there may be multiple exits from the original region, make the new
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000374 // function return an unsigned, switch on that number. This loop iterates
375 // over all of the blocks in the extracted region, updating any terminator
376 // instructions in the to-be-extracted region that branch to blocks that are
377 // not in the region to be extracted.
378 std::map<BasicBlock*, BasicBlock*> ExitBlockMap;
379
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000380 unsigned switchVal = 0;
Chris Lattner9c431f62004-03-14 22:34:55 +0000381 for (std::set<BasicBlock*>::const_iterator i = BlocksToExtract.begin(),
382 e = BlocksToExtract.end(); i != e; ++i) {
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000383 TerminatorInst *TI = (*i)->getTerminator();
384 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
385 if (!BlocksToExtract.count(TI->getSuccessor(i))) {
386 BasicBlock *OldTarget = TI->getSuccessor(i);
387 // add a new basic block which returns the appropriate value
388 BasicBlock *&NewTarget = ExitBlockMap[OldTarget];
389 if (!NewTarget) {
390 // If we don't already have an exit stub for this non-extracted
391 // destination, create one now!
392 NewTarget = new BasicBlock(OldTarget->getName() + ".exitStub",
393 newFunction);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000394
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000395 ConstantUInt *brVal = ConstantUInt::get(Type::UShortTy, switchVal++);
396 ReturnInst *NTRet = new ReturnInst(brVal, NewTarget);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000397
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000398 // Update the switch instruction.
Chris Lattner5b2072e2004-03-14 23:43:24 +0000399 TheSwitch->addCase(brVal, OldTarget);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000400
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000401 // Restore values just before we exit
402 // FIXME: Use a GetElementPtr to bunch the outputs in a struct
403 for (unsigned out = 0, e = outputs.size(); out != e; ++out)
404 new StoreInst(outputs[out], getFunctionArg(newFunction, out),NTRet);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000405 }
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000406
407 // rewrite the original branch instruction with this new target
408 TI->setSuccessor(i, NewTarget);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000409 }
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000410 }
Chris Lattner5b2072e2004-03-14 23:43:24 +0000411
412 // Now that we've done the deed, make the default destination of the switch
413 // instruction be one of the exit blocks of the region.
414 if (TheSwitch->getNumSuccessors() > 1) {
415 // FIXME: this is broken w.r.t. PHI nodes, but the old code was more broken.
416 // This edge is not traversable.
417 TheSwitch->setSuccessor(0, TheSwitch->getSuccessor(1));
418 }
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000419}
420
421
422/// ExtractRegion - Removes a loop from a function, replaces it with a call to
423/// new function. Returns pointer to the new function.
424///
425/// algorithm:
426///
427/// find inputs and outputs for the region
428///
429/// for inputs: add to function as args, map input instr* to arg#
430/// for outputs: add allocas for scalars,
431/// add to func as args, map output instr* to arg#
432///
433/// rewrite func to use argument #s instead of instr*
434///
435/// for each scalar output in the function: at every exit, store intermediate
436/// computed result back into memory.
437///
438Function *CodeExtractor::ExtractCodeRegion(const std::vector<BasicBlock*> &code)
439{
440 // 1) Find inputs, outputs
441 // 2) Construct new function
442 // * Add allocas for defs, pass as args by reference
443 // * Pass in uses as args
444 // 3) Move code region, add call instr to func
Chris Lattner9c431f62004-03-14 22:34:55 +0000445 //
446 BlocksToExtract.insert(code.begin(), code.end());
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000447
448 Values inputs, outputs;
449
450 // Assumption: this is a single-entry code region, and the header is the first
Chris Lattner73ab1fa2004-03-15 01:18:23 +0000451 // block in the region.
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000452 BasicBlock *header = code[0];
Chris Lattner73ab1fa2004-03-15 01:18:23 +0000453 for (unsigned i = 1, e = code.size(); i != e; ++i)
454 for (pred_iterator PI = pred_begin(code[i]), E = pred_end(code[i]);
455 PI != E; ++PI)
456 assert(BlocksToExtract.count(*PI) &&
457 "No blocks in this region may have entries from outside the region"
458 " except for the first block!");
459
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000460 Function *oldFunction = header->getParent();
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000461
462 // This takes place of the original loop
463 BasicBlock *codeReplacer = new BasicBlock("codeRepl", oldFunction);
464
465 // The new function needs a root node because other nodes can branch to the
466 // head of the loop, and the root cannot have predecessors
467 BasicBlock *newFuncRoot = new BasicBlock("newFuncRoot");
468 newFuncRoot->getInstList().push_back(new BranchInst(header));
469
470 // Find inputs to, outputs from the code region
471 //
472 // If one of the inputs is coming from a different basic block and it's in a
473 // phi node, we need to rewrite the phi node:
474 //
475 // * All the inputs which involve basic blocks OUTSIDE of this region go into
476 // a NEW phi node that takes care of finding which value really came in.
477 // The result of this phi is passed to the function as an argument.
478 //
479 // * All the other phi values stay.
480 //
481 // FIXME: PHI nodes' incoming blocks aren't being rewritten to accomodate for
482 // blocks moving to a new function.
483 // SOLUTION: move Phi nodes out of the loop header into the codeReplacer, pass
484 // the values as parameters to the function
Chris Lattner9c431f62004-03-14 22:34:55 +0000485 findInputsOutputs(inputs, outputs, codeReplacer, newFuncRoot);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000486
487 // Step 2: Construct new function based on inputs/outputs,
488 // Add allocas for all defs
489 Function *newFunction = constructFunction(inputs, outputs, newFuncRoot,
Chris Lattner73ab1fa2004-03-15 01:18:23 +0000490 codeReplacer, oldFunction,
491 oldFunction->getParent());
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000492
493 rewritePhiNodes(newFunction, newFuncRoot);
494
Chris Lattner9c431f62004-03-14 22:34:55 +0000495 emitCallAndSwitchStatement(newFunction, codeReplacer, inputs, outputs);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000496
Chris Lattner9c431f62004-03-14 22:34:55 +0000497 moveCodeToFunction(newFunction);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000498
Chris Lattner36844692004-03-14 03:17:22 +0000499 DEBUG(if (verifyFunction(*newFunction)) abort());
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000500 return newFunction;
501}
502
Misha Brukmanf44acae2004-03-02 00:20:57 +0000503/// ExtractCodeRegion - slurp a sequence of basic blocks into a brand new
504/// function
505///
506Function* llvm::ExtractCodeRegion(const std::vector<BasicBlock*> &code) {
Chris Lattner4fca71e2004-03-14 04:01:47 +0000507 return CodeExtractor().ExtractCodeRegion(code);
Misha Brukmanf44acae2004-03-02 00:20:57 +0000508}
509
Misha Brukman5af2be72004-03-01 18:28:34 +0000510/// ExtractBasicBlock - slurp a natural loop into a brand new function
511///
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000512Function* llvm::ExtractLoop(Loop *L) {
Chris Lattner4fca71e2004-03-14 04:01:47 +0000513 return CodeExtractor().ExtractCodeRegion(L->getBlocks());
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000514}
515
Misha Brukman5af2be72004-03-01 18:28:34 +0000516/// ExtractBasicBlock - slurp a basic block into a brand new function
517///
518Function* llvm::ExtractBasicBlock(BasicBlock *BB) {
Misha Brukman5af2be72004-03-01 18:28:34 +0000519 std::vector<BasicBlock*> Blocks;
520 Blocks.push_back(BB);
Chris Lattner4fca71e2004-03-14 04:01:47 +0000521 return CodeExtractor().ExtractCodeRegion(Blocks);
Misha Brukman5af2be72004-03-01 18:28:34 +0000522}