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