1 //===- CodeExtractor.cpp - Pull code region into a new function -----------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file was developed by the LLVM research group and is distributed under 6 // the University of Illinois Open Source License. See LICENSE.TXT for details. 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/BasicBlock.h" 17 #include "llvm/Constants.h" 18 #include "llvm/DerivedTypes.h" 19 #include "llvm/Instructions.h" 20 #include "llvm/Module.h" 21 #include "llvm/Pass.h" 22 #include "llvm/Analysis/LoopInfo.h" 23 #include "llvm/Analysis/Verifier.h" 24 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 25 #include "llvm/Transforms/Utils/FunctionUtils.h" 26 #include "Support/Debug.h" 27 #include "Support/StringExtras.h" 28 #include <algorithm> 29 #include <map> 30 #include <vector> 31 using namespace llvm; 32 33 namespace { 34 35 inline bool contains(const std::vector<BasicBlock*> &V, const BasicBlock *BB){ 36 return std::find(V.begin(), V.end(), BB) != V.end(); 37 } 38 39 /// getFunctionArg - Return a pointer to F's ARGNOth argument. 40 /// 41 Argument *getFunctionArg(Function *F, unsigned argno) { 42 Function::aiterator ai = F->abegin(); 43 while (argno) { ++ai; --argno; } 44 return &*ai; 45 } 46 47 struct CodeExtractor { 48 typedef std::vector<Value*> Values; 49 typedef std::vector<std::pair<unsigned, unsigned> > PhiValChangesTy; 50 typedef std::map<PHINode*, PhiValChangesTy> PhiVal2ArgTy; 51 PhiVal2ArgTy PhiVal2Arg; 52 53 public: 54 Function *ExtractCodeRegion(const std::vector<BasicBlock*> &code); 55 56 private: 57 void findInputsOutputs(const std::vector<BasicBlock*> &code, 58 Values &inputs, 59 Values &outputs, 60 BasicBlock *newHeader, 61 BasicBlock *newRootNode); 62 63 void processPhiNodeInputs(PHINode *Phi, 64 const std::vector<BasicBlock*> &code, 65 Values &inputs, 66 BasicBlock *newHeader, 67 BasicBlock *newRootNode); 68 69 void rewritePhiNodes(Function *F, BasicBlock *newFuncRoot); 70 71 Function *constructFunction(const Values &inputs, 72 const Values &outputs, 73 BasicBlock *newRootNode, BasicBlock *newHeader, 74 const std::vector<BasicBlock*> &code, 75 Function *oldFunction, Module *M); 76 77 void moveCodeToFunction(const std::vector<BasicBlock*> &code, 78 Function *newFunction); 79 80 void emitCallAndSwitchStatement(Function *newFunction, 81 BasicBlock *newHeader, 82 const std::vector<BasicBlock*> &code, 83 Values &inputs, 84 Values &outputs); 85 86 }; 87 } 88 89 void CodeExtractor::processPhiNodeInputs(PHINode *Phi, 90 const std::vector<BasicBlock*> &code, 91 Values &inputs, 92 BasicBlock *codeReplacer, 93 BasicBlock *newFuncRoot) 94 { 95 // Separate incoming values and BasicBlocks as internal/external. We ignore 96 // the case where both the value and BasicBlock are internal, because we don't 97 // need to do a thing. 98 std::vector<unsigned> EValEBB; 99 std::vector<unsigned> EValIBB; 100 std::vector<unsigned> IValEBB; 101 102 for (unsigned i = 0, e = Phi->getNumIncomingValues(); i != e; ++i) { 103 Value *phiVal = Phi->getIncomingValue(i); 104 if (Instruction *Inst = dyn_cast<Instruction>(phiVal)) { 105 if (contains(code, Inst->getParent())) { 106 if (!contains(code, Phi->getIncomingBlock(i))) 107 IValEBB.push_back(i); 108 } else { 109 if (contains(code, Phi->getIncomingBlock(i))) 110 EValIBB.push_back(i); 111 else 112 EValEBB.push_back(i); 113 } 114 } else if (Constant *Const = dyn_cast<Constant>(phiVal)) { 115 // Constants are internal, but considered `external' if they are coming 116 // from an external block. 117 if (!contains(code, Phi->getIncomingBlock(i))) 118 EValEBB.push_back(i); 119 } else if (Argument *Arg = dyn_cast<Argument>(phiVal)) { 120 // arguments are external 121 if (contains(code, Phi->getIncomingBlock(i))) 122 EValIBB.push_back(i); 123 else 124 EValEBB.push_back(i); 125 } else { 126 phiVal->dump(); 127 assert(0 && "Unhandled input in a Phi node"); 128 } 129 } 130 131 // Both value and block are external. Need to group all of 132 // these, have an external phi, pass the result as an 133 // argument, and have THIS phi use that result. 134 if (EValEBB.size() > 0) { 135 if (EValEBB.size() == 1) { 136 // Now if it's coming from the newFuncRoot, it's that funky input 137 unsigned phiIdx = EValEBB[0]; 138 if (!dyn_cast<Constant>(Phi->getIncomingValue(phiIdx))) 139 { 140 PhiVal2Arg[Phi].push_back(std::make_pair(phiIdx, inputs.size())); 141 // We can just pass this value in as argument 142 inputs.push_back(Phi->getIncomingValue(phiIdx)); 143 } 144 Phi->setIncomingBlock(phiIdx, newFuncRoot); 145 } else { 146 PHINode *externalPhi = new PHINode(Phi->getType(), "extPhi"); 147 codeReplacer->getInstList().insert(codeReplacer->begin(), externalPhi); 148 for (std::vector<unsigned>::iterator i = EValEBB.begin(), 149 e = EValEBB.end(); i != e; ++i) 150 { 151 externalPhi->addIncoming(Phi->getIncomingValue(*i), 152 Phi->getIncomingBlock(*i)); 153 154 // We make these values invalid instead of deleting them because that 155 // would shift the indices of other values... The fixPhiNodes should 156 // clean these phi nodes up later. 157 Phi->setIncomingValue(*i, 0); 158 Phi->setIncomingBlock(*i, 0); 159 } 160 PhiVal2Arg[Phi].push_back(std::make_pair(Phi->getNumIncomingValues(), 161 inputs.size())); 162 // We can just pass this value in as argument 163 inputs.push_back(externalPhi); 164 } 165 } 166 167 // When the value is external, but block internal... 168 // just pass it in as argument, no change to phi node 169 for (std::vector<unsigned>::iterator i = EValIBB.begin(), 170 e = EValIBB.end(); i != e; ++i) 171 { 172 // rewrite the phi input node to be an argument 173 PhiVal2Arg[Phi].push_back(std::make_pair(*i, inputs.size())); 174 inputs.push_back(Phi->getIncomingValue(*i)); 175 } 176 177 // Value internal, block external 178 // this can happen if we are extracting a part of a loop 179 for (std::vector<unsigned>::iterator i = IValEBB.begin(), 180 e = IValEBB.end(); i != e; ++i) 181 { 182 assert(0 && "Cannot (YET) handle internal values via external blocks"); 183 } 184 } 185 186 187 void CodeExtractor::findInputsOutputs(const std::vector<BasicBlock*> &code, 188 Values &inputs, 189 Values &outputs, 190 BasicBlock *newHeader, 191 BasicBlock *newRootNode) 192 { 193 for (std::vector<BasicBlock*>::const_iterator ci = code.begin(), 194 ce = code.end(); ci != ce; ++ci) { 195 BasicBlock *BB = *ci; 196 for (BasicBlock::iterator BBi = BB->begin(), BBe = BB->end(); 197 BBi != BBe; ++BBi) { 198 // If a use is defined outside the region, it's an input. 199 // If a def is used outside the region, it's an output. 200 if (Instruction *I = dyn_cast<Instruction>(&*BBi)) { 201 // If it's a phi node 202 if (PHINode *Phi = dyn_cast<PHINode>(I)) { 203 processPhiNodeInputs(Phi, code, inputs, newHeader, newRootNode); 204 } else { 205 // All other instructions go through the generic input finder 206 // Loop over the operands of each instruction (inputs) 207 for (User::op_iterator op = I->op_begin(), opE = I->op_end(); 208 op != opE; ++op) { 209 if (Instruction *opI = dyn_cast<Instruction>(op->get())) { 210 // Check if definition of this operand is within the loop 211 if (!contains(code, opI->getParent())) { 212 // add this operand to the inputs 213 inputs.push_back(opI); 214 } 215 } 216 } 217 } 218 219 // Consider uses of this instruction (outputs) 220 for (Value::use_iterator use = I->use_begin(), useE = I->use_end(); 221 use != useE; ++use) { 222 if (Instruction* inst = dyn_cast<Instruction>(*use)) { 223 if (!contains(code, inst->getParent())) { 224 // add this op to the outputs 225 outputs.push_back(I); 226 } 227 } 228 } 229 } /* if */ 230 } /* for: insts */ 231 } /* for: basic blocks */ 232 } 233 234 void CodeExtractor::rewritePhiNodes(Function *F, 235 BasicBlock *newFuncRoot) { 236 // Write any changes that were saved before: use function arguments as inputs 237 for (PhiVal2ArgTy::iterator i = PhiVal2Arg.begin(), e = PhiVal2Arg.end(); 238 i != e; ++i) 239 { 240 PHINode *phi = (*i).first; 241 PhiValChangesTy &values = (*i).second; 242 for (unsigned cIdx = 0, ce = values.size(); cIdx != ce; ++cIdx) 243 { 244 unsigned phiValueIdx = values[cIdx].first, argNum = values[cIdx].second; 245 if (phiValueIdx < phi->getNumIncomingValues()) 246 phi->setIncomingValue(phiValueIdx, getFunctionArg(F, argNum)); 247 else 248 phi->addIncoming(getFunctionArg(F, argNum), newFuncRoot); 249 } 250 } 251 252 // Delete any invalid Phi node inputs that were marked as NULL previously 253 for (PhiVal2ArgTy::iterator i = PhiVal2Arg.begin(), e = PhiVal2Arg.end(); 254 i != e; ++i) 255 { 256 PHINode *phi = (*i).first; 257 for (unsigned idx = 0, end = phi->getNumIncomingValues(); idx != end; ++idx) 258 { 259 if (phi->getIncomingValue(idx) == 0 && phi->getIncomingBlock(idx) == 0) { 260 phi->removeIncomingValue(idx); 261 --idx; 262 --end; 263 } 264 } 265 } 266 267 // We are done with the saved values 268 PhiVal2Arg.clear(); 269 } 270 271 272 /// constructFunction - make a function based on inputs and outputs, as follows: 273 /// f(in0, ..., inN, out0, ..., outN) 274 /// 275 Function *CodeExtractor::constructFunction(const Values &inputs, 276 const Values &outputs, 277 BasicBlock *newRootNode, 278 BasicBlock *newHeader, 279 const std::vector<BasicBlock*> &code, 280 Function *oldFunction, Module *M) { 281 DEBUG(std::cerr << "inputs: " << inputs.size() << "\n"); 282 DEBUG(std::cerr << "outputs: " << outputs.size() << "\n"); 283 BasicBlock *header = code[0]; 284 285 // This function returns unsigned, outputs will go back by reference. 286 Type *retTy = Type::UShortTy; 287 std::vector<const Type*> paramTy; 288 289 // Add the types of the input values to the function's argument list 290 for (Values::const_iterator i = inputs.begin(), 291 e = inputs.end(); i != e; ++i) { 292 const Value *value = *i; 293 DEBUG(std::cerr << "value used in func: " << value << "\n"); 294 paramTy.push_back(value->getType()); 295 } 296 297 // Add the types of the output values to the function's argument list, but 298 // make them pointer types for scalars 299 for (Values::const_iterator i = outputs.begin(), 300 e = outputs.end(); i != e; ++i) { 301 const Value *value = *i; 302 DEBUG(std::cerr << "instr used in func: " << value << "\n"); 303 const Type *valueType = value->getType(); 304 // Convert scalar types into a pointer of that type 305 if (valueType->isPrimitiveType()) { 306 valueType = PointerType::get(valueType); 307 } 308 paramTy.push_back(valueType); 309 } 310 311 DEBUG(std::cerr << "Function type: " << retTy << " f("); 312 for (std::vector<const Type*>::iterator i = paramTy.begin(), 313 e = paramTy.end(); i != e; ++i) 314 DEBUG(std::cerr << (*i) << ", "); 315 DEBUG(std::cerr << ")\n"); 316 317 const FunctionType *funcType = FunctionType::get(retTy, paramTy, false); 318 319 // Create the new function 320 Function *newFunction = new Function(funcType, 321 GlobalValue::InternalLinkage, 322 oldFunction->getName() + "_code", M); 323 newFunction->getBasicBlockList().push_back(newRootNode); 324 325 for (unsigned i = 0, e = inputs.size(); i != e; ++i) { 326 std::vector<User*> Users(inputs[i]->use_begin(), inputs[i]->use_end()); 327 for (std::vector<User*>::iterator use = Users.begin(), useE = Users.end(); 328 use != useE; ++use) 329 if (Instruction* inst = dyn_cast<Instruction>(*use)) 330 if (contains(code, inst->getParent())) 331 inst->replaceUsesOfWith(inputs[i], getFunctionArg(newFunction, i)); 332 } 333 334 // Rewrite branches to basic blocks outside of the loop to new dummy blocks 335 // within the new function. This must be done before we lose track of which 336 // blocks were originally in the code region. 337 std::vector<User*> Users(header->use_begin(), header->use_end()); 338 for (std::vector<User*>::iterator i = Users.begin(), e = Users.end(); 339 i != e; ++i) { 340 if (BranchInst *inst = dyn_cast<BranchInst>(*i)) { 341 BasicBlock *BB = inst->getParent(); 342 if (!contains(code, BB) && BB->getParent() == oldFunction) { 343 // The BasicBlock which contains the branch is not in the region 344 // modify the branch target to a new block 345 inst->replaceUsesOfWith(header, newHeader); 346 } 347 } 348 } 349 350 return newFunction; 351 } 352 353 void CodeExtractor::moveCodeToFunction(const std::vector<BasicBlock*> &code, 354 Function *newFunction) 355 { 356 for (std::vector<BasicBlock*>::const_iterator i = code.begin(), e =code.end(); 357 i != e; ++i) { 358 BasicBlock *BB = *i; 359 Function *oldFunc = BB->getParent(); 360 Function::BasicBlockListType &oldBlocks = oldFunc->getBasicBlockList(); 361 362 // Delete the basic block from the old function, and the list of blocks 363 oldBlocks.remove(BB); 364 365 // Insert this basic block into the new function 366 Function::BasicBlockListType &newBlocks = newFunction->getBasicBlockList(); 367 newBlocks.push_back(BB); 368 } 369 } 370 371 void 372 CodeExtractor::emitCallAndSwitchStatement(Function *newFunction, 373 BasicBlock *codeReplacer, 374 const std::vector<BasicBlock*> &code, 375 Values &inputs, 376 Values &outputs) 377 { 378 // Emit a call to the new function, passing allocated memory for outputs and 379 // just plain inputs for non-scalars 380 std::vector<Value*> params; 381 BasicBlock *codeReplacerTail = new BasicBlock("codeReplTail", 382 codeReplacer->getParent()); 383 for (Values::const_iterator i = inputs.begin(), 384 e = inputs.end(); i != e; ++i) 385 params.push_back(*i); 386 for (Values::const_iterator i = outputs.begin(), 387 e = outputs.end(); i != e; ++i) { 388 // Create allocas for scalar outputs 389 if ((*i)->getType()->isPrimitiveType()) { 390 Constant *one = ConstantUInt::get(Type::UIntTy, 1); 391 AllocaInst *alloca = new AllocaInst((*i)->getType(), one); 392 codeReplacer->getInstList().push_back(alloca); 393 params.push_back(alloca); 394 395 LoadInst *load = new LoadInst(alloca, "alloca"); 396 codeReplacerTail->getInstList().push_back(load); 397 std::vector<User*> Users((*i)->use_begin(), (*i)->use_end()); 398 for (std::vector<User*>::iterator use = Users.begin(), useE =Users.end(); 399 use != useE; ++use) { 400 if (Instruction* inst = dyn_cast<Instruction>(*use)) { 401 if (!contains(code, inst->getParent())) { 402 inst->replaceUsesOfWith(*i, load); 403 } 404 } 405 } 406 } else { 407 params.push_back(*i); 408 } 409 } 410 CallInst *call = new CallInst(newFunction, params, "targetBlock"); 411 codeReplacer->getInstList().push_back(call); 412 codeReplacer->getInstList().push_back(new BranchInst(codeReplacerTail)); 413 414 // Now we can emit a switch statement using the call as a value. 415 // FIXME: perhaps instead of default being self BB, it should be a second 416 // dummy block which asserts that the value is not within the range...? 417 //BasicBlock *defaultBlock = new BasicBlock("defaultBlock", oldF); 418 //insert abort() ? 419 //defaultBlock->getInstList().push_back(new BranchInst(codeReplacer)); 420 421 SwitchInst *switchInst = new SwitchInst(call, codeReplacerTail, 422 codeReplacerTail); 423 424 // Since there may be multiple exits from the original region, make the new 425 // function return an unsigned, switch on that number 426 unsigned switchVal = 0; 427 for (std::vector<BasicBlock*>::const_iterator i =code.begin(), e = code.end(); 428 i != e; ++i) { 429 BasicBlock *BB = *i; 430 431 // rewrite the terminator of the original BasicBlock 432 Instruction *term = BB->getTerminator(); 433 if (BranchInst *brInst = dyn_cast<BranchInst>(term)) { 434 435 // Restore values just before we exit 436 // FIXME: Use a GetElementPtr to bunch the outputs in a struct 437 for (unsigned outIdx = 0, outE = outputs.size(); outIdx != outE; ++outIdx) 438 { 439 new StoreInst(outputs[outIdx], 440 getFunctionArg(newFunction, outIdx), 441 brInst); 442 } 443 444 // Rewrite branches into exits which return a value based on which 445 // exit we take from this function 446 if (brInst->isUnconditional()) { 447 if (!contains(code, brInst->getSuccessor(0))) { 448 ConstantUInt *brVal = ConstantUInt::get(Type::UShortTy, switchVal); 449 ReturnInst *newRet = new ReturnInst(brVal); 450 // add a new target to the switch 451 switchInst->addCase(brVal, brInst->getSuccessor(0)); 452 ++switchVal; 453 // rewrite the branch with a return 454 BasicBlock::iterator ii(brInst); 455 ReplaceInstWithInst(BB->getInstList(), ii, newRet); 456 delete brInst; 457 } 458 } else { 459 // Replace the conditional branch to branch 460 // to two new blocks, each of which returns a different code. 461 for (unsigned idx = 0; idx < 2; ++idx) { 462 BasicBlock *oldTarget = brInst->getSuccessor(idx); 463 if (!contains(code, oldTarget)) { 464 // add a new basic block which returns the appropriate value 465 BasicBlock *newTarget = new BasicBlock("newTarget", newFunction); 466 ConstantUInt *brVal = ConstantUInt::get(Type::UShortTy, switchVal); 467 ReturnInst *newRet = new ReturnInst(brVal); 468 newTarget->getInstList().push_back(newRet); 469 // rewrite the original branch instruction with this new target 470 brInst->setSuccessor(idx, newTarget); 471 // the switch statement knows what to do with this value 472 switchInst->addCase(brVal, oldTarget); 473 ++switchVal; 474 } 475 } 476 } 477 } else if (ReturnInst *retTerm = dyn_cast<ReturnInst>(term)) { 478 assert(0 && "Cannot handle return instructions just yet."); 479 // FIXME: what if the terminator is a return!??! 480 // Need to rewrite: add new basic block, move the return there 481 // treat the original as an unconditional branch to that basicblock 482 } else if (SwitchInst *swTerm = dyn_cast<SwitchInst>(term)) { 483 assert(0 && "Cannot handle switch instructions just yet."); 484 } else if (InvokeInst *invInst = dyn_cast<InvokeInst>(term)) { 485 assert(0 && "Cannot handle invoke instructions just yet."); 486 } else { 487 assert(0 && "Unrecognized terminator, or badly-formed BasicBlock."); 488 } 489 } 490 } 491 492 493 /// ExtractRegion - Removes a loop from a function, replaces it with a call to 494 /// new function. Returns pointer to the new function. 495 /// 496 /// algorithm: 497 /// 498 /// find inputs and outputs for the region 499 /// 500 /// for inputs: add to function as args, map input instr* to arg# 501 /// for outputs: add allocas for scalars, 502 /// add to func as args, map output instr* to arg# 503 /// 504 /// rewrite func to use argument #s instead of instr* 505 /// 506 /// for each scalar output in the function: at every exit, store intermediate 507 /// computed result back into memory. 508 /// 509 Function *CodeExtractor::ExtractCodeRegion(const std::vector<BasicBlock*> &code) 510 { 511 // 1) Find inputs, outputs 512 // 2) Construct new function 513 // * Add allocas for defs, pass as args by reference 514 // * Pass in uses as args 515 // 3) Move code region, add call instr to func 516 // 517 518 Values inputs, outputs; 519 520 // Assumption: this is a single-entry code region, and the header is the first 521 // block in the region. FIXME: is this true for a list of blocks from a 522 // natural function? 523 BasicBlock *header = code[0]; 524 Function *oldFunction = header->getParent(); 525 Module *module = oldFunction->getParent(); 526 527 // This takes place of the original loop 528 BasicBlock *codeReplacer = new BasicBlock("codeRepl", oldFunction); 529 530 // The new function needs a root node because other nodes can branch to the 531 // head of the loop, and the root cannot have predecessors 532 BasicBlock *newFuncRoot = new BasicBlock("newFuncRoot"); 533 newFuncRoot->getInstList().push_back(new BranchInst(header)); 534 535 // Find inputs to, outputs from the code region 536 // 537 // If one of the inputs is coming from a different basic block and it's in a 538 // phi node, we need to rewrite the phi node: 539 // 540 // * All the inputs which involve basic blocks OUTSIDE of this region go into 541 // a NEW phi node that takes care of finding which value really came in. 542 // The result of this phi is passed to the function as an argument. 543 // 544 // * All the other phi values stay. 545 // 546 // FIXME: PHI nodes' incoming blocks aren't being rewritten to accomodate for 547 // blocks moving to a new function. 548 // SOLUTION: move Phi nodes out of the loop header into the codeReplacer, pass 549 // the values as parameters to the function 550 findInputsOutputs(code, inputs, outputs, codeReplacer, newFuncRoot); 551 552 // Step 2: Construct new function based on inputs/outputs, 553 // Add allocas for all defs 554 Function *newFunction = constructFunction(inputs, outputs, newFuncRoot, 555 codeReplacer, code, 556 oldFunction, module); 557 558 rewritePhiNodes(newFunction, newFuncRoot); 559 560 emitCallAndSwitchStatement(newFunction, codeReplacer, code, inputs, outputs); 561 562 moveCodeToFunction(code, newFunction); 563 564 DEBUG(if (verifyFunction(*newFunction)) abort()); 565 return newFunction; 566 } 567 568 /// ExtractCodeRegion - slurp a sequence of basic blocks into a brand new 569 /// function 570 /// 571 Function* llvm::ExtractCodeRegion(const std::vector<BasicBlock*> &code) { 572 CodeExtractor CE; 573 return CE.ExtractCodeRegion(code); 574 } 575 576 /// ExtractBasicBlock - slurp a natural loop into a brand new function 577 /// 578 Function* llvm::ExtractLoop(Loop *L) { 579 CodeExtractor CE; 580 return CE.ExtractCodeRegion(L->getBlocks()); 581 } 582 583 /// ExtractBasicBlock - slurp a basic block into a brand new function 584 /// 585 Function* llvm::ExtractBasicBlock(BasicBlock *BB) { 586 CodeExtractor CE; 587 std::vector<BasicBlock*> Blocks; 588 Blocks.push_back(BB); 589 return CE.ExtractCodeRegion(Blocks); 590 } 591