1 //===- CloneFunction.cpp - Clone a function into another 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 CloneFunctionInto interface, which is used as the 11 // low-level function cloner. This is used by the CloneFunction and function 12 // inliner to do the dirty work of copying the body of a function around. 13 // 14 //===----------------------------------------------------------------------===// 15 16 #include "llvm/Transforms/Utils/Cloning.h" 17 #include "llvm/ADT/SmallVector.h" 18 #include "llvm/Analysis/ConstantFolding.h" 19 #include "llvm/Analysis/InstructionSimplify.h" 20 #include "llvm/DebugInfo.h" 21 #include "llvm/IR/Constants.h" 22 #include "llvm/IR/DerivedTypes.h" 23 #include "llvm/IR/Function.h" 24 #include "llvm/IR/GlobalVariable.h" 25 #include "llvm/IR/Instructions.h" 26 #include "llvm/IR/IntrinsicInst.h" 27 #include "llvm/IR/LLVMContext.h" 28 #include "llvm/IR/Metadata.h" 29 #include "llvm/Support/CFG.h" 30 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 31 #include "llvm/Transforms/Utils/Local.h" 32 #include "llvm/Transforms/Utils/ValueMapper.h" 33 #include <map> 34 using namespace llvm; 35 36 // CloneBasicBlock - See comments in Cloning.h 37 BasicBlock *llvm::CloneBasicBlock(const BasicBlock *BB, 38 ValueToValueMapTy &VMap, 39 const Twine &NameSuffix, Function *F, 40 ClonedCodeInfo *CodeInfo) { 41 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "", F); 42 if (BB->hasName()) NewBB->setName(BB->getName()+NameSuffix); 43 44 bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false; 45 46 // Loop over all instructions, and copy them over. 47 for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end(); 48 II != IE; ++II) { 49 Instruction *NewInst = II->clone(); 50 if (II->hasName()) 51 NewInst->setName(II->getName()+NameSuffix); 52 NewBB->getInstList().push_back(NewInst); 53 VMap[II] = NewInst; // Add instruction map to value. 54 55 hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II)); 56 if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) { 57 if (isa<ConstantInt>(AI->getArraySize())) 58 hasStaticAllocas = true; 59 else 60 hasDynamicAllocas = true; 61 } 62 } 63 64 if (CodeInfo) { 65 CodeInfo->ContainsCalls |= hasCalls; 66 CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas; 67 CodeInfo->ContainsDynamicAllocas |= hasStaticAllocas && 68 BB != &BB->getParent()->getEntryBlock(); 69 } 70 return NewBB; 71 } 72 73 // Clone OldFunc into NewFunc, transforming the old arguments into references to 74 // VMap values. 75 // 76 void llvm::CloneFunctionInto(Function *NewFunc, const Function *OldFunc, 77 ValueToValueMapTy &VMap, 78 bool ModuleLevelChanges, 79 SmallVectorImpl<ReturnInst*> &Returns, 80 const char *NameSuffix, ClonedCodeInfo *CodeInfo, 81 ValueMapTypeRemapper *TypeMapper) { 82 assert(NameSuffix && "NameSuffix cannot be null!"); 83 84 #ifndef NDEBUG 85 for (Function::const_arg_iterator I = OldFunc->arg_begin(), 86 E = OldFunc->arg_end(); I != E; ++I) 87 assert(VMap.count(I) && "No mapping from source argument specified!"); 88 #endif 89 90 // Clone any attributes. 91 if (NewFunc->arg_size() == OldFunc->arg_size()) 92 NewFunc->copyAttributesFrom(OldFunc); 93 else { 94 //Some arguments were deleted with the VMap. Copy arguments one by one 95 for (Function::const_arg_iterator I = OldFunc->arg_begin(), 96 E = OldFunc->arg_end(); I != E; ++I) 97 if (Argument* Anew = dyn_cast<Argument>(VMap[I])) { 98 AttributeSet attrs = OldFunc->getAttributes() 99 .getParamAttributes(I->getArgNo() + 1); 100 if (attrs.getNumSlots() > 0) 101 Anew->addAttr(attrs); 102 } 103 NewFunc->setAttributes(NewFunc->getAttributes() 104 .addAttributes(NewFunc->getContext(), 105 AttributeSet::ReturnIndex, 106 OldFunc->getAttributes())); 107 NewFunc->setAttributes(NewFunc->getAttributes() 108 .addAttributes(NewFunc->getContext(), 109 AttributeSet::FunctionIndex, 110 OldFunc->getAttributes())); 111 112 } 113 114 // Loop over all of the basic blocks in the function, cloning them as 115 // appropriate. Note that we save BE this way in order to handle cloning of 116 // recursive functions into themselves. 117 // 118 for (Function::const_iterator BI = OldFunc->begin(), BE = OldFunc->end(); 119 BI != BE; ++BI) { 120 const BasicBlock &BB = *BI; 121 122 // Create a new basic block and copy instructions into it! 123 BasicBlock *CBB = CloneBasicBlock(&BB, VMap, NameSuffix, NewFunc, CodeInfo); 124 125 // Add basic block mapping. 126 VMap[&BB] = CBB; 127 128 // It is only legal to clone a function if a block address within that 129 // function is never referenced outside of the function. Given that, we 130 // want to map block addresses from the old function to block addresses in 131 // the clone. (This is different from the generic ValueMapper 132 // implementation, which generates an invalid blockaddress when 133 // cloning a function.) 134 if (BB.hasAddressTaken()) { 135 Constant *OldBBAddr = BlockAddress::get(const_cast<Function*>(OldFunc), 136 const_cast<BasicBlock*>(&BB)); 137 VMap[OldBBAddr] = BlockAddress::get(NewFunc, CBB); 138 } 139 140 // Note return instructions for the caller. 141 if (ReturnInst *RI = dyn_cast<ReturnInst>(CBB->getTerminator())) 142 Returns.push_back(RI); 143 } 144 145 // Loop over all of the instructions in the function, fixing up operand 146 // references as we go. This uses VMap to do all the hard work. 147 for (Function::iterator BB = cast<BasicBlock>(VMap[OldFunc->begin()]), 148 BE = NewFunc->end(); BB != BE; ++BB) 149 // Loop over all instructions, fixing each one as we find it... 150 for (BasicBlock::iterator II = BB->begin(); II != BB->end(); ++II) 151 RemapInstruction(II, VMap, 152 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges, 153 TypeMapper); 154 } 155 156 /// CloneFunction - Return a copy of the specified function, but without 157 /// embedding the function into another module. Also, any references specified 158 /// in the VMap are changed to refer to their mapped value instead of the 159 /// original one. If any of the arguments to the function are in the VMap, 160 /// the arguments are deleted from the resultant function. The VMap is 161 /// updated to include mappings from all of the instructions and basicblocks in 162 /// the function from their old to new values. 163 /// 164 Function *llvm::CloneFunction(const Function *F, ValueToValueMapTy &VMap, 165 bool ModuleLevelChanges, 166 ClonedCodeInfo *CodeInfo) { 167 std::vector<Type*> ArgTypes; 168 169 // The user might be deleting arguments to the function by specifying them in 170 // the VMap. If so, we need to not add the arguments to the arg ty vector 171 // 172 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end(); 173 I != E; ++I) 174 if (VMap.count(I) == 0) // Haven't mapped the argument to anything yet? 175 ArgTypes.push_back(I->getType()); 176 177 // Create a new function type... 178 FunctionType *FTy = FunctionType::get(F->getFunctionType()->getReturnType(), 179 ArgTypes, F->getFunctionType()->isVarArg()); 180 181 // Create the new function... 182 Function *NewF = Function::Create(FTy, F->getLinkage(), F->getName()); 183 184 // Loop over the arguments, copying the names of the mapped arguments over... 185 Function::arg_iterator DestI = NewF->arg_begin(); 186 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end(); 187 I != E; ++I) 188 if (VMap.count(I) == 0) { // Is this argument preserved? 189 DestI->setName(I->getName()); // Copy the name over... 190 VMap[I] = DestI++; // Add mapping to VMap 191 } 192 193 SmallVector<ReturnInst*, 8> Returns; // Ignore returns cloned. 194 CloneFunctionInto(NewF, F, VMap, ModuleLevelChanges, Returns, "", CodeInfo); 195 return NewF; 196 } 197 198 199 200 namespace { 201 /// PruningFunctionCloner - This class is a private class used to implement 202 /// the CloneAndPruneFunctionInto method. 203 struct PruningFunctionCloner { 204 Function *NewFunc; 205 const Function *OldFunc; 206 ValueToValueMapTy &VMap; 207 bool ModuleLevelChanges; 208 const char *NameSuffix; 209 ClonedCodeInfo *CodeInfo; 210 const DataLayout *TD; 211 public: 212 PruningFunctionCloner(Function *newFunc, const Function *oldFunc, 213 ValueToValueMapTy &valueMap, 214 bool moduleLevelChanges, 215 const char *nameSuffix, 216 ClonedCodeInfo *codeInfo, 217 const DataLayout *td) 218 : NewFunc(newFunc), OldFunc(oldFunc), 219 VMap(valueMap), ModuleLevelChanges(moduleLevelChanges), 220 NameSuffix(nameSuffix), CodeInfo(codeInfo), TD(td) { 221 } 222 223 /// CloneBlock - The specified block is found to be reachable, clone it and 224 /// anything that it can reach. 225 void CloneBlock(const BasicBlock *BB, 226 std::vector<const BasicBlock*> &ToClone); 227 }; 228 } 229 230 /// CloneBlock - The specified block is found to be reachable, clone it and 231 /// anything that it can reach. 232 void PruningFunctionCloner::CloneBlock(const BasicBlock *BB, 233 std::vector<const BasicBlock*> &ToClone){ 234 WeakVH &BBEntry = VMap[BB]; 235 236 // Have we already cloned this block? 237 if (BBEntry) return; 238 239 // Nope, clone it now. 240 BasicBlock *NewBB; 241 BBEntry = NewBB = BasicBlock::Create(BB->getContext()); 242 if (BB->hasName()) NewBB->setName(BB->getName()+NameSuffix); 243 244 // It is only legal to clone a function if a block address within that 245 // function is never referenced outside of the function. Given that, we 246 // want to map block addresses from the old function to block addresses in 247 // the clone. (This is different from the generic ValueMapper 248 // implementation, which generates an invalid blockaddress when 249 // cloning a function.) 250 // 251 // Note that we don't need to fix the mapping for unreachable blocks; 252 // the default mapping there is safe. 253 if (BB->hasAddressTaken()) { 254 Constant *OldBBAddr = BlockAddress::get(const_cast<Function*>(OldFunc), 255 const_cast<BasicBlock*>(BB)); 256 VMap[OldBBAddr] = BlockAddress::get(NewFunc, NewBB); 257 } 258 259 260 bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false; 261 262 // Loop over all instructions, and copy them over, DCE'ing as we go. This 263 // loop doesn't include the terminator. 264 for (BasicBlock::const_iterator II = BB->begin(), IE = --BB->end(); 265 II != IE; ++II) { 266 Instruction *NewInst = II->clone(); 267 268 // Eagerly remap operands to the newly cloned instruction, except for PHI 269 // nodes for which we defer processing until we update the CFG. 270 if (!isa<PHINode>(NewInst)) { 271 RemapInstruction(NewInst, VMap, 272 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges); 273 274 // If we can simplify this instruction to some other value, simply add 275 // a mapping to that value rather than inserting a new instruction into 276 // the basic block. 277 if (Value *V = SimplifyInstruction(NewInst, TD)) { 278 // On the off-chance that this simplifies to an instruction in the old 279 // function, map it back into the new function. 280 if (Value *MappedV = VMap.lookup(V)) 281 V = MappedV; 282 283 VMap[II] = V; 284 delete NewInst; 285 continue; 286 } 287 } 288 289 if (II->hasName()) 290 NewInst->setName(II->getName()+NameSuffix); 291 VMap[II] = NewInst; // Add instruction map to value. 292 NewBB->getInstList().push_back(NewInst); 293 hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II)); 294 if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) { 295 if (isa<ConstantInt>(AI->getArraySize())) 296 hasStaticAllocas = true; 297 else 298 hasDynamicAllocas = true; 299 } 300 } 301 302 // Finally, clone over the terminator. 303 const TerminatorInst *OldTI = BB->getTerminator(); 304 bool TerminatorDone = false; 305 if (const BranchInst *BI = dyn_cast<BranchInst>(OldTI)) { 306 if (BI->isConditional()) { 307 // If the condition was a known constant in the callee... 308 ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition()); 309 // Or is a known constant in the caller... 310 if (Cond == 0) { 311 Value *V = VMap[BI->getCondition()]; 312 Cond = dyn_cast_or_null<ConstantInt>(V); 313 } 314 315 // Constant fold to uncond branch! 316 if (Cond) { 317 BasicBlock *Dest = BI->getSuccessor(!Cond->getZExtValue()); 318 VMap[OldTI] = BranchInst::Create(Dest, NewBB); 319 ToClone.push_back(Dest); 320 TerminatorDone = true; 321 } 322 } 323 } else if (const SwitchInst *SI = dyn_cast<SwitchInst>(OldTI)) { 324 // If switching on a value known constant in the caller. 325 ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition()); 326 if (Cond == 0) { // Or known constant after constant prop in the callee... 327 Value *V = VMap[SI->getCondition()]; 328 Cond = dyn_cast_or_null<ConstantInt>(V); 329 } 330 if (Cond) { // Constant fold to uncond branch! 331 SwitchInst::ConstCaseIt Case = SI->findCaseValue(Cond); 332 BasicBlock *Dest = const_cast<BasicBlock*>(Case.getCaseSuccessor()); 333 VMap[OldTI] = BranchInst::Create(Dest, NewBB); 334 ToClone.push_back(Dest); 335 TerminatorDone = true; 336 } 337 } 338 339 if (!TerminatorDone) { 340 Instruction *NewInst = OldTI->clone(); 341 if (OldTI->hasName()) 342 NewInst->setName(OldTI->getName()+NameSuffix); 343 NewBB->getInstList().push_back(NewInst); 344 VMap[OldTI] = NewInst; // Add instruction map to value. 345 346 // Recursively clone any reachable successor blocks. 347 const TerminatorInst *TI = BB->getTerminator(); 348 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) 349 ToClone.push_back(TI->getSuccessor(i)); 350 } 351 352 if (CodeInfo) { 353 CodeInfo->ContainsCalls |= hasCalls; 354 CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas; 355 CodeInfo->ContainsDynamicAllocas |= hasStaticAllocas && 356 BB != &BB->getParent()->front(); 357 } 358 } 359 360 /// CloneAndPruneFunctionInto - This works exactly like CloneFunctionInto, 361 /// except that it does some simple constant prop and DCE on the fly. The 362 /// effect of this is to copy significantly less code in cases where (for 363 /// example) a function call with constant arguments is inlined, and those 364 /// constant arguments cause a significant amount of code in the callee to be 365 /// dead. Since this doesn't produce an exact copy of the input, it can't be 366 /// used for things like CloneFunction or CloneModule. 367 void llvm::CloneAndPruneFunctionInto(Function *NewFunc, const Function *OldFunc, 368 ValueToValueMapTy &VMap, 369 bool ModuleLevelChanges, 370 SmallVectorImpl<ReturnInst*> &Returns, 371 const char *NameSuffix, 372 ClonedCodeInfo *CodeInfo, 373 const DataLayout *TD, 374 Instruction *TheCall) { 375 assert(NameSuffix && "NameSuffix cannot be null!"); 376 377 #ifndef NDEBUG 378 for (Function::const_arg_iterator II = OldFunc->arg_begin(), 379 E = OldFunc->arg_end(); II != E; ++II) 380 assert(VMap.count(II) && "No mapping from source argument specified!"); 381 #endif 382 383 PruningFunctionCloner PFC(NewFunc, OldFunc, VMap, ModuleLevelChanges, 384 NameSuffix, CodeInfo, TD); 385 386 // Clone the entry block, and anything recursively reachable from it. 387 std::vector<const BasicBlock*> CloneWorklist; 388 CloneWorklist.push_back(&OldFunc->getEntryBlock()); 389 while (!CloneWorklist.empty()) { 390 const BasicBlock *BB = CloneWorklist.back(); 391 CloneWorklist.pop_back(); 392 PFC.CloneBlock(BB, CloneWorklist); 393 } 394 395 // Loop over all of the basic blocks in the old function. If the block was 396 // reachable, we have cloned it and the old block is now in the value map: 397 // insert it into the new function in the right order. If not, ignore it. 398 // 399 // Defer PHI resolution until rest of function is resolved. 400 SmallVector<const PHINode*, 16> PHIToResolve; 401 for (Function::const_iterator BI = OldFunc->begin(), BE = OldFunc->end(); 402 BI != BE; ++BI) { 403 Value *V = VMap[BI]; 404 BasicBlock *NewBB = cast_or_null<BasicBlock>(V); 405 if (NewBB == 0) continue; // Dead block. 406 407 // Add the new block to the new function. 408 NewFunc->getBasicBlockList().push_back(NewBB); 409 410 // Handle PHI nodes specially, as we have to remove references to dead 411 // blocks. 412 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end(); I != E; ++I) 413 if (const PHINode *PN = dyn_cast<PHINode>(I)) 414 PHIToResolve.push_back(PN); 415 else 416 break; 417 418 // Finally, remap the terminator instructions, as those can't be remapped 419 // until all BBs are mapped. 420 RemapInstruction(NewBB->getTerminator(), VMap, 421 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges); 422 } 423 424 // Defer PHI resolution until rest of function is resolved, PHI resolution 425 // requires the CFG to be up-to-date. 426 for (unsigned phino = 0, e = PHIToResolve.size(); phino != e; ) { 427 const PHINode *OPN = PHIToResolve[phino]; 428 unsigned NumPreds = OPN->getNumIncomingValues(); 429 const BasicBlock *OldBB = OPN->getParent(); 430 BasicBlock *NewBB = cast<BasicBlock>(VMap[OldBB]); 431 432 // Map operands for blocks that are live and remove operands for blocks 433 // that are dead. 434 for (; phino != PHIToResolve.size() && 435 PHIToResolve[phino]->getParent() == OldBB; ++phino) { 436 OPN = PHIToResolve[phino]; 437 PHINode *PN = cast<PHINode>(VMap[OPN]); 438 for (unsigned pred = 0, e = NumPreds; pred != e; ++pred) { 439 Value *V = VMap[PN->getIncomingBlock(pred)]; 440 if (BasicBlock *MappedBlock = cast_or_null<BasicBlock>(V)) { 441 Value *InVal = MapValue(PN->getIncomingValue(pred), 442 VMap, 443 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges); 444 assert(InVal && "Unknown input value?"); 445 PN->setIncomingValue(pred, InVal); 446 PN->setIncomingBlock(pred, MappedBlock); 447 } else { 448 PN->removeIncomingValue(pred, false); 449 --pred, --e; // Revisit the next entry. 450 } 451 } 452 } 453 454 // The loop above has removed PHI entries for those blocks that are dead 455 // and has updated others. However, if a block is live (i.e. copied over) 456 // but its terminator has been changed to not go to this block, then our 457 // phi nodes will have invalid entries. Update the PHI nodes in this 458 // case. 459 PHINode *PN = cast<PHINode>(NewBB->begin()); 460 NumPreds = std::distance(pred_begin(NewBB), pred_end(NewBB)); 461 if (NumPreds != PN->getNumIncomingValues()) { 462 assert(NumPreds < PN->getNumIncomingValues()); 463 // Count how many times each predecessor comes to this block. 464 std::map<BasicBlock*, unsigned> PredCount; 465 for (pred_iterator PI = pred_begin(NewBB), E = pred_end(NewBB); 466 PI != E; ++PI) 467 --PredCount[*PI]; 468 469 // Figure out how many entries to remove from each PHI. 470 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 471 ++PredCount[PN->getIncomingBlock(i)]; 472 473 // At this point, the excess predecessor entries are positive in the 474 // map. Loop over all of the PHIs and remove excess predecessor 475 // entries. 476 BasicBlock::iterator I = NewBB->begin(); 477 for (; (PN = dyn_cast<PHINode>(I)); ++I) { 478 for (std::map<BasicBlock*, unsigned>::iterator PCI =PredCount.begin(), 479 E = PredCount.end(); PCI != E; ++PCI) { 480 BasicBlock *Pred = PCI->first; 481 for (unsigned NumToRemove = PCI->second; NumToRemove; --NumToRemove) 482 PN->removeIncomingValue(Pred, false); 483 } 484 } 485 } 486 487 // If the loops above have made these phi nodes have 0 or 1 operand, 488 // replace them with undef or the input value. We must do this for 489 // correctness, because 0-operand phis are not valid. 490 PN = cast<PHINode>(NewBB->begin()); 491 if (PN->getNumIncomingValues() == 0) { 492 BasicBlock::iterator I = NewBB->begin(); 493 BasicBlock::const_iterator OldI = OldBB->begin(); 494 while ((PN = dyn_cast<PHINode>(I++))) { 495 Value *NV = UndefValue::get(PN->getType()); 496 PN->replaceAllUsesWith(NV); 497 assert(VMap[OldI] == PN && "VMap mismatch"); 498 VMap[OldI] = NV; 499 PN->eraseFromParent(); 500 ++OldI; 501 } 502 } 503 } 504 505 // Make a second pass over the PHINodes now that all of them have been 506 // remapped into the new function, simplifying the PHINode and performing any 507 // recursive simplifications exposed. This will transparently update the 508 // WeakVH in the VMap. Notably, we rely on that so that if we coalesce 509 // two PHINodes, the iteration over the old PHIs remains valid, and the 510 // mapping will just map us to the new node (which may not even be a PHI 511 // node). 512 for (unsigned Idx = 0, Size = PHIToResolve.size(); Idx != Size; ++Idx) 513 if (PHINode *PN = dyn_cast<PHINode>(VMap[PHIToResolve[Idx]])) 514 recursivelySimplifyInstruction(PN, TD); 515 516 // Now that the inlined function body has been fully constructed, go through 517 // and zap unconditional fall-through branches. This happen all the time when 518 // specializing code: code specialization turns conditional branches into 519 // uncond branches, and this code folds them. 520 Function::iterator Begin = cast<BasicBlock>(VMap[&OldFunc->getEntryBlock()]); 521 Function::iterator I = Begin; 522 while (I != NewFunc->end()) { 523 // Check if this block has become dead during inlining or other 524 // simplifications. Note that the first block will appear dead, as it has 525 // not yet been wired up properly. 526 if (I != Begin && (pred_begin(I) == pred_end(I) || 527 I->getSinglePredecessor() == I)) { 528 BasicBlock *DeadBB = I++; 529 DeleteDeadBlock(DeadBB); 530 continue; 531 } 532 533 // We need to simplify conditional branches and switches with a constant 534 // operand. We try to prune these out when cloning, but if the 535 // simplification required looking through PHI nodes, those are only 536 // available after forming the full basic block. That may leave some here, 537 // and we still want to prune the dead code as early as possible. 538 ConstantFoldTerminator(I); 539 540 BranchInst *BI = dyn_cast<BranchInst>(I->getTerminator()); 541 if (!BI || BI->isConditional()) { ++I; continue; } 542 543 BasicBlock *Dest = BI->getSuccessor(0); 544 if (!Dest->getSinglePredecessor()) { 545 ++I; continue; 546 } 547 548 // We shouldn't be able to get single-entry PHI nodes here, as instsimplify 549 // above should have zapped all of them.. 550 assert(!isa<PHINode>(Dest->begin())); 551 552 // We know all single-entry PHI nodes in the inlined function have been 553 // removed, so we just need to splice the blocks. 554 BI->eraseFromParent(); 555 556 // Make all PHI nodes that referred to Dest now refer to I as their source. 557 Dest->replaceAllUsesWith(I); 558 559 // Move all the instructions in the succ to the pred. 560 I->getInstList().splice(I->end(), Dest->getInstList()); 561 562 // Remove the dest block. 563 Dest->eraseFromParent(); 564 565 // Do not increment I, iteratively merge all things this block branches to. 566 } 567 568 // Make a final pass over the basic blocks from theh old function to gather 569 // any return instructions which survived folding. We have to do this here 570 // because we can iteratively remove and merge returns above. 571 for (Function::iterator I = cast<BasicBlock>(VMap[&OldFunc->getEntryBlock()]), 572 E = NewFunc->end(); 573 I != E; ++I) 574 if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator())) 575 Returns.push_back(RI); 576 } 577