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