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/Transforms/Utils/FunctionUtils.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/Dominators.h"
23 #include "llvm/Analysis/LoopInfo.h"
24 #include "llvm/Analysis/Verifier.h"
25 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
26 #include "Support/CommandLine.h"
27 #include "Support/Debug.h"
28 #include "Support/StringExtras.h"
33 // Provide a command-line option to aggregate function arguments into a struct
34 // for functions produced by the code extrator. This is useful when converting
35 // extracted functions to pthread-based code, as only one argument (void*) can
36 // be passed in to pthread_create().
38 AggregateArgsOpt("aggregate-extracted-args", cl::Hidden,
39 cl::desc("Aggregate arguments to code-extracted functions"));
43 typedef std::vector<Value*> Values;
44 std::set<BasicBlock*> BlocksToExtract;
48 CodeExtractor(DominatorSet *ds = 0, bool AggArgs = false)
49 : DS(ds), AggregateArgs(AggregateArgsOpt) {}
51 Function *ExtractCodeRegion(const std::vector<BasicBlock*> &code);
53 bool isEligible(const std::vector<BasicBlock*> &code);
56 void findInputsOutputs(Values &inputs, Values &outputs,
57 BasicBlock *newHeader,
58 BasicBlock *newRootNode);
60 Function *constructFunction(const Values &inputs,
61 const Values &outputs,
63 BasicBlock *newRootNode, BasicBlock *newHeader,
64 Function *oldFunction, Module *M);
66 void moveCodeToFunction(Function *newFunction);
68 void emitCallAndSwitchStatement(Function *newFunction,
69 BasicBlock *newHeader,
76 void CodeExtractor::findInputsOutputs(Values &inputs, Values &outputs,
77 BasicBlock *newHeader,
78 BasicBlock *newRootNode) {
79 for (std::set<BasicBlock*>::const_iterator ci = BlocksToExtract.begin(),
80 ce = BlocksToExtract.end(); ci != ce; ++ci) {
82 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
83 // If a used value is defined outside the region, it's an input. If an
84 // instruction is used outside the region, it's an output.
85 if (PHINode *PN = dyn_cast<PHINode>(I)) {
86 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
87 Value *V = PN->getIncomingValue(i);
88 if (!BlocksToExtract.count(PN->getIncomingBlock(i)) &&
89 (isa<Instruction>(V) || isa<Argument>(V)))
91 else if (Instruction *opI = dyn_cast<Instruction>(V)) {
92 if (!BlocksToExtract.count(opI->getParent()))
93 inputs.push_back(opI);
94 } else if (isa<Argument>(V))
98 // All other instructions go through the generic input finder
99 // Loop over the operands of each instruction (inputs)
100 for (User::op_iterator op = I->op_begin(), opE = I->op_end();
102 if (Instruction *opI = dyn_cast<Instruction>(*op)) {
103 // Check if definition of this operand is within the loop
104 if (!BlocksToExtract.count(opI->getParent()))
105 inputs.push_back(opI);
106 } else if (isa<Argument>(*op)) {
107 inputs.push_back(*op);
111 // Consider uses of this instruction (outputs)
112 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
114 if (!BlocksToExtract.count(cast<Instruction>(*UI)->getParent())) {
115 outputs.push_back(I);
119 } // for: basic blocks
122 /// constructFunction - make a function based on inputs and outputs, as follows:
123 /// f(in0, ..., inN, out0, ..., outN)
125 Function *CodeExtractor::constructFunction(const Values &inputs,
126 const Values &outputs,
128 BasicBlock *newRootNode,
129 BasicBlock *newHeader,
130 Function *oldFunction,
132 DEBUG(std::cerr << "inputs: " << inputs.size() << "\n");
133 DEBUG(std::cerr << "outputs: " << outputs.size() << "\n");
135 // This function returns unsigned, outputs will go back by reference.
136 Type *retTy = Type::UShortTy;
137 std::vector<const Type*> paramTy;
139 // Add the types of the input values to the function's argument list
140 for (Values::const_iterator i = inputs.begin(),
141 e = inputs.end(); i != e; ++i) {
142 const Value *value = *i;
143 DEBUG(std::cerr << "value used in func: " << value << "\n");
144 paramTy.push_back(value->getType());
147 // Add the types of the output values to the function's argument list.
148 for (Values::const_iterator I = outputs.begin(), E = outputs.end();
150 DEBUG(std::cerr << "instr used in func: " << *I << "\n");
152 paramTy.push_back((*I)->getType());
154 paramTy.push_back(PointerType::get((*I)->getType()));
157 DEBUG(std::cerr << "Function type: " << retTy << " f(");
158 DEBUG(for (std::vector<const Type*>::iterator i = paramTy.begin(),
159 e = paramTy.end(); i != e; ++i) std::cerr << *i << ", ");
160 DEBUG(std::cerr << ")\n");
162 if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
163 PointerType *StructPtr = PointerType::get(StructType::get(paramTy));
165 paramTy.push_back(StructPtr);
167 const FunctionType *funcType = FunctionType::get(retTy, paramTy, false);
169 // Create the new function
170 Function *newFunction = new Function(funcType,
171 GlobalValue::InternalLinkage,
172 oldFunction->getName() + "_code", M);
173 newFunction->getBasicBlockList().push_back(newRootNode);
175 // Create an iterator to name all of the arguments we inserted.
176 Function::aiterator AI = newFunction->abegin();
178 // Rewrite all users of the inputs in the extracted region to use the
179 // arguments (or appropriate addressing into struct) instead.
180 for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
183 std::vector<Value*> Indices;
184 Indices.push_back(Constant::getNullValue(Type::UIntTy));
185 Indices.push_back(ConstantUInt::get(Type::UIntTy, i));
186 std::string GEPname = "gep_" + inputs[i]->getName();
187 TerminatorInst *TI = newFunction->begin()->getTerminator();
188 GetElementPtrInst *GEP = new GetElementPtrInst(AI, Indices, GEPname, TI);
189 RewriteVal = new LoadInst(GEP, "load" + GEPname, TI);
193 std::vector<User*> Users(inputs[i]->use_begin(), inputs[i]->use_end());
194 for (std::vector<User*>::iterator use = Users.begin(), useE = Users.end();
196 if (Instruction* inst = dyn_cast<Instruction>(*use))
197 if (BlocksToExtract.count(inst->getParent()))
198 inst->replaceUsesOfWith(inputs[i], RewriteVal);
201 // Set names for input and output arguments.
202 if (!AggregateArgs) {
203 AI = newFunction->abegin();
204 for (unsigned i = 0, e = inputs.size(); i != e; ++i, ++AI)
205 AI->setName(inputs[i]->getName());
206 for (unsigned i = 0, e = outputs.size(); i != e; ++i, ++AI)
207 AI->setName(outputs[i]->getName()+".out");
210 // Rewrite branches to basic blocks outside of the loop to new dummy blocks
211 // within the new function. This must be done before we lose track of which
212 // blocks were originally in the code region.
213 std::vector<User*> Users(header->use_begin(), header->use_end());
214 for (unsigned i = 0, e = Users.size(); i != e; ++i)
215 // The BasicBlock which contains the branch is not in the region
216 // modify the branch target to a new block
217 if (TerminatorInst *TI = dyn_cast<TerminatorInst>(Users[i]))
218 if (!BlocksToExtract.count(TI->getParent()) &&
219 TI->getParent()->getParent() == oldFunction)
220 TI->replaceUsesOfWith(header, newHeader);
225 void CodeExtractor::moveCodeToFunction(Function *newFunction) {
226 Function *oldFunc = (*BlocksToExtract.begin())->getParent();
227 Function::BasicBlockListType &oldBlocks = oldFunc->getBasicBlockList();
228 Function::BasicBlockListType &newBlocks = newFunction->getBasicBlockList();
230 for (std::set<BasicBlock*>::const_iterator i = BlocksToExtract.begin(),
231 e = BlocksToExtract.end(); i != e; ++i) {
232 // Delete the basic block from the old function, and the list of blocks
233 oldBlocks.remove(*i);
235 // Insert this basic block into the new function
236 newBlocks.push_back(*i);
241 CodeExtractor::emitCallAndSwitchStatement(Function *newFunction,
242 BasicBlock *codeReplacer,
246 // Emit a call to the new function, passing in:
247 // *pointer to struct (if aggregating parameters), or
248 // plan inputs and allocated memory for outputs
249 std::vector<Value*> params, StructValues, ReloadOutputs;
251 // Add inputs as params, or to be filled into the struct
252 for (Values::iterator i = inputs.begin(), e = inputs.end(); i != e; ++i)
254 StructValues.push_back(*i);
256 params.push_back(*i);
258 // Create allocas for the outputs
259 for (Values::iterator i = outputs.begin(), e = outputs.end(); i != e; ++i) {
261 StructValues.push_back(*i);
264 new AllocaInst((*i)->getType(), 0, (*i)->getName()+".loc",
265 codeReplacer->getParent()->begin()->begin());
266 ReloadOutputs.push_back(alloca);
267 params.push_back(alloca);
271 AllocaInst *Struct = 0;
272 if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
273 std::vector<const Type*> ArgTypes;
274 for (Values::iterator v = StructValues.begin(),
275 ve = StructValues.end(); v != ve; ++v)
276 ArgTypes.push_back((*v)->getType());
278 // Allocate a struct at the beginning of this function
279 Type *StructArgTy = StructType::get(ArgTypes);
281 new AllocaInst(StructArgTy, 0, "structArg",
282 codeReplacer->getParent()->begin()->begin());
283 params.push_back(Struct);
285 for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
286 std::vector<Value*> Indices;
287 Indices.push_back(Constant::getNullValue(Type::UIntTy));
288 Indices.push_back(ConstantUInt::get(Type::UIntTy, i));
289 GetElementPtrInst *GEP =
290 new GetElementPtrInst(Struct, Indices,
291 "gep_" + StructValues[i]->getName(), 0);
292 codeReplacer->getInstList().push_back(GEP);
293 StoreInst *SI = new StoreInst(StructValues[i], GEP);
294 codeReplacer->getInstList().push_back(SI);
298 // Emit the call to the function
299 CallInst *call = new CallInst(newFunction, params, "targetBlock");
300 codeReplacer->getInstList().push_back(call);
302 Function::aiterator OutputArgBegin = newFunction->abegin();
303 unsigned FirstOut = inputs.size();
305 std::advance(OutputArgBegin, inputs.size());
307 // Reload the outputs passed in by reference
308 for (unsigned i = 0, e = outputs.size(); i != e; ++i) {
311 std::vector<Value*> Indices;
312 Indices.push_back(Constant::getNullValue(Type::UIntTy));
313 Indices.push_back(ConstantUInt::get(Type::UIntTy, FirstOut + i));
314 GetElementPtrInst *GEP
315 = new GetElementPtrInst(Struct, Indices,
316 "gep_reload_" + outputs[i]->getName(), 0);
317 codeReplacer->getInstList().push_back(GEP);
320 Output = ReloadOutputs[i];
322 LoadInst *load = new LoadInst(Output, outputs[i]->getName()+".reload");
323 codeReplacer->getInstList().push_back(load);
324 std::vector<User*> Users(outputs[i]->use_begin(), outputs[i]->use_end());
325 for (unsigned u = 0, e = Users.size(); u != e; ++u) {
326 Instruction *inst = cast<Instruction>(Users[u]);
327 if (!BlocksToExtract.count(inst->getParent()))
328 inst->replaceUsesOfWith(outputs[i], load);
332 // Now we can emit a switch statement using the call as a value.
333 SwitchInst *TheSwitch = new SwitchInst(call, codeReplacer, codeReplacer);
335 // Since there may be multiple exits from the original region, make the new
336 // function return an unsigned, switch on that number. This loop iterates
337 // over all of the blocks in the extracted region, updating any terminator
338 // instructions in the to-be-extracted region that branch to blocks that are
339 // not in the region to be extracted.
340 std::map<BasicBlock*, BasicBlock*> ExitBlockMap;
342 unsigned switchVal = 0;
343 for (std::set<BasicBlock*>::const_iterator i = BlocksToExtract.begin(),
344 e = BlocksToExtract.end(); i != e; ++i) {
345 TerminatorInst *TI = (*i)->getTerminator();
346 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
347 if (!BlocksToExtract.count(TI->getSuccessor(i))) {
348 BasicBlock *OldTarget = TI->getSuccessor(i);
349 // add a new basic block which returns the appropriate value
350 BasicBlock *&NewTarget = ExitBlockMap[OldTarget];
352 // If we don't already have an exit stub for this non-extracted
353 // destination, create one now!
354 NewTarget = new BasicBlock(OldTarget->getName() + ".exitStub",
357 ConstantUInt *brVal = ConstantUInt::get(Type::UShortTy, switchVal++);
358 ReturnInst *NTRet = new ReturnInst(brVal, NewTarget);
360 // Update the switch instruction.
361 TheSwitch->addCase(brVal, OldTarget);
363 // Restore values just before we exit
364 Function::aiterator OAI = OutputArgBegin;
365 for (unsigned out = 0, e = outputs.size(); out != e; ++out) {
366 // For an invoke, the normal destination is the only one that is
367 // dominated by the result of the invocation
368 BasicBlock *DefBlock = cast<Instruction>(outputs[out])->getParent();
369 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(outputs[out]))
370 DefBlock = Invoke->getNormalDest();
371 if (!DS || DS->dominates(DefBlock, TI->getParent()))
373 std::vector<Value*> Indices;
374 Indices.push_back(Constant::getNullValue(Type::UIntTy));
375 Indices.push_back(ConstantUInt::get(Type::UIntTy,FirstOut+out));
376 GetElementPtrInst *GEP =
377 new GetElementPtrInst(OAI, Indices,
378 "gep_" + outputs[out]->getName(),
380 new StoreInst(outputs[out], GEP, NTRet);
382 new StoreInst(outputs[out], OAI, NTRet);
383 // Advance output iterator even if we don't emit a store
384 if (!AggregateArgs) ++OAI;
388 // rewrite the original branch instruction with this new target
389 TI->setSuccessor(i, NewTarget);
393 // Now that we've done the deed, make the default destination of the switch
394 // instruction be a block with a call to abort() -- since this path should not
395 // be taken, this will abort sooner rather than later.
396 if (TheSwitch->getNumSuccessors() > 1) {
397 Function *container = codeReplacer->getParent();
398 BasicBlock *abortBB = new BasicBlock("abortBlock", container);
399 std::vector<const Type*> paramTypes;
400 FunctionType *abortTy = FunctionType::get(Type::VoidTy, paramTypes, false);
401 Function *abortFunc =
402 container->getParent()->getOrInsertFunction("abort", abortTy);
403 abortBB->getInstList().push_back(new CallInst(abortFunc));
404 Function *ParentFunc = TheSwitch->getParent()->getParent();
405 if (ParentFunc->getReturnType() == Type::VoidTy)
406 new ReturnInst(0, abortBB);
408 new ReturnInst(Constant::getNullValue(ParentFunc->getReturnType()),
410 TheSwitch->setSuccessor(0, abortBB);
412 // There is only 1 successor (the block containing the switch itself), which
413 // means that previously this was the last part of the function, and hence
414 // this should be rewritten as a `ret'
416 // Check if the function should return a value
417 if (TheSwitch->getParent()->getParent()->getReturnType() != Type::VoidTy &&
418 TheSwitch->getParent()->getParent()->getReturnType() ==
419 TheSwitch->getCondition()->getType())
420 // return what we have
421 new ReturnInst(TheSwitch->getCondition(), TheSwitch);
424 new ReturnInst(0, TheSwitch);
426 TheSwitch->getParent()->getInstList().erase(TheSwitch);
431 /// ExtractRegion - Removes a loop from a function, replaces it with a call to
432 /// new function. Returns pointer to the new function.
436 /// find inputs and outputs for the region
438 /// for inputs: add to function as args, map input instr* to arg#
439 /// for outputs: add allocas for scalars,
440 /// add to func as args, map output instr* to arg#
442 /// rewrite func to use argument #s instead of instr*
444 /// for each scalar output in the function: at every exit, store intermediate
445 /// computed result back into memory.
447 Function *CodeExtractor::ExtractCodeRegion(const std::vector<BasicBlock*> &code)
449 if (!isEligible(code))
452 // 1) Find inputs, outputs
453 // 2) Construct new function
454 // * Add allocas for defs, pass as args by reference
455 // * Pass in uses as args
456 // 3) Move code region, add call instr to func
458 BlocksToExtract.insert(code.begin(), code.end());
460 Values inputs, outputs;
462 // Assumption: this is a single-entry code region, and the header is the first
463 // block in the region.
464 BasicBlock *header = code[0];
465 for (unsigned i = 1, e = code.size(); i != e; ++i)
466 for (pred_iterator PI = pred_begin(code[i]), E = pred_end(code[i]);
468 assert(BlocksToExtract.count(*PI) &&
469 "No blocks in this region may have entries from outside the region"
470 " except for the first block!");
472 Function *oldFunction = header->getParent();
474 // This takes place of the original loop
475 BasicBlock *codeReplacer = new BasicBlock("codeRepl", oldFunction);
477 // The new function needs a root node because other nodes can branch to the
478 // head of the loop, and the root cannot have predecessors
479 BasicBlock *newFuncRoot = new BasicBlock("newFuncRoot");
480 newFuncRoot->getInstList().push_back(new BranchInst(header));
482 // Find inputs to, outputs from the code region
484 // If one of the inputs is coming from a different basic block and it's in a
485 // phi node, we need to rewrite the phi node:
487 // * All the inputs which involve basic blocks OUTSIDE of this region go into
488 // a NEW phi node that takes care of finding which value really came in.
489 // The result of this phi is passed to the function as an argument.
491 // * All the other phi values stay.
493 // FIXME: PHI nodes' incoming blocks aren't being rewritten to accomodate for
494 // blocks moving to a new function.
495 // SOLUTION: move Phi nodes out of the loop header into the codeReplacer, pass
496 // the values as parameters to the function
497 findInputsOutputs(inputs, outputs, codeReplacer, newFuncRoot);
499 // Step 2: Construct new function based on inputs/outputs,
500 // Add allocas for all defs
501 Function *newFunction = constructFunction(inputs, outputs, code[0],
503 codeReplacer, oldFunction,
504 oldFunction->getParent());
506 emitCallAndSwitchStatement(newFunction, codeReplacer, inputs, outputs);
508 moveCodeToFunction(newFunction);
510 // Loop over all of the PHI nodes in the entry block (code[0]), and change any
511 // references to the old incoming edge to be the new incoming edge.
512 for (BasicBlock::iterator I = code[0]->begin();
513 PHINode *PN = dyn_cast<PHINode>(I); ++I)
514 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
515 if (!BlocksToExtract.count(PN->getIncomingBlock(i)))
516 PN->setIncomingBlock(i, newFuncRoot);
518 // Look at all successors of the codeReplacer block. If any of these blocks
519 // had PHI nodes in them, we need to update the "from" block to be the code
520 // replacer, not the original block in the extracted region.
521 std::vector<BasicBlock*> Succs(succ_begin(codeReplacer),
522 succ_end(codeReplacer));
523 for (unsigned i = 0, e = Succs.size(); i != e; ++i)
524 for (BasicBlock::iterator I = Succs[i]->begin();
525 PHINode *PN = dyn_cast<PHINode>(I); ++I)
526 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
527 if (BlocksToExtract.count(PN->getIncomingBlock(i)))
528 PN->setIncomingBlock(i, codeReplacer);
531 DEBUG(if (verifyFunction(*newFunction)) abort());
535 bool CodeExtractor::isEligible(const std::vector<BasicBlock*> &code) {
536 // Deny code region if it contains allocas
537 for (std::vector<BasicBlock*>::const_iterator BB = code.begin(), e=code.end();
539 for (BasicBlock::const_iterator I = (*BB)->begin(), Ie = (*BB)->end();
541 if (isa<AllocaInst>(*I))
547 /// ExtractCodeRegion - slurp a sequence of basic blocks into a brand new
550 Function* llvm::ExtractCodeRegion(DominatorSet &DS,
551 const std::vector<BasicBlock*> &code,
552 bool AggregateArgs) {
553 return CodeExtractor(&DS, AggregateArgs).ExtractCodeRegion(code);
556 /// ExtractBasicBlock - slurp a natural loop into a brand new function
558 Function* llvm::ExtractLoop(DominatorSet &DS, Loop *L, bool AggregateArgs) {
559 return CodeExtractor(&DS, AggregateArgs).ExtractCodeRegion(L->getBlocks());
562 /// ExtractBasicBlock - slurp a basic block into a brand new function
564 Function* llvm::ExtractBasicBlock(BasicBlock *BB, bool AggregateArgs) {
565 std::vector<BasicBlock*> Blocks;
566 Blocks.push_back(BB);
567 return CodeExtractor(0, AggregateArgs).ExtractCodeRegion(Blocks);