blob: 3d08a5dffc5fb3dfb1e31c9c950d49b234a95949 [file] [log] [blame]
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001//===- CodeExtractor.cpp - Pull code region into a new function -----------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00008//===----------------------------------------------------------------------===//
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
Chandler Carruth0fde0012012-05-04 10:18:49 +000016#include "llvm/Transforms/Utils/CodeExtractor.h"
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000017#include "llvm/Constants.h"
18#include "llvm/DerivedTypes.h"
19#include "llvm/Instructions.h"
Chris Lattner3b2917b2004-05-12 06:01:40 +000020#include "llvm/Intrinsics.h"
Owen Andersone70b6372009-07-05 22:41:43 +000021#include "llvm/LLVMContext.h"
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000022#include "llvm/Module.h"
23#include "llvm/Pass.h"
Chris Lattner37de2572004-03-18 03:49:40 +000024#include "llvm/Analysis/Dominators.h"
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000025#include "llvm/Analysis/LoopInfo.h"
Chris Lattner36844692004-03-14 03:17:22 +000026#include "llvm/Analysis/Verifier.h"
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000027#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000028#include "llvm/Support/CommandLine.h"
29#include "llvm/Support/Debug.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000030#include "llvm/Support/ErrorHandling.h"
Chris Lattnerb25de3f2009-08-23 04:37:46 +000031#include "llvm/Support/raw_ostream.h"
Julien Lerougef50a3f12010-01-09 01:06:49 +000032#include "llvm/ADT/SetVector.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000033#include "llvm/ADT/StringExtras.h"
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000034#include <algorithm>
Chris Lattner9c431f62004-03-14 22:34:55 +000035#include <set>
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000036using namespace llvm;
37
Misha Brukman3596f0a2004-04-23 23:54:17 +000038// Provide a command-line option to aggregate function arguments into a struct
Misha Brukman234b44a2008-12-13 05:21:37 +000039// for functions produced by the code extractor. This is useful when converting
Misha Brukman3596f0a2004-04-23 23:54:17 +000040// extracted functions to pthread-based code, as only one argument (void*) can
41// be passed in to pthread_create().
42static cl::opt<bool>
43AggregateArgsOpt("aggregate-extracted-args", cl::Hidden,
44 cl::desc("Aggregate arguments to code-extracted functions"));
45
Chandler Carruth0fde0012012-05-04 10:18:49 +000046/// \brief Test whether a block is valid for extraction.
47static bool isBlockValidForExtraction(const BasicBlock &BB) {
48 // Landing pads must be in the function where they were inserted for cleanup.
49 if (BB.isLandingPad())
50 return false;
Chris Lattner37de2572004-03-18 03:49:40 +000051
Chandler Carruth0fde0012012-05-04 10:18:49 +000052 // 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))
Chris Lattner3b2917b2004-05-12 06:01:40 +000055 return false;
Chandler Carruth0fde0012012-05-04 10:18:49 +000056 if (const CallInst *CI = dyn_cast<CallInst>(I))
57 if (const Function *F = CI->getCalledFunction())
58 if (F->getIntrinsicID() == Intrinsic::vastart)
59 return false;
60 }
61
62 return true;
63}
64
65/// \brief Build a set of blocks to extract if the input blocks are viable.
66static SetVector<BasicBlock *>
67buildExtractionBlockSet(ArrayRef<BasicBlock *> BBs) {
68 SetVector<BasicBlock *> Result;
69
Chandler Carruth2f5d0192012-05-04 10:26:45 +000070 assert(!BBs.empty());
71
Chandler Carruth0fde0012012-05-04 10:18:49 +000072 // 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();
75 I != E; ++I) {
76 if (!Result.insert(*I))
77 continue;
78
79 if (!isBlockValidForExtraction(**I)) {
80 Result.clear();
81 break;
Chris Lattner3b2917b2004-05-12 06:01:40 +000082 }
Chandler Carruth0fde0012012-05-04 10:18:49 +000083 }
Misha Brukmanb1c93172005-04-21 23:48:37 +000084
Chandler Carruth2f5d0192012-05-04 10:26:45 +000085#ifndef NDEBUG
86 for (ArrayRef<BasicBlock *>::iterator I = llvm::next(BBs.begin()),
87 E = BBs.end();
88 I != E; ++I)
89 for (pred_iterator PI = pred_begin(*I), PE = pred_end(*I);
90 PI != PE; ++PI)
91 assert(Result.count(*PI) &&
92 "No blocks in this region may have entries from outside the region"
93 " except for the first block!");
94#endif
95
Chandler Carruth0fde0012012-05-04 10:18:49 +000096 return Result;
97}
Chris Lattner3b2917b2004-05-12 06:01:40 +000098
Chandler Carruth0fde0012012-05-04 10:18:49 +000099CodeExtractor::CodeExtractor(BasicBlock *BB, bool AggregateArgs)
100 : DT(0), AggregateArgs(AggregateArgs||AggregateArgsOpt),
101 Blocks(buildExtractionBlockSet(BB)), NumExitBlocks(~0U) {}
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000102
Chandler Carruth0fde0012012-05-04 10:18:49 +0000103CodeExtractor::CodeExtractor(ArrayRef<BasicBlock *> BBs, DominatorTree *DT,
104 bool AggregateArgs)
105 : DT(DT), AggregateArgs(AggregateArgs||AggregateArgsOpt),
106 Blocks(buildExtractionBlockSet(BBs)), NumExitBlocks(~0U) {}
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000107
Chandler Carruth0fde0012012-05-04 10:18:49 +0000108CodeExtractor::CodeExtractor(DominatorTree &DT, Loop &L, bool AggregateArgs)
109 : DT(&DT), AggregateArgs(AggregateArgs||AggregateArgsOpt),
110 Blocks(buildExtractionBlockSet(L.getBlocks())), NumExitBlocks(~0U) {}
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000111
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000112
Chandler Carruth0fde0012012-05-04 10:18:49 +0000113/// definedInRegion - Return true if the specified value is defined in the
114/// extracted region.
115static bool definedInRegion(const SetVector<BasicBlock *> &Blocks, Value *V) {
116 if (Instruction *I = dyn_cast<Instruction>(V))
117 if (Blocks.count(I->getParent()))
118 return true;
119 return false;
120}
121
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.
125static 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()))
129 return true;
130 return false;
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000131}
132
Chris Lattner3b2917b2004-05-12 06:01:40 +0000133/// 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.
136void CodeExtractor::severSplitPHINodes(BasicBlock *&Header) {
Jay Foade0938d82011-03-30 11:19:20 +0000137 unsigned NumPredsFromRegion = 0;
Chris Lattner795c9932004-05-12 15:29:13 +0000138 unsigned NumPredsOutsideRegion = 0;
Chris Lattner3b2917b2004-05-12 06:01:40 +0000139
Dan Gohmandcb291f2007-03-22 16:38:57 +0000140 if (Header != &Header->getParent()->getEntryBlock()) {
Chris Lattner795c9932004-05-12 15:29:13 +0000141 PHINode *PN = dyn_cast<PHINode>(Header->begin());
142 if (!PN) return; // No PHI nodes.
Chris Lattner3b2917b2004-05-12 06:01:40 +0000143
Chris Lattner795c9932004-05-12 15:29:13 +0000144 // 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)
Chandler Carruth0fde0012012-05-04 10:18:49 +0000148 if (Blocks.count(PN->getIncomingBlock(i)))
Jay Foade0938d82011-03-30 11:19:20 +0000149 ++NumPredsFromRegion;
Chris Lattner795c9932004-05-12 15:29:13 +0000150 else
151 ++NumPredsOutsideRegion;
152
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;
156 }
157
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.
Dan Gohmanf96e1372008-05-23 21:05:58 +0000162 BasicBlock::iterator AfterPHIs = Header->getFirstNonPHI();
Chris Lattner795c9932004-05-12 15:29:13 +0000163 BasicBlock *NewBB = Header->splitBasicBlock(AfterPHIs,
164 Header->getName()+".ce");
165
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;
Chandler Carruth0fde0012012-05-04 10:18:49 +0000169 Blocks.remove(OldPred);
170 Blocks.insert(NewBB);
Chris Lattner795c9932004-05-12 15:29:13 +0000171 Header = NewBB;
172
173 // Okay, update dominator sets. The blocks that dominate the new one are the
174 // blocks that dominate TIBB plus the new block itself.
Devang Pateld5258a232007-06-21 17:23:45 +0000175 if (DT)
176 DT->splitBlock(NewBB);
Chris Lattner795c9932004-05-12 15:29:13 +0000177
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.
Jay Foade0938d82011-03-30 11:19:20 +0000180 if (NumPredsFromRegion) {
Chris Lattner795c9932004-05-12 15:29:13 +0000181 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)
Chandler Carruth0fde0012012-05-04 10:18:49 +0000185 if (Blocks.count(PN->getIncomingBlock(i))) {
Chris Lattner795c9932004-05-12 15:29:13 +0000186 TerminatorInst *TI = PN->getIncomingBlock(i)->getTerminator();
187 TI->replaceUsesOfWith(OldPred, NewBB);
188 }
189
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000190 // Okay, everything within the region is now branching to the right block, we
Chris Lattner795c9932004-05-12 15:29:13 +0000191 // just have to update the PHI nodes now, inserting PHI nodes into NewBB.
Reid Spencer66149462004-09-15 17:06:42 +0000192 for (AfterPHIs = OldPred->begin(); isa<PHINode>(AfterPHIs); ++AfterPHIs) {
193 PHINode *PN = cast<PHINode>(AfterPHIs);
Chris Lattner795c9932004-05-12 15:29:13 +0000194 // Create a new PHI node in the new region, which has an incoming value
195 // from OldPred of PN.
Jay Foad52131342011-03-30 11:28:46 +0000196 PHINode *NewPN = PHINode::Create(PN->getType(), 1 + NumPredsFromRegion,
197 PN->getName()+".ce", NewBB->begin());
Chris Lattner795c9932004-05-12 15:29:13 +0000198 NewPN->addIncoming(PN, OldPred);
199
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) {
Chandler Carruth0fde0012012-05-04 10:18:49 +0000203 if (Blocks.count(PN->getIncomingBlock(i))) {
Chris Lattner795c9932004-05-12 15:29:13 +0000204 NewPN->addIncoming(PN->getIncomingValue(i), PN->getIncomingBlock(i));
205 PN->removeIncomingValue(i);
206 --i;
207 }
208 }
209 }
210 }
Chris Lattner13d2ddf2004-05-12 16:07:41 +0000211}
Chris Lattner795c9932004-05-12 15:29:13 +0000212
Chris Lattner13d2ddf2004-05-12 16:07:41 +0000213void CodeExtractor::splitReturnBlocks() {
Chandler Carruth0fde0012012-05-04 10:18:49 +0000214 for (SetVector<BasicBlock *>::iterator I = Blocks.begin(), E = Blocks.end();
215 I != E; ++I)
Owen Andersonb4aa5b12009-08-24 23:32:14 +0000216 if (ReturnInst *RI = dyn_cast<ReturnInst>((*I)->getTerminator())) {
217 BasicBlock *New = (*I)->splitBasicBlock(RI, (*I)->getName()+".ret");
218 if (DT) {
Gabor Greif2f5f6962010-09-10 22:25:58 +0000219 // Old dominates New. New node dominates all other nodes dominated
220 // by Old.
Owen Andersonb4aa5b12009-08-24 23:32:14 +0000221 DomTreeNode *OldNode = DT->getNode(*I);
Owen Andersonf18cae42009-08-25 17:35:37 +0000222 SmallVector<DomTreeNode*, 8> Children;
Owen Andersonb4aa5b12009-08-24 23:32:14 +0000223 for (DomTreeNode::iterator DI = OldNode->begin(), DE = OldNode->end();
224 DI != DE; ++DI)
225 Children.push_back(*DI);
226
227 DomTreeNode *NewNode = DT->addNewBlock(New, *I);
228
Owen Andersonf18cae42009-08-25 17:35:37 +0000229 for (SmallVector<DomTreeNode*, 8>::iterator I = Children.begin(),
Owen Andersonb4aa5b12009-08-24 23:32:14 +0000230 E = Children.end(); I != E; ++I)
231 DT->changeImmediateDominator(*I, NewNode);
232 }
233 }
Chris Lattner3b2917b2004-05-12 06:01:40 +0000234}
235
236// findInputsOutputs - Find inputs to, outputs from the code region.
237//
Chandler Carruth0fde0012012-05-04 10:18:49 +0000238void CodeExtractor::findInputsOutputs(ValueSet &inputs, ValueSet &outputs) {
Chris Lattnerffc49262004-05-12 04:14:24 +0000239 std::set<BasicBlock*> ExitBlocks;
Chandler Carruth0fde0012012-05-04 10:18:49 +0000240 for (SetVector<BasicBlock*>::const_iterator ci = Blocks.begin(),
241 ce = Blocks.end(); ci != ce; ++ci) {
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000242 BasicBlock *BB = *ci;
Chris Lattner3b2917b2004-05-12 06:01:40 +0000243
Chris Lattner73ab1fa2004-03-15 01:18:23 +0000244 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.
Chris Lattner3b2917b2004-05-12 06:01:40 +0000247 for (User::op_iterator O = I->op_begin(), E = I->op_end(); O != E; ++O)
Chandler Carruth0fde0012012-05-04 10:18:49 +0000248 if (definedInCaller(Blocks, *O))
Julien Lerouge321098e2010-01-10 01:07:22 +0000249 inputs.insert(*O);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000250
Chris Lattner3b2917b2004-05-12 06:01:40 +0000251 // Consider uses of this instruction (outputs).
Chris Lattner73ab1fa2004-03-15 01:18:23 +0000252 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
253 UI != E; ++UI)
Chandler Carruth0fde0012012-05-04 10:18:49 +0000254 if (!definedInRegion(Blocks, *UI)) {
Julien Lerouge321098e2010-01-10 01:07:22 +0000255 outputs.insert(I);
Chris Lattner37de2572004-03-18 03:49:40 +0000256 break;
257 }
Chris Lattner73ab1fa2004-03-15 01:18:23 +0000258 } // for: insts
Chris Lattnerffc49262004-05-12 04:14:24 +0000259
Chris Lattner3b2917b2004-05-12 06:01:40 +0000260 // Keep track of the exit blocks from the region.
Chris Lattnerffc49262004-05-12 04:14:24 +0000261 TerminatorInst *TI = BB->getTerminator();
262 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chandler Carruth0fde0012012-05-04 10:18:49 +0000263 if (!Blocks.count(TI->getSuccessor(i)))
Chris Lattnerffc49262004-05-12 04:14:24 +0000264 ExitBlocks.insert(TI->getSuccessor(i));
Chris Lattner73ab1fa2004-03-15 01:18:23 +0000265 } // for: basic blocks
Chris Lattnerffc49262004-05-12 04:14:24 +0000266
267 NumExitBlocks = ExitBlocks.size();
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000268}
269
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000270/// constructFunction - make a function based on inputs and outputs, as follows:
271/// f(in0, ..., inN, out0, ..., outN)
272///
Chandler Carruth0fde0012012-05-04 10:18:49 +0000273Function *CodeExtractor::constructFunction(const ValueSet &inputs,
274 const ValueSet &outputs,
Chris Lattner320d59f2004-03-18 05:28:49 +0000275 BasicBlock *header,
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000276 BasicBlock *newRootNode,
277 BasicBlock *newHeader,
Chris Lattner320d59f2004-03-18 05:28:49 +0000278 Function *oldFunction,
279 Module *M) {
David Greene0ad6dce2010-01-05 01:26:44 +0000280 DEBUG(dbgs() << "inputs: " << inputs.size() << "\n");
281 DEBUG(dbgs() << "outputs: " << outputs.size() << "\n");
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000282
283 // This function returns unsigned, outputs will go back by reference.
Chris Lattnerffc49262004-05-12 04:14:24 +0000284 switch (NumExitBlocks) {
285 case 0:
Owen Anderson55f1c092009-08-13 21:58:54 +0000286 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;
Chris Lattnerffc49262004-05-12 04:14:24 +0000289 }
290
Jay Foadb804a2b2011-07-12 14:06:48 +0000291 std::vector<Type*> paramTy;
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000292
293 // Add the types of the input values to the function's argument list
Chandler Carruth0fde0012012-05-04 10:18:49 +0000294 for (ValueSet::const_iterator i = inputs.begin(), e = inputs.end();
295 i != e; ++i) {
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000296 const Value *value = *i;
David Greene0ad6dce2010-01-05 01:26:44 +0000297 DEBUG(dbgs() << "value used in func: " << *value << "\n");
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000298 paramTy.push_back(value->getType());
299 }
300
Chris Lattner37de2572004-03-18 03:49:40 +0000301 // Add the types of the output values to the function's argument list.
Chandler Carruth0fde0012012-05-04 10:18:49 +0000302 for (ValueSet::const_iterator I = outputs.begin(), E = outputs.end();
Chris Lattner37de2572004-03-18 03:49:40 +0000303 I != E; ++I) {
David Greene0ad6dce2010-01-05 01:26:44 +0000304 DEBUG(dbgs() << "instr used in func: " << **I << "\n");
Misha Brukman3596f0a2004-04-23 23:54:17 +0000305 if (AggregateArgs)
306 paramTy.push_back((*I)->getType());
307 else
Owen Anderson4056ca92009-07-29 22:17:13 +0000308 paramTy.push_back(PointerType::getUnqual((*I)->getType()));
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000309 }
310
David Greene0ad6dce2010-01-05 01:26:44 +0000311 DEBUG(dbgs() << "Function type: " << *RetTy << " f(");
Jay Foadb804a2b2011-07-12 14:06:48 +0000312 for (std::vector<Type*>::iterator i = paramTy.begin(),
Bill Wendling4ae40102006-11-26 10:17:54 +0000313 e = paramTy.end(); i != e; ++i)
David Greene0ad6dce2010-01-05 01:26:44 +0000314 DEBUG(dbgs() << **i << ", ");
315 DEBUG(dbgs() << ")\n");
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000316
Misha Brukman3596f0a2004-04-23 23:54:17 +0000317 if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
Owen Andersone70b6372009-07-05 22:41:43 +0000318 PointerType *StructPtr =
Owen Anderson03cb69f2009-08-05 23:16:16 +0000319 PointerType::getUnqual(StructType::get(M->getContext(), paramTy));
Misha Brukman3596f0a2004-04-23 23:54:17 +0000320 paramTy.clear();
321 paramTy.push_back(StructPtr);
322 }
Chris Lattner229907c2011-07-18 04:54:35 +0000323 FunctionType *funcType =
Owen Anderson4056ca92009-07-29 22:17:13 +0000324 FunctionType::get(RetTy, paramTy, false);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000325
326 // Create the new function
Gabor Greife9ecc682008-04-06 20:25:17 +0000327 Function *newFunction = Function::Create(funcType,
328 GlobalValue::InternalLinkage,
329 oldFunction->getName() + "_" +
330 header->getName(), M);
Chris Lattner4caf5eb2008-12-18 05:52:56 +0000331 // If the old function is no-throw, so is the new one.
332 if (oldFunction->doesNotThrow())
333 newFunction->setDoesNotThrow(true);
334
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000335 newFunction->getBasicBlockList().push_back(newRootNode);
336
Chris Lattner37de2572004-03-18 03:49:40 +0000337 // Create an iterator to name all of the arguments we inserted.
Chris Lattner531f9e92005-03-15 04:54:21 +0000338 Function::arg_iterator AI = newFunction->arg_begin();
Chris Lattner37de2572004-03-18 03:49:40 +0000339
340 // Rewrite all users of the inputs in the extracted region to use the
Misha Brukman3596f0a2004-04-23 23:54:17 +0000341 // arguments (or appropriate addressing into struct) instead.
342 for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
343 Value *RewriteVal;
344 if (AggregateArgs) {
David Greenec656cbb2007-09-04 15:46:09 +0000345 Value *Idx[2];
Owen Anderson55f1c092009-08-13 21:58:54 +0000346 Idx[0] = Constant::getNullValue(Type::getInt32Ty(header->getContext()));
347 Idx[1] = ConstantInt::get(Type::getInt32Ty(header->getContext()), i);
Misha Brukman3596f0a2004-04-23 23:54:17 +0000348 TerminatorInst *TI = newFunction->begin()->getTerminator();
Daniel Dunbar123686852009-07-24 08:24:36 +0000349 GetElementPtrInst *GEP =
Jay Foadd1b78492011-07-25 09:48:08 +0000350 GetElementPtrInst::Create(AI, Idx, "gep_" + inputs[i]->getName(), TI);
Daniel Dunbar123686852009-07-24 08:24:36 +0000351 RewriteVal = new LoadInst(GEP, "loadgep_" + inputs[i]->getName(), TI);
Misha Brukman3596f0a2004-04-23 23:54:17 +0000352 } else
353 RewriteVal = AI++;
354
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000355 std::vector<User*> Users(inputs[i]->use_begin(), inputs[i]->use_end());
356 for (std::vector<User*>::iterator use = Users.begin(), useE = Users.end();
Chris Lattner36844692004-03-14 03:17:22 +0000357 use != useE; ++use)
358 if (Instruction* inst = dyn_cast<Instruction>(*use))
Chandler Carruth0fde0012012-05-04 10:18:49 +0000359 if (Blocks.count(inst->getParent()))
Misha Brukman3596f0a2004-04-23 23:54:17 +0000360 inst->replaceUsesOfWith(inputs[i], RewriteVal);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000361 }
362
Misha Brukman3596f0a2004-04-23 23:54:17 +0000363 // Set names for input and output arguments.
364 if (!AggregateArgs) {
Chris Lattner531f9e92005-03-15 04:54:21 +0000365 AI = newFunction->arg_begin();
Misha Brukman3596f0a2004-04-23 23:54:17 +0000366 for (unsigned i = 0, e = inputs.size(); i != e; ++i, ++AI)
Owen Anderson7629b712008-04-14 17:38:21 +0000367 AI->setName(inputs[i]->getName());
Misha Brukman3596f0a2004-04-23 23:54:17 +0000368 for (unsigned i = 0, e = outputs.size(); i != e; ++i, ++AI)
Misha Brukmanb1c93172005-04-21 23:48:37 +0000369 AI->setName(outputs[i]->getName()+".out");
Misha Brukman3596f0a2004-04-23 23:54:17 +0000370 }
Chris Lattner37de2572004-03-18 03:49:40 +0000371
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000372 // 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());
Chris Lattner320d59f2004-03-18 05:28:49 +0000376 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]))
Chandler Carruth0fde0012012-05-04 10:18:49 +0000380 if (!Blocks.count(TI->getParent()) &&
Chris Lattner320d59f2004-03-18 05:28:49 +0000381 TI->getParent()->getParent() == oldFunction)
382 TI->replaceUsesOfWith(header, newHeader);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000383
384 return newFunction;
385}
386
Owen Anderson4e9ac2a2009-08-25 17:42:07 +0000387/// 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.
Owen Anderson5e39d1d2009-08-25 17:26:32 +0000390static 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);
396 }
397
398 return 0;
399}
400
Chris Lattner3b2917b2004-05-12 06:01:40 +0000401/// emitCallAndSwitchStatement - This method sets up the caller side by adding
402/// the call instruction, splitting any PHI nodes in the header block as
403/// necessary.
404void CodeExtractor::
405emitCallAndSwitchStatement(Function *newFunction, BasicBlock *codeReplacer,
Chandler Carruth0fde0012012-05-04 10:18:49 +0000406 ValueSet &inputs, ValueSet &outputs) {
Chris Lattner3b2917b2004-05-12 06:01:40 +0000407 // Emit a call to the new function, passing in: *pointer to struct (if
408 // aggregating parameters), or plan inputs and allocated memory for outputs
Owen Anderson34e61482009-08-25 00:54:39 +0000409 std::vector<Value*> params, StructValues, ReloadOutputs, Reloads;
Owen Anderson55f1c092009-08-13 21:58:54 +0000410
411 LLVMContext &Context = newFunction->getContext();
Chris Lattnerd8017a32004-03-18 04:12:05 +0000412
Misha Brukman3596f0a2004-04-23 23:54:17 +0000413 // Add inputs as params, or to be filled into the struct
Chandler Carruth0fde0012012-05-04 10:18:49 +0000414 for (ValueSet::iterator i = inputs.begin(), e = inputs.end(); i != e; ++i)
Misha Brukman3596f0a2004-04-23 23:54:17 +0000415 if (AggregateArgs)
416 StructValues.push_back(*i);
417 else
418 params.push_back(*i);
419
420 // Create allocas for the outputs
Chandler Carruth0fde0012012-05-04 10:18:49 +0000421 for (ValueSet::iterator i = outputs.begin(), e = outputs.end(); i != e; ++i) {
Misha Brukman3596f0a2004-04-23 23:54:17 +0000422 if (AggregateArgs) {
423 StructValues.push_back(*i);
424 } else {
425 AllocaInst *alloca =
Owen Anderson4fdeba92009-07-15 23:53:25 +0000426 new AllocaInst((*i)->getType(), 0, (*i)->getName()+".loc",
Misha Brukman3596f0a2004-04-23 23:54:17 +0000427 codeReplacer->getParent()->begin()->begin());
428 ReloadOutputs.push_back(alloca);
429 params.push_back(alloca);
430 }
431 }
432
433 AllocaInst *Struct = 0;
434 if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
Jay Foadb804a2b2011-07-12 14:06:48 +0000435 std::vector<Type*> ArgTypes;
Chandler Carruth0fde0012012-05-04 10:18:49 +0000436 for (ValueSet::iterator v = StructValues.begin(),
Misha Brukman3596f0a2004-04-23 23:54:17 +0000437 ve = StructValues.end(); v != ve; ++v)
438 ArgTypes.push_back((*v)->getType());
439
440 // Allocate a struct at the beginning of this function
Owen Anderson03cb69f2009-08-05 23:16:16 +0000441 Type *StructArgTy = StructType::get(newFunction->getContext(), ArgTypes);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000442 Struct =
Owen Anderson4fdeba92009-07-15 23:53:25 +0000443 new AllocaInst(StructArgTy, 0, "structArg",
Chris Lattner37de2572004-03-18 03:49:40 +0000444 codeReplacer->getParent()->begin()->begin());
Misha Brukman3596f0a2004-04-23 23:54:17 +0000445 params.push_back(Struct);
446
447 for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
David Greenec656cbb2007-09-04 15:46:09 +0000448 Value *Idx[2];
Owen Anderson55f1c092009-08-13 21:58:54 +0000449 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
450 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), i);
Misha Brukman3596f0a2004-04-23 23:54:17 +0000451 GetElementPtrInst *GEP =
Jay Foadd1b78492011-07-25 09:48:08 +0000452 GetElementPtrInst::Create(Struct, Idx,
Gabor Greife9ecc682008-04-06 20:25:17 +0000453 "gep_" + StructValues[i]->getName());
Misha Brukman3596f0a2004-04-23 23:54:17 +0000454 codeReplacer->getInstList().push_back(GEP);
455 StoreInst *SI = new StoreInst(StructValues[i], GEP);
456 codeReplacer->getInstList().push_back(SI);
457 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000458 }
Misha Brukman3596f0a2004-04-23 23:54:17 +0000459
460 // Emit the call to the function
Jay Foad5bd375a2011-07-15 08:37:34 +0000461 CallInst *call = CallInst::Create(newFunction, params,
Gabor Greife9ecc682008-04-06 20:25:17 +0000462 NumExitBlocks > 1 ? "targetBlock" : "");
Misha Brukman3596f0a2004-04-23 23:54:17 +0000463 codeReplacer->getInstList().push_back(call);
464
Chris Lattner531f9e92005-03-15 04:54:21 +0000465 Function::arg_iterator OutputArgBegin = newFunction->arg_begin();
Misha Brukman3596f0a2004-04-23 23:54:17 +0000466 unsigned FirstOut = inputs.size();
467 if (!AggregateArgs)
468 std::advance(OutputArgBegin, inputs.size());
469
470 // Reload the outputs passed in by reference
471 for (unsigned i = 0, e = outputs.size(); i != e; ++i) {
472 Value *Output = 0;
473 if (AggregateArgs) {
David Greenec656cbb2007-09-04 15:46:09 +0000474 Value *Idx[2];
Owen Anderson55f1c092009-08-13 21:58:54 +0000475 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
476 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), FirstOut + i);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000477 GetElementPtrInst *GEP
Jay Foadd1b78492011-07-25 09:48:08 +0000478 = GetElementPtrInst::Create(Struct, Idx,
Gabor Greife9ecc682008-04-06 20:25:17 +0000479 "gep_reload_" + outputs[i]->getName());
Misha Brukman3596f0a2004-04-23 23:54:17 +0000480 codeReplacer->getInstList().push_back(GEP);
481 Output = GEP;
482 } else {
483 Output = ReloadOutputs[i];
484 }
485 LoadInst *load = new LoadInst(Output, outputs[i]->getName()+".reload");
Owen Anderson34e61482009-08-25 00:54:39 +0000486 Reloads.push_back(load);
Chris Lattner37de2572004-03-18 03:49:40 +0000487 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]);
Chandler Carruth0fde0012012-05-04 10:18:49 +0000491 if (!Blocks.count(inst->getParent()))
Chris Lattner37de2572004-03-18 03:49:40 +0000492 inst->replaceUsesOfWith(outputs[i], load);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000493 }
494 }
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000495
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000496 // Now we can emit a switch statement using the call as a value.
Chris Lattnerffc49262004-05-12 04:14:24 +0000497 SwitchInst *TheSwitch =
Owen Anderson55f1c092009-08-13 21:58:54 +0000498 SwitchInst::Create(Constant::getNullValue(Type::getInt16Ty(Context)),
Gabor Greife9ecc682008-04-06 20:25:17 +0000499 codeReplacer, 0, codeReplacer);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000500
501 // Since there may be multiple exits from the original region, make the new
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000502 // 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;
507
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000508 unsigned switchVal = 0;
Chandler Carruth0fde0012012-05-04 10:18:49 +0000509 for (SetVector<BasicBlock*>::const_iterator i = Blocks.begin(),
510 e = Blocks.end(); i != e; ++i) {
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000511 TerminatorInst *TI = (*i)->getTerminator();
512 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chandler Carruth0fde0012012-05-04 10:18:49 +0000513 if (!Blocks.count(TI->getSuccessor(i))) {
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000514 BasicBlock *OldTarget = TI->getSuccessor(i);
515 // add a new basic block which returns the appropriate value
516 BasicBlock *&NewTarget = ExitBlockMap[OldTarget];
517 if (!NewTarget) {
518 // If we don't already have an exit stub for this non-extracted
519 // destination, create one now!
Owen Anderson55f1c092009-08-13 21:58:54 +0000520 NewTarget = BasicBlock::Create(Context,
521 OldTarget->getName() + ".exitStub",
Gabor Greife9ecc682008-04-06 20:25:17 +0000522 newFunction);
Chris Lattnerffc49262004-05-12 04:14:24 +0000523 unsigned SuccNum = switchVal++;
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000524
Chris Lattnerffc49262004-05-12 04:14:24 +0000525 Value *brVal = 0;
526 switch (NumExitBlocks) {
527 case 0:
528 case 1: break; // No value needed.
529 case 2: // Conditional branch, return a bool
Owen Anderson55f1c092009-08-13 21:58:54 +0000530 brVal = ConstantInt::get(Type::getInt1Ty(Context), !SuccNum);
Chris Lattnerffc49262004-05-12 04:14:24 +0000531 break;
532 default:
Owen Anderson55f1c092009-08-13 21:58:54 +0000533 brVal = ConstantInt::get(Type::getInt16Ty(Context), SuccNum);
Chris Lattnerffc49262004-05-12 04:14:24 +0000534 break;
535 }
536
Owen Anderson55f1c092009-08-13 21:58:54 +0000537 ReturnInst *NTRet = ReturnInst::Create(Context, brVal, NewTarget);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000538
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000539 // Update the switch instruction.
Owen Anderson55f1c092009-08-13 21:58:54 +0000540 TheSwitch->addCase(ConstantInt::get(Type::getInt16Ty(Context),
541 SuccNum),
Chris Lattnerffc49262004-05-12 04:14:24 +0000542 OldTarget);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000543
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000544 // Restore values just before we exit
Chris Lattner531f9e92005-03-15 04:54:21 +0000545 Function::arg_iterator OAI = OutputArgBegin;
Misha Brukman3596f0a2004-04-23 23:54:17 +0000546 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();
Chris Lattner9b0291b2004-11-13 00:06:45 +0000550
551 bool DominatesDef = true;
552
Chris Lattner5bcca602004-11-12 23:50:44 +0000553 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(outputs[out])) {
Misha Brukman3596f0a2004-04-23 23:54:17 +0000554 DefBlock = Invoke->getNormalDest();
Chris Lattner5bcca602004-11-12 23:50:44 +0000555
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
558 // info.
559 for (std::map<BasicBlock*, BasicBlock*>::iterator I =
560 ExitBlockMap.begin(), E = ExitBlockMap.end(); I != E; ++I)
561 if (DefBlock == I->second) {
562 DefBlock = I->first;
563 break;
564 }
Chris Lattner9b0291b2004-11-13 00:06:45 +0000565
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.
Devang Patelcf470e52007-06-07 22:17:16 +0000569 if (!DT && DefBlock != OldTarget)
Chris Lattner9b0291b2004-11-13 00:06:45 +0000570 DominatesDef = false;
Chris Lattner5bcca602004-11-12 23:50:44 +0000571 }
572
Owen Anderson34e61482009-08-25 00:54:39 +0000573 if (DT) {
Devang Patelcf470e52007-06-07 22:17:16 +0000574 DominatesDef = DT->dominates(DefBlock, OldTarget);
Owen Anderson34e61482009-08-25 00:54:39 +0000575
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.
Owen Anderson5e39d1d2009-08-25 17:26:32 +0000580 BasicBlock* pred = FindPhiPredForUseInBlock(Reloads[out],
581 OldTarget);
582 if (pred && DT && DT->dominates(DefBlock, pred))
583 DominatesDef = true;
Owen Anderson34e61482009-08-25 00:54:39 +0000584 }
Chris Lattner9b0291b2004-11-13 00:06:45 +0000585
586 if (DominatesDef) {
Misha Brukman3596f0a2004-04-23 23:54:17 +0000587 if (AggregateArgs) {
David Greenec656cbb2007-09-04 15:46:09 +0000588 Value *Idx[2];
Owen Anderson55f1c092009-08-13 21:58:54 +0000589 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
590 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context),
591 FirstOut+out);
Misha Brukman3596f0a2004-04-23 23:54:17 +0000592 GetElementPtrInst *GEP =
Jay Foadd1b78492011-07-25 09:48:08 +0000593 GetElementPtrInst::Create(OAI, Idx,
Gabor Greife9ecc682008-04-06 20:25:17 +0000594 "gep_" + outputs[out]->getName(),
595 NTRet);
Misha Brukman3596f0a2004-04-23 23:54:17 +0000596 new StoreInst(outputs[out], GEP, NTRet);
Chris Lattner9b0291b2004-11-13 00:06:45 +0000597 } else {
Misha Brukman3596f0a2004-04-23 23:54:17 +0000598 new StoreInst(outputs[out], OAI, NTRet);
Chris Lattner9b0291b2004-11-13 00:06:45 +0000599 }
600 }
Misha Brukman3596f0a2004-04-23 23:54:17 +0000601 // Advance output iterator even if we don't emit a store
602 if (!AggregateArgs) ++OAI;
603 }
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000604 }
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000605
606 // rewrite the original branch instruction with this new target
607 TI->setSuccessor(i, NewTarget);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000608 }
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000609 }
Chris Lattner5b2072e2004-03-14 23:43:24 +0000610
Chris Lattner3d1ca672004-05-12 03:22:33 +0000611 // Now that we've done the deed, simplify the switch instruction.
Chris Lattner229907c2011-07-18 04:54:35 +0000612 Type *OldFnRetTy = TheSwitch->getParent()->getParent()->getReturnType();
Chris Lattnerffc49262004-05-12 04:14:24 +0000613 switch (NumExitBlocks) {
614 case 0:
Chris Lattner7f1c7ed2004-08-12 03:17:02 +0000615 // There are no successors (the block containing the switch itself), which
Misha Brukman3596f0a2004-04-23 23:54:17 +0000616 // means that previously this was the last part of the function, and hence
617 // this should be rewritten as a `ret'
Misha Brukmanb1c93172005-04-21 23:48:37 +0000618
Misha Brukman3596f0a2004-04-23 23:54:17 +0000619 // Check if the function should return a value
Benjamin Kramerccce8ba2010-01-05 13:12:22 +0000620 if (OldFnRetTy->isVoidTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +0000621 ReturnInst::Create(Context, 0, TheSwitch); // Return void
Chris Lattner7f1c7ed2004-08-12 03:17:02 +0000622 } else if (OldFnRetTy == TheSwitch->getCondition()->getType()) {
Misha Brukman3596f0a2004-04-23 23:54:17 +0000623 // return what we have
Owen Anderson55f1c092009-08-13 21:58:54 +0000624 ReturnInst::Create(Context, TheSwitch->getCondition(), TheSwitch);
Chris Lattner7f1c7ed2004-08-12 03:17:02 +0000625 } else {
626 // Otherwise we must have code extracted an unwind or something, just
627 // return whatever we want.
Owen Anderson55f1c092009-08-13 21:58:54 +0000628 ReturnInst::Create(Context,
629 Constant::getNullValue(OldFnRetTy), TheSwitch);
Chris Lattner7f1c7ed2004-08-12 03:17:02 +0000630 }
Misha Brukman3596f0a2004-04-23 23:54:17 +0000631
Dan Gohman158ff2c2008-06-21 22:08:46 +0000632 TheSwitch->eraseFromParent();
Chris Lattnerffc49262004-05-12 04:14:24 +0000633 break;
634 case 1:
635 // Only a single destination, change the switch into an unconditional
636 // branch.
Gabor Greife9ecc682008-04-06 20:25:17 +0000637 BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch);
Dan Gohman158ff2c2008-06-21 22:08:46 +0000638 TheSwitch->eraseFromParent();
Chris Lattnerffc49262004-05-12 04:14:24 +0000639 break;
640 case 2:
Gabor Greife9ecc682008-04-06 20:25:17 +0000641 BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch->getSuccessor(2),
642 call, TheSwitch);
Dan Gohman158ff2c2008-06-21 22:08:46 +0000643 TheSwitch->eraseFromParent();
Chris Lattnerffc49262004-05-12 04:14:24 +0000644 break;
645 default:
646 // Otherwise, make the default destination of the switch instruction be one
647 // of the other successors.
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +0000648 TheSwitch->setCondition(call);
649 TheSwitch->setDefaultDest(TheSwitch->getSuccessor(NumExitBlocks));
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +0000650 // Remove redundant case
651 TheSwitch->removeCase(SwitchInst::CaseIt(TheSwitch, NumExitBlocks-1));
Chris Lattnerffc49262004-05-12 04:14:24 +0000652 break;
Chris Lattner5b2072e2004-03-14 23:43:24 +0000653 }
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000654}
655
Chris Lattner3b2917b2004-05-12 06:01:40 +0000656void CodeExtractor::moveCodeToFunction(Function *newFunction) {
Chandler Carruth0fde0012012-05-04 10:18:49 +0000657 Function *oldFunc = (*Blocks.begin())->getParent();
Chris Lattner3b2917b2004-05-12 06:01:40 +0000658 Function::BasicBlockListType &oldBlocks = oldFunc->getBasicBlockList();
659 Function::BasicBlockListType &newBlocks = newFunction->getBasicBlockList();
660
Chandler Carruth0fde0012012-05-04 10:18:49 +0000661 for (SetVector<BasicBlock*>::const_iterator i = Blocks.begin(),
662 e = Blocks.end(); i != e; ++i) {
Chris Lattner3b2917b2004-05-12 06:01:40 +0000663 // Delete the basic block from the old function, and the list of blocks
664 oldBlocks.remove(*i);
665
666 // Insert this basic block into the new function
667 newBlocks.push_back(*i);
668 }
669}
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000670
Chandler Carruth0fde0012012-05-04 10:18:49 +0000671Function *CodeExtractor::extractCodeRegion() {
672 if (!isEligible())
Misha Brukman3596f0a2004-04-23 23:54:17 +0000673 return 0;
674
Chandler Carruth0fde0012012-05-04 10:18:49 +0000675 ValueSet inputs, outputs;
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000676
677 // Assumption: this is a single-entry code region, and the header is the first
Chris Lattner73ab1fa2004-03-15 01:18:23 +0000678 // block in the region.
Chandler Carruth0fde0012012-05-04 10:18:49 +0000679 BasicBlock *header = *Blocks.begin();
Chris Lattner3b2917b2004-05-12 06:01:40 +0000680
Chris Lattner13d2ddf2004-05-12 16:07:41 +0000681 // If we have to split PHI nodes or the entry block, do so now.
Chris Lattner795c9932004-05-12 15:29:13 +0000682 severSplitPHINodes(header);
683
Chris Lattner13d2ddf2004-05-12 16:07:41 +0000684 // If we have any return instructions in the region, split those blocks so
685 // that the return is not in the region.
686 splitReturnBlocks();
687
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000688 Function *oldFunction = header->getParent();
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000689
690 // This takes place of the original loop
Owen Anderson55f1c092009-08-13 21:58:54 +0000691 BasicBlock *codeReplacer = BasicBlock::Create(header->getContext(),
692 "codeRepl", oldFunction,
Gabor Greif697e94c2008-05-15 10:04:30 +0000693 header);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000694
695 // The new function needs a root node because other nodes can branch to the
Chris Lattner3b2917b2004-05-12 06:01:40 +0000696 // head of the region, but the entry node of a function cannot have preds.
Owen Anderson55f1c092009-08-13 21:58:54 +0000697 BasicBlock *newFuncRoot = BasicBlock::Create(header->getContext(),
698 "newFuncRoot");
Gabor Greife9ecc682008-04-06 20:25:17 +0000699 newFuncRoot->getInstList().push_back(BranchInst::Create(header));
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000700
Chris Lattner3b2917b2004-05-12 06:01:40 +0000701 // Find inputs to, outputs from the code region.
702 findInputsOutputs(inputs, outputs);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000703
Chris Lattner3b2917b2004-05-12 06:01:40 +0000704 // Construct new function based on inputs/outputs & add allocas for all defs.
Chris Lattner795c9932004-05-12 15:29:13 +0000705 Function *newFunction = constructFunction(inputs, outputs, header,
Misha Brukmanb1c93172005-04-21 23:48:37 +0000706 newFuncRoot,
Chris Lattner73ab1fa2004-03-15 01:18:23 +0000707 codeReplacer, oldFunction,
708 oldFunction->getParent());
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000709
Chris Lattner9c431f62004-03-14 22:34:55 +0000710 emitCallAndSwitchStatement(newFunction, codeReplacer, inputs, outputs);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000711
Chris Lattner9c431f62004-03-14 22:34:55 +0000712 moveCodeToFunction(newFunction);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000713
Chris Lattner795c9932004-05-12 15:29:13 +0000714 // Loop over all of the PHI nodes in the header block, and change any
Chris Lattner320d59f2004-03-18 05:28:49 +0000715 // references to the old incoming edge to be the new incoming edge.
Reid Spencer66149462004-09-15 17:06:42 +0000716 for (BasicBlock::iterator I = header->begin(); isa<PHINode>(I); ++I) {
717 PHINode *PN = cast<PHINode>(I);
Chris Lattner320d59f2004-03-18 05:28:49 +0000718 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
Chandler Carruth0fde0012012-05-04 10:18:49 +0000719 if (!Blocks.count(PN->getIncomingBlock(i)))
Chris Lattner320d59f2004-03-18 05:28:49 +0000720 PN->setIncomingBlock(i, newFuncRoot);
Reid Spencer66149462004-09-15 17:06:42 +0000721 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000722
Chris Lattneracd75982004-03-18 05:38:31 +0000723 // 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)
Reid Spencer66149462004-09-15 17:06:42 +0000729 for (BasicBlock::iterator I = Succs[i]->begin(); isa<PHINode>(I); ++I) {
730 PHINode *PN = cast<PHINode>(I);
Chris Lattner56273822004-08-13 03:27:07 +0000731 std::set<BasicBlock*> ProcessedPreds;
Chris Lattneracd75982004-03-18 05:38:31 +0000732 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
Chandler Carruth0fde0012012-05-04 10:18:49 +0000733 if (Blocks.count(PN->getIncomingBlock(i))) {
Chris Lattner56273822004-08-13 03:27:07 +0000734 if (ProcessedPreds.insert(PN->getIncomingBlock(i)).second)
735 PN->setIncomingBlock(i, codeReplacer);
736 else {
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);
740 --i; --e;
741 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +0000742 }
Chris Lattner56273822004-08-13 03:27:07 +0000743 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000744
Bill Wendlingf3baad32006-12-07 01:30:32 +0000745 //cerr << "NEW FUNCTION: " << *newFunction;
Chris Lattner795c9932004-05-12 15:29:13 +0000746 // verifyFunction(*newFunction);
747
Bill Wendlingf3baad32006-12-07 01:30:32 +0000748 // cerr << "OLD FUNCTION: " << *oldFunction;
Chris Lattner795c9932004-05-12 15:29:13 +0000749 // verifyFunction(*oldFunction);
Chris Lattneracd75982004-03-18 05:38:31 +0000750
Torok Edwinccb29cd2009-07-11 13:10:19 +0000751 DEBUG(if (verifyFunction(*newFunction))
Chris Lattner2104b8d2010-04-07 22:58:41 +0000752 report_fatal_error("verifyFunction failed!"));
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000753 return newFunction;
754}