CodeExtractor.cpp revision 30ba82933c433611e05b07ef95da36bba8721b8b
1//===- CodeExtractor.cpp - Pull code region into a new function -----------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 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 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/RegionInfo.h" 27#include "llvm/Analysis/RegionIterator.h" 28#include "llvm/Analysis/Verifier.h" 29#include "llvm/Transforms/Utils/BasicBlockUtils.h" 30#include "llvm/Support/CommandLine.h" 31#include "llvm/Support/Debug.h" 32#include "llvm/Support/ErrorHandling.h" 33#include "llvm/Support/raw_ostream.h" 34#include "llvm/ADT/SetVector.h" 35#include "llvm/ADT/StringExtras.h" 36#include <algorithm> 37#include <set> 38using namespace llvm; 39 40// Provide a command-line option to aggregate function arguments into a struct 41// for functions produced by the code extractor. This is useful when converting 42// extracted functions to pthread-based code, as only one argument (void*) can 43// be passed in to pthread_create(). 44static cl::opt<bool> 45AggregateArgsOpt("aggregate-extracted-args", cl::Hidden, 46 cl::desc("Aggregate arguments to code-extracted functions")); 47 48/// \brief Test whether a block is valid for extraction. 49static bool isBlockValidForExtraction(const BasicBlock &BB) { 50 // Landing pads must be in the function where they were inserted for cleanup. 51 if (BB.isLandingPad()) 52 return false; 53 54 // Don't hoist code containing allocas, invokes, or vastarts. 55 for (BasicBlock::const_iterator I = BB.begin(), E = BB.end(); I != E; ++I) { 56 if (isa<AllocaInst>(I) || isa<InvokeInst>(I)) 57 return false; 58 if (const CallInst *CI = dyn_cast<CallInst>(I)) 59 if (const Function *F = CI->getCalledFunction()) 60 if (F->getIntrinsicID() == Intrinsic::vastart) 61 return false; 62 } 63 64 return true; 65} 66 67/// \brief Build a set of blocks to extract if the input blocks are viable. 68template <typename IteratorT> 69static SetVector<BasicBlock *> buildExtractionBlockSet(IteratorT BBBegin, 70 IteratorT BBEnd) { 71 SetVector<BasicBlock *> Result; 72 73 assert(BBBegin != BBEnd); 74 75 // Loop over the blocks, adding them to our set-vector, and aborting with an 76 // empty set if we encounter invalid blocks. 77 for (IteratorT I = BBBegin, E = BBEnd; I != E; ++I) { 78 if (!Result.insert(*I)) 79 llvm_unreachable("Repeated basic blocks in extraction input"); 80 81 if (!isBlockValidForExtraction(**I)) { 82 Result.clear(); 83 return Result; 84 } 85 } 86 87#ifndef NDEBUG 88 for (SetVector<BasicBlock *>::iterator I = llvm::next(Result.begin()), 89 E = Result.end(); 90 I != E; ++I) 91 for (pred_iterator PI = pred_begin(*I), PE = pred_end(*I); 92 PI != PE; ++PI) 93 assert(Result.count(*PI) && 94 "No blocks in this region may have entries from outside the region" 95 " except for the first block!"); 96#endif 97 98 return Result; 99} 100 101/// \brief Helper to call buildExtractionBlockSet with an ArrayRef. 102static SetVector<BasicBlock *> 103buildExtractionBlockSet(ArrayRef<BasicBlock *> BBs) { 104 return buildExtractionBlockSet(BBs.begin(), BBs.end()); 105} 106 107/// \brief Helper to call buildExtractionBlockSet with a RegionNode. 108static SetVector<BasicBlock *> 109buildExtractionBlockSet(const RegionNode &RN) { 110 if (!RN.isSubRegion()) 111 // Just a single BasicBlock. 112 return buildExtractionBlockSet(RN.getNodeAs<BasicBlock>()); 113 114 const Region &R = *RN.getNodeAs<Region>(); 115 116 return buildExtractionBlockSet(R.block_begin(), R.block_end()); 117} 118 119CodeExtractor::CodeExtractor(BasicBlock *BB, bool AggregateArgs) 120 : DT(0), AggregateArgs(AggregateArgs||AggregateArgsOpt), 121 Blocks(buildExtractionBlockSet(BB)), NumExitBlocks(~0U) {} 122 123CodeExtractor::CodeExtractor(ArrayRef<BasicBlock *> BBs, DominatorTree *DT, 124 bool AggregateArgs) 125 : DT(DT), AggregateArgs(AggregateArgs||AggregateArgsOpt), 126 Blocks(buildExtractionBlockSet(BBs)), NumExitBlocks(~0U) {} 127 128CodeExtractor::CodeExtractor(DominatorTree &DT, Loop &L, bool AggregateArgs) 129 : DT(&DT), AggregateArgs(AggregateArgs||AggregateArgsOpt), 130 Blocks(buildExtractionBlockSet(L.getBlocks())), NumExitBlocks(~0U) {} 131 132CodeExtractor::CodeExtractor(DominatorTree &DT, const RegionNode &RN, 133 bool AggregateArgs) 134 : DT(&DT), AggregateArgs(AggregateArgs||AggregateArgsOpt), 135 Blocks(buildExtractionBlockSet(RN)), NumExitBlocks(~0U) {} 136 137/// definedInRegion - Return true if the specified value is defined in the 138/// extracted region. 139static bool definedInRegion(const SetVector<BasicBlock *> &Blocks, Value *V) { 140 if (Instruction *I = dyn_cast<Instruction>(V)) 141 if (Blocks.count(I->getParent())) 142 return true; 143 return false; 144} 145 146/// definedInCaller - Return true if the specified value is defined in the 147/// function being code extracted, but not in the region being extracted. 148/// These values must be passed in as live-ins to the function. 149static bool definedInCaller(const SetVector<BasicBlock *> &Blocks, Value *V) { 150 if (isa<Argument>(V)) return true; 151 if (Instruction *I = dyn_cast<Instruction>(V)) 152 if (!Blocks.count(I->getParent())) 153 return true; 154 return false; 155} 156 157void CodeExtractor::findInputsOutputs(ValueSet &Inputs, 158 ValueSet &Outputs) const { 159 for (SetVector<BasicBlock *>::const_iterator I = Blocks.begin(), 160 E = Blocks.end(); 161 I != E; ++I) { 162 BasicBlock *BB = *I; 163 164 // If a used value is defined outside the region, it's an input. If an 165 // instruction is used outside the region, it's an output. 166 for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); 167 II != IE; ++II) { 168 for (User::op_iterator OI = II->op_begin(), OE = II->op_end(); 169 OI != OE; ++OI) 170 if (definedInCaller(Blocks, *OI)) 171 Inputs.insert(*OI); 172 173 for (Value::use_iterator UI = II->use_begin(), UE = II->use_end(); 174 UI != UE; ++UI) 175 if (!definedInRegion(Blocks, *UI)) { 176 Outputs.insert(II); 177 break; 178 } 179 } 180 } 181} 182 183/// severSplitPHINodes - If a PHI node has multiple inputs from outside of the 184/// region, we need to split the entry block of the region so that the PHI node 185/// is easier to deal with. 186void CodeExtractor::severSplitPHINodes(BasicBlock *&Header) { 187 unsigned NumPredsFromRegion = 0; 188 unsigned NumPredsOutsideRegion = 0; 189 190 if (Header != &Header->getParent()->getEntryBlock()) { 191 PHINode *PN = dyn_cast<PHINode>(Header->begin()); 192 if (!PN) return; // No PHI nodes. 193 194 // If the header node contains any PHI nodes, check to see if there is more 195 // than one entry from outside the region. If so, we need to sever the 196 // header block into two. 197 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 198 if (Blocks.count(PN->getIncomingBlock(i))) 199 ++NumPredsFromRegion; 200 else 201 ++NumPredsOutsideRegion; 202 203 // If there is one (or fewer) predecessor from outside the region, we don't 204 // need to do anything special. 205 if (NumPredsOutsideRegion <= 1) return; 206 } 207 208 // Otherwise, we need to split the header block into two pieces: one 209 // containing PHI nodes merging values from outside of the region, and a 210 // second that contains all of the code for the block and merges back any 211 // incoming values from inside of the region. 212 BasicBlock::iterator AfterPHIs = Header->getFirstNonPHI(); 213 BasicBlock *NewBB = Header->splitBasicBlock(AfterPHIs, 214 Header->getName()+".ce"); 215 216 // We only want to code extract the second block now, and it becomes the new 217 // header of the region. 218 BasicBlock *OldPred = Header; 219 Blocks.remove(OldPred); 220 Blocks.insert(NewBB); 221 Header = NewBB; 222 223 // Okay, update dominator sets. The blocks that dominate the new one are the 224 // blocks that dominate TIBB plus the new block itself. 225 if (DT) 226 DT->splitBlock(NewBB); 227 228 // Okay, now we need to adjust the PHI nodes and any branches from within the 229 // region to go to the new header block instead of the old header block. 230 if (NumPredsFromRegion) { 231 PHINode *PN = cast<PHINode>(OldPred->begin()); 232 // Loop over all of the predecessors of OldPred that are in the region, 233 // changing them to branch to NewBB instead. 234 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 235 if (Blocks.count(PN->getIncomingBlock(i))) { 236 TerminatorInst *TI = PN->getIncomingBlock(i)->getTerminator(); 237 TI->replaceUsesOfWith(OldPred, NewBB); 238 } 239 240 // Okay, everything within the region is now branching to the right block, we 241 // just have to update the PHI nodes now, inserting PHI nodes into NewBB. 242 for (AfterPHIs = OldPred->begin(); isa<PHINode>(AfterPHIs); ++AfterPHIs) { 243 PHINode *PN = cast<PHINode>(AfterPHIs); 244 // Create a new PHI node in the new region, which has an incoming value 245 // from OldPred of PN. 246 PHINode *NewPN = PHINode::Create(PN->getType(), 1 + NumPredsFromRegion, 247 PN->getName()+".ce", NewBB->begin()); 248 NewPN->addIncoming(PN, OldPred); 249 250 // Loop over all of the incoming value in PN, moving them to NewPN if they 251 // are from the extracted region. 252 for (unsigned i = 0; i != PN->getNumIncomingValues(); ++i) { 253 if (Blocks.count(PN->getIncomingBlock(i))) { 254 NewPN->addIncoming(PN->getIncomingValue(i), PN->getIncomingBlock(i)); 255 PN->removeIncomingValue(i); 256 --i; 257 } 258 } 259 } 260 } 261} 262 263void CodeExtractor::splitReturnBlocks() { 264 for (SetVector<BasicBlock *>::iterator I = Blocks.begin(), E = Blocks.end(); 265 I != E; ++I) 266 if (ReturnInst *RI = dyn_cast<ReturnInst>((*I)->getTerminator())) { 267 BasicBlock *New = (*I)->splitBasicBlock(RI, (*I)->getName()+".ret"); 268 if (DT) { 269 // Old dominates New. New node dominates all other nodes dominated 270 // by Old. 271 DomTreeNode *OldNode = DT->getNode(*I); 272 SmallVector<DomTreeNode*, 8> Children; 273 for (DomTreeNode::iterator DI = OldNode->begin(), DE = OldNode->end(); 274 DI != DE; ++DI) 275 Children.push_back(*DI); 276 277 DomTreeNode *NewNode = DT->addNewBlock(New, *I); 278 279 for (SmallVector<DomTreeNode*, 8>::iterator I = Children.begin(), 280 E = Children.end(); I != E; ++I) 281 DT->changeImmediateDominator(*I, NewNode); 282 } 283 } 284} 285 286/// constructFunction - make a function based on inputs and outputs, as follows: 287/// f(in0, ..., inN, out0, ..., outN) 288/// 289Function *CodeExtractor::constructFunction(const ValueSet &inputs, 290 const ValueSet &outputs, 291 BasicBlock *header, 292 BasicBlock *newRootNode, 293 BasicBlock *newHeader, 294 Function *oldFunction, 295 Module *M) { 296 DEBUG(dbgs() << "inputs: " << inputs.size() << "\n"); 297 DEBUG(dbgs() << "outputs: " << outputs.size() << "\n"); 298 299 // This function returns unsigned, outputs will go back by reference. 300 switch (NumExitBlocks) { 301 case 0: 302 case 1: RetTy = Type::getVoidTy(header->getContext()); break; 303 case 2: RetTy = Type::getInt1Ty(header->getContext()); break; 304 default: RetTy = Type::getInt16Ty(header->getContext()); break; 305 } 306 307 std::vector<Type*> paramTy; 308 309 // Add the types of the input values to the function's argument list 310 for (ValueSet::const_iterator i = inputs.begin(), e = inputs.end(); 311 i != e; ++i) { 312 const Value *value = *i; 313 DEBUG(dbgs() << "value used in func: " << *value << "\n"); 314 paramTy.push_back(value->getType()); 315 } 316 317 // Add the types of the output values to the function's argument list. 318 for (ValueSet::const_iterator I = outputs.begin(), E = outputs.end(); 319 I != E; ++I) { 320 DEBUG(dbgs() << "instr used in func: " << **I << "\n"); 321 if (AggregateArgs) 322 paramTy.push_back((*I)->getType()); 323 else 324 paramTy.push_back(PointerType::getUnqual((*I)->getType())); 325 } 326 327 DEBUG(dbgs() << "Function type: " << *RetTy << " f("); 328 for (std::vector<Type*>::iterator i = paramTy.begin(), 329 e = paramTy.end(); i != e; ++i) 330 DEBUG(dbgs() << **i << ", "); 331 DEBUG(dbgs() << ")\n"); 332 333 if (AggregateArgs && (inputs.size() + outputs.size() > 0)) { 334 PointerType *StructPtr = 335 PointerType::getUnqual(StructType::get(M->getContext(), paramTy)); 336 paramTy.clear(); 337 paramTy.push_back(StructPtr); 338 } 339 FunctionType *funcType = 340 FunctionType::get(RetTy, paramTy, false); 341 342 // Create the new function 343 Function *newFunction = Function::Create(funcType, 344 GlobalValue::InternalLinkage, 345 oldFunction->getName() + "_" + 346 header->getName(), M); 347 // If the old function is no-throw, so is the new one. 348 if (oldFunction->doesNotThrow()) 349 newFunction->setDoesNotThrow(true); 350 351 newFunction->getBasicBlockList().push_back(newRootNode); 352 353 // Create an iterator to name all of the arguments we inserted. 354 Function::arg_iterator AI = newFunction->arg_begin(); 355 356 // Rewrite all users of the inputs in the extracted region to use the 357 // arguments (or appropriate addressing into struct) instead. 358 for (unsigned i = 0, e = inputs.size(); i != e; ++i) { 359 Value *RewriteVal; 360 if (AggregateArgs) { 361 Value *Idx[2]; 362 Idx[0] = Constant::getNullValue(Type::getInt32Ty(header->getContext())); 363 Idx[1] = ConstantInt::get(Type::getInt32Ty(header->getContext()), i); 364 TerminatorInst *TI = newFunction->begin()->getTerminator(); 365 GetElementPtrInst *GEP = 366 GetElementPtrInst::Create(AI, Idx, "gep_" + inputs[i]->getName(), TI); 367 RewriteVal = new LoadInst(GEP, "loadgep_" + inputs[i]->getName(), TI); 368 } else 369 RewriteVal = AI++; 370 371 std::vector<User*> Users(inputs[i]->use_begin(), inputs[i]->use_end()); 372 for (std::vector<User*>::iterator use = Users.begin(), useE = Users.end(); 373 use != useE; ++use) 374 if (Instruction* inst = dyn_cast<Instruction>(*use)) 375 if (Blocks.count(inst->getParent())) 376 inst->replaceUsesOfWith(inputs[i], RewriteVal); 377 } 378 379 // Set names for input and output arguments. 380 if (!AggregateArgs) { 381 AI = newFunction->arg_begin(); 382 for (unsigned i = 0, e = inputs.size(); i != e; ++i, ++AI) 383 AI->setName(inputs[i]->getName()); 384 for (unsigned i = 0, e = outputs.size(); i != e; ++i, ++AI) 385 AI->setName(outputs[i]->getName()+".out"); 386 } 387 388 // Rewrite branches to basic blocks outside of the loop to new dummy blocks 389 // within the new function. This must be done before we lose track of which 390 // blocks were originally in the code region. 391 std::vector<User*> Users(header->use_begin(), header->use_end()); 392 for (unsigned i = 0, e = Users.size(); i != e; ++i) 393 // The BasicBlock which contains the branch is not in the region 394 // modify the branch target to a new block 395 if (TerminatorInst *TI = dyn_cast<TerminatorInst>(Users[i])) 396 if (!Blocks.count(TI->getParent()) && 397 TI->getParent()->getParent() == oldFunction) 398 TI->replaceUsesOfWith(header, newHeader); 399 400 return newFunction; 401} 402 403/// FindPhiPredForUseInBlock - Given a value and a basic block, find a PHI 404/// that uses the value within the basic block, and return the predecessor 405/// block associated with that use, or return 0 if none is found. 406static BasicBlock* FindPhiPredForUseInBlock(Value* Used, BasicBlock* BB) { 407 for (Value::use_iterator UI = Used->use_begin(), 408 UE = Used->use_end(); UI != UE; ++UI) { 409 PHINode *P = dyn_cast<PHINode>(*UI); 410 if (P && P->getParent() == BB) 411 return P->getIncomingBlock(UI); 412 } 413 414 return 0; 415} 416 417/// emitCallAndSwitchStatement - This method sets up the caller side by adding 418/// the call instruction, splitting any PHI nodes in the header block as 419/// necessary. 420void CodeExtractor:: 421emitCallAndSwitchStatement(Function *newFunction, BasicBlock *codeReplacer, 422 ValueSet &inputs, ValueSet &outputs) { 423 // Emit a call to the new function, passing in: *pointer to struct (if 424 // aggregating parameters), or plan inputs and allocated memory for outputs 425 std::vector<Value*> params, StructValues, ReloadOutputs, Reloads; 426 427 LLVMContext &Context = newFunction->getContext(); 428 429 // Add inputs as params, or to be filled into the struct 430 for (ValueSet::iterator i = inputs.begin(), e = inputs.end(); i != e; ++i) 431 if (AggregateArgs) 432 StructValues.push_back(*i); 433 else 434 params.push_back(*i); 435 436 // Create allocas for the outputs 437 for (ValueSet::iterator i = outputs.begin(), e = outputs.end(); i != e; ++i) { 438 if (AggregateArgs) { 439 StructValues.push_back(*i); 440 } else { 441 AllocaInst *alloca = 442 new AllocaInst((*i)->getType(), 0, (*i)->getName()+".loc", 443 codeReplacer->getParent()->begin()->begin()); 444 ReloadOutputs.push_back(alloca); 445 params.push_back(alloca); 446 } 447 } 448 449 AllocaInst *Struct = 0; 450 if (AggregateArgs && (inputs.size() + outputs.size() > 0)) { 451 std::vector<Type*> ArgTypes; 452 for (ValueSet::iterator v = StructValues.begin(), 453 ve = StructValues.end(); v != ve; ++v) 454 ArgTypes.push_back((*v)->getType()); 455 456 // Allocate a struct at the beginning of this function 457 Type *StructArgTy = StructType::get(newFunction->getContext(), ArgTypes); 458 Struct = 459 new AllocaInst(StructArgTy, 0, "structArg", 460 codeReplacer->getParent()->begin()->begin()); 461 params.push_back(Struct); 462 463 for (unsigned i = 0, e = inputs.size(); i != e; ++i) { 464 Value *Idx[2]; 465 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context)); 466 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), i); 467 GetElementPtrInst *GEP = 468 GetElementPtrInst::Create(Struct, Idx, 469 "gep_" + StructValues[i]->getName()); 470 codeReplacer->getInstList().push_back(GEP); 471 StoreInst *SI = new StoreInst(StructValues[i], GEP); 472 codeReplacer->getInstList().push_back(SI); 473 } 474 } 475 476 // Emit the call to the function 477 CallInst *call = CallInst::Create(newFunction, params, 478 NumExitBlocks > 1 ? "targetBlock" : ""); 479 codeReplacer->getInstList().push_back(call); 480 481 Function::arg_iterator OutputArgBegin = newFunction->arg_begin(); 482 unsigned FirstOut = inputs.size(); 483 if (!AggregateArgs) 484 std::advance(OutputArgBegin, inputs.size()); 485 486 // Reload the outputs passed in by reference 487 for (unsigned i = 0, e = outputs.size(); i != e; ++i) { 488 Value *Output = 0; 489 if (AggregateArgs) { 490 Value *Idx[2]; 491 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context)); 492 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), FirstOut + i); 493 GetElementPtrInst *GEP 494 = GetElementPtrInst::Create(Struct, Idx, 495 "gep_reload_" + outputs[i]->getName()); 496 codeReplacer->getInstList().push_back(GEP); 497 Output = GEP; 498 } else { 499 Output = ReloadOutputs[i]; 500 } 501 LoadInst *load = new LoadInst(Output, outputs[i]->getName()+".reload"); 502 Reloads.push_back(load); 503 codeReplacer->getInstList().push_back(load); 504 std::vector<User*> Users(outputs[i]->use_begin(), outputs[i]->use_end()); 505 for (unsigned u = 0, e = Users.size(); u != e; ++u) { 506 Instruction *inst = cast<Instruction>(Users[u]); 507 if (!Blocks.count(inst->getParent())) 508 inst->replaceUsesOfWith(outputs[i], load); 509 } 510 } 511 512 // Now we can emit a switch statement using the call as a value. 513 SwitchInst *TheSwitch = 514 SwitchInst::Create(Constant::getNullValue(Type::getInt16Ty(Context)), 515 codeReplacer, 0, codeReplacer); 516 517 // Since there may be multiple exits from the original region, make the new 518 // function return an unsigned, switch on that number. This loop iterates 519 // over all of the blocks in the extracted region, updating any terminator 520 // instructions in the to-be-extracted region that branch to blocks that are 521 // not in the region to be extracted. 522 std::map<BasicBlock*, BasicBlock*> ExitBlockMap; 523 524 unsigned switchVal = 0; 525 for (SetVector<BasicBlock*>::const_iterator i = Blocks.begin(), 526 e = Blocks.end(); i != e; ++i) { 527 TerminatorInst *TI = (*i)->getTerminator(); 528 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) 529 if (!Blocks.count(TI->getSuccessor(i))) { 530 BasicBlock *OldTarget = TI->getSuccessor(i); 531 // add a new basic block which returns the appropriate value 532 BasicBlock *&NewTarget = ExitBlockMap[OldTarget]; 533 if (!NewTarget) { 534 // If we don't already have an exit stub for this non-extracted 535 // destination, create one now! 536 NewTarget = BasicBlock::Create(Context, 537 OldTarget->getName() + ".exitStub", 538 newFunction); 539 unsigned SuccNum = switchVal++; 540 541 Value *brVal = 0; 542 switch (NumExitBlocks) { 543 case 0: 544 case 1: break; // No value needed. 545 case 2: // Conditional branch, return a bool 546 brVal = ConstantInt::get(Type::getInt1Ty(Context), !SuccNum); 547 break; 548 default: 549 brVal = ConstantInt::get(Type::getInt16Ty(Context), SuccNum); 550 break; 551 } 552 553 ReturnInst *NTRet = ReturnInst::Create(Context, brVal, NewTarget); 554 555 // Update the switch instruction. 556 TheSwitch->addCase(ConstantInt::get(Type::getInt16Ty(Context), 557 SuccNum), 558 OldTarget); 559 560 // Restore values just before we exit 561 Function::arg_iterator OAI = OutputArgBegin; 562 for (unsigned out = 0, e = outputs.size(); out != e; ++out) { 563 // For an invoke, the normal destination is the only one that is 564 // dominated by the result of the invocation 565 BasicBlock *DefBlock = cast<Instruction>(outputs[out])->getParent(); 566 567 bool DominatesDef = true; 568 569 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(outputs[out])) { 570 DefBlock = Invoke->getNormalDest(); 571 572 // Make sure we are looking at the original successor block, not 573 // at a newly inserted exit block, which won't be in the dominator 574 // info. 575 for (std::map<BasicBlock*, BasicBlock*>::iterator I = 576 ExitBlockMap.begin(), E = ExitBlockMap.end(); I != E; ++I) 577 if (DefBlock == I->second) { 578 DefBlock = I->first; 579 break; 580 } 581 582 // In the extract block case, if the block we are extracting ends 583 // with an invoke instruction, make sure that we don't emit a 584 // store of the invoke value for the unwind block. 585 if (!DT && DefBlock != OldTarget) 586 DominatesDef = false; 587 } 588 589 if (DT) { 590 DominatesDef = DT->dominates(DefBlock, OldTarget); 591 592 // If the output value is used by a phi in the target block, 593 // then we need to test for dominance of the phi's predecessor 594 // instead. Unfortunately, this a little complicated since we 595 // have already rewritten uses of the value to uses of the reload. 596 BasicBlock* pred = FindPhiPredForUseInBlock(Reloads[out], 597 OldTarget); 598 if (pred && DT && DT->dominates(DefBlock, pred)) 599 DominatesDef = true; 600 } 601 602 if (DominatesDef) { 603 if (AggregateArgs) { 604 Value *Idx[2]; 605 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context)); 606 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), 607 FirstOut+out); 608 GetElementPtrInst *GEP = 609 GetElementPtrInst::Create(OAI, Idx, 610 "gep_" + outputs[out]->getName(), 611 NTRet); 612 new StoreInst(outputs[out], GEP, NTRet); 613 } else { 614 new StoreInst(outputs[out], OAI, NTRet); 615 } 616 } 617 // Advance output iterator even if we don't emit a store 618 if (!AggregateArgs) ++OAI; 619 } 620 } 621 622 // rewrite the original branch instruction with this new target 623 TI->setSuccessor(i, NewTarget); 624 } 625 } 626 627 // Now that we've done the deed, simplify the switch instruction. 628 Type *OldFnRetTy = TheSwitch->getParent()->getParent()->getReturnType(); 629 switch (NumExitBlocks) { 630 case 0: 631 // There are no successors (the block containing the switch itself), which 632 // means that previously this was the last part of the function, and hence 633 // this should be rewritten as a `ret' 634 635 // Check if the function should return a value 636 if (OldFnRetTy->isVoidTy()) { 637 ReturnInst::Create(Context, 0, TheSwitch); // Return void 638 } else if (OldFnRetTy == TheSwitch->getCondition()->getType()) { 639 // return what we have 640 ReturnInst::Create(Context, TheSwitch->getCondition(), TheSwitch); 641 } else { 642 // Otherwise we must have code extracted an unwind or something, just 643 // return whatever we want. 644 ReturnInst::Create(Context, 645 Constant::getNullValue(OldFnRetTy), TheSwitch); 646 } 647 648 TheSwitch->eraseFromParent(); 649 break; 650 case 1: 651 // Only a single destination, change the switch into an unconditional 652 // branch. 653 BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch); 654 TheSwitch->eraseFromParent(); 655 break; 656 case 2: 657 BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch->getSuccessor(2), 658 call, TheSwitch); 659 TheSwitch->eraseFromParent(); 660 break; 661 default: 662 // Otherwise, make the default destination of the switch instruction be one 663 // of the other successors. 664 TheSwitch->setCondition(call); 665 TheSwitch->setDefaultDest(TheSwitch->getSuccessor(NumExitBlocks)); 666 // Remove redundant case 667 TheSwitch->removeCase(SwitchInst::CaseIt(TheSwitch, NumExitBlocks-1)); 668 break; 669 } 670} 671 672void CodeExtractor::moveCodeToFunction(Function *newFunction) { 673 Function *oldFunc = (*Blocks.begin())->getParent(); 674 Function::BasicBlockListType &oldBlocks = oldFunc->getBasicBlockList(); 675 Function::BasicBlockListType &newBlocks = newFunction->getBasicBlockList(); 676 677 for (SetVector<BasicBlock*>::const_iterator i = Blocks.begin(), 678 e = Blocks.end(); i != e; ++i) { 679 // Delete the basic block from the old function, and the list of blocks 680 oldBlocks.remove(*i); 681 682 // Insert this basic block into the new function 683 newBlocks.push_back(*i); 684 } 685} 686 687Function *CodeExtractor::extractCodeRegion() { 688 if (!isEligible()) 689 return 0; 690 691 ValueSet inputs, outputs; 692 693 // Assumption: this is a single-entry code region, and the header is the first 694 // block in the region. 695 BasicBlock *header = *Blocks.begin(); 696 697 // If we have to split PHI nodes or the entry block, do so now. 698 severSplitPHINodes(header); 699 700 // If we have any return instructions in the region, split those blocks so 701 // that the return is not in the region. 702 splitReturnBlocks(); 703 704 Function *oldFunction = header->getParent(); 705 706 // This takes place of the original loop 707 BasicBlock *codeReplacer = BasicBlock::Create(header->getContext(), 708 "codeRepl", oldFunction, 709 header); 710 711 // The new function needs a root node because other nodes can branch to the 712 // head of the region, but the entry node of a function cannot have preds. 713 BasicBlock *newFuncRoot = BasicBlock::Create(header->getContext(), 714 "newFuncRoot"); 715 newFuncRoot->getInstList().push_back(BranchInst::Create(header)); 716 717 // Find inputs to, outputs from the code region. 718 findInputsOutputs(inputs, outputs); 719 720 SmallPtrSet<BasicBlock *, 1> ExitBlocks; 721 for (SetVector<BasicBlock *>::iterator I = Blocks.begin(), E = Blocks.end(); 722 I != E; ++I) 723 for (succ_iterator SI = succ_begin(*I), SE = succ_end(*I); SI != SE; ++SI) 724 if (!Blocks.count(*SI)) 725 ExitBlocks.insert(*SI); 726 NumExitBlocks = ExitBlocks.size(); 727 728 // Construct new function based on inputs/outputs & add allocas for all defs. 729 Function *newFunction = constructFunction(inputs, outputs, header, 730 newFuncRoot, 731 codeReplacer, oldFunction, 732 oldFunction->getParent()); 733 734 emitCallAndSwitchStatement(newFunction, codeReplacer, inputs, outputs); 735 736 moveCodeToFunction(newFunction); 737 738 // Loop over all of the PHI nodes in the header block, and change any 739 // references to the old incoming edge to be the new incoming edge. 740 for (BasicBlock::iterator I = header->begin(); isa<PHINode>(I); ++I) { 741 PHINode *PN = cast<PHINode>(I); 742 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 743 if (!Blocks.count(PN->getIncomingBlock(i))) 744 PN->setIncomingBlock(i, newFuncRoot); 745 } 746 747 // Look at all successors of the codeReplacer block. If any of these blocks 748 // had PHI nodes in them, we need to update the "from" block to be the code 749 // replacer, not the original block in the extracted region. 750 std::vector<BasicBlock*> Succs(succ_begin(codeReplacer), 751 succ_end(codeReplacer)); 752 for (unsigned i = 0, e = Succs.size(); i != e; ++i) 753 for (BasicBlock::iterator I = Succs[i]->begin(); isa<PHINode>(I); ++I) { 754 PHINode *PN = cast<PHINode>(I); 755 std::set<BasicBlock*> ProcessedPreds; 756 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 757 if (Blocks.count(PN->getIncomingBlock(i))) { 758 if (ProcessedPreds.insert(PN->getIncomingBlock(i)).second) 759 PN->setIncomingBlock(i, codeReplacer); 760 else { 761 // There were multiple entries in the PHI for this block, now there 762 // is only one, so remove the duplicated entries. 763 PN->removeIncomingValue(i, false); 764 --i; --e; 765 } 766 } 767 } 768 769 //cerr << "NEW FUNCTION: " << *newFunction; 770 // verifyFunction(*newFunction); 771 772 // cerr << "OLD FUNCTION: " << *oldFunction; 773 // verifyFunction(*oldFunction); 774 775 DEBUG(if (verifyFunction(*newFunction)) 776 report_fatal_error("verifyFunction failed!")); 777 return newFunction; 778} 779