1 //===- CodeExtractor.cpp - Pull code region into a new function -----------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
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.
14 //===----------------------------------------------------------------------===//
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"
23 #include "llvm/Analysis/Verifier.h"
24 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
25 #include "llvm/Transforms/Utils/FunctionUtils.h"
26 #include "Support/Debug.h"
27 #include "Support/StringExtras.h"
35 inline bool contains(const std::vector<BasicBlock*> &V, const BasicBlock *BB){
36 return std::find(V.begin(), V.end(), BB) != V.end();
39 /// getFunctionArg - Return a pointer to F's ARGNOth argument.
41 Argument *getFunctionArg(Function *F, unsigned argno) {
42 Function::aiterator ai = F->abegin();
43 while (argno) { ++ai; --argno; }
47 struct CodeExtractor {
48 typedef std::vector<Value*> Values;
49 typedef std::vector<std::pair<unsigned, unsigned> > PhiValChangesTy;
50 typedef std::map<PHINode*, PhiValChangesTy> PhiVal2ArgTy;
51 PhiVal2ArgTy PhiVal2Arg;
54 Function *ExtractCodeRegion(const std::vector<BasicBlock*> &code);
57 void findInputsOutputs(const std::vector<BasicBlock*> &code,
60 BasicBlock *newHeader,
61 BasicBlock *newRootNode);
63 void processPhiNodeInputs(PHINode *Phi,
64 const std::vector<BasicBlock*> &code,
66 BasicBlock *newHeader,
67 BasicBlock *newRootNode);
69 void rewritePhiNodes(Function *F, BasicBlock *newFuncRoot);
71 Function *constructFunction(const Values &inputs,
72 const Values &outputs,
73 BasicBlock *newRootNode, BasicBlock *newHeader,
74 const std::vector<BasicBlock*> &code,
75 Function *oldFunction, Module *M);
77 void moveCodeToFunction(const std::vector<BasicBlock*> &code,
78 Function *newFunction);
80 void emitCallAndSwitchStatement(Function *newFunction,
81 BasicBlock *newHeader,
82 const std::vector<BasicBlock*> &code,
89 void CodeExtractor::processPhiNodeInputs(PHINode *Phi,
90 const std::vector<BasicBlock*> &code,
92 BasicBlock *codeReplacer,
93 BasicBlock *newFuncRoot)
95 // Separate incoming values and BasicBlocks as internal/external. We ignore
96 // the case where both the value and BasicBlock are internal, because we don't
97 // need to do a thing.
98 std::vector<unsigned> EValEBB;
99 std::vector<unsigned> EValIBB;
100 std::vector<unsigned> IValEBB;
102 for (unsigned i = 0, e = Phi->getNumIncomingValues(); i != e; ++i) {
103 Value *phiVal = Phi->getIncomingValue(i);
104 if (Instruction *Inst = dyn_cast<Instruction>(phiVal)) {
105 if (contains(code, Inst->getParent())) {
106 if (!contains(code, Phi->getIncomingBlock(i)))
107 IValEBB.push_back(i);
109 if (contains(code, Phi->getIncomingBlock(i)))
110 EValIBB.push_back(i);
112 EValEBB.push_back(i);
114 } else if (Constant *Const = dyn_cast<Constant>(phiVal)) {
115 // Constants are internal, but considered `external' if they are coming
116 // from an external block.
117 if (!contains(code, Phi->getIncomingBlock(i)))
118 EValEBB.push_back(i);
119 } else if (Argument *Arg = dyn_cast<Argument>(phiVal)) {
120 // arguments are external
121 if (contains(code, Phi->getIncomingBlock(i)))
122 EValIBB.push_back(i);
124 EValEBB.push_back(i);
127 assert(0 && "Unhandled input in a Phi node");
131 // Both value and block are external. Need to group all of
132 // these, have an external phi, pass the result as an
133 // argument, and have THIS phi use that result.
134 if (EValEBB.size() > 0) {
135 if (EValEBB.size() == 1) {
136 // Now if it's coming from the newFuncRoot, it's that funky input
137 unsigned phiIdx = EValEBB[0];
138 if (!dyn_cast<Constant>(Phi->getIncomingValue(phiIdx)))
140 PhiVal2Arg[Phi].push_back(std::make_pair(phiIdx, inputs.size()));
141 // We can just pass this value in as argument
142 inputs.push_back(Phi->getIncomingValue(phiIdx));
144 Phi->setIncomingBlock(phiIdx, newFuncRoot);
146 PHINode *externalPhi = new PHINode(Phi->getType(), "extPhi");
147 codeReplacer->getInstList().insert(codeReplacer->begin(), externalPhi);
148 for (std::vector<unsigned>::iterator i = EValEBB.begin(),
149 e = EValEBB.end(); i != e; ++i)
151 externalPhi->addIncoming(Phi->getIncomingValue(*i),
152 Phi->getIncomingBlock(*i));
154 // We make these values invalid instead of deleting them because that
155 // would shift the indices of other values... The fixPhiNodes should
156 // clean these phi nodes up later.
157 Phi->setIncomingValue(*i, 0);
158 Phi->setIncomingBlock(*i, 0);
160 PhiVal2Arg[Phi].push_back(std::make_pair(Phi->getNumIncomingValues(),
162 // We can just pass this value in as argument
163 inputs.push_back(externalPhi);
167 // When the value is external, but block internal...
168 // just pass it in as argument, no change to phi node
169 for (std::vector<unsigned>::iterator i = EValIBB.begin(),
170 e = EValIBB.end(); i != e; ++i)
172 // rewrite the phi input node to be an argument
173 PhiVal2Arg[Phi].push_back(std::make_pair(*i, inputs.size()));
174 inputs.push_back(Phi->getIncomingValue(*i));
177 // Value internal, block external
178 // this can happen if we are extracting a part of a loop
179 for (std::vector<unsigned>::iterator i = IValEBB.begin(),
180 e = IValEBB.end(); i != e; ++i)
182 assert(0 && "Cannot (YET) handle internal values via external blocks");
187 void CodeExtractor::findInputsOutputs(const std::vector<BasicBlock*> &code,
190 BasicBlock *newHeader,
191 BasicBlock *newRootNode)
193 for (std::vector<BasicBlock*>::const_iterator ci = code.begin(),
194 ce = code.end(); ci != ce; ++ci) {
195 BasicBlock *BB = *ci;
196 for (BasicBlock::iterator BBi = BB->begin(), BBe = BB->end();
198 // If a use is defined outside the region, it's an input.
199 // If a def is used outside the region, it's an output.
200 if (Instruction *I = dyn_cast<Instruction>(&*BBi)) {
201 // If it's a phi node
202 if (PHINode *Phi = dyn_cast<PHINode>(I)) {
203 processPhiNodeInputs(Phi, code, inputs, newHeader, newRootNode);
205 // All other instructions go through the generic input finder
206 // Loop over the operands of each instruction (inputs)
207 for (User::op_iterator op = I->op_begin(), opE = I->op_end();
209 if (Instruction *opI = dyn_cast<Instruction>(op->get())) {
210 // Check if definition of this operand is within the loop
211 if (!contains(code, opI->getParent())) {
212 // add this operand to the inputs
213 inputs.push_back(opI);
219 // Consider uses of this instruction (outputs)
220 for (Value::use_iterator use = I->use_begin(), useE = I->use_end();
221 use != useE; ++use) {
222 if (Instruction* inst = dyn_cast<Instruction>(*use)) {
223 if (!contains(code, inst->getParent())) {
224 // add this op to the outputs
225 outputs.push_back(I);
231 } /* for: basic blocks */
234 void CodeExtractor::rewritePhiNodes(Function *F,
235 BasicBlock *newFuncRoot) {
236 // Write any changes that were saved before: use function arguments as inputs
237 for (PhiVal2ArgTy::iterator i = PhiVal2Arg.begin(), e = PhiVal2Arg.end();
240 PHINode *phi = (*i).first;
241 PhiValChangesTy &values = (*i).second;
242 for (unsigned cIdx = 0, ce = values.size(); cIdx != ce; ++cIdx)
244 unsigned phiValueIdx = values[cIdx].first, argNum = values[cIdx].second;
245 if (phiValueIdx < phi->getNumIncomingValues())
246 phi->setIncomingValue(phiValueIdx, getFunctionArg(F, argNum));
248 phi->addIncoming(getFunctionArg(F, argNum), newFuncRoot);
252 // Delete any invalid Phi node inputs that were marked as NULL previously
253 for (PhiVal2ArgTy::iterator i = PhiVal2Arg.begin(), e = PhiVal2Arg.end();
256 PHINode *phi = (*i).first;
257 for (unsigned idx = 0, end = phi->getNumIncomingValues(); idx != end; ++idx)
259 if (phi->getIncomingValue(idx) == 0 && phi->getIncomingBlock(idx) == 0) {
260 phi->removeIncomingValue(idx);
267 // We are done with the saved values
272 /// constructFunction - make a function based on inputs and outputs, as follows:
273 /// f(in0, ..., inN, out0, ..., outN)
275 Function *CodeExtractor::constructFunction(const Values &inputs,
276 const Values &outputs,
277 BasicBlock *newRootNode,
278 BasicBlock *newHeader,
279 const std::vector<BasicBlock*> &code,
280 Function *oldFunction, Module *M) {
281 DEBUG(std::cerr << "inputs: " << inputs.size() << "\n");
282 DEBUG(std::cerr << "outputs: " << outputs.size() << "\n");
283 BasicBlock *header = code[0];
285 // This function returns unsigned, outputs will go back by reference.
286 Type *retTy = Type::UShortTy;
287 std::vector<const Type*> paramTy;
289 // Add the types of the input values to the function's argument list
290 for (Values::const_iterator i = inputs.begin(),
291 e = inputs.end(); i != e; ++i) {
292 const Value *value = *i;
293 DEBUG(std::cerr << "value used in func: " << value << "\n");
294 paramTy.push_back(value->getType());
297 // Add the types of the output values to the function's argument list, but
298 // make them pointer types for scalars
299 for (Values::const_iterator i = outputs.begin(),
300 e = outputs.end(); i != e; ++i) {
301 const Value *value = *i;
302 DEBUG(std::cerr << "instr used in func: " << value << "\n");
303 const Type *valueType = value->getType();
304 // Convert scalar types into a pointer of that type
305 if (valueType->isPrimitiveType()) {
306 valueType = PointerType::get(valueType);
308 paramTy.push_back(valueType);
311 DEBUG(std::cerr << "Function type: " << retTy << " f(");
312 for (std::vector<const Type*>::iterator i = paramTy.begin(),
313 e = paramTy.end(); i != e; ++i)
314 DEBUG(std::cerr << (*i) << ", ");
315 DEBUG(std::cerr << ")\n");
317 const FunctionType *funcType = FunctionType::get(retTy, paramTy, false);
319 // Create the new function
320 Function *newFunction = new Function(funcType,
321 GlobalValue::InternalLinkage,
322 oldFunction->getName() + "_code", M);
323 newFunction->getBasicBlockList().push_back(newRootNode);
325 for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
326 std::vector<User*> Users(inputs[i]->use_begin(), inputs[i]->use_end());
327 for (std::vector<User*>::iterator use = Users.begin(), useE = Users.end();
329 if (Instruction* inst = dyn_cast<Instruction>(*use))
330 if (contains(code, inst->getParent()))
331 inst->replaceUsesOfWith(inputs[i], getFunctionArg(newFunction, i));
334 // Rewrite branches to basic blocks outside of the loop to new dummy blocks
335 // within the new function. This must be done before we lose track of which
336 // blocks were originally in the code region.
337 std::vector<User*> Users(header->use_begin(), header->use_end());
338 for (std::vector<User*>::iterator i = Users.begin(), e = Users.end();
340 if (BranchInst *inst = dyn_cast<BranchInst>(*i)) {
341 BasicBlock *BB = inst->getParent();
342 if (!contains(code, BB) && BB->getParent() == oldFunction) {
343 // The BasicBlock which contains the branch is not in the region
344 // modify the branch target to a new block
345 inst->replaceUsesOfWith(header, newHeader);
353 void CodeExtractor::moveCodeToFunction(const std::vector<BasicBlock*> &code,
354 Function *newFunction)
356 Function *oldFunc = code[0]->getParent();
357 Function::BasicBlockListType &oldBlocks = oldFunc->getBasicBlockList();
358 Function::BasicBlockListType &newBlocks = newFunction->getBasicBlockList();
360 for (std::vector<BasicBlock*>::const_iterator i = code.begin(), e =code.end();
364 // Delete the basic block from the old function, and the list of blocks
365 oldBlocks.remove(BB);
367 // Insert this basic block into the new function
368 newBlocks.push_back(BB);
373 CodeExtractor::emitCallAndSwitchStatement(Function *newFunction,
374 BasicBlock *codeReplacer,
375 const std::vector<BasicBlock*> &code,
379 // Emit a call to the new function, passing allocated memory for outputs and
380 // just plain inputs for non-scalars
381 std::vector<Value*> params;
382 BasicBlock *codeReplacerTail = new BasicBlock("codeReplTail",
383 codeReplacer->getParent());
384 for (Values::const_iterator i = inputs.begin(),
385 e = inputs.end(); i != e; ++i)
386 params.push_back(*i);
387 for (Values::const_iterator i = outputs.begin(),
388 e = outputs.end(); i != e; ++i) {
389 // Create allocas for scalar outputs
390 if ((*i)->getType()->isPrimitiveType()) {
391 Constant *one = ConstantUInt::get(Type::UIntTy, 1);
392 AllocaInst *alloca = new AllocaInst((*i)->getType(), one);
393 codeReplacer->getInstList().push_back(alloca);
394 params.push_back(alloca);
396 LoadInst *load = new LoadInst(alloca, "alloca");
397 codeReplacerTail->getInstList().push_back(load);
398 std::vector<User*> Users((*i)->use_begin(), (*i)->use_end());
399 for (std::vector<User*>::iterator use = Users.begin(), useE =Users.end();
400 use != useE; ++use) {
401 if (Instruction* inst = dyn_cast<Instruction>(*use)) {
402 if (!contains(code, inst->getParent())) {
403 inst->replaceUsesOfWith(*i, load);
408 params.push_back(*i);
411 CallInst *call = new CallInst(newFunction, params, "targetBlock");
412 codeReplacer->getInstList().push_back(call);
413 codeReplacer->getInstList().push_back(new BranchInst(codeReplacerTail));
415 // Now we can emit a switch statement using the call as a value.
416 // FIXME: perhaps instead of default being self BB, it should be a second
417 // dummy block which asserts that the value is not within the range...?
418 //BasicBlock *defaultBlock = new BasicBlock("defaultBlock", oldF);
420 //defaultBlock->getInstList().push_back(new BranchInst(codeReplacer));
422 SwitchInst *switchInst = new SwitchInst(call, codeReplacerTail,
425 // Since there may be multiple exits from the original region, make the new
426 // function return an unsigned, switch on that number
427 unsigned switchVal = 0;
428 for (std::vector<BasicBlock*>::const_iterator i =code.begin(), e = code.end();
432 // rewrite the terminator of the original BasicBlock
433 Instruction *term = BB->getTerminator();
434 if (BranchInst *brInst = dyn_cast<BranchInst>(term)) {
436 // Restore values just before we exit
437 // FIXME: Use a GetElementPtr to bunch the outputs in a struct
438 for (unsigned outIdx = 0, outE = outputs.size(); outIdx != outE; ++outIdx)
440 new StoreInst(outputs[outIdx],
441 getFunctionArg(newFunction, outIdx),
445 // Rewrite branches into exits which return a value based on which
446 // exit we take from this function
447 if (brInst->isUnconditional()) {
448 if (!contains(code, brInst->getSuccessor(0))) {
449 ConstantUInt *brVal = ConstantUInt::get(Type::UShortTy, switchVal);
450 ReturnInst *newRet = new ReturnInst(brVal);
451 // add a new target to the switch
452 switchInst->addCase(brVal, brInst->getSuccessor(0));
454 // rewrite the branch with a return
455 BasicBlock::iterator ii(brInst);
456 ReplaceInstWithInst(BB->getInstList(), ii, newRet);
460 // Replace the conditional branch to branch
461 // to two new blocks, each of which returns a different code.
462 for (unsigned idx = 0; idx < 2; ++idx) {
463 BasicBlock *oldTarget = brInst->getSuccessor(idx);
464 if (!contains(code, oldTarget)) {
465 // add a new basic block which returns the appropriate value
466 BasicBlock *newTarget = new BasicBlock("newTarget", newFunction);
467 ConstantUInt *brVal = ConstantUInt::get(Type::UShortTy, switchVal);
468 ReturnInst *newRet = new ReturnInst(brVal);
469 newTarget->getInstList().push_back(newRet);
470 // rewrite the original branch instruction with this new target
471 brInst->setSuccessor(idx, newTarget);
472 // the switch statement knows what to do with this value
473 switchInst->addCase(brVal, oldTarget);
478 } else if (ReturnInst *retTerm = dyn_cast<ReturnInst>(term)) {
479 assert(0 && "Cannot handle return instructions just yet.");
480 // FIXME: what if the terminator is a return!??!
481 // Need to rewrite: add new basic block, move the return there
482 // treat the original as an unconditional branch to that basicblock
483 } else if (SwitchInst *swTerm = dyn_cast<SwitchInst>(term)) {
484 assert(0 && "Cannot handle switch instructions just yet.");
485 } else if (InvokeInst *invInst = dyn_cast<InvokeInst>(term)) {
486 assert(0 && "Cannot handle invoke instructions just yet.");
488 assert(0 && "Unrecognized terminator, or badly-formed BasicBlock.");
494 /// ExtractRegion - Removes a loop from a function, replaces it with a call to
495 /// new function. Returns pointer to the new function.
499 /// find inputs and outputs for the region
501 /// for inputs: add to function as args, map input instr* to arg#
502 /// for outputs: add allocas for scalars,
503 /// add to func as args, map output instr* to arg#
505 /// rewrite func to use argument #s instead of instr*
507 /// for each scalar output in the function: at every exit, store intermediate
508 /// computed result back into memory.
510 Function *CodeExtractor::ExtractCodeRegion(const std::vector<BasicBlock*> &code)
512 // 1) Find inputs, outputs
513 // 2) Construct new function
514 // * Add allocas for defs, pass as args by reference
515 // * Pass in uses as args
516 // 3) Move code region, add call instr to func
519 Values inputs, outputs;
521 // Assumption: this is a single-entry code region, and the header is the first
522 // block in the region. FIXME: is this true for a list of blocks from a
524 BasicBlock *header = code[0];
525 Function *oldFunction = header->getParent();
526 Module *module = oldFunction->getParent();
528 // This takes place of the original loop
529 BasicBlock *codeReplacer = new BasicBlock("codeRepl", oldFunction);
531 // The new function needs a root node because other nodes can branch to the
532 // head of the loop, and the root cannot have predecessors
533 BasicBlock *newFuncRoot = new BasicBlock("newFuncRoot");
534 newFuncRoot->getInstList().push_back(new BranchInst(header));
536 // Find inputs to, outputs from the code region
538 // If one of the inputs is coming from a different basic block and it's in a
539 // phi node, we need to rewrite the phi node:
541 // * All the inputs which involve basic blocks OUTSIDE of this region go into
542 // a NEW phi node that takes care of finding which value really came in.
543 // The result of this phi is passed to the function as an argument.
545 // * All the other phi values stay.
547 // FIXME: PHI nodes' incoming blocks aren't being rewritten to accomodate for
548 // blocks moving to a new function.
549 // SOLUTION: move Phi nodes out of the loop header into the codeReplacer, pass
550 // the values as parameters to the function
551 findInputsOutputs(code, inputs, outputs, codeReplacer, newFuncRoot);
553 // Step 2: Construct new function based on inputs/outputs,
554 // Add allocas for all defs
555 Function *newFunction = constructFunction(inputs, outputs, newFuncRoot,
557 oldFunction, module);
559 rewritePhiNodes(newFunction, newFuncRoot);
561 emitCallAndSwitchStatement(newFunction, codeReplacer, code, inputs, outputs);
563 moveCodeToFunction(code, newFunction);
565 DEBUG(if (verifyFunction(*newFunction)) abort());
569 /// ExtractCodeRegion - slurp a sequence of basic blocks into a brand new
572 Function* llvm::ExtractCodeRegion(const std::vector<BasicBlock*> &code) {
573 return CodeExtractor().ExtractCodeRegion(code);
576 /// ExtractBasicBlock - slurp a natural loop into a brand new function
578 Function* llvm::ExtractLoop(Loop *L) {
579 return CodeExtractor().ExtractCodeRegion(L->getBlocks());
582 /// ExtractBasicBlock - slurp a basic block into a brand new function
584 Function* llvm::ExtractBasicBlock(BasicBlock *BB) {
585 std::vector<BasicBlock*> Blocks;
586 Blocks.push_back(BB);
587 return CodeExtractor().ExtractCodeRegion(Blocks);