1 //===- CodeExtractor.cpp - Pull code region into a new function -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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/CodeExtractor.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Intrinsics.h"
21 #include "llvm/LLVMContext.h"
22 #include "llvm/Module.h"
23 #include "llvm/Pass.h"
24 #include "llvm/Analysis/Dominators.h"
25 #include "llvm/Analysis/LoopInfo.h"
26 #include "llvm/Analysis/Verifier.h"
27 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/ADT/SetVector.h"
33 #include "llvm/ADT/StringExtras.h"
38 // Provide a command-line option to aggregate function arguments into a struct
39 // for functions produced by the code extractor. This is useful when converting
40 // extracted functions to pthread-based code, as only one argument (void*) can
41 // be passed in to pthread_create().
43 AggregateArgsOpt("aggregate-extracted-args", cl::Hidden,
44 cl::desc("Aggregate arguments to code-extracted functions"));
46 /// \brief Test whether a block is valid for extraction.
47 static bool isBlockValidForExtraction(const BasicBlock &BB) {
48 // Landing pads must be in the function where they were inserted for cleanup.
49 if (BB.isLandingPad())
52 // Don't hoist code containing allocas, invokes, or vastarts.
53 for (BasicBlock::const_iterator I = BB.begin(), E = BB.end(); I != E; ++I) {
54 if (isa<AllocaInst>(I) || isa<InvokeInst>(I))
56 if (const CallInst *CI = dyn_cast<CallInst>(I))
57 if (const Function *F = CI->getCalledFunction())
58 if (F->getIntrinsicID() == Intrinsic::vastart)
65 /// \brief Build a set of blocks to extract if the input blocks are viable.
66 static SetVector<BasicBlock *>
67 buildExtractionBlockSet(ArrayRef<BasicBlock *> BBs) {
68 SetVector<BasicBlock *> Result;
72 // Loop over the blocks, adding them to our set-vector, and aborting with an
73 // empty set if we encounter invalid blocks.
74 for (ArrayRef<BasicBlock *>::iterator I = BBs.begin(), E = BBs.end();
76 if (!Result.insert(*I))
77 llvm_unreachable("Repeated basic blocks in extraction input");
79 if (!isBlockValidForExtraction(**I)) {
86 for (ArrayRef<BasicBlock *>::iterator I = llvm::next(BBs.begin()),
89 for (pred_iterator PI = pred_begin(*I), PE = pred_end(*I);
91 assert(Result.count(*PI) &&
92 "No blocks in this region may have entries from outside the region"
93 " except for the first block!");
99 CodeExtractor::CodeExtractor(BasicBlock *BB, bool AggregateArgs)
100 : DT(0), AggregateArgs(AggregateArgs||AggregateArgsOpt),
101 Blocks(buildExtractionBlockSet(BB)), NumExitBlocks(~0U) {}
103 CodeExtractor::CodeExtractor(ArrayRef<BasicBlock *> BBs, DominatorTree *DT,
105 : DT(DT), AggregateArgs(AggregateArgs||AggregateArgsOpt),
106 Blocks(buildExtractionBlockSet(BBs)), NumExitBlocks(~0U) {}
108 CodeExtractor::CodeExtractor(DominatorTree &DT, Loop &L, bool AggregateArgs)
109 : DT(&DT), AggregateArgs(AggregateArgs||AggregateArgsOpt),
110 Blocks(buildExtractionBlockSet(L.getBlocks())), NumExitBlocks(~0U) {}
113 /// definedInRegion - Return true if the specified value is defined in the
114 /// extracted region.
115 static bool definedInRegion(const SetVector<BasicBlock *> &Blocks, Value *V) {
116 if (Instruction *I = dyn_cast<Instruction>(V))
117 if (Blocks.count(I->getParent()))
122 /// definedInCaller - Return true if the specified value is defined in the
123 /// function being code extracted, but not in the region being extracted.
124 /// These values must be passed in as live-ins to the function.
125 static bool definedInCaller(const SetVector<BasicBlock *> &Blocks, Value *V) {
126 if (isa<Argument>(V)) return true;
127 if (Instruction *I = dyn_cast<Instruction>(V))
128 if (!Blocks.count(I->getParent()))
133 /// severSplitPHINodes - If a PHI node has multiple inputs from outside of the
134 /// region, we need to split the entry block of the region so that the PHI node
135 /// is easier to deal with.
136 void CodeExtractor::severSplitPHINodes(BasicBlock *&Header) {
137 unsigned NumPredsFromRegion = 0;
138 unsigned NumPredsOutsideRegion = 0;
140 if (Header != &Header->getParent()->getEntryBlock()) {
141 PHINode *PN = dyn_cast<PHINode>(Header->begin());
142 if (!PN) return; // No PHI nodes.
144 // If the header node contains any PHI nodes, check to see if there is more
145 // than one entry from outside the region. If so, we need to sever the
146 // header block into two.
147 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
148 if (Blocks.count(PN->getIncomingBlock(i)))
149 ++NumPredsFromRegion;
151 ++NumPredsOutsideRegion;
153 // If there is one (or fewer) predecessor from outside the region, we don't
154 // need to do anything special.
155 if (NumPredsOutsideRegion <= 1) return;
158 // Otherwise, we need to split the header block into two pieces: one
159 // containing PHI nodes merging values from outside of the region, and a
160 // second that contains all of the code for the block and merges back any
161 // incoming values from inside of the region.
162 BasicBlock::iterator AfterPHIs = Header->getFirstNonPHI();
163 BasicBlock *NewBB = Header->splitBasicBlock(AfterPHIs,
164 Header->getName()+".ce");
166 // We only want to code extract the second block now, and it becomes the new
167 // header of the region.
168 BasicBlock *OldPred = Header;
169 Blocks.remove(OldPred);
170 Blocks.insert(NewBB);
173 // Okay, update dominator sets. The blocks that dominate the new one are the
174 // blocks that dominate TIBB plus the new block itself.
176 DT->splitBlock(NewBB);
178 // Okay, now we need to adjust the PHI nodes and any branches from within the
179 // region to go to the new header block instead of the old header block.
180 if (NumPredsFromRegion) {
181 PHINode *PN = cast<PHINode>(OldPred->begin());
182 // Loop over all of the predecessors of OldPred that are in the region,
183 // changing them to branch to NewBB instead.
184 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
185 if (Blocks.count(PN->getIncomingBlock(i))) {
186 TerminatorInst *TI = PN->getIncomingBlock(i)->getTerminator();
187 TI->replaceUsesOfWith(OldPred, NewBB);
190 // Okay, everything within the region is now branching to the right block, we
191 // just have to update the PHI nodes now, inserting PHI nodes into NewBB.
192 for (AfterPHIs = OldPred->begin(); isa<PHINode>(AfterPHIs); ++AfterPHIs) {
193 PHINode *PN = cast<PHINode>(AfterPHIs);
194 // Create a new PHI node in the new region, which has an incoming value
195 // from OldPred of PN.
196 PHINode *NewPN = PHINode::Create(PN->getType(), 1 + NumPredsFromRegion,
197 PN->getName()+".ce", NewBB->begin());
198 NewPN->addIncoming(PN, OldPred);
200 // Loop over all of the incoming value in PN, moving them to NewPN if they
201 // are from the extracted region.
202 for (unsigned i = 0; i != PN->getNumIncomingValues(); ++i) {
203 if (Blocks.count(PN->getIncomingBlock(i))) {
204 NewPN->addIncoming(PN->getIncomingValue(i), PN->getIncomingBlock(i));
205 PN->removeIncomingValue(i);
213 void CodeExtractor::splitReturnBlocks() {
214 for (SetVector<BasicBlock *>::iterator I = Blocks.begin(), E = Blocks.end();
216 if (ReturnInst *RI = dyn_cast<ReturnInst>((*I)->getTerminator())) {
217 BasicBlock *New = (*I)->splitBasicBlock(RI, (*I)->getName()+".ret");
219 // Old dominates New. New node dominates all other nodes dominated
221 DomTreeNode *OldNode = DT->getNode(*I);
222 SmallVector<DomTreeNode*, 8> Children;
223 for (DomTreeNode::iterator DI = OldNode->begin(), DE = OldNode->end();
225 Children.push_back(*DI);
227 DomTreeNode *NewNode = DT->addNewBlock(New, *I);
229 for (SmallVector<DomTreeNode*, 8>::iterator I = Children.begin(),
230 E = Children.end(); I != E; ++I)
231 DT->changeImmediateDominator(*I, NewNode);
236 // findInputsOutputs - Find inputs to, outputs from the code region.
238 void CodeExtractor::findInputsOutputs(ValueSet &inputs, ValueSet &outputs) {
239 std::set<BasicBlock*> ExitBlocks;
240 for (SetVector<BasicBlock*>::const_iterator ci = Blocks.begin(),
241 ce = Blocks.end(); ci != ce; ++ci) {
242 BasicBlock *BB = *ci;
244 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
245 // If a used value is defined outside the region, it's an input. If an
246 // instruction is used outside the region, it's an output.
247 for (User::op_iterator O = I->op_begin(), E = I->op_end(); O != E; ++O)
248 if (definedInCaller(Blocks, *O))
251 // Consider uses of this instruction (outputs).
252 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
254 if (!definedInRegion(Blocks, *UI)) {
260 // Keep track of the exit blocks from the region.
261 TerminatorInst *TI = BB->getTerminator();
262 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
263 if (!Blocks.count(TI->getSuccessor(i)))
264 ExitBlocks.insert(TI->getSuccessor(i));
265 } // for: basic blocks
267 NumExitBlocks = ExitBlocks.size();
270 /// constructFunction - make a function based on inputs and outputs, as follows:
271 /// f(in0, ..., inN, out0, ..., outN)
273 Function *CodeExtractor::constructFunction(const ValueSet &inputs,
274 const ValueSet &outputs,
276 BasicBlock *newRootNode,
277 BasicBlock *newHeader,
278 Function *oldFunction,
280 DEBUG(dbgs() << "inputs: " << inputs.size() << "\n");
281 DEBUG(dbgs() << "outputs: " << outputs.size() << "\n");
283 // This function returns unsigned, outputs will go back by reference.
284 switch (NumExitBlocks) {
286 case 1: RetTy = Type::getVoidTy(header->getContext()); break;
287 case 2: RetTy = Type::getInt1Ty(header->getContext()); break;
288 default: RetTy = Type::getInt16Ty(header->getContext()); break;
291 std::vector<Type*> paramTy;
293 // Add the types of the input values to the function's argument list
294 for (ValueSet::const_iterator i = inputs.begin(), e = inputs.end();
296 const Value *value = *i;
297 DEBUG(dbgs() << "value used in func: " << *value << "\n");
298 paramTy.push_back(value->getType());
301 // Add the types of the output values to the function's argument list.
302 for (ValueSet::const_iterator I = outputs.begin(), E = outputs.end();
304 DEBUG(dbgs() << "instr used in func: " << **I << "\n");
306 paramTy.push_back((*I)->getType());
308 paramTy.push_back(PointerType::getUnqual((*I)->getType()));
311 DEBUG(dbgs() << "Function type: " << *RetTy << " f(");
312 for (std::vector<Type*>::iterator i = paramTy.begin(),
313 e = paramTy.end(); i != e; ++i)
314 DEBUG(dbgs() << **i << ", ");
315 DEBUG(dbgs() << ")\n");
317 if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
318 PointerType *StructPtr =
319 PointerType::getUnqual(StructType::get(M->getContext(), paramTy));
321 paramTy.push_back(StructPtr);
323 FunctionType *funcType =
324 FunctionType::get(RetTy, paramTy, false);
326 // Create the new function
327 Function *newFunction = Function::Create(funcType,
328 GlobalValue::InternalLinkage,
329 oldFunction->getName() + "_" +
330 header->getName(), M);
331 // If the old function is no-throw, so is the new one.
332 if (oldFunction->doesNotThrow())
333 newFunction->setDoesNotThrow(true);
335 newFunction->getBasicBlockList().push_back(newRootNode);
337 // Create an iterator to name all of the arguments we inserted.
338 Function::arg_iterator AI = newFunction->arg_begin();
340 // Rewrite all users of the inputs in the extracted region to use the
341 // arguments (or appropriate addressing into struct) instead.
342 for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
346 Idx[0] = Constant::getNullValue(Type::getInt32Ty(header->getContext()));
347 Idx[1] = ConstantInt::get(Type::getInt32Ty(header->getContext()), i);
348 TerminatorInst *TI = newFunction->begin()->getTerminator();
349 GetElementPtrInst *GEP =
350 GetElementPtrInst::Create(AI, Idx, "gep_" + inputs[i]->getName(), TI);
351 RewriteVal = new LoadInst(GEP, "loadgep_" + inputs[i]->getName(), TI);
355 std::vector<User*> Users(inputs[i]->use_begin(), inputs[i]->use_end());
356 for (std::vector<User*>::iterator use = Users.begin(), useE = Users.end();
358 if (Instruction* inst = dyn_cast<Instruction>(*use))
359 if (Blocks.count(inst->getParent()))
360 inst->replaceUsesOfWith(inputs[i], RewriteVal);
363 // Set names for input and output arguments.
364 if (!AggregateArgs) {
365 AI = newFunction->arg_begin();
366 for (unsigned i = 0, e = inputs.size(); i != e; ++i, ++AI)
367 AI->setName(inputs[i]->getName());
368 for (unsigned i = 0, e = outputs.size(); i != e; ++i, ++AI)
369 AI->setName(outputs[i]->getName()+".out");
372 // Rewrite branches to basic blocks outside of the loop to new dummy blocks
373 // within the new function. This must be done before we lose track of which
374 // blocks were originally in the code region.
375 std::vector<User*> Users(header->use_begin(), header->use_end());
376 for (unsigned i = 0, e = Users.size(); i != e; ++i)
377 // The BasicBlock which contains the branch is not in the region
378 // modify the branch target to a new block
379 if (TerminatorInst *TI = dyn_cast<TerminatorInst>(Users[i]))
380 if (!Blocks.count(TI->getParent()) &&
381 TI->getParent()->getParent() == oldFunction)
382 TI->replaceUsesOfWith(header, newHeader);
387 /// FindPhiPredForUseInBlock - Given a value and a basic block, find a PHI
388 /// that uses the value within the basic block, and return the predecessor
389 /// block associated with that use, or return 0 if none is found.
390 static BasicBlock* FindPhiPredForUseInBlock(Value* Used, BasicBlock* BB) {
391 for (Value::use_iterator UI = Used->use_begin(),
392 UE = Used->use_end(); UI != UE; ++UI) {
393 PHINode *P = dyn_cast<PHINode>(*UI);
394 if (P && P->getParent() == BB)
395 return P->getIncomingBlock(UI);
401 /// emitCallAndSwitchStatement - This method sets up the caller side by adding
402 /// the call instruction, splitting any PHI nodes in the header block as
405 emitCallAndSwitchStatement(Function *newFunction, BasicBlock *codeReplacer,
406 ValueSet &inputs, ValueSet &outputs) {
407 // Emit a call to the new function, passing in: *pointer to struct (if
408 // aggregating parameters), or plan inputs and allocated memory for outputs
409 std::vector<Value*> params, StructValues, ReloadOutputs, Reloads;
411 LLVMContext &Context = newFunction->getContext();
413 // Add inputs as params, or to be filled into the struct
414 for (ValueSet::iterator i = inputs.begin(), e = inputs.end(); i != e; ++i)
416 StructValues.push_back(*i);
418 params.push_back(*i);
420 // Create allocas for the outputs
421 for (ValueSet::iterator i = outputs.begin(), e = outputs.end(); i != e; ++i) {
423 StructValues.push_back(*i);
426 new AllocaInst((*i)->getType(), 0, (*i)->getName()+".loc",
427 codeReplacer->getParent()->begin()->begin());
428 ReloadOutputs.push_back(alloca);
429 params.push_back(alloca);
433 AllocaInst *Struct = 0;
434 if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
435 std::vector<Type*> ArgTypes;
436 for (ValueSet::iterator v = StructValues.begin(),
437 ve = StructValues.end(); v != ve; ++v)
438 ArgTypes.push_back((*v)->getType());
440 // Allocate a struct at the beginning of this function
441 Type *StructArgTy = StructType::get(newFunction->getContext(), ArgTypes);
443 new AllocaInst(StructArgTy, 0, "structArg",
444 codeReplacer->getParent()->begin()->begin());
445 params.push_back(Struct);
447 for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
449 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
450 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), i);
451 GetElementPtrInst *GEP =
452 GetElementPtrInst::Create(Struct, Idx,
453 "gep_" + StructValues[i]->getName());
454 codeReplacer->getInstList().push_back(GEP);
455 StoreInst *SI = new StoreInst(StructValues[i], GEP);
456 codeReplacer->getInstList().push_back(SI);
460 // Emit the call to the function
461 CallInst *call = CallInst::Create(newFunction, params,
462 NumExitBlocks > 1 ? "targetBlock" : "");
463 codeReplacer->getInstList().push_back(call);
465 Function::arg_iterator OutputArgBegin = newFunction->arg_begin();
466 unsigned FirstOut = inputs.size();
468 std::advance(OutputArgBegin, inputs.size());
470 // Reload the outputs passed in by reference
471 for (unsigned i = 0, e = outputs.size(); i != e; ++i) {
475 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
476 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), FirstOut + i);
477 GetElementPtrInst *GEP
478 = GetElementPtrInst::Create(Struct, Idx,
479 "gep_reload_" + outputs[i]->getName());
480 codeReplacer->getInstList().push_back(GEP);
483 Output = ReloadOutputs[i];
485 LoadInst *load = new LoadInst(Output, outputs[i]->getName()+".reload");
486 Reloads.push_back(load);
487 codeReplacer->getInstList().push_back(load);
488 std::vector<User*> Users(outputs[i]->use_begin(), outputs[i]->use_end());
489 for (unsigned u = 0, e = Users.size(); u != e; ++u) {
490 Instruction *inst = cast<Instruction>(Users[u]);
491 if (!Blocks.count(inst->getParent()))
492 inst->replaceUsesOfWith(outputs[i], load);
496 // Now we can emit a switch statement using the call as a value.
497 SwitchInst *TheSwitch =
498 SwitchInst::Create(Constant::getNullValue(Type::getInt16Ty(Context)),
499 codeReplacer, 0, codeReplacer);
501 // Since there may be multiple exits from the original region, make the new
502 // function return an unsigned, switch on that number. This loop iterates
503 // over all of the blocks in the extracted region, updating any terminator
504 // instructions in the to-be-extracted region that branch to blocks that are
505 // not in the region to be extracted.
506 std::map<BasicBlock*, BasicBlock*> ExitBlockMap;
508 unsigned switchVal = 0;
509 for (SetVector<BasicBlock*>::const_iterator i = Blocks.begin(),
510 e = Blocks.end(); i != e; ++i) {
511 TerminatorInst *TI = (*i)->getTerminator();
512 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
513 if (!Blocks.count(TI->getSuccessor(i))) {
514 BasicBlock *OldTarget = TI->getSuccessor(i);
515 // add a new basic block which returns the appropriate value
516 BasicBlock *&NewTarget = ExitBlockMap[OldTarget];
518 // If we don't already have an exit stub for this non-extracted
519 // destination, create one now!
520 NewTarget = BasicBlock::Create(Context,
521 OldTarget->getName() + ".exitStub",
523 unsigned SuccNum = switchVal++;
526 switch (NumExitBlocks) {
528 case 1: break; // No value needed.
529 case 2: // Conditional branch, return a bool
530 brVal = ConstantInt::get(Type::getInt1Ty(Context), !SuccNum);
533 brVal = ConstantInt::get(Type::getInt16Ty(Context), SuccNum);
537 ReturnInst *NTRet = ReturnInst::Create(Context, brVal, NewTarget);
539 // Update the switch instruction.
540 TheSwitch->addCase(ConstantInt::get(Type::getInt16Ty(Context),
544 // Restore values just before we exit
545 Function::arg_iterator OAI = OutputArgBegin;
546 for (unsigned out = 0, e = outputs.size(); out != e; ++out) {
547 // For an invoke, the normal destination is the only one that is
548 // dominated by the result of the invocation
549 BasicBlock *DefBlock = cast<Instruction>(outputs[out])->getParent();
551 bool DominatesDef = true;
553 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(outputs[out])) {
554 DefBlock = Invoke->getNormalDest();
556 // Make sure we are looking at the original successor block, not
557 // at a newly inserted exit block, which won't be in the dominator
559 for (std::map<BasicBlock*, BasicBlock*>::iterator I =
560 ExitBlockMap.begin(), E = ExitBlockMap.end(); I != E; ++I)
561 if (DefBlock == I->second) {
566 // In the extract block case, if the block we are extracting ends
567 // with an invoke instruction, make sure that we don't emit a
568 // store of the invoke value for the unwind block.
569 if (!DT && DefBlock != OldTarget)
570 DominatesDef = false;
574 DominatesDef = DT->dominates(DefBlock, OldTarget);
576 // If the output value is used by a phi in the target block,
577 // then we need to test for dominance of the phi's predecessor
578 // instead. Unfortunately, this a little complicated since we
579 // have already rewritten uses of the value to uses of the reload.
580 BasicBlock* pred = FindPhiPredForUseInBlock(Reloads[out],
582 if (pred && DT && DT->dominates(DefBlock, pred))
589 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
590 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context),
592 GetElementPtrInst *GEP =
593 GetElementPtrInst::Create(OAI, Idx,
594 "gep_" + outputs[out]->getName(),
596 new StoreInst(outputs[out], GEP, NTRet);
598 new StoreInst(outputs[out], OAI, NTRet);
601 // Advance output iterator even if we don't emit a store
602 if (!AggregateArgs) ++OAI;
606 // rewrite the original branch instruction with this new target
607 TI->setSuccessor(i, NewTarget);
611 // Now that we've done the deed, simplify the switch instruction.
612 Type *OldFnRetTy = TheSwitch->getParent()->getParent()->getReturnType();
613 switch (NumExitBlocks) {
615 // There are no successors (the block containing the switch itself), which
616 // means that previously this was the last part of the function, and hence
617 // this should be rewritten as a `ret'
619 // Check if the function should return a value
620 if (OldFnRetTy->isVoidTy()) {
621 ReturnInst::Create(Context, 0, TheSwitch); // Return void
622 } else if (OldFnRetTy == TheSwitch->getCondition()->getType()) {
623 // return what we have
624 ReturnInst::Create(Context, TheSwitch->getCondition(), TheSwitch);
626 // Otherwise we must have code extracted an unwind or something, just
627 // return whatever we want.
628 ReturnInst::Create(Context,
629 Constant::getNullValue(OldFnRetTy), TheSwitch);
632 TheSwitch->eraseFromParent();
635 // Only a single destination, change the switch into an unconditional
637 BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch);
638 TheSwitch->eraseFromParent();
641 BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch->getSuccessor(2),
643 TheSwitch->eraseFromParent();
646 // Otherwise, make the default destination of the switch instruction be one
647 // of the other successors.
648 TheSwitch->setCondition(call);
649 TheSwitch->setDefaultDest(TheSwitch->getSuccessor(NumExitBlocks));
650 // Remove redundant case
651 TheSwitch->removeCase(SwitchInst::CaseIt(TheSwitch, NumExitBlocks-1));
656 void CodeExtractor::moveCodeToFunction(Function *newFunction) {
657 Function *oldFunc = (*Blocks.begin())->getParent();
658 Function::BasicBlockListType &oldBlocks = oldFunc->getBasicBlockList();
659 Function::BasicBlockListType &newBlocks = newFunction->getBasicBlockList();
661 for (SetVector<BasicBlock*>::const_iterator i = Blocks.begin(),
662 e = Blocks.end(); i != e; ++i) {
663 // Delete the basic block from the old function, and the list of blocks
664 oldBlocks.remove(*i);
666 // Insert this basic block into the new function
667 newBlocks.push_back(*i);
671 Function *CodeExtractor::extractCodeRegion() {
675 ValueSet inputs, outputs;
677 // Assumption: this is a single-entry code region, and the header is the first
678 // block in the region.
679 BasicBlock *header = *Blocks.begin();
681 // If we have to split PHI nodes or the entry block, do so now.
682 severSplitPHINodes(header);
684 // If we have any return instructions in the region, split those blocks so
685 // that the return is not in the region.
688 Function *oldFunction = header->getParent();
690 // This takes place of the original loop
691 BasicBlock *codeReplacer = BasicBlock::Create(header->getContext(),
692 "codeRepl", oldFunction,
695 // The new function needs a root node because other nodes can branch to the
696 // head of the region, but the entry node of a function cannot have preds.
697 BasicBlock *newFuncRoot = BasicBlock::Create(header->getContext(),
699 newFuncRoot->getInstList().push_back(BranchInst::Create(header));
701 // Find inputs to, outputs from the code region.
702 findInputsOutputs(inputs, outputs);
704 // Construct new function based on inputs/outputs & add allocas for all defs.
705 Function *newFunction = constructFunction(inputs, outputs, header,
707 codeReplacer, oldFunction,
708 oldFunction->getParent());
710 emitCallAndSwitchStatement(newFunction, codeReplacer, inputs, outputs);
712 moveCodeToFunction(newFunction);
714 // Loop over all of the PHI nodes in the header block, and change any
715 // references to the old incoming edge to be the new incoming edge.
716 for (BasicBlock::iterator I = header->begin(); isa<PHINode>(I); ++I) {
717 PHINode *PN = cast<PHINode>(I);
718 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
719 if (!Blocks.count(PN->getIncomingBlock(i)))
720 PN->setIncomingBlock(i, newFuncRoot);
723 // Look at all successors of the codeReplacer block. If any of these blocks
724 // had PHI nodes in them, we need to update the "from" block to be the code
725 // replacer, not the original block in the extracted region.
726 std::vector<BasicBlock*> Succs(succ_begin(codeReplacer),
727 succ_end(codeReplacer));
728 for (unsigned i = 0, e = Succs.size(); i != e; ++i)
729 for (BasicBlock::iterator I = Succs[i]->begin(); isa<PHINode>(I); ++I) {
730 PHINode *PN = cast<PHINode>(I);
731 std::set<BasicBlock*> ProcessedPreds;
732 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
733 if (Blocks.count(PN->getIncomingBlock(i))) {
734 if (ProcessedPreds.insert(PN->getIncomingBlock(i)).second)
735 PN->setIncomingBlock(i, codeReplacer);
737 // There were multiple entries in the PHI for this block, now there
738 // is only one, so remove the duplicated entries.
739 PN->removeIncomingValue(i, false);
745 //cerr << "NEW FUNCTION: " << *newFunction;
746 // verifyFunction(*newFunction);
748 // cerr << "OLD FUNCTION: " << *oldFunction;
749 // verifyFunction(*oldFunction);
751 DEBUG(if (verifyFunction(*newFunction))
752 report_fatal_error("verifyFunction failed!"));