LLVM API Documentation
00001 //===- CodeExtractor.cpp - Pull code region into a new function -----------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file implements the interface to tear out a code region, such as an 00011 // individual loop or a parallel section, into a new function, replacing it with 00012 // a call to the new function. 00013 // 00014 //===----------------------------------------------------------------------===// 00015 00016 #include "llvm/Transforms/Utils/CodeExtractor.h" 00017 #include "llvm/ADT/SetVector.h" 00018 #include "llvm/ADT/STLExtras.h" 00019 #include "llvm/ADT/StringExtras.h" 00020 #include "llvm/Analysis/Dominators.h" 00021 #include "llvm/Analysis/LoopInfo.h" 00022 #include "llvm/Analysis/RegionInfo.h" 00023 #include "llvm/Analysis/RegionIterator.h" 00024 #include "llvm/Analysis/Verifier.h" 00025 #include "llvm/IR/Constants.h" 00026 #include "llvm/IR/DerivedTypes.h" 00027 #include "llvm/IR/Instructions.h" 00028 #include "llvm/IR/Intrinsics.h" 00029 #include "llvm/IR/LLVMContext.h" 00030 #include "llvm/IR/Module.h" 00031 #include "llvm/Pass.h" 00032 #include "llvm/Support/CommandLine.h" 00033 #include "llvm/Support/Debug.h" 00034 #include "llvm/Support/ErrorHandling.h" 00035 #include "llvm/Support/raw_ostream.h" 00036 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 00037 #include <algorithm> 00038 #include <set> 00039 using namespace llvm; 00040 00041 // Provide a command-line option to aggregate function arguments into a struct 00042 // for functions produced by the code extractor. This is useful when converting 00043 // extracted functions to pthread-based code, as only one argument (void*) can 00044 // be passed in to pthread_create(). 00045 static cl::opt<bool> 00046 AggregateArgsOpt("aggregate-extracted-args", cl::Hidden, 00047 cl::desc("Aggregate arguments to code-extracted functions")); 00048 00049 /// \brief Test whether a block is valid for extraction. 00050 static bool isBlockValidForExtraction(const BasicBlock &BB) { 00051 // Landing pads must be in the function where they were inserted for cleanup. 00052 if (BB.isLandingPad()) 00053 return false; 00054 00055 // Don't hoist code containing allocas, invokes, or vastarts. 00056 for (BasicBlock::const_iterator I = BB.begin(), E = BB.end(); I != E; ++I) { 00057 if (isa<AllocaInst>(I) || isa<InvokeInst>(I)) 00058 return false; 00059 if (const CallInst *CI = dyn_cast<CallInst>(I)) 00060 if (const Function *F = CI->getCalledFunction()) 00061 if (F->getIntrinsicID() == Intrinsic::vastart) 00062 return false; 00063 } 00064 00065 return true; 00066 } 00067 00068 /// \brief Build a set of blocks to extract if the input blocks are viable. 00069 template <typename IteratorT> 00070 static SetVector<BasicBlock *> buildExtractionBlockSet(IteratorT BBBegin, 00071 IteratorT BBEnd) { 00072 SetVector<BasicBlock *> Result; 00073 00074 assert(BBBegin != BBEnd); 00075 00076 // Loop over the blocks, adding them to our set-vector, and aborting with an 00077 // empty set if we encounter invalid blocks. 00078 for (IteratorT I = BBBegin, E = BBEnd; I != E; ++I) { 00079 if (!Result.insert(*I)) 00080 llvm_unreachable("Repeated basic blocks in extraction input"); 00081 00082 if (!isBlockValidForExtraction(**I)) { 00083 Result.clear(); 00084 return Result; 00085 } 00086 } 00087 00088 #ifndef NDEBUG 00089 for (SetVector<BasicBlock *>::iterator I = llvm::next(Result.begin()), 00090 E = Result.end(); 00091 I != E; ++I) 00092 for (pred_iterator PI = pred_begin(*I), PE = pred_end(*I); 00093 PI != PE; ++PI) 00094 assert(Result.count(*PI) && 00095 "No blocks in this region may have entries from outside the region" 00096 " except for the first block!"); 00097 #endif 00098 00099 return Result; 00100 } 00101 00102 /// \brief Helper to call buildExtractionBlockSet with an ArrayRef. 00103 static SetVector<BasicBlock *> 00104 buildExtractionBlockSet(ArrayRef<BasicBlock *> BBs) { 00105 return buildExtractionBlockSet(BBs.begin(), BBs.end()); 00106 } 00107 00108 /// \brief Helper to call buildExtractionBlockSet with a RegionNode. 00109 static SetVector<BasicBlock *> 00110 buildExtractionBlockSet(const RegionNode &RN) { 00111 if (!RN.isSubRegion()) 00112 // Just a single BasicBlock. 00113 return buildExtractionBlockSet(RN.getNodeAs<BasicBlock>()); 00114 00115 const Region &R = *RN.getNodeAs<Region>(); 00116 00117 return buildExtractionBlockSet(R.block_begin(), R.block_end()); 00118 } 00119 00120 CodeExtractor::CodeExtractor(BasicBlock *BB, bool AggregateArgs) 00121 : DT(0), AggregateArgs(AggregateArgs||AggregateArgsOpt), 00122 Blocks(buildExtractionBlockSet(BB)), NumExitBlocks(~0U) {} 00123 00124 CodeExtractor::CodeExtractor(ArrayRef<BasicBlock *> BBs, DominatorTree *DT, 00125 bool AggregateArgs) 00126 : DT(DT), AggregateArgs(AggregateArgs||AggregateArgsOpt), 00127 Blocks(buildExtractionBlockSet(BBs)), NumExitBlocks(~0U) {} 00128 00129 CodeExtractor::CodeExtractor(DominatorTree &DT, Loop &L, bool AggregateArgs) 00130 : DT(&DT), AggregateArgs(AggregateArgs||AggregateArgsOpt), 00131 Blocks(buildExtractionBlockSet(L.getBlocks())), NumExitBlocks(~0U) {} 00132 00133 CodeExtractor::CodeExtractor(DominatorTree &DT, const RegionNode &RN, 00134 bool AggregateArgs) 00135 : DT(&DT), AggregateArgs(AggregateArgs||AggregateArgsOpt), 00136 Blocks(buildExtractionBlockSet(RN)), NumExitBlocks(~0U) {} 00137 00138 /// definedInRegion - Return true if the specified value is defined in the 00139 /// extracted region. 00140 static bool definedInRegion(const SetVector<BasicBlock *> &Blocks, Value *V) { 00141 if (Instruction *I = dyn_cast<Instruction>(V)) 00142 if (Blocks.count(I->getParent())) 00143 return true; 00144 return false; 00145 } 00146 00147 /// definedInCaller - Return true if the specified value is defined in the 00148 /// function being code extracted, but not in the region being extracted. 00149 /// These values must be passed in as live-ins to the function. 00150 static bool definedInCaller(const SetVector<BasicBlock *> &Blocks, Value *V) { 00151 if (isa<Argument>(V)) return true; 00152 if (Instruction *I = dyn_cast<Instruction>(V)) 00153 if (!Blocks.count(I->getParent())) 00154 return true; 00155 return false; 00156 } 00157 00158 void CodeExtractor::findInputsOutputs(ValueSet &Inputs, 00159 ValueSet &Outputs) const { 00160 for (SetVector<BasicBlock *>::const_iterator I = Blocks.begin(), 00161 E = Blocks.end(); 00162 I != E; ++I) { 00163 BasicBlock *BB = *I; 00164 00165 // If a used value is defined outside the region, it's an input. If an 00166 // instruction is used outside the region, it's an output. 00167 for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); 00168 II != IE; ++II) { 00169 for (User::op_iterator OI = II->op_begin(), OE = II->op_end(); 00170 OI != OE; ++OI) 00171 if (definedInCaller(Blocks, *OI)) 00172 Inputs.insert(*OI); 00173 00174 for (Value::use_iterator UI = II->use_begin(), UE = II->use_end(); 00175 UI != UE; ++UI) 00176 if (!definedInRegion(Blocks, *UI)) { 00177 Outputs.insert(II); 00178 break; 00179 } 00180 } 00181 } 00182 } 00183 00184 /// severSplitPHINodes - If a PHI node has multiple inputs from outside of the 00185 /// region, we need to split the entry block of the region so that the PHI node 00186 /// is easier to deal with. 00187 void CodeExtractor::severSplitPHINodes(BasicBlock *&Header) { 00188 unsigned NumPredsFromRegion = 0; 00189 unsigned NumPredsOutsideRegion = 0; 00190 00191 if (Header != &Header->getParent()->getEntryBlock()) { 00192 PHINode *PN = dyn_cast<PHINode>(Header->begin()); 00193 if (!PN) return; // No PHI nodes. 00194 00195 // If the header node contains any PHI nodes, check to see if there is more 00196 // than one entry from outside the region. If so, we need to sever the 00197 // header block into two. 00198 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 00199 if (Blocks.count(PN->getIncomingBlock(i))) 00200 ++NumPredsFromRegion; 00201 else 00202 ++NumPredsOutsideRegion; 00203 00204 // If there is one (or fewer) predecessor from outside the region, we don't 00205 // need to do anything special. 00206 if (NumPredsOutsideRegion <= 1) return; 00207 } 00208 00209 // Otherwise, we need to split the header block into two pieces: one 00210 // containing PHI nodes merging values from outside of the region, and a 00211 // second that contains all of the code for the block and merges back any 00212 // incoming values from inside of the region. 00213 BasicBlock::iterator AfterPHIs = Header->getFirstNonPHI(); 00214 BasicBlock *NewBB = Header->splitBasicBlock(AfterPHIs, 00215 Header->getName()+".ce"); 00216 00217 // We only want to code extract the second block now, and it becomes the new 00218 // header of the region. 00219 BasicBlock *OldPred = Header; 00220 Blocks.remove(OldPred); 00221 Blocks.insert(NewBB); 00222 Header = NewBB; 00223 00224 // Okay, update dominator sets. The blocks that dominate the new one are the 00225 // blocks that dominate TIBB plus the new block itself. 00226 if (DT) 00227 DT->splitBlock(NewBB); 00228 00229 // Okay, now we need to adjust the PHI nodes and any branches from within the 00230 // region to go to the new header block instead of the old header block. 00231 if (NumPredsFromRegion) { 00232 PHINode *PN = cast<PHINode>(OldPred->begin()); 00233 // Loop over all of the predecessors of OldPred that are in the region, 00234 // changing them to branch to NewBB instead. 00235 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 00236 if (Blocks.count(PN->getIncomingBlock(i))) { 00237 TerminatorInst *TI = PN->getIncomingBlock(i)->getTerminator(); 00238 TI->replaceUsesOfWith(OldPred, NewBB); 00239 } 00240 00241 // Okay, everything within the region is now branching to the right block, we 00242 // just have to update the PHI nodes now, inserting PHI nodes into NewBB. 00243 for (AfterPHIs = OldPred->begin(); isa<PHINode>(AfterPHIs); ++AfterPHIs) { 00244 PHINode *PN = cast<PHINode>(AfterPHIs); 00245 // Create a new PHI node in the new region, which has an incoming value 00246 // from OldPred of PN. 00247 PHINode *NewPN = PHINode::Create(PN->getType(), 1 + NumPredsFromRegion, 00248 PN->getName()+".ce", NewBB->begin()); 00249 NewPN->addIncoming(PN, OldPred); 00250 00251 // Loop over all of the incoming value in PN, moving them to NewPN if they 00252 // are from the extracted region. 00253 for (unsigned i = 0; i != PN->getNumIncomingValues(); ++i) { 00254 if (Blocks.count(PN->getIncomingBlock(i))) { 00255 NewPN->addIncoming(PN->getIncomingValue(i), PN->getIncomingBlock(i)); 00256 PN->removeIncomingValue(i); 00257 --i; 00258 } 00259 } 00260 } 00261 } 00262 } 00263 00264 void CodeExtractor::splitReturnBlocks() { 00265 for (SetVector<BasicBlock *>::iterator I = Blocks.begin(), E = Blocks.end(); 00266 I != E; ++I) 00267 if (ReturnInst *RI = dyn_cast<ReturnInst>((*I)->getTerminator())) { 00268 BasicBlock *New = (*I)->splitBasicBlock(RI, (*I)->getName()+".ret"); 00269 if (DT) { 00270 // Old dominates New. New node dominates all other nodes dominated 00271 // by Old. 00272 DomTreeNode *OldNode = DT->getNode(*I); 00273 SmallVector<DomTreeNode*, 8> Children; 00274 for (DomTreeNode::iterator DI = OldNode->begin(), DE = OldNode->end(); 00275 DI != DE; ++DI) 00276 Children.push_back(*DI); 00277 00278 DomTreeNode *NewNode = DT->addNewBlock(New, *I); 00279 00280 for (SmallVector<DomTreeNode*, 8>::iterator I = Children.begin(), 00281 E = Children.end(); I != E; ++I) 00282 DT->changeImmediateDominator(*I, NewNode); 00283 } 00284 } 00285 } 00286 00287 /// constructFunction - make a function based on inputs and outputs, as follows: 00288 /// f(in0, ..., inN, out0, ..., outN) 00289 /// 00290 Function *CodeExtractor::constructFunction(const ValueSet &inputs, 00291 const ValueSet &outputs, 00292 BasicBlock *header, 00293 BasicBlock *newRootNode, 00294 BasicBlock *newHeader, 00295 Function *oldFunction, 00296 Module *M) { 00297 DEBUG(dbgs() << "inputs: " << inputs.size() << "\n"); 00298 DEBUG(dbgs() << "outputs: " << outputs.size() << "\n"); 00299 00300 // This function returns unsigned, outputs will go back by reference. 00301 switch (NumExitBlocks) { 00302 case 0: 00303 case 1: RetTy = Type::getVoidTy(header->getContext()); break; 00304 case 2: RetTy = Type::getInt1Ty(header->getContext()); break; 00305 default: RetTy = Type::getInt16Ty(header->getContext()); break; 00306 } 00307 00308 std::vector<Type*> paramTy; 00309 00310 // Add the types of the input values to the function's argument list 00311 for (ValueSet::const_iterator i = inputs.begin(), e = inputs.end(); 00312 i != e; ++i) { 00313 const Value *value = *i; 00314 DEBUG(dbgs() << "value used in func: " << *value << "\n"); 00315 paramTy.push_back(value->getType()); 00316 } 00317 00318 // Add the types of the output values to the function's argument list. 00319 for (ValueSet::const_iterator I = outputs.begin(), E = outputs.end(); 00320 I != E; ++I) { 00321 DEBUG(dbgs() << "instr used in func: " << **I << "\n"); 00322 if (AggregateArgs) 00323 paramTy.push_back((*I)->getType()); 00324 else 00325 paramTy.push_back(PointerType::getUnqual((*I)->getType())); 00326 } 00327 00328 DEBUG(dbgs() << "Function type: " << *RetTy << " f("); 00329 for (std::vector<Type*>::iterator i = paramTy.begin(), 00330 e = paramTy.end(); i != e; ++i) 00331 DEBUG(dbgs() << **i << ", "); 00332 DEBUG(dbgs() << ")\n"); 00333 00334 if (AggregateArgs && (inputs.size() + outputs.size() > 0)) { 00335 PointerType *StructPtr = 00336 PointerType::getUnqual(StructType::get(M->getContext(), paramTy)); 00337 paramTy.clear(); 00338 paramTy.push_back(StructPtr); 00339 } 00340 FunctionType *funcType = 00341 FunctionType::get(RetTy, paramTy, false); 00342 00343 // Create the new function 00344 Function *newFunction = Function::Create(funcType, 00345 GlobalValue::InternalLinkage, 00346 oldFunction->getName() + "_" + 00347 header->getName(), M); 00348 // If the old function is no-throw, so is the new one. 00349 if (oldFunction->doesNotThrow()) 00350 newFunction->setDoesNotThrow(); 00351 00352 newFunction->getBasicBlockList().push_back(newRootNode); 00353 00354 // Create an iterator to name all of the arguments we inserted. 00355 Function::arg_iterator AI = newFunction->arg_begin(); 00356 00357 // Rewrite all users of the inputs in the extracted region to use the 00358 // arguments (or appropriate addressing into struct) instead. 00359 for (unsigned i = 0, e = inputs.size(); i != e; ++i) { 00360 Value *RewriteVal; 00361 if (AggregateArgs) { 00362 Value *Idx[2]; 00363 Idx[0] = Constant::getNullValue(Type::getInt32Ty(header->getContext())); 00364 Idx[1] = ConstantInt::get(Type::getInt32Ty(header->getContext()), i); 00365 TerminatorInst *TI = newFunction->begin()->getTerminator(); 00366 GetElementPtrInst *GEP = 00367 GetElementPtrInst::Create(AI, Idx, "gep_" + inputs[i]->getName(), TI); 00368 RewriteVal = new LoadInst(GEP, "loadgep_" + inputs[i]->getName(), TI); 00369 } else 00370 RewriteVal = AI++; 00371 00372 std::vector<User*> Users(inputs[i]->use_begin(), inputs[i]->use_end()); 00373 for (std::vector<User*>::iterator use = Users.begin(), useE = Users.end(); 00374 use != useE; ++use) 00375 if (Instruction* inst = dyn_cast<Instruction>(*use)) 00376 if (Blocks.count(inst->getParent())) 00377 inst->replaceUsesOfWith(inputs[i], RewriteVal); 00378 } 00379 00380 // Set names for input and output arguments. 00381 if (!AggregateArgs) { 00382 AI = newFunction->arg_begin(); 00383 for (unsigned i = 0, e = inputs.size(); i != e; ++i, ++AI) 00384 AI->setName(inputs[i]->getName()); 00385 for (unsigned i = 0, e = outputs.size(); i != e; ++i, ++AI) 00386 AI->setName(outputs[i]->getName()+".out"); 00387 } 00388 00389 // Rewrite branches to basic blocks outside of the loop to new dummy blocks 00390 // within the new function. This must be done before we lose track of which 00391 // blocks were originally in the code region. 00392 std::vector<User*> Users(header->use_begin(), header->use_end()); 00393 for (unsigned i = 0, e = Users.size(); i != e; ++i) 00394 // The BasicBlock which contains the branch is not in the region 00395 // modify the branch target to a new block 00396 if (TerminatorInst *TI = dyn_cast<TerminatorInst>(Users[i])) 00397 if (!Blocks.count(TI->getParent()) && 00398 TI->getParent()->getParent() == oldFunction) 00399 TI->replaceUsesOfWith(header, newHeader); 00400 00401 return newFunction; 00402 } 00403 00404 /// FindPhiPredForUseInBlock - Given a value and a basic block, find a PHI 00405 /// that uses the value within the basic block, and return the predecessor 00406 /// block associated with that use, or return 0 if none is found. 00407 static BasicBlock* FindPhiPredForUseInBlock(Value* Used, BasicBlock* BB) { 00408 for (Value::use_iterator UI = Used->use_begin(), 00409 UE = Used->use_end(); UI != UE; ++UI) { 00410 PHINode *P = dyn_cast<PHINode>(*UI); 00411 if (P && P->getParent() == BB) 00412 return P->getIncomingBlock(UI); 00413 } 00414 00415 return 0; 00416 } 00417 00418 /// emitCallAndSwitchStatement - This method sets up the caller side by adding 00419 /// the call instruction, splitting any PHI nodes in the header block as 00420 /// necessary. 00421 void CodeExtractor:: 00422 emitCallAndSwitchStatement(Function *newFunction, BasicBlock *codeReplacer, 00423 ValueSet &inputs, ValueSet &outputs) { 00424 // Emit a call to the new function, passing in: *pointer to struct (if 00425 // aggregating parameters), or plan inputs and allocated memory for outputs 00426 std::vector<Value*> params, StructValues, ReloadOutputs, Reloads; 00427 00428 LLVMContext &Context = newFunction->getContext(); 00429 00430 // Add inputs as params, or to be filled into the struct 00431 for (ValueSet::iterator i = inputs.begin(), e = inputs.end(); i != e; ++i) 00432 if (AggregateArgs) 00433 StructValues.push_back(*i); 00434 else 00435 params.push_back(*i); 00436 00437 // Create allocas for the outputs 00438 for (ValueSet::iterator i = outputs.begin(), e = outputs.end(); i != e; ++i) { 00439 if (AggregateArgs) { 00440 StructValues.push_back(*i); 00441 } else { 00442 AllocaInst *alloca = 00443 new AllocaInst((*i)->getType(), 0, (*i)->getName()+".loc", 00444 codeReplacer->getParent()->begin()->begin()); 00445 ReloadOutputs.push_back(alloca); 00446 params.push_back(alloca); 00447 } 00448 } 00449 00450 AllocaInst *Struct = 0; 00451 if (AggregateArgs && (inputs.size() + outputs.size() > 0)) { 00452 std::vector<Type*> ArgTypes; 00453 for (ValueSet::iterator v = StructValues.begin(), 00454 ve = StructValues.end(); v != ve; ++v) 00455 ArgTypes.push_back((*v)->getType()); 00456 00457 // Allocate a struct at the beginning of this function 00458 Type *StructArgTy = StructType::get(newFunction->getContext(), ArgTypes); 00459 Struct = 00460 new AllocaInst(StructArgTy, 0, "structArg", 00461 codeReplacer->getParent()->begin()->begin()); 00462 params.push_back(Struct); 00463 00464 for (unsigned i = 0, e = inputs.size(); i != e; ++i) { 00465 Value *Idx[2]; 00466 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context)); 00467 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), i); 00468 GetElementPtrInst *GEP = 00469 GetElementPtrInst::Create(Struct, Idx, 00470 "gep_" + StructValues[i]->getName()); 00471 codeReplacer->getInstList().push_back(GEP); 00472 StoreInst *SI = new StoreInst(StructValues[i], GEP); 00473 codeReplacer->getInstList().push_back(SI); 00474 } 00475 } 00476 00477 // Emit the call to the function 00478 CallInst *call = CallInst::Create(newFunction, params, 00479 NumExitBlocks > 1 ? "targetBlock" : ""); 00480 codeReplacer->getInstList().push_back(call); 00481 00482 Function::arg_iterator OutputArgBegin = newFunction->arg_begin(); 00483 unsigned FirstOut = inputs.size(); 00484 if (!AggregateArgs) 00485 std::advance(OutputArgBegin, inputs.size()); 00486 00487 // Reload the outputs passed in by reference 00488 for (unsigned i = 0, e = outputs.size(); i != e; ++i) { 00489 Value *Output = 0; 00490 if (AggregateArgs) { 00491 Value *Idx[2]; 00492 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context)); 00493 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), FirstOut + i); 00494 GetElementPtrInst *GEP 00495 = GetElementPtrInst::Create(Struct, Idx, 00496 "gep_reload_" + outputs[i]->getName()); 00497 codeReplacer->getInstList().push_back(GEP); 00498 Output = GEP; 00499 } else { 00500 Output = ReloadOutputs[i]; 00501 } 00502 LoadInst *load = new LoadInst(Output, outputs[i]->getName()+".reload"); 00503 Reloads.push_back(load); 00504 codeReplacer->getInstList().push_back(load); 00505 std::vector<User*> Users(outputs[i]->use_begin(), outputs[i]->use_end()); 00506 for (unsigned u = 0, e = Users.size(); u != e; ++u) { 00507 Instruction *inst = cast<Instruction>(Users[u]); 00508 if (!Blocks.count(inst->getParent())) 00509 inst->replaceUsesOfWith(outputs[i], load); 00510 } 00511 } 00512 00513 // Now we can emit a switch statement using the call as a value. 00514 SwitchInst *TheSwitch = 00515 SwitchInst::Create(Constant::getNullValue(Type::getInt16Ty(Context)), 00516 codeReplacer, 0, codeReplacer); 00517 00518 // Since there may be multiple exits from the original region, make the new 00519 // function return an unsigned, switch on that number. This loop iterates 00520 // over all of the blocks in the extracted region, updating any terminator 00521 // instructions in the to-be-extracted region that branch to blocks that are 00522 // not in the region to be extracted. 00523 std::map<BasicBlock*, BasicBlock*> ExitBlockMap; 00524 00525 unsigned switchVal = 0; 00526 for (SetVector<BasicBlock*>::const_iterator i = Blocks.begin(), 00527 e = Blocks.end(); i != e; ++i) { 00528 TerminatorInst *TI = (*i)->getTerminator(); 00529 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) 00530 if (!Blocks.count(TI->getSuccessor(i))) { 00531 BasicBlock *OldTarget = TI->getSuccessor(i); 00532 // add a new basic block which returns the appropriate value 00533 BasicBlock *&NewTarget = ExitBlockMap[OldTarget]; 00534 if (!NewTarget) { 00535 // If we don't already have an exit stub for this non-extracted 00536 // destination, create one now! 00537 NewTarget = BasicBlock::Create(Context, 00538 OldTarget->getName() + ".exitStub", 00539 newFunction); 00540 unsigned SuccNum = switchVal++; 00541 00542 Value *brVal = 0; 00543 switch (NumExitBlocks) { 00544 case 0: 00545 case 1: break; // No value needed. 00546 case 2: // Conditional branch, return a bool 00547 brVal = ConstantInt::get(Type::getInt1Ty(Context), !SuccNum); 00548 break; 00549 default: 00550 brVal = ConstantInt::get(Type::getInt16Ty(Context), SuccNum); 00551 break; 00552 } 00553 00554 ReturnInst *NTRet = ReturnInst::Create(Context, brVal, NewTarget); 00555 00556 // Update the switch instruction. 00557 TheSwitch->addCase(ConstantInt::get(Type::getInt16Ty(Context), 00558 SuccNum), 00559 OldTarget); 00560 00561 // Restore values just before we exit 00562 Function::arg_iterator OAI = OutputArgBegin; 00563 for (unsigned out = 0, e = outputs.size(); out != e; ++out) { 00564 // For an invoke, the normal destination is the only one that is 00565 // dominated by the result of the invocation 00566 BasicBlock *DefBlock = cast<Instruction>(outputs[out])->getParent(); 00567 00568 bool DominatesDef = true; 00569 00570 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(outputs[out])) { 00571 DefBlock = Invoke->getNormalDest(); 00572 00573 // Make sure we are looking at the original successor block, not 00574 // at a newly inserted exit block, which won't be in the dominator 00575 // info. 00576 for (std::map<BasicBlock*, BasicBlock*>::iterator I = 00577 ExitBlockMap.begin(), E = ExitBlockMap.end(); I != E; ++I) 00578 if (DefBlock == I->second) { 00579 DefBlock = I->first; 00580 break; 00581 } 00582 00583 // In the extract block case, if the block we are extracting ends 00584 // with an invoke instruction, make sure that we don't emit a 00585 // store of the invoke value for the unwind block. 00586 if (!DT && DefBlock != OldTarget) 00587 DominatesDef = false; 00588 } 00589 00590 if (DT) { 00591 DominatesDef = DT->dominates(DefBlock, OldTarget); 00592 00593 // If the output value is used by a phi in the target block, 00594 // then we need to test for dominance of the phi's predecessor 00595 // instead. Unfortunately, this a little complicated since we 00596 // have already rewritten uses of the value to uses of the reload. 00597 BasicBlock* pred = FindPhiPredForUseInBlock(Reloads[out], 00598 OldTarget); 00599 if (pred && DT && DT->dominates(DefBlock, pred)) 00600 DominatesDef = true; 00601 } 00602 00603 if (DominatesDef) { 00604 if (AggregateArgs) { 00605 Value *Idx[2]; 00606 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context)); 00607 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), 00608 FirstOut+out); 00609 GetElementPtrInst *GEP = 00610 GetElementPtrInst::Create(OAI, Idx, 00611 "gep_" + outputs[out]->getName(), 00612 NTRet); 00613 new StoreInst(outputs[out], GEP, NTRet); 00614 } else { 00615 new StoreInst(outputs[out], OAI, NTRet); 00616 } 00617 } 00618 // Advance output iterator even if we don't emit a store 00619 if (!AggregateArgs) ++OAI; 00620 } 00621 } 00622 00623 // rewrite the original branch instruction with this new target 00624 TI->setSuccessor(i, NewTarget); 00625 } 00626 } 00627 00628 // Now that we've done the deed, simplify the switch instruction. 00629 Type *OldFnRetTy = TheSwitch->getParent()->getParent()->getReturnType(); 00630 switch (NumExitBlocks) { 00631 case 0: 00632 // There are no successors (the block containing the switch itself), which 00633 // means that previously this was the last part of the function, and hence 00634 // this should be rewritten as a `ret' 00635 00636 // Check if the function should return a value 00637 if (OldFnRetTy->isVoidTy()) { 00638 ReturnInst::Create(Context, 0, TheSwitch); // Return void 00639 } else if (OldFnRetTy == TheSwitch->getCondition()->getType()) { 00640 // return what we have 00641 ReturnInst::Create(Context, TheSwitch->getCondition(), TheSwitch); 00642 } else { 00643 // Otherwise we must have code extracted an unwind or something, just 00644 // return whatever we want. 00645 ReturnInst::Create(Context, 00646 Constant::getNullValue(OldFnRetTy), TheSwitch); 00647 } 00648 00649 TheSwitch->eraseFromParent(); 00650 break; 00651 case 1: 00652 // Only a single destination, change the switch into an unconditional 00653 // branch. 00654 BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch); 00655 TheSwitch->eraseFromParent(); 00656 break; 00657 case 2: 00658 BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch->getSuccessor(2), 00659 call, TheSwitch); 00660 TheSwitch->eraseFromParent(); 00661 break; 00662 default: 00663 // Otherwise, make the default destination of the switch instruction be one 00664 // of the other successors. 00665 TheSwitch->setCondition(call); 00666 TheSwitch->setDefaultDest(TheSwitch->getSuccessor(NumExitBlocks)); 00667 // Remove redundant case 00668 SwitchInst::CaseIt ToBeRemoved(TheSwitch, NumExitBlocks-1); 00669 TheSwitch->removeCase(ToBeRemoved); 00670 break; 00671 } 00672 } 00673 00674 void CodeExtractor::moveCodeToFunction(Function *newFunction) { 00675 Function *oldFunc = (*Blocks.begin())->getParent(); 00676 Function::BasicBlockListType &oldBlocks = oldFunc->getBasicBlockList(); 00677 Function::BasicBlockListType &newBlocks = newFunction->getBasicBlockList(); 00678 00679 for (SetVector<BasicBlock*>::const_iterator i = Blocks.begin(), 00680 e = Blocks.end(); i != e; ++i) { 00681 // Delete the basic block from the old function, and the list of blocks 00682 oldBlocks.remove(*i); 00683 00684 // Insert this basic block into the new function 00685 newBlocks.push_back(*i); 00686 } 00687 } 00688 00689 Function *CodeExtractor::extractCodeRegion() { 00690 if (!isEligible()) 00691 return 0; 00692 00693 ValueSet inputs, outputs; 00694 00695 // Assumption: this is a single-entry code region, and the header is the first 00696 // block in the region. 00697 BasicBlock *header = *Blocks.begin(); 00698 00699 // If we have to split PHI nodes or the entry block, do so now. 00700 severSplitPHINodes(header); 00701 00702 // If we have any return instructions in the region, split those blocks so 00703 // that the return is not in the region. 00704 splitReturnBlocks(); 00705 00706 Function *oldFunction = header->getParent(); 00707 00708 // This takes place of the original loop 00709 BasicBlock *codeReplacer = BasicBlock::Create(header->getContext(), 00710 "codeRepl", oldFunction, 00711 header); 00712 00713 // The new function needs a root node because other nodes can branch to the 00714 // head of the region, but the entry node of a function cannot have preds. 00715 BasicBlock *newFuncRoot = BasicBlock::Create(header->getContext(), 00716 "newFuncRoot"); 00717 newFuncRoot->getInstList().push_back(BranchInst::Create(header)); 00718 00719 // Find inputs to, outputs from the code region. 00720 findInputsOutputs(inputs, outputs); 00721 00722 SmallPtrSet<BasicBlock *, 1> ExitBlocks; 00723 for (SetVector<BasicBlock *>::iterator I = Blocks.begin(), E = Blocks.end(); 00724 I != E; ++I) 00725 for (succ_iterator SI = succ_begin(*I), SE = succ_end(*I); SI != SE; ++SI) 00726 if (!Blocks.count(*SI)) 00727 ExitBlocks.insert(*SI); 00728 NumExitBlocks = ExitBlocks.size(); 00729 00730 // Construct new function based on inputs/outputs & add allocas for all defs. 00731 Function *newFunction = constructFunction(inputs, outputs, header, 00732 newFuncRoot, 00733 codeReplacer, oldFunction, 00734 oldFunction->getParent()); 00735 00736 emitCallAndSwitchStatement(newFunction, codeReplacer, inputs, outputs); 00737 00738 moveCodeToFunction(newFunction); 00739 00740 // Loop over all of the PHI nodes in the header block, and change any 00741 // references to the old incoming edge to be the new incoming edge. 00742 for (BasicBlock::iterator I = header->begin(); isa<PHINode>(I); ++I) { 00743 PHINode *PN = cast<PHINode>(I); 00744 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 00745 if (!Blocks.count(PN->getIncomingBlock(i))) 00746 PN->setIncomingBlock(i, newFuncRoot); 00747 } 00748 00749 // Look at all successors of the codeReplacer block. If any of these blocks 00750 // had PHI nodes in them, we need to update the "from" block to be the code 00751 // replacer, not the original block in the extracted region. 00752 std::vector<BasicBlock*> Succs(succ_begin(codeReplacer), 00753 succ_end(codeReplacer)); 00754 for (unsigned i = 0, e = Succs.size(); i != e; ++i) 00755 for (BasicBlock::iterator I = Succs[i]->begin(); isa<PHINode>(I); ++I) { 00756 PHINode *PN = cast<PHINode>(I); 00757 std::set<BasicBlock*> ProcessedPreds; 00758 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 00759 if (Blocks.count(PN->getIncomingBlock(i))) { 00760 if (ProcessedPreds.insert(PN->getIncomingBlock(i)).second) 00761 PN->setIncomingBlock(i, codeReplacer); 00762 else { 00763 // There were multiple entries in the PHI for this block, now there 00764 // is only one, so remove the duplicated entries. 00765 PN->removeIncomingValue(i, false); 00766 --i; --e; 00767 } 00768 } 00769 } 00770 00771 //cerr << "NEW FUNCTION: " << *newFunction; 00772 // verifyFunction(*newFunction); 00773 00774 // cerr << "OLD FUNCTION: " << *oldFunction; 00775 // verifyFunction(*oldFunction); 00776 00777 DEBUG(if (verifyFunction(*newFunction)) 00778 report_fatal_error("verifyFunction failed!")); 00779 return newFunction; 00780 }