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/SetVector.h" 18 #include "llvm/ADT/SmallVector.h" 19 #include "llvm/Analysis/ConstantFolding.h" 20 #include "llvm/Analysis/InstructionSimplify.h" 21 #include "llvm/Analysis/LoopInfo.h" 22 #include "llvm/IR/CFG.h" 23 #include "llvm/IR/Constants.h" 24 #include "llvm/IR/DebugInfo.h" 25 #include "llvm/IR/DerivedTypes.h" 26 #include "llvm/IR/Function.h" 27 #include "llvm/IR/GlobalVariable.h" 28 #include "llvm/IR/Instructions.h" 29 #include "llvm/IR/IntrinsicInst.h" 30 #include "llvm/IR/LLVMContext.h" 31 #include "llvm/IR/Metadata.h" 32 #include "llvm/IR/Module.h" 33 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 34 #include "llvm/Transforms/Utils/Local.h" 35 #include "llvm/Transforms/Utils/ValueMapper.h" 36 #include <map> 37 using namespace llvm; 38 39 /// See comments in Cloning.h. 40 BasicBlock *llvm::CloneBasicBlock(const BasicBlock *BB, 41 ValueToValueMapTy &VMap, 42 const Twine &NameSuffix, Function *F, 43 ClonedCodeInfo *CodeInfo) { 44 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "", F); 45 if (BB->hasName()) NewBB->setName(BB->getName()+NameSuffix); 46 47 bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false; 48 49 // Loop over all instructions, and copy them over. 50 for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end(); 51 II != IE; ++II) { 52 Instruction *NewInst = II->clone(); 53 if (II->hasName()) 54 NewInst->setName(II->getName()+NameSuffix); 55 NewBB->getInstList().push_back(NewInst); 56 VMap[&*II] = NewInst; // Add instruction map to value. 57 58 hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II)); 59 if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) { 60 if (isa<ConstantInt>(AI->getArraySize())) 61 hasStaticAllocas = true; 62 else 63 hasDynamicAllocas = true; 64 } 65 } 66 67 if (CodeInfo) { 68 CodeInfo->ContainsCalls |= hasCalls; 69 CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas; 70 CodeInfo->ContainsDynamicAllocas |= hasStaticAllocas && 71 BB != &BB->getParent()->getEntryBlock(); 72 } 73 return NewBB; 74 } 75 76 // Clone OldFunc into NewFunc, transforming the old arguments into references to 77 // VMap values. 78 // 79 void llvm::CloneFunctionInto(Function *NewFunc, const Function *OldFunc, 80 ValueToValueMapTy &VMap, 81 bool ModuleLevelChanges, 82 SmallVectorImpl<ReturnInst*> &Returns, 83 const char *NameSuffix, ClonedCodeInfo *CodeInfo, 84 ValueMapTypeRemapper *TypeMapper, 85 ValueMaterializer *Materializer) { 86 assert(NameSuffix && "NameSuffix cannot be null!"); 87 88 #ifndef NDEBUG 89 for (const Argument &I : OldFunc->args()) 90 assert(VMap.count(&I) && "No mapping from source argument specified!"); 91 #endif 92 93 // Copy all attributes other than those stored in the AttributeSet. We need 94 // to remap the parameter indices of the AttributeSet. 95 AttributeSet NewAttrs = NewFunc->getAttributes(); 96 NewFunc->copyAttributesFrom(OldFunc); 97 NewFunc->setAttributes(NewAttrs); 98 99 // Fix up the personality function that got copied over. 100 if (OldFunc->hasPersonalityFn()) 101 NewFunc->setPersonalityFn( 102 MapValue(OldFunc->getPersonalityFn(), VMap, 103 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges, 104 TypeMapper, Materializer)); 105 106 AttributeSet OldAttrs = OldFunc->getAttributes(); 107 // Clone any argument attributes that are present in the VMap. 108 for (const Argument &OldArg : OldFunc->args()) 109 if (Argument *NewArg = dyn_cast<Argument>(VMap[&OldArg])) { 110 AttributeSet attrs = 111 OldAttrs.getParamAttributes(OldArg.getArgNo() + 1); 112 if (attrs.getNumSlots() > 0) 113 NewArg->addAttr(attrs); 114 } 115 116 NewFunc->setAttributes( 117 NewFunc->getAttributes() 118 .addAttributes(NewFunc->getContext(), AttributeSet::ReturnIndex, 119 OldAttrs.getRetAttributes()) 120 .addAttributes(NewFunc->getContext(), AttributeSet::FunctionIndex, 121 OldAttrs.getFnAttributes())); 122 123 SmallVector<std::pair<unsigned, MDNode *>, 1> MDs; 124 OldFunc->getAllMetadata(MDs); 125 for (auto MD : MDs) 126 NewFunc->addMetadata( 127 MD.first, 128 *MapMetadata(MD.second, VMap, 129 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges, 130 TypeMapper, Materializer)); 131 132 // Loop over all of the basic blocks in the function, cloning them as 133 // appropriate. Note that we save BE this way in order to handle cloning of 134 // recursive functions into themselves. 135 // 136 for (Function::const_iterator BI = OldFunc->begin(), BE = OldFunc->end(); 137 BI != BE; ++BI) { 138 const BasicBlock &BB = *BI; 139 140 // Create a new basic block and copy instructions into it! 141 BasicBlock *CBB = CloneBasicBlock(&BB, VMap, NameSuffix, NewFunc, CodeInfo); 142 143 // Add basic block mapping. 144 VMap[&BB] = CBB; 145 146 // It is only legal to clone a function if a block address within that 147 // function is never referenced outside of the function. Given that, we 148 // want to map block addresses from the old function to block addresses in 149 // the clone. (This is different from the generic ValueMapper 150 // implementation, which generates an invalid blockaddress when 151 // cloning a function.) 152 if (BB.hasAddressTaken()) { 153 Constant *OldBBAddr = BlockAddress::get(const_cast<Function*>(OldFunc), 154 const_cast<BasicBlock*>(&BB)); 155 VMap[OldBBAddr] = BlockAddress::get(NewFunc, CBB); 156 } 157 158 // Note return instructions for the caller. 159 if (ReturnInst *RI = dyn_cast<ReturnInst>(CBB->getTerminator())) 160 Returns.push_back(RI); 161 } 162 163 // Loop over all of the instructions in the function, fixing up operand 164 // references as we go. This uses VMap to do all the hard work. 165 for (Function::iterator BB = 166 cast<BasicBlock>(VMap[&OldFunc->front()])->getIterator(), 167 BE = NewFunc->end(); 168 BB != BE; ++BB) 169 // Loop over all instructions, fixing each one as we find it... 170 for (Instruction &II : *BB) 171 RemapInstruction(&II, VMap, 172 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges, 173 TypeMapper, Materializer); 174 } 175 176 /// Return a copy of the specified function and add it to that function's 177 /// module. Also, any references specified in the VMap are changed to refer to 178 /// their mapped value instead of the original one. If any of the arguments to 179 /// the function are in the VMap, the arguments are deleted from the resultant 180 /// function. The VMap is updated to include mappings from all of the 181 /// instructions and basicblocks in the function from their old to new values. 182 /// 183 Function *llvm::CloneFunction(Function *F, ValueToValueMapTy &VMap, 184 ClonedCodeInfo *CodeInfo) { 185 std::vector<Type*> ArgTypes; 186 187 // The user might be deleting arguments to the function by specifying them in 188 // the VMap. If so, we need to not add the arguments to the arg ty vector 189 // 190 for (const Argument &I : F->args()) 191 if (VMap.count(&I) == 0) // Haven't mapped the argument to anything yet? 192 ArgTypes.push_back(I.getType()); 193 194 // Create a new function type... 195 FunctionType *FTy = FunctionType::get(F->getFunctionType()->getReturnType(), 196 ArgTypes, F->getFunctionType()->isVarArg()); 197 198 // Create the new function... 199 Function *NewF = 200 Function::Create(FTy, F->getLinkage(), F->getName(), F->getParent()); 201 202 // Loop over the arguments, copying the names of the mapped arguments over... 203 Function::arg_iterator DestI = NewF->arg_begin(); 204 for (const Argument & I : F->args()) 205 if (VMap.count(&I) == 0) { // Is this argument preserved? 206 DestI->setName(I.getName()); // Copy the name over... 207 VMap[&I] = &*DestI++; // Add mapping to VMap 208 } 209 210 SmallVector<ReturnInst*, 8> Returns; // Ignore returns cloned. 211 CloneFunctionInto(NewF, F, VMap, /*ModuleLevelChanges=*/false, Returns, "", 212 CodeInfo); 213 214 return NewF; 215 } 216 217 218 219 namespace { 220 /// This is a private class used to implement CloneAndPruneFunctionInto. 221 struct PruningFunctionCloner { 222 Function *NewFunc; 223 const Function *OldFunc; 224 ValueToValueMapTy &VMap; 225 bool ModuleLevelChanges; 226 const char *NameSuffix; 227 ClonedCodeInfo *CodeInfo; 228 229 public: 230 PruningFunctionCloner(Function *newFunc, const Function *oldFunc, 231 ValueToValueMapTy &valueMap, bool moduleLevelChanges, 232 const char *nameSuffix, ClonedCodeInfo *codeInfo) 233 : NewFunc(newFunc), OldFunc(oldFunc), VMap(valueMap), 234 ModuleLevelChanges(moduleLevelChanges), NameSuffix(nameSuffix), 235 CodeInfo(codeInfo) {} 236 237 /// The specified block is found to be reachable, clone it and 238 /// anything that it can reach. 239 void CloneBlock(const BasicBlock *BB, 240 BasicBlock::const_iterator StartingInst, 241 std::vector<const BasicBlock*> &ToClone); 242 }; 243 } 244 245 /// The specified block is found to be reachable, clone it and 246 /// anything that it can reach. 247 void PruningFunctionCloner::CloneBlock(const BasicBlock *BB, 248 BasicBlock::const_iterator StartingInst, 249 std::vector<const BasicBlock*> &ToClone){ 250 WeakVH &BBEntry = VMap[BB]; 251 252 // Have we already cloned this block? 253 if (BBEntry) return; 254 255 // Nope, clone it now. 256 BasicBlock *NewBB; 257 BBEntry = NewBB = BasicBlock::Create(BB->getContext()); 258 if (BB->hasName()) NewBB->setName(BB->getName()+NameSuffix); 259 260 // It is only legal to clone a function if a block address within that 261 // function is never referenced outside of the function. Given that, we 262 // want to map block addresses from the old function to block addresses in 263 // the clone. (This is different from the generic ValueMapper 264 // implementation, which generates an invalid blockaddress when 265 // cloning a function.) 266 // 267 // Note that we don't need to fix the mapping for unreachable blocks; 268 // the default mapping there is safe. 269 if (BB->hasAddressTaken()) { 270 Constant *OldBBAddr = BlockAddress::get(const_cast<Function*>(OldFunc), 271 const_cast<BasicBlock*>(BB)); 272 VMap[OldBBAddr] = BlockAddress::get(NewFunc, NewBB); 273 } 274 275 bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false; 276 277 // Loop over all instructions, and copy them over, DCE'ing as we go. This 278 // loop doesn't include the terminator. 279 for (BasicBlock::const_iterator II = StartingInst, IE = --BB->end(); 280 II != IE; ++II) { 281 282 Instruction *NewInst = II->clone(); 283 284 // Eagerly remap operands to the newly cloned instruction, except for PHI 285 // nodes for which we defer processing until we update the CFG. 286 if (!isa<PHINode>(NewInst)) { 287 RemapInstruction(NewInst, VMap, 288 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges); 289 290 // If we can simplify this instruction to some other value, simply add 291 // a mapping to that value rather than inserting a new instruction into 292 // the basic block. 293 if (Value *V = 294 SimplifyInstruction(NewInst, BB->getModule()->getDataLayout())) { 295 // On the off-chance that this simplifies to an instruction in the old 296 // function, map it back into the new function. 297 if (Value *MappedV = VMap.lookup(V)) 298 V = MappedV; 299 300 if (!NewInst->mayHaveSideEffects()) { 301 VMap[&*II] = V; 302 delete NewInst; 303 continue; 304 } 305 } 306 } 307 308 if (II->hasName()) 309 NewInst->setName(II->getName()+NameSuffix); 310 VMap[&*II] = NewInst; // Add instruction map to value. 311 NewBB->getInstList().push_back(NewInst); 312 hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II)); 313 314 if (CodeInfo) 315 if (auto CS = ImmutableCallSite(&*II)) 316 if (CS.hasOperandBundles()) 317 CodeInfo->OperandBundleCallSites.push_back(NewInst); 318 319 if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) { 320 if (isa<ConstantInt>(AI->getArraySize())) 321 hasStaticAllocas = true; 322 else 323 hasDynamicAllocas = true; 324 } 325 } 326 327 // Finally, clone over the terminator. 328 const TerminatorInst *OldTI = BB->getTerminator(); 329 bool TerminatorDone = false; 330 if (const BranchInst *BI = dyn_cast<BranchInst>(OldTI)) { 331 if (BI->isConditional()) { 332 // If the condition was a known constant in the callee... 333 ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition()); 334 // Or is a known constant in the caller... 335 if (!Cond) { 336 Value *V = VMap.lookup(BI->getCondition()); 337 Cond = dyn_cast_or_null<ConstantInt>(V); 338 } 339 340 // Constant fold to uncond branch! 341 if (Cond) { 342 BasicBlock *Dest = BI->getSuccessor(!Cond->getZExtValue()); 343 VMap[OldTI] = BranchInst::Create(Dest, NewBB); 344 ToClone.push_back(Dest); 345 TerminatorDone = true; 346 } 347 } 348 } else if (const SwitchInst *SI = dyn_cast<SwitchInst>(OldTI)) { 349 // If switching on a value known constant in the caller. 350 ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition()); 351 if (!Cond) { // Or known constant after constant prop in the callee... 352 Value *V = VMap.lookup(SI->getCondition()); 353 Cond = dyn_cast_or_null<ConstantInt>(V); 354 } 355 if (Cond) { // Constant fold to uncond branch! 356 SwitchInst::ConstCaseIt Case = SI->findCaseValue(Cond); 357 BasicBlock *Dest = const_cast<BasicBlock*>(Case.getCaseSuccessor()); 358 VMap[OldTI] = BranchInst::Create(Dest, NewBB); 359 ToClone.push_back(Dest); 360 TerminatorDone = true; 361 } 362 } 363 364 if (!TerminatorDone) { 365 Instruction *NewInst = OldTI->clone(); 366 if (OldTI->hasName()) 367 NewInst->setName(OldTI->getName()+NameSuffix); 368 NewBB->getInstList().push_back(NewInst); 369 VMap[OldTI] = NewInst; // Add instruction map to value. 370 371 if (CodeInfo) 372 if (auto CS = ImmutableCallSite(OldTI)) 373 if (CS.hasOperandBundles()) 374 CodeInfo->OperandBundleCallSites.push_back(NewInst); 375 376 // Recursively clone any reachable successor blocks. 377 const TerminatorInst *TI = BB->getTerminator(); 378 for (const BasicBlock *Succ : TI->successors()) 379 ToClone.push_back(Succ); 380 } 381 382 if (CodeInfo) { 383 CodeInfo->ContainsCalls |= hasCalls; 384 CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas; 385 CodeInfo->ContainsDynamicAllocas |= hasStaticAllocas && 386 BB != &BB->getParent()->front(); 387 } 388 } 389 390 /// This works like CloneAndPruneFunctionInto, except that it does not clone the 391 /// entire function. Instead it starts at an instruction provided by the caller 392 /// and copies (and prunes) only the code reachable from that instruction. 393 void llvm::CloneAndPruneIntoFromInst(Function *NewFunc, const Function *OldFunc, 394 const Instruction *StartingInst, 395 ValueToValueMapTy &VMap, 396 bool ModuleLevelChanges, 397 SmallVectorImpl<ReturnInst *> &Returns, 398 const char *NameSuffix, 399 ClonedCodeInfo *CodeInfo) { 400 assert(NameSuffix && "NameSuffix cannot be null!"); 401 402 ValueMapTypeRemapper *TypeMapper = nullptr; 403 ValueMaterializer *Materializer = nullptr; 404 405 #ifndef NDEBUG 406 // If the cloning starts at the beginning of the function, verify that 407 // the function arguments are mapped. 408 if (!StartingInst) 409 for (const Argument &II : OldFunc->args()) 410 assert(VMap.count(&II) && "No mapping from source argument specified!"); 411 #endif 412 413 PruningFunctionCloner PFC(NewFunc, OldFunc, VMap, ModuleLevelChanges, 414 NameSuffix, CodeInfo); 415 const BasicBlock *StartingBB; 416 if (StartingInst) 417 StartingBB = StartingInst->getParent(); 418 else { 419 StartingBB = &OldFunc->getEntryBlock(); 420 StartingInst = &StartingBB->front(); 421 } 422 423 // Clone the entry block, and anything recursively reachable from it. 424 std::vector<const BasicBlock*> CloneWorklist; 425 PFC.CloneBlock(StartingBB, StartingInst->getIterator(), CloneWorklist); 426 while (!CloneWorklist.empty()) { 427 const BasicBlock *BB = CloneWorklist.back(); 428 CloneWorklist.pop_back(); 429 PFC.CloneBlock(BB, BB->begin(), CloneWorklist); 430 } 431 432 // Loop over all of the basic blocks in the old function. If the block was 433 // reachable, we have cloned it and the old block is now in the value map: 434 // insert it into the new function in the right order. If not, ignore it. 435 // 436 // Defer PHI resolution until rest of function is resolved. 437 SmallVector<const PHINode*, 16> PHIToResolve; 438 for (const BasicBlock &BI : *OldFunc) { 439 Value *V = VMap.lookup(&BI); 440 BasicBlock *NewBB = cast_or_null<BasicBlock>(V); 441 if (!NewBB) continue; // Dead block. 442 443 // Add the new block to the new function. 444 NewFunc->getBasicBlockList().push_back(NewBB); 445 446 // Handle PHI nodes specially, as we have to remove references to dead 447 // blocks. 448 for (BasicBlock::const_iterator I = BI.begin(), E = BI.end(); I != E; ++I) { 449 // PHI nodes may have been remapped to non-PHI nodes by the caller or 450 // during the cloning process. 451 if (const PHINode *PN = dyn_cast<PHINode>(I)) { 452 if (isa<PHINode>(VMap[PN])) 453 PHIToResolve.push_back(PN); 454 else 455 break; 456 } else { 457 break; 458 } 459 } 460 461 // Finally, remap the terminator instructions, as those can't be remapped 462 // until all BBs are mapped. 463 RemapInstruction(NewBB->getTerminator(), VMap, 464 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges, 465 TypeMapper, Materializer); 466 } 467 468 // Defer PHI resolution until rest of function is resolved, PHI resolution 469 // requires the CFG to be up-to-date. 470 for (unsigned phino = 0, e = PHIToResolve.size(); phino != e; ) { 471 const PHINode *OPN = PHIToResolve[phino]; 472 unsigned NumPreds = OPN->getNumIncomingValues(); 473 const BasicBlock *OldBB = OPN->getParent(); 474 BasicBlock *NewBB = cast<BasicBlock>(VMap[OldBB]); 475 476 // Map operands for blocks that are live and remove operands for blocks 477 // that are dead. 478 for (; phino != PHIToResolve.size() && 479 PHIToResolve[phino]->getParent() == OldBB; ++phino) { 480 OPN = PHIToResolve[phino]; 481 PHINode *PN = cast<PHINode>(VMap[OPN]); 482 for (unsigned pred = 0, e = NumPreds; pred != e; ++pred) { 483 Value *V = VMap.lookup(PN->getIncomingBlock(pred)); 484 if (BasicBlock *MappedBlock = cast_or_null<BasicBlock>(V)) { 485 Value *InVal = MapValue(PN->getIncomingValue(pred), 486 VMap, 487 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges); 488 assert(InVal && "Unknown input value?"); 489 PN->setIncomingValue(pred, InVal); 490 PN->setIncomingBlock(pred, MappedBlock); 491 } else { 492 PN->removeIncomingValue(pred, false); 493 --pred; // Revisit the next entry. 494 --e; 495 } 496 } 497 } 498 499 // The loop above has removed PHI entries for those blocks that are dead 500 // and has updated others. However, if a block is live (i.e. copied over) 501 // but its terminator has been changed to not go to this block, then our 502 // phi nodes will have invalid entries. Update the PHI nodes in this 503 // case. 504 PHINode *PN = cast<PHINode>(NewBB->begin()); 505 NumPreds = std::distance(pred_begin(NewBB), pred_end(NewBB)); 506 if (NumPreds != PN->getNumIncomingValues()) { 507 assert(NumPreds < PN->getNumIncomingValues()); 508 // Count how many times each predecessor comes to this block. 509 std::map<BasicBlock*, unsigned> PredCount; 510 for (pred_iterator PI = pred_begin(NewBB), E = pred_end(NewBB); 511 PI != E; ++PI) 512 --PredCount[*PI]; 513 514 // Figure out how many entries to remove from each PHI. 515 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 516 ++PredCount[PN->getIncomingBlock(i)]; 517 518 // At this point, the excess predecessor entries are positive in the 519 // map. Loop over all of the PHIs and remove excess predecessor 520 // entries. 521 BasicBlock::iterator I = NewBB->begin(); 522 for (; (PN = dyn_cast<PHINode>(I)); ++I) { 523 for (const auto &PCI : PredCount) { 524 BasicBlock *Pred = PCI.first; 525 for (unsigned NumToRemove = PCI.second; NumToRemove; --NumToRemove) 526 PN->removeIncomingValue(Pred, false); 527 } 528 } 529 } 530 531 // If the loops above have made these phi nodes have 0 or 1 operand, 532 // replace them with undef or the input value. We must do this for 533 // correctness, because 0-operand phis are not valid. 534 PN = cast<PHINode>(NewBB->begin()); 535 if (PN->getNumIncomingValues() == 0) { 536 BasicBlock::iterator I = NewBB->begin(); 537 BasicBlock::const_iterator OldI = OldBB->begin(); 538 while ((PN = dyn_cast<PHINode>(I++))) { 539 Value *NV = UndefValue::get(PN->getType()); 540 PN->replaceAllUsesWith(NV); 541 assert(VMap[&*OldI] == PN && "VMap mismatch"); 542 VMap[&*OldI] = NV; 543 PN->eraseFromParent(); 544 ++OldI; 545 } 546 } 547 } 548 549 // Make a second pass over the PHINodes now that all of them have been 550 // remapped into the new function, simplifying the PHINode and performing any 551 // recursive simplifications exposed. This will transparently update the 552 // WeakVH in the VMap. Notably, we rely on that so that if we coalesce 553 // two PHINodes, the iteration over the old PHIs remains valid, and the 554 // mapping will just map us to the new node (which may not even be a PHI 555 // node). 556 const DataLayout &DL = NewFunc->getParent()->getDataLayout(); 557 SmallSetVector<const Value *, 8> Worklist; 558 for (unsigned Idx = 0, Size = PHIToResolve.size(); Idx != Size; ++Idx) 559 if (isa<PHINode>(VMap[PHIToResolve[Idx]])) 560 Worklist.insert(PHIToResolve[Idx]); 561 562 // Note that we must test the size on each iteration, the worklist can grow. 563 for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) { 564 const Value *OrigV = Worklist[Idx]; 565 auto *I = dyn_cast_or_null<Instruction>(VMap.lookup(OrigV)); 566 if (!I) 567 continue; 568 569 // See if this instruction simplifies. 570 Value *SimpleV = SimplifyInstruction(I, DL); 571 if (!SimpleV) 572 continue; 573 574 // Stash away all the uses of the old instruction so we can check them for 575 // recursive simplifications after a RAUW. This is cheaper than checking all 576 // uses of To on the recursive step in most cases. 577 for (const User *U : OrigV->users()) 578 Worklist.insert(cast<Instruction>(U)); 579 580 // Replace the instruction with its simplified value. 581 I->replaceAllUsesWith(SimpleV); 582 583 // If the original instruction had no side effects, remove it. 584 if (isInstructionTriviallyDead(I)) 585 I->eraseFromParent(); 586 else 587 VMap[OrigV] = I; 588 } 589 590 // Now that the inlined function body has been fully constructed, go through 591 // and zap unconditional fall-through branches. This happens all the time when 592 // specializing code: code specialization turns conditional branches into 593 // uncond branches, and this code folds them. 594 Function::iterator Begin = cast<BasicBlock>(VMap[StartingBB])->getIterator(); 595 Function::iterator I = Begin; 596 while (I != NewFunc->end()) { 597 // Check if this block has become dead during inlining or other 598 // simplifications. Note that the first block will appear dead, as it has 599 // not yet been wired up properly. 600 if (I != Begin && (pred_begin(&*I) == pred_end(&*I) || 601 I->getSinglePredecessor() == &*I)) { 602 BasicBlock *DeadBB = &*I++; 603 DeleteDeadBlock(DeadBB); 604 continue; 605 } 606 607 // We need to simplify conditional branches and switches with a constant 608 // operand. We try to prune these out when cloning, but if the 609 // simplification required looking through PHI nodes, those are only 610 // available after forming the full basic block. That may leave some here, 611 // and we still want to prune the dead code as early as possible. 612 ConstantFoldTerminator(&*I); 613 614 BranchInst *BI = dyn_cast<BranchInst>(I->getTerminator()); 615 if (!BI || BI->isConditional()) { ++I; continue; } 616 617 BasicBlock *Dest = BI->getSuccessor(0); 618 if (!Dest->getSinglePredecessor()) { 619 ++I; continue; 620 } 621 622 // We shouldn't be able to get single-entry PHI nodes here, as instsimplify 623 // above should have zapped all of them.. 624 assert(!isa<PHINode>(Dest->begin())); 625 626 // We know all single-entry PHI nodes in the inlined function have been 627 // removed, so we just need to splice the blocks. 628 BI->eraseFromParent(); 629 630 // Make all PHI nodes that referred to Dest now refer to I as their source. 631 Dest->replaceAllUsesWith(&*I); 632 633 // Move all the instructions in the succ to the pred. 634 I->getInstList().splice(I->end(), Dest->getInstList()); 635 636 // Remove the dest block. 637 Dest->eraseFromParent(); 638 639 // Do not increment I, iteratively merge all things this block branches to. 640 } 641 642 // Make a final pass over the basic blocks from the old function to gather 643 // any return instructions which survived folding. We have to do this here 644 // because we can iteratively remove and merge returns above. 645 for (Function::iterator I = cast<BasicBlock>(VMap[StartingBB])->getIterator(), 646 E = NewFunc->end(); 647 I != E; ++I) 648 if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator())) 649 Returns.push_back(RI); 650 } 651 652 653 /// This works exactly like CloneFunctionInto, 654 /// except that it does some simple constant prop and DCE on the fly. The 655 /// effect of this is to copy significantly less code in cases where (for 656 /// example) a function call with constant arguments is inlined, and those 657 /// constant arguments cause a significant amount of code in the callee to be 658 /// dead. Since this doesn't produce an exact copy of the input, it can't be 659 /// used for things like CloneFunction or CloneModule. 660 void llvm::CloneAndPruneFunctionInto(Function *NewFunc, const Function *OldFunc, 661 ValueToValueMapTy &VMap, 662 bool ModuleLevelChanges, 663 SmallVectorImpl<ReturnInst*> &Returns, 664 const char *NameSuffix, 665 ClonedCodeInfo *CodeInfo, 666 Instruction *TheCall) { 667 CloneAndPruneIntoFromInst(NewFunc, OldFunc, &OldFunc->front().front(), VMap, 668 ModuleLevelChanges, Returns, NameSuffix, CodeInfo); 669 } 670 671 /// \brief Remaps instructions in \p Blocks using the mapping in \p VMap. 672 void llvm::remapInstructionsInBlocks( 673 const SmallVectorImpl<BasicBlock *> &Blocks, ValueToValueMapTy &VMap) { 674 // Rewrite the code to refer to itself. 675 for (auto *BB : Blocks) 676 for (auto &Inst : *BB) 677 RemapInstruction(&Inst, VMap, 678 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals); 679 } 680 681 /// \brief Clones a loop \p OrigLoop. Returns the loop and the blocks in \p 682 /// Blocks. 683 /// 684 /// Updates LoopInfo and DominatorTree assuming the loop is dominated by block 685 /// \p LoopDomBB. Insert the new blocks before block specified in \p Before. 686 Loop *llvm::cloneLoopWithPreheader(BasicBlock *Before, BasicBlock *LoopDomBB, 687 Loop *OrigLoop, ValueToValueMapTy &VMap, 688 const Twine &NameSuffix, LoopInfo *LI, 689 DominatorTree *DT, 690 SmallVectorImpl<BasicBlock *> &Blocks) { 691 assert(OrigLoop->getSubLoops().empty() && 692 "Loop to be cloned cannot have inner loop"); 693 Function *F = OrigLoop->getHeader()->getParent(); 694 Loop *ParentLoop = OrigLoop->getParentLoop(); 695 696 Loop *NewLoop = new Loop(); 697 if (ParentLoop) 698 ParentLoop->addChildLoop(NewLoop); 699 else 700 LI->addTopLevelLoop(NewLoop); 701 702 BasicBlock *OrigPH = OrigLoop->getLoopPreheader(); 703 assert(OrigPH && "No preheader"); 704 BasicBlock *NewPH = CloneBasicBlock(OrigPH, VMap, NameSuffix, F); 705 // To rename the loop PHIs. 706 VMap[OrigPH] = NewPH; 707 Blocks.push_back(NewPH); 708 709 // Update LoopInfo. 710 if (ParentLoop) 711 ParentLoop->addBasicBlockToLoop(NewPH, *LI); 712 713 // Update DominatorTree. 714 DT->addNewBlock(NewPH, LoopDomBB); 715 716 for (BasicBlock *BB : OrigLoop->getBlocks()) { 717 BasicBlock *NewBB = CloneBasicBlock(BB, VMap, NameSuffix, F); 718 VMap[BB] = NewBB; 719 720 // Update LoopInfo. 721 NewLoop->addBasicBlockToLoop(NewBB, *LI); 722 723 // Add DominatorTree node. After seeing all blocks, update to correct IDom. 724 DT->addNewBlock(NewBB, NewPH); 725 726 Blocks.push_back(NewBB); 727 } 728 729 for (BasicBlock *BB : OrigLoop->getBlocks()) { 730 // Update DominatorTree. 731 BasicBlock *IDomBB = DT->getNode(BB)->getIDom()->getBlock(); 732 DT->changeImmediateDominator(cast<BasicBlock>(VMap[BB]), 733 cast<BasicBlock>(VMap[IDomBB])); 734 } 735 736 // Move them physically from the end of the block list. 737 F->getBasicBlockList().splice(Before->getIterator(), F->getBasicBlockList(), 738 NewPH); 739 F->getBasicBlockList().splice(Before->getIterator(), F->getBasicBlockList(), 740 NewLoop->getHeader()->getIterator(), F->end()); 741 742 return NewLoop; 743 } 744