10b57cec5SDimitry Andric //===- CloneFunction.cpp - Clone a function into another function ---------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file implements the CloneFunctionInto interface, which is used as the
100b57cec5SDimitry Andric // low-level function cloner.  This is used by the CloneFunction and function
110b57cec5SDimitry Andric // inliner to do the dirty work of copying the body of a function around.
120b57cec5SDimitry Andric //
130b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
140b57cec5SDimitry Andric 
150b57cec5SDimitry Andric #include "llvm/ADT/SetVector.h"
160b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
170b57cec5SDimitry Andric #include "llvm/Analysis/ConstantFolding.h"
180b57cec5SDimitry Andric #include "llvm/Analysis/DomTreeUpdater.h"
190b57cec5SDimitry Andric #include "llvm/Analysis/InstructionSimplify.h"
200b57cec5SDimitry Andric #include "llvm/Analysis/LoopInfo.h"
210b57cec5SDimitry Andric #include "llvm/IR/CFG.h"
220b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
230b57cec5SDimitry Andric #include "llvm/IR/DebugInfo.h"
240b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h"
250b57cec5SDimitry Andric #include "llvm/IR/Function.h"
260b57cec5SDimitry Andric #include "llvm/IR/GlobalVariable.h"
270b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
280b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
290b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h"
30af732203SDimitry Andric #include "llvm/IR/MDBuilder.h"
310b57cec5SDimitry Andric #include "llvm/IR/Metadata.h"
320b57cec5SDimitry Andric #include "llvm/IR/Module.h"
330b57cec5SDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h"
340b57cec5SDimitry Andric #include "llvm/Transforms/Utils/Cloning.h"
350b57cec5SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
360b57cec5SDimitry Andric #include "llvm/Transforms/Utils/ValueMapper.h"
370b57cec5SDimitry Andric #include <map>
380b57cec5SDimitry Andric using namespace llvm;
390b57cec5SDimitry Andric 
40af732203SDimitry Andric #define DEBUG_TYPE "clone-function"
41af732203SDimitry Andric 
420b57cec5SDimitry Andric /// See comments in Cloning.h.
CloneBasicBlock(const BasicBlock * BB,ValueToValueMapTy & VMap,const Twine & NameSuffix,Function * F,ClonedCodeInfo * CodeInfo,DebugInfoFinder * DIFinder)430b57cec5SDimitry Andric BasicBlock *llvm::CloneBasicBlock(const BasicBlock *BB, ValueToValueMapTy &VMap,
440b57cec5SDimitry Andric                                   const Twine &NameSuffix, Function *F,
450b57cec5SDimitry Andric                                   ClonedCodeInfo *CodeInfo,
460b57cec5SDimitry Andric                                   DebugInfoFinder *DIFinder) {
470b57cec5SDimitry Andric   BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "", F);
480b57cec5SDimitry Andric   if (BB->hasName())
490b57cec5SDimitry Andric     NewBB->setName(BB->getName() + NameSuffix);
500b57cec5SDimitry Andric 
515ffd83dbSDimitry Andric   bool hasCalls = false, hasDynamicAllocas = false;
520b57cec5SDimitry Andric   Module *TheModule = F ? F->getParent() : nullptr;
530b57cec5SDimitry Andric 
540b57cec5SDimitry Andric   // Loop over all instructions, and copy them over.
550b57cec5SDimitry Andric   for (const Instruction &I : *BB) {
560b57cec5SDimitry Andric     if (DIFinder && TheModule)
570b57cec5SDimitry Andric       DIFinder->processInstruction(*TheModule, I);
580b57cec5SDimitry Andric 
590b57cec5SDimitry Andric     Instruction *NewInst = I.clone();
600b57cec5SDimitry Andric     if (I.hasName())
610b57cec5SDimitry Andric       NewInst->setName(I.getName() + NameSuffix);
620b57cec5SDimitry Andric     NewBB->getInstList().push_back(NewInst);
630b57cec5SDimitry Andric     VMap[&I] = NewInst; // Add instruction map to value.
640b57cec5SDimitry Andric 
650b57cec5SDimitry Andric     hasCalls |= (isa<CallInst>(I) && !isa<DbgInfoIntrinsic>(I));
660b57cec5SDimitry Andric     if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
675ffd83dbSDimitry Andric       if (!AI->isStaticAlloca()) {
680b57cec5SDimitry Andric         hasDynamicAllocas = true;
690b57cec5SDimitry Andric       }
700b57cec5SDimitry Andric     }
715ffd83dbSDimitry Andric   }
720b57cec5SDimitry Andric 
730b57cec5SDimitry Andric   if (CodeInfo) {
740b57cec5SDimitry Andric     CodeInfo->ContainsCalls |= hasCalls;
750b57cec5SDimitry Andric     CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
760b57cec5SDimitry Andric   }
770b57cec5SDimitry Andric   return NewBB;
780b57cec5SDimitry Andric }
790b57cec5SDimitry Andric 
800b57cec5SDimitry Andric // Clone OldFunc into NewFunc, transforming the old arguments into references to
810b57cec5SDimitry Andric // VMap values.
820b57cec5SDimitry Andric //
CloneFunctionInto(Function * NewFunc,const Function * OldFunc,ValueToValueMapTy & VMap,CloneFunctionChangeType Changes,SmallVectorImpl<ReturnInst * > & Returns,const char * NameSuffix,ClonedCodeInfo * CodeInfo,ValueMapTypeRemapper * TypeMapper,ValueMaterializer * Materializer)830b57cec5SDimitry Andric void llvm::CloneFunctionInto(Function *NewFunc, const Function *OldFunc,
840b57cec5SDimitry Andric                              ValueToValueMapTy &VMap,
85*5f7ddb14SDimitry Andric                              CloneFunctionChangeType Changes,
860b57cec5SDimitry Andric                              SmallVectorImpl<ReturnInst *> &Returns,
870b57cec5SDimitry Andric                              const char *NameSuffix, ClonedCodeInfo *CodeInfo,
880b57cec5SDimitry Andric                              ValueMapTypeRemapper *TypeMapper,
890b57cec5SDimitry Andric                              ValueMaterializer *Materializer) {
900b57cec5SDimitry Andric   assert(NameSuffix && "NameSuffix cannot be null!");
910b57cec5SDimitry Andric 
920b57cec5SDimitry Andric #ifndef NDEBUG
930b57cec5SDimitry Andric   for (const Argument &I : OldFunc->args())
940b57cec5SDimitry Andric     assert(VMap.count(&I) && "No mapping from source argument specified!");
950b57cec5SDimitry Andric #endif
960b57cec5SDimitry Andric 
97*5f7ddb14SDimitry Andric   bool ModuleLevelChanges = Changes > CloneFunctionChangeType::LocalChangesOnly;
98*5f7ddb14SDimitry Andric 
990b57cec5SDimitry Andric   // Copy all attributes other than those stored in the AttributeList.  We need
1000b57cec5SDimitry Andric   // to remap the parameter indices of the AttributeList.
1010b57cec5SDimitry Andric   AttributeList NewAttrs = NewFunc->getAttributes();
1020b57cec5SDimitry Andric   NewFunc->copyAttributesFrom(OldFunc);
1030b57cec5SDimitry Andric   NewFunc->setAttributes(NewAttrs);
1040b57cec5SDimitry Andric 
1050b57cec5SDimitry Andric   // Fix up the personality function that got copied over.
1060b57cec5SDimitry Andric   if (OldFunc->hasPersonalityFn())
1070b57cec5SDimitry Andric     NewFunc->setPersonalityFn(
1080b57cec5SDimitry Andric         MapValue(OldFunc->getPersonalityFn(), VMap,
1090b57cec5SDimitry Andric                  ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
1100b57cec5SDimitry Andric                  TypeMapper, Materializer));
1110b57cec5SDimitry Andric 
1120b57cec5SDimitry Andric   SmallVector<AttributeSet, 4> NewArgAttrs(NewFunc->arg_size());
1130b57cec5SDimitry Andric   AttributeList OldAttrs = OldFunc->getAttributes();
1140b57cec5SDimitry Andric 
1150b57cec5SDimitry Andric   // Clone any argument attributes that are present in the VMap.
1160b57cec5SDimitry Andric   for (const Argument &OldArg : OldFunc->args()) {
1170b57cec5SDimitry Andric     if (Argument *NewArg = dyn_cast<Argument>(VMap[&OldArg])) {
1180b57cec5SDimitry Andric       NewArgAttrs[NewArg->getArgNo()] =
1190b57cec5SDimitry Andric           OldAttrs.getParamAttributes(OldArg.getArgNo());
1200b57cec5SDimitry Andric     }
1210b57cec5SDimitry Andric   }
1220b57cec5SDimitry Andric 
1230b57cec5SDimitry Andric   NewFunc->setAttributes(
1240b57cec5SDimitry Andric       AttributeList::get(NewFunc->getContext(), OldAttrs.getFnAttributes(),
1250b57cec5SDimitry Andric                          OldAttrs.getRetAttributes(), NewArgAttrs));
1260b57cec5SDimitry Andric 
127af732203SDimitry Andric   // Everything else beyond this point deals with function instructions,
128af732203SDimitry Andric   // so if we are dealing with a function declaration, we're done.
129af732203SDimitry Andric   if (OldFunc->isDeclaration())
130af732203SDimitry Andric     return;
1310b57cec5SDimitry Andric 
132*5f7ddb14SDimitry Andric   // When we remap instructions within the same module, we want to avoid
133*5f7ddb14SDimitry Andric   // duplicating inlined DISubprograms, so record all subprograms we find as we
134*5f7ddb14SDimitry Andric   // duplicate instructions and then freeze them in the MD map. We also record
135*5f7ddb14SDimitry Andric   // information about dbg.value and dbg.declare to avoid duplicating the
136*5f7ddb14SDimitry Andric   // types.
137*5f7ddb14SDimitry Andric   Optional<DebugInfoFinder> DIFinder;
138*5f7ddb14SDimitry Andric 
139*5f7ddb14SDimitry Andric   // Track the subprogram attachment that needs to be cloned to fine-tune the
140*5f7ddb14SDimitry Andric   // mapping within the same module.
141*5f7ddb14SDimitry Andric   DISubprogram *SPClonedWithinModule = nullptr;
142*5f7ddb14SDimitry Andric   if (Changes < CloneFunctionChangeType::DifferentModule) {
143*5f7ddb14SDimitry Andric     assert((NewFunc->getParent() == nullptr ||
144*5f7ddb14SDimitry Andric             NewFunc->getParent() == OldFunc->getParent()) &&
145*5f7ddb14SDimitry Andric            "Expected NewFunc to have the same parent, or no parent");
146*5f7ddb14SDimitry Andric 
147*5f7ddb14SDimitry Andric     // Need to find subprograms, types, and compile units.
148*5f7ddb14SDimitry Andric     DIFinder.emplace();
149*5f7ddb14SDimitry Andric 
150*5f7ddb14SDimitry Andric     SPClonedWithinModule = OldFunc->getSubprogram();
151*5f7ddb14SDimitry Andric     if (SPClonedWithinModule)
152*5f7ddb14SDimitry Andric       DIFinder->processSubprogram(SPClonedWithinModule);
153*5f7ddb14SDimitry Andric   } else {
154*5f7ddb14SDimitry Andric     assert((NewFunc->getParent() == nullptr ||
155*5f7ddb14SDimitry Andric             NewFunc->getParent() != OldFunc->getParent()) &&
156*5f7ddb14SDimitry Andric            "Expected NewFunc to have different parents, or no parent");
157*5f7ddb14SDimitry Andric 
158*5f7ddb14SDimitry Andric     if (Changes == CloneFunctionChangeType::DifferentModule) {
159*5f7ddb14SDimitry Andric       assert(NewFunc->getParent() &&
160*5f7ddb14SDimitry Andric              "Need parent of new function to maintain debug info invariants");
161*5f7ddb14SDimitry Andric 
162*5f7ddb14SDimitry Andric       // Need to find all the compile units.
163*5f7ddb14SDimitry Andric       DIFinder.emplace();
164*5f7ddb14SDimitry Andric     }
165*5f7ddb14SDimitry Andric   }
1660b57cec5SDimitry Andric 
1670b57cec5SDimitry Andric   // Loop over all of the basic blocks in the function, cloning them as
1680b57cec5SDimitry Andric   // appropriate.  Note that we save BE this way in order to handle cloning of
1690b57cec5SDimitry Andric   // recursive functions into themselves.
170*5f7ddb14SDimitry Andric   for (const BasicBlock &BB : *OldFunc) {
1710b57cec5SDimitry Andric 
1720b57cec5SDimitry Andric     // Create a new basic block and copy instructions into it!
1730b57cec5SDimitry Andric     BasicBlock *CBB = CloneBasicBlock(&BB, VMap, NameSuffix, NewFunc, CodeInfo,
174*5f7ddb14SDimitry Andric                                       DIFinder ? &*DIFinder : nullptr);
1750b57cec5SDimitry Andric 
1760b57cec5SDimitry Andric     // Add basic block mapping.
1770b57cec5SDimitry Andric     VMap[&BB] = CBB;
1780b57cec5SDimitry Andric 
1790b57cec5SDimitry Andric     // It is only legal to clone a function if a block address within that
1800b57cec5SDimitry Andric     // function is never referenced outside of the function.  Given that, we
1810b57cec5SDimitry Andric     // want to map block addresses from the old function to block addresses in
1820b57cec5SDimitry Andric     // the clone. (This is different from the generic ValueMapper
1830b57cec5SDimitry Andric     // implementation, which generates an invalid blockaddress when
1840b57cec5SDimitry Andric     // cloning a function.)
1850b57cec5SDimitry Andric     if (BB.hasAddressTaken()) {
1860b57cec5SDimitry Andric       Constant *OldBBAddr = BlockAddress::get(const_cast<Function *>(OldFunc),
1870b57cec5SDimitry Andric                                               const_cast<BasicBlock *>(&BB));
1880b57cec5SDimitry Andric       VMap[OldBBAddr] = BlockAddress::get(NewFunc, CBB);
1890b57cec5SDimitry Andric     }
1900b57cec5SDimitry Andric 
1910b57cec5SDimitry Andric     // Note return instructions for the caller.
1920b57cec5SDimitry Andric     if (ReturnInst *RI = dyn_cast<ReturnInst>(CBB->getTerminator()))
1930b57cec5SDimitry Andric       Returns.push_back(RI);
1940b57cec5SDimitry Andric   }
1950b57cec5SDimitry Andric 
196*5f7ddb14SDimitry Andric   if (Changes < CloneFunctionChangeType::DifferentModule &&
197*5f7ddb14SDimitry Andric       DIFinder->subprogram_count() > 0) {
198*5f7ddb14SDimitry Andric     // Turn on module-level changes, since we need to clone (some of) the
199*5f7ddb14SDimitry Andric     // debug info metadata.
200*5f7ddb14SDimitry Andric     //
201*5f7ddb14SDimitry Andric     // FIXME: Metadata effectively owned by a function should be made
202*5f7ddb14SDimitry Andric     // local, and only that local metadata should be cloned.
203*5f7ddb14SDimitry Andric     ModuleLevelChanges = true;
2040b57cec5SDimitry Andric 
205*5f7ddb14SDimitry Andric     auto mapToSelfIfNew = [&VMap](MDNode *N) {
206*5f7ddb14SDimitry Andric       // Avoid clobbering an existing mapping.
207*5f7ddb14SDimitry Andric       (void)VMap.MD().try_emplace(N, N);
208*5f7ddb14SDimitry Andric     };
2090b57cec5SDimitry Andric 
210*5f7ddb14SDimitry Andric     // Avoid cloning types, compile units, and (other) subprograms.
211*5f7ddb14SDimitry Andric     for (DISubprogram *ISP : DIFinder->subprograms())
212*5f7ddb14SDimitry Andric       if (ISP != SPClonedWithinModule)
213*5f7ddb14SDimitry Andric         mapToSelfIfNew(ISP);
2140b57cec5SDimitry Andric 
215*5f7ddb14SDimitry Andric     for (DICompileUnit *CU : DIFinder->compile_units())
216*5f7ddb14SDimitry Andric       mapToSelfIfNew(CU);
217*5f7ddb14SDimitry Andric 
218*5f7ddb14SDimitry Andric     for (DIType *Type : DIFinder->types())
219*5f7ddb14SDimitry Andric       mapToSelfIfNew(Type);
220*5f7ddb14SDimitry Andric   } else {
221*5f7ddb14SDimitry Andric     assert(!SPClonedWithinModule &&
222*5f7ddb14SDimitry Andric            "Subprogram should be in DIFinder->subprogram_count()...");
223*5f7ddb14SDimitry Andric   }
224*5f7ddb14SDimitry Andric 
225*5f7ddb14SDimitry Andric   const auto RemapFlag = ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges;
226af732203SDimitry Andric   // Duplicate the metadata that is attached to the cloned function.
227af732203SDimitry Andric   // Subprograms/CUs/types that were already mapped to themselves won't be
228af732203SDimitry Andric   // duplicated.
229af732203SDimitry Andric   SmallVector<std::pair<unsigned, MDNode *>, 1> MDs;
230af732203SDimitry Andric   OldFunc->getAllMetadata(MDs);
231af732203SDimitry Andric   for (auto MD : MDs) {
232*5f7ddb14SDimitry Andric     NewFunc->addMetadata(MD.first, *MapMetadata(MD.second, VMap, RemapFlag,
233af732203SDimitry Andric                                                 TypeMapper, Materializer));
234af732203SDimitry Andric   }
235af732203SDimitry Andric 
236*5f7ddb14SDimitry Andric   // Loop over all of the instructions in the new function, fixing up operand
2370b57cec5SDimitry Andric   // references as we go. This uses VMap to do all the hard work.
238*5f7ddb14SDimitry Andric   for (Function::iterator
239*5f7ddb14SDimitry Andric            BB = cast<BasicBlock>(VMap[&OldFunc->front()])->getIterator(),
2400b57cec5SDimitry Andric            BE = NewFunc->end();
2410b57cec5SDimitry Andric        BB != BE; ++BB)
2420b57cec5SDimitry Andric     // Loop over all instructions, fixing each one as we find it...
2430b57cec5SDimitry Andric     for (Instruction &II : *BB)
244*5f7ddb14SDimitry Andric       RemapInstruction(&II, VMap, RemapFlag, TypeMapper, Materializer);
2458bcb0991SDimitry Andric 
246*5f7ddb14SDimitry Andric   // Only update !llvm.dbg.cu for DifferentModule (not CloneModule). In the
247*5f7ddb14SDimitry Andric   // same module, the compile unit will already be listed (or not). When
248*5f7ddb14SDimitry Andric   // cloning a module, CloneModule() will handle creating the named metadata.
249*5f7ddb14SDimitry Andric   if (Changes != CloneFunctionChangeType::DifferentModule)
250*5f7ddb14SDimitry Andric     return;
251*5f7ddb14SDimitry Andric 
252*5f7ddb14SDimitry Andric   // Update !llvm.dbg.cu with compile units added to the new module if this
253*5f7ddb14SDimitry Andric   // function is being cloned in isolation.
254*5f7ddb14SDimitry Andric   //
255*5f7ddb14SDimitry Andric   // FIXME: This is making global / module-level changes, which doesn't seem
256*5f7ddb14SDimitry Andric   // like the right encapsulation  Consider dropping the requirement to update
257*5f7ddb14SDimitry Andric   // !llvm.dbg.cu (either obsoleting the node, or restricting it to
258*5f7ddb14SDimitry Andric   // non-discardable compile units) instead of discovering compile units by
259*5f7ddb14SDimitry Andric   // visiting the metadata attached to global values, which would allow this
260*5f7ddb14SDimitry Andric   // code to be deleted. Alternatively, perhaps give responsibility for this
261*5f7ddb14SDimitry Andric   // update to CloneFunctionInto's callers.
2628bcb0991SDimitry Andric   auto *NewModule = NewFunc->getParent();
2638bcb0991SDimitry Andric   auto *NMD = NewModule->getOrInsertNamedMetadata("llvm.dbg.cu");
2648bcb0991SDimitry Andric   // Avoid multiple insertions of the same DICompileUnit to NMD.
2658bcb0991SDimitry Andric   SmallPtrSet<const void *, 8> Visited;
2668bcb0991SDimitry Andric   for (auto *Operand : NMD->operands())
2678bcb0991SDimitry Andric     Visited.insert(Operand);
268*5f7ddb14SDimitry Andric   for (auto *Unit : DIFinder->compile_units()) {
269*5f7ddb14SDimitry Andric     MDNode *MappedUnit =
270*5f7ddb14SDimitry Andric         MapMetadata(Unit, VMap, RF_None, TypeMapper, Materializer);
271*5f7ddb14SDimitry Andric     if (Visited.insert(MappedUnit).second)
272*5f7ddb14SDimitry Andric       NMD->addOperand(MappedUnit);
2738bcb0991SDimitry Andric   }
2740b57cec5SDimitry Andric }
2750b57cec5SDimitry Andric 
2760b57cec5SDimitry Andric /// Return a copy of the specified function and add it to that function's
2770b57cec5SDimitry Andric /// module.  Also, any references specified in the VMap are changed to refer to
2780b57cec5SDimitry Andric /// their mapped value instead of the original one.  If any of the arguments to
2790b57cec5SDimitry Andric /// the function are in the VMap, the arguments are deleted from the resultant
2800b57cec5SDimitry Andric /// function.  The VMap is updated to include mappings from all of the
2810b57cec5SDimitry Andric /// instructions and basicblocks in the function from their old to new values.
2820b57cec5SDimitry Andric ///
CloneFunction(Function * F,ValueToValueMapTy & VMap,ClonedCodeInfo * CodeInfo)2830b57cec5SDimitry Andric Function *llvm::CloneFunction(Function *F, ValueToValueMapTy &VMap,
2840b57cec5SDimitry Andric                               ClonedCodeInfo *CodeInfo) {
2850b57cec5SDimitry Andric   std::vector<Type *> ArgTypes;
2860b57cec5SDimitry Andric 
2870b57cec5SDimitry Andric   // The user might be deleting arguments to the function by specifying them in
2880b57cec5SDimitry Andric   // the VMap.  If so, we need to not add the arguments to the arg ty vector
2890b57cec5SDimitry Andric   //
2900b57cec5SDimitry Andric   for (const Argument &I : F->args())
2910b57cec5SDimitry Andric     if (VMap.count(&I) == 0) // Haven't mapped the argument to anything yet?
2920b57cec5SDimitry Andric       ArgTypes.push_back(I.getType());
2930b57cec5SDimitry Andric 
2940b57cec5SDimitry Andric   // Create a new function type...
295*5f7ddb14SDimitry Andric   FunctionType *FTy =
296*5f7ddb14SDimitry Andric       FunctionType::get(F->getFunctionType()->getReturnType(), ArgTypes,
297*5f7ddb14SDimitry Andric                         F->getFunctionType()->isVarArg());
2980b57cec5SDimitry Andric 
2990b57cec5SDimitry Andric   // Create the new function...
3000b57cec5SDimitry Andric   Function *NewF = Function::Create(FTy, F->getLinkage(), F->getAddressSpace(),
3010b57cec5SDimitry Andric                                     F->getName(), F->getParent());
3020b57cec5SDimitry Andric 
3030b57cec5SDimitry Andric   // Loop over the arguments, copying the names of the mapped arguments over...
3040b57cec5SDimitry Andric   Function::arg_iterator DestI = NewF->arg_begin();
3050b57cec5SDimitry Andric   for (const Argument &I : F->args())
3060b57cec5SDimitry Andric     if (VMap.count(&I) == 0) {     // Is this argument preserved?
3070b57cec5SDimitry Andric       DestI->setName(I.getName()); // Copy the name over...
3080b57cec5SDimitry Andric       VMap[&I] = &*DestI++;        // Add mapping to VMap
3090b57cec5SDimitry Andric     }
3100b57cec5SDimitry Andric 
3110b57cec5SDimitry Andric   SmallVector<ReturnInst *, 8> Returns; // Ignore returns cloned.
312*5f7ddb14SDimitry Andric   CloneFunctionInto(NewF, F, VMap, CloneFunctionChangeType::LocalChangesOnly,
313*5f7ddb14SDimitry Andric                     Returns, "", CodeInfo);
3140b57cec5SDimitry Andric 
3150b57cec5SDimitry Andric   return NewF;
3160b57cec5SDimitry Andric }
3170b57cec5SDimitry Andric 
3180b57cec5SDimitry Andric namespace {
3190b57cec5SDimitry Andric /// This is a private class used to implement CloneAndPruneFunctionInto.
3200b57cec5SDimitry Andric struct PruningFunctionCloner {
3210b57cec5SDimitry Andric   Function *NewFunc;
3220b57cec5SDimitry Andric   const Function *OldFunc;
3230b57cec5SDimitry Andric   ValueToValueMapTy &VMap;
3240b57cec5SDimitry Andric   bool ModuleLevelChanges;
3250b57cec5SDimitry Andric   const char *NameSuffix;
3260b57cec5SDimitry Andric   ClonedCodeInfo *CodeInfo;
3270b57cec5SDimitry Andric 
3280b57cec5SDimitry Andric public:
PruningFunctionCloner__anon43d456190211::PruningFunctionCloner3290b57cec5SDimitry Andric   PruningFunctionCloner(Function *newFunc, const Function *oldFunc,
3300b57cec5SDimitry Andric                         ValueToValueMapTy &valueMap, bool moduleLevelChanges,
3310b57cec5SDimitry Andric                         const char *nameSuffix, ClonedCodeInfo *codeInfo)
3320b57cec5SDimitry Andric       : NewFunc(newFunc), OldFunc(oldFunc), VMap(valueMap),
3330b57cec5SDimitry Andric         ModuleLevelChanges(moduleLevelChanges), NameSuffix(nameSuffix),
3340b57cec5SDimitry Andric         CodeInfo(codeInfo) {}
3350b57cec5SDimitry Andric 
3360b57cec5SDimitry Andric   /// The specified block is found to be reachable, clone it and
3370b57cec5SDimitry Andric   /// anything that it can reach.
338*5f7ddb14SDimitry Andric   void CloneBlock(const BasicBlock *BB, BasicBlock::const_iterator StartingInst,
3390b57cec5SDimitry Andric                   std::vector<const BasicBlock *> &ToClone);
3400b57cec5SDimitry Andric };
341*5f7ddb14SDimitry Andric } // namespace
3420b57cec5SDimitry Andric 
3430b57cec5SDimitry Andric /// The specified block is found to be reachable, clone it and
3440b57cec5SDimitry Andric /// anything that it can reach.
CloneBlock(const BasicBlock * BB,BasicBlock::const_iterator StartingInst,std::vector<const BasicBlock * > & ToClone)345*5f7ddb14SDimitry Andric void PruningFunctionCloner::CloneBlock(
346*5f7ddb14SDimitry Andric     const BasicBlock *BB, BasicBlock::const_iterator StartingInst,
3470b57cec5SDimitry Andric     std::vector<const BasicBlock *> &ToClone) {
3480b57cec5SDimitry Andric   WeakTrackingVH &BBEntry = VMap[BB];
3490b57cec5SDimitry Andric 
3500b57cec5SDimitry Andric   // Have we already cloned this block?
351*5f7ddb14SDimitry Andric   if (BBEntry)
352*5f7ddb14SDimitry Andric     return;
3530b57cec5SDimitry Andric 
3540b57cec5SDimitry Andric   // Nope, clone it now.
3550b57cec5SDimitry Andric   BasicBlock *NewBB;
3560b57cec5SDimitry Andric   BBEntry = NewBB = BasicBlock::Create(BB->getContext());
357*5f7ddb14SDimitry Andric   if (BB->hasName())
358*5f7ddb14SDimitry Andric     NewBB->setName(BB->getName() + NameSuffix);
3590b57cec5SDimitry Andric 
3600b57cec5SDimitry Andric   // It is only legal to clone a function if a block address within that
3610b57cec5SDimitry Andric   // function is never referenced outside of the function.  Given that, we
3620b57cec5SDimitry Andric   // want to map block addresses from the old function to block addresses in
3630b57cec5SDimitry Andric   // the clone. (This is different from the generic ValueMapper
3640b57cec5SDimitry Andric   // implementation, which generates an invalid blockaddress when
3650b57cec5SDimitry Andric   // cloning a function.)
3660b57cec5SDimitry Andric   //
3670b57cec5SDimitry Andric   // Note that we don't need to fix the mapping for unreachable blocks;
3680b57cec5SDimitry Andric   // the default mapping there is safe.
3690b57cec5SDimitry Andric   if (BB->hasAddressTaken()) {
3700b57cec5SDimitry Andric     Constant *OldBBAddr = BlockAddress::get(const_cast<Function *>(OldFunc),
3710b57cec5SDimitry Andric                                             const_cast<BasicBlock *>(BB));
3720b57cec5SDimitry Andric     VMap[OldBBAddr] = BlockAddress::get(NewFunc, NewBB);
3730b57cec5SDimitry Andric   }
3740b57cec5SDimitry Andric 
3750b57cec5SDimitry Andric   bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false;
3760b57cec5SDimitry Andric 
3770b57cec5SDimitry Andric   // Loop over all instructions, and copy them over, DCE'ing as we go.  This
3780b57cec5SDimitry Andric   // loop doesn't include the terminator.
379*5f7ddb14SDimitry Andric   for (BasicBlock::const_iterator II = StartingInst, IE = --BB->end(); II != IE;
380*5f7ddb14SDimitry Andric        ++II) {
3810b57cec5SDimitry Andric 
3820b57cec5SDimitry Andric     Instruction *NewInst = II->clone();
3830b57cec5SDimitry Andric 
3840b57cec5SDimitry Andric     // Eagerly remap operands to the newly cloned instruction, except for PHI
3850b57cec5SDimitry Andric     // nodes for which we defer processing until we update the CFG.
3860b57cec5SDimitry Andric     if (!isa<PHINode>(NewInst)) {
3870b57cec5SDimitry Andric       RemapInstruction(NewInst, VMap,
3880b57cec5SDimitry Andric                        ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
3890b57cec5SDimitry Andric 
3900b57cec5SDimitry Andric       // If we can simplify this instruction to some other value, simply add
3910b57cec5SDimitry Andric       // a mapping to that value rather than inserting a new instruction into
3920b57cec5SDimitry Andric       // the basic block.
3930b57cec5SDimitry Andric       if (Value *V =
3940b57cec5SDimitry Andric               SimplifyInstruction(NewInst, BB->getModule()->getDataLayout())) {
3950b57cec5SDimitry Andric         // On the off-chance that this simplifies to an instruction in the old
3960b57cec5SDimitry Andric         // function, map it back into the new function.
3970b57cec5SDimitry Andric         if (NewFunc != OldFunc)
3980b57cec5SDimitry Andric           if (Value *MappedV = VMap.lookup(V))
3990b57cec5SDimitry Andric             V = MappedV;
4000b57cec5SDimitry Andric 
4010b57cec5SDimitry Andric         if (!NewInst->mayHaveSideEffects()) {
4020b57cec5SDimitry Andric           VMap[&*II] = V;
4030b57cec5SDimitry Andric           NewInst->deleteValue();
4040b57cec5SDimitry Andric           continue;
4050b57cec5SDimitry Andric         }
4060b57cec5SDimitry Andric       }
4070b57cec5SDimitry Andric     }
4080b57cec5SDimitry Andric 
4090b57cec5SDimitry Andric     if (II->hasName())
4100b57cec5SDimitry Andric       NewInst->setName(II->getName() + NameSuffix);
4110b57cec5SDimitry Andric     VMap[&*II] = NewInst; // Add instruction map to value.
4120b57cec5SDimitry Andric     NewBB->getInstList().push_back(NewInst);
4130b57cec5SDimitry Andric     hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II));
4140b57cec5SDimitry Andric 
415*5f7ddb14SDimitry Andric     if (CodeInfo) {
416*5f7ddb14SDimitry Andric       CodeInfo->OrigVMap[&*II] = NewInst;
4175ffd83dbSDimitry Andric       if (auto *CB = dyn_cast<CallBase>(&*II))
4185ffd83dbSDimitry Andric         if (CB->hasOperandBundles())
4190b57cec5SDimitry Andric           CodeInfo->OperandBundleCallSites.push_back(NewInst);
420*5f7ddb14SDimitry Andric     }
4210b57cec5SDimitry Andric 
4220b57cec5SDimitry Andric     if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
4230b57cec5SDimitry Andric       if (isa<ConstantInt>(AI->getArraySize()))
4240b57cec5SDimitry Andric         hasStaticAllocas = true;
4250b57cec5SDimitry Andric       else
4260b57cec5SDimitry Andric         hasDynamicAllocas = true;
4270b57cec5SDimitry Andric     }
4280b57cec5SDimitry Andric   }
4290b57cec5SDimitry Andric 
4300b57cec5SDimitry Andric   // Finally, clone over the terminator.
4310b57cec5SDimitry Andric   const Instruction *OldTI = BB->getTerminator();
4320b57cec5SDimitry Andric   bool TerminatorDone = false;
4330b57cec5SDimitry Andric   if (const BranchInst *BI = dyn_cast<BranchInst>(OldTI)) {
4340b57cec5SDimitry Andric     if (BI->isConditional()) {
4350b57cec5SDimitry Andric       // If the condition was a known constant in the callee...
4360b57cec5SDimitry Andric       ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
4370b57cec5SDimitry Andric       // Or is a known constant in the caller...
4380b57cec5SDimitry Andric       if (!Cond) {
4390b57cec5SDimitry Andric         Value *V = VMap.lookup(BI->getCondition());
4400b57cec5SDimitry Andric         Cond = dyn_cast_or_null<ConstantInt>(V);
4410b57cec5SDimitry Andric       }
4420b57cec5SDimitry Andric 
4430b57cec5SDimitry Andric       // Constant fold to uncond branch!
4440b57cec5SDimitry Andric       if (Cond) {
4450b57cec5SDimitry Andric         BasicBlock *Dest = BI->getSuccessor(!Cond->getZExtValue());
4460b57cec5SDimitry Andric         VMap[OldTI] = BranchInst::Create(Dest, NewBB);
4470b57cec5SDimitry Andric         ToClone.push_back(Dest);
4480b57cec5SDimitry Andric         TerminatorDone = true;
4490b57cec5SDimitry Andric       }
4500b57cec5SDimitry Andric     }
4510b57cec5SDimitry Andric   } else if (const SwitchInst *SI = dyn_cast<SwitchInst>(OldTI)) {
4520b57cec5SDimitry Andric     // If switching on a value known constant in the caller.
4530b57cec5SDimitry Andric     ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition());
4540b57cec5SDimitry Andric     if (!Cond) { // Or known constant after constant prop in the callee...
4550b57cec5SDimitry Andric       Value *V = VMap.lookup(SI->getCondition());
4560b57cec5SDimitry Andric       Cond = dyn_cast_or_null<ConstantInt>(V);
4570b57cec5SDimitry Andric     }
4580b57cec5SDimitry Andric     if (Cond) { // Constant fold to uncond branch!
4590b57cec5SDimitry Andric       SwitchInst::ConstCaseHandle Case = *SI->findCaseValue(Cond);
4600b57cec5SDimitry Andric       BasicBlock *Dest = const_cast<BasicBlock *>(Case.getCaseSuccessor());
4610b57cec5SDimitry Andric       VMap[OldTI] = BranchInst::Create(Dest, NewBB);
4620b57cec5SDimitry Andric       ToClone.push_back(Dest);
4630b57cec5SDimitry Andric       TerminatorDone = true;
4640b57cec5SDimitry Andric     }
4650b57cec5SDimitry Andric   }
4660b57cec5SDimitry Andric 
4670b57cec5SDimitry Andric   if (!TerminatorDone) {
4680b57cec5SDimitry Andric     Instruction *NewInst = OldTI->clone();
4690b57cec5SDimitry Andric     if (OldTI->hasName())
4700b57cec5SDimitry Andric       NewInst->setName(OldTI->getName() + NameSuffix);
4710b57cec5SDimitry Andric     NewBB->getInstList().push_back(NewInst);
4720b57cec5SDimitry Andric     VMap[OldTI] = NewInst; // Add instruction map to value.
4730b57cec5SDimitry Andric 
474*5f7ddb14SDimitry Andric     if (CodeInfo) {
475*5f7ddb14SDimitry Andric       CodeInfo->OrigVMap[OldTI] = NewInst;
4765ffd83dbSDimitry Andric       if (auto *CB = dyn_cast<CallBase>(OldTI))
4775ffd83dbSDimitry Andric         if (CB->hasOperandBundles())
4780b57cec5SDimitry Andric           CodeInfo->OperandBundleCallSites.push_back(NewInst);
479*5f7ddb14SDimitry Andric     }
4800b57cec5SDimitry Andric 
4810b57cec5SDimitry Andric     // Recursively clone any reachable successor blocks.
482af732203SDimitry Andric     append_range(ToClone, successors(BB->getTerminator()));
4830b57cec5SDimitry Andric   }
4840b57cec5SDimitry Andric 
4850b57cec5SDimitry Andric   if (CodeInfo) {
4860b57cec5SDimitry Andric     CodeInfo->ContainsCalls |= hasCalls;
4870b57cec5SDimitry Andric     CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
488*5f7ddb14SDimitry Andric     CodeInfo->ContainsDynamicAllocas |=
489*5f7ddb14SDimitry Andric         hasStaticAllocas && BB != &BB->getParent()->front();
4900b57cec5SDimitry Andric   }
4910b57cec5SDimitry Andric }
4920b57cec5SDimitry Andric 
4930b57cec5SDimitry Andric /// This works like CloneAndPruneFunctionInto, except that it does not clone the
4940b57cec5SDimitry Andric /// entire function. Instead it starts at an instruction provided by the caller
4950b57cec5SDimitry Andric /// and copies (and prunes) only the code reachable from that instruction.
CloneAndPruneIntoFromInst(Function * NewFunc,const Function * OldFunc,const Instruction * StartingInst,ValueToValueMapTy & VMap,bool ModuleLevelChanges,SmallVectorImpl<ReturnInst * > & Returns,const char * NameSuffix,ClonedCodeInfo * CodeInfo)4960b57cec5SDimitry Andric void llvm::CloneAndPruneIntoFromInst(Function *NewFunc, const Function *OldFunc,
4970b57cec5SDimitry Andric                                      const Instruction *StartingInst,
4980b57cec5SDimitry Andric                                      ValueToValueMapTy &VMap,
4990b57cec5SDimitry Andric                                      bool ModuleLevelChanges,
5000b57cec5SDimitry Andric                                      SmallVectorImpl<ReturnInst *> &Returns,
5010b57cec5SDimitry Andric                                      const char *NameSuffix,
5020b57cec5SDimitry Andric                                      ClonedCodeInfo *CodeInfo) {
5030b57cec5SDimitry Andric   assert(NameSuffix && "NameSuffix cannot be null!");
5040b57cec5SDimitry Andric 
5050b57cec5SDimitry Andric   ValueMapTypeRemapper *TypeMapper = nullptr;
5060b57cec5SDimitry Andric   ValueMaterializer *Materializer = nullptr;
5070b57cec5SDimitry Andric 
5080b57cec5SDimitry Andric #ifndef NDEBUG
5090b57cec5SDimitry Andric   // If the cloning starts at the beginning of the function, verify that
5100b57cec5SDimitry Andric   // the function arguments are mapped.
5110b57cec5SDimitry Andric   if (!StartingInst)
5120b57cec5SDimitry Andric     for (const Argument &II : OldFunc->args())
5130b57cec5SDimitry Andric       assert(VMap.count(&II) && "No mapping from source argument specified!");
5140b57cec5SDimitry Andric #endif
5150b57cec5SDimitry Andric 
5160b57cec5SDimitry Andric   PruningFunctionCloner PFC(NewFunc, OldFunc, VMap, ModuleLevelChanges,
5170b57cec5SDimitry Andric                             NameSuffix, CodeInfo);
5180b57cec5SDimitry Andric   const BasicBlock *StartingBB;
5190b57cec5SDimitry Andric   if (StartingInst)
5200b57cec5SDimitry Andric     StartingBB = StartingInst->getParent();
5210b57cec5SDimitry Andric   else {
5220b57cec5SDimitry Andric     StartingBB = &OldFunc->getEntryBlock();
5230b57cec5SDimitry Andric     StartingInst = &StartingBB->front();
5240b57cec5SDimitry Andric   }
5250b57cec5SDimitry Andric 
5260b57cec5SDimitry Andric   // Clone the entry block, and anything recursively reachable from it.
5270b57cec5SDimitry Andric   std::vector<const BasicBlock *> CloneWorklist;
5280b57cec5SDimitry Andric   PFC.CloneBlock(StartingBB, StartingInst->getIterator(), CloneWorklist);
5290b57cec5SDimitry Andric   while (!CloneWorklist.empty()) {
5300b57cec5SDimitry Andric     const BasicBlock *BB = CloneWorklist.back();
5310b57cec5SDimitry Andric     CloneWorklist.pop_back();
5320b57cec5SDimitry Andric     PFC.CloneBlock(BB, BB->begin(), CloneWorklist);
5330b57cec5SDimitry Andric   }
5340b57cec5SDimitry Andric 
5350b57cec5SDimitry Andric   // Loop over all of the basic blocks in the old function.  If the block was
5360b57cec5SDimitry Andric   // reachable, we have cloned it and the old block is now in the value map:
5370b57cec5SDimitry Andric   // insert it into the new function in the right order.  If not, ignore it.
5380b57cec5SDimitry Andric   //
5390b57cec5SDimitry Andric   // Defer PHI resolution until rest of function is resolved.
5400b57cec5SDimitry Andric   SmallVector<const PHINode *, 16> PHIToResolve;
5410b57cec5SDimitry Andric   for (const BasicBlock &BI : *OldFunc) {
5420b57cec5SDimitry Andric     Value *V = VMap.lookup(&BI);
5430b57cec5SDimitry Andric     BasicBlock *NewBB = cast_or_null<BasicBlock>(V);
544*5f7ddb14SDimitry Andric     if (!NewBB)
545*5f7ddb14SDimitry Andric       continue; // Dead block.
5460b57cec5SDimitry Andric 
5470b57cec5SDimitry Andric     // Add the new block to the new function.
5480b57cec5SDimitry Andric     NewFunc->getBasicBlockList().push_back(NewBB);
5490b57cec5SDimitry Andric 
5500b57cec5SDimitry Andric     // Handle PHI nodes specially, as we have to remove references to dead
5510b57cec5SDimitry Andric     // blocks.
5520b57cec5SDimitry Andric     for (const PHINode &PN : BI.phis()) {
5530b57cec5SDimitry Andric       // PHI nodes may have been remapped to non-PHI nodes by the caller or
5540b57cec5SDimitry Andric       // during the cloning process.
5550b57cec5SDimitry Andric       if (isa<PHINode>(VMap[&PN]))
5560b57cec5SDimitry Andric         PHIToResolve.push_back(&PN);
5570b57cec5SDimitry Andric       else
5580b57cec5SDimitry Andric         break;
5590b57cec5SDimitry Andric     }
5600b57cec5SDimitry Andric 
5610b57cec5SDimitry Andric     // Finally, remap the terminator instructions, as those can't be remapped
5620b57cec5SDimitry Andric     // until all BBs are mapped.
5630b57cec5SDimitry Andric     RemapInstruction(NewBB->getTerminator(), VMap,
5640b57cec5SDimitry Andric                      ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
5650b57cec5SDimitry Andric                      TypeMapper, Materializer);
5660b57cec5SDimitry Andric   }
5670b57cec5SDimitry Andric 
5680b57cec5SDimitry Andric   // Defer PHI resolution until rest of function is resolved, PHI resolution
5690b57cec5SDimitry Andric   // requires the CFG to be up-to-date.
5700b57cec5SDimitry Andric   for (unsigned phino = 0, e = PHIToResolve.size(); phino != e;) {
5710b57cec5SDimitry Andric     const PHINode *OPN = PHIToResolve[phino];
5720b57cec5SDimitry Andric     unsigned NumPreds = OPN->getNumIncomingValues();
5730b57cec5SDimitry Andric     const BasicBlock *OldBB = OPN->getParent();
5740b57cec5SDimitry Andric     BasicBlock *NewBB = cast<BasicBlock>(VMap[OldBB]);
5750b57cec5SDimitry Andric 
5760b57cec5SDimitry Andric     // Map operands for blocks that are live and remove operands for blocks
5770b57cec5SDimitry Andric     // that are dead.
5780b57cec5SDimitry Andric     for (; phino != PHIToResolve.size() &&
579*5f7ddb14SDimitry Andric            PHIToResolve[phino]->getParent() == OldBB;
580*5f7ddb14SDimitry Andric          ++phino) {
5810b57cec5SDimitry Andric       OPN = PHIToResolve[phino];
5820b57cec5SDimitry Andric       PHINode *PN = cast<PHINode>(VMap[OPN]);
5830b57cec5SDimitry Andric       for (unsigned pred = 0, e = NumPreds; pred != e; ++pred) {
5840b57cec5SDimitry Andric         Value *V = VMap.lookup(PN->getIncomingBlock(pred));
5850b57cec5SDimitry Andric         if (BasicBlock *MappedBlock = cast_or_null<BasicBlock>(V)) {
586*5f7ddb14SDimitry Andric           Value *InVal =
587*5f7ddb14SDimitry Andric               MapValue(PN->getIncomingValue(pred), VMap,
5880b57cec5SDimitry Andric                        ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
5890b57cec5SDimitry Andric           assert(InVal && "Unknown input value?");
5900b57cec5SDimitry Andric           PN->setIncomingValue(pred, InVal);
5910b57cec5SDimitry Andric           PN->setIncomingBlock(pred, MappedBlock);
5920b57cec5SDimitry Andric         } else {
5930b57cec5SDimitry Andric           PN->removeIncomingValue(pred, false);
5940b57cec5SDimitry Andric           --pred; // Revisit the next entry.
5950b57cec5SDimitry Andric           --e;
5960b57cec5SDimitry Andric         }
5970b57cec5SDimitry Andric       }
5980b57cec5SDimitry Andric     }
5990b57cec5SDimitry Andric 
6000b57cec5SDimitry Andric     // The loop above has removed PHI entries for those blocks that are dead
6010b57cec5SDimitry Andric     // and has updated others.  However, if a block is live (i.e. copied over)
6020b57cec5SDimitry Andric     // but its terminator has been changed to not go to this block, then our
6030b57cec5SDimitry Andric     // phi nodes will have invalid entries.  Update the PHI nodes in this
6040b57cec5SDimitry Andric     // case.
6050b57cec5SDimitry Andric     PHINode *PN = cast<PHINode>(NewBB->begin());
6060b57cec5SDimitry Andric     NumPreds = pred_size(NewBB);
6070b57cec5SDimitry Andric     if (NumPreds != PN->getNumIncomingValues()) {
6080b57cec5SDimitry Andric       assert(NumPreds < PN->getNumIncomingValues());
6090b57cec5SDimitry Andric       // Count how many times each predecessor comes to this block.
6100b57cec5SDimitry Andric       std::map<BasicBlock *, unsigned> PredCount;
611*5f7ddb14SDimitry Andric       for (BasicBlock *Pred : predecessors(NewBB))
612*5f7ddb14SDimitry Andric         --PredCount[Pred];
6130b57cec5SDimitry Andric 
6140b57cec5SDimitry Andric       // Figure out how many entries to remove from each PHI.
6150b57cec5SDimitry Andric       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
6160b57cec5SDimitry Andric         ++PredCount[PN->getIncomingBlock(i)];
6170b57cec5SDimitry Andric 
6180b57cec5SDimitry Andric       // At this point, the excess predecessor entries are positive in the
6190b57cec5SDimitry Andric       // map.  Loop over all of the PHIs and remove excess predecessor
6200b57cec5SDimitry Andric       // entries.
6210b57cec5SDimitry Andric       BasicBlock::iterator I = NewBB->begin();
6220b57cec5SDimitry Andric       for (; (PN = dyn_cast<PHINode>(I)); ++I) {
6230b57cec5SDimitry Andric         for (const auto &PCI : PredCount) {
6240b57cec5SDimitry Andric           BasicBlock *Pred = PCI.first;
6250b57cec5SDimitry Andric           for (unsigned NumToRemove = PCI.second; NumToRemove; --NumToRemove)
6260b57cec5SDimitry Andric             PN->removeIncomingValue(Pred, false);
6270b57cec5SDimitry Andric         }
6280b57cec5SDimitry Andric       }
6290b57cec5SDimitry Andric     }
6300b57cec5SDimitry Andric 
6310b57cec5SDimitry Andric     // If the loops above have made these phi nodes have 0 or 1 operand,
6320b57cec5SDimitry Andric     // replace them with undef or the input value.  We must do this for
6330b57cec5SDimitry Andric     // correctness, because 0-operand phis are not valid.
6340b57cec5SDimitry Andric     PN = cast<PHINode>(NewBB->begin());
6350b57cec5SDimitry Andric     if (PN->getNumIncomingValues() == 0) {
6360b57cec5SDimitry Andric       BasicBlock::iterator I = NewBB->begin();
6370b57cec5SDimitry Andric       BasicBlock::const_iterator OldI = OldBB->begin();
6380b57cec5SDimitry Andric       while ((PN = dyn_cast<PHINode>(I++))) {
6390b57cec5SDimitry Andric         Value *NV = UndefValue::get(PN->getType());
6400b57cec5SDimitry Andric         PN->replaceAllUsesWith(NV);
6410b57cec5SDimitry Andric         assert(VMap[&*OldI] == PN && "VMap mismatch");
6420b57cec5SDimitry Andric         VMap[&*OldI] = NV;
6430b57cec5SDimitry Andric         PN->eraseFromParent();
6440b57cec5SDimitry Andric         ++OldI;
6450b57cec5SDimitry Andric       }
6460b57cec5SDimitry Andric     }
6470b57cec5SDimitry Andric   }
6480b57cec5SDimitry Andric 
6490b57cec5SDimitry Andric   // Make a second pass over the PHINodes now that all of them have been
6500b57cec5SDimitry Andric   // remapped into the new function, simplifying the PHINode and performing any
6510b57cec5SDimitry Andric   // recursive simplifications exposed. This will transparently update the
6520b57cec5SDimitry Andric   // WeakTrackingVH in the VMap. Notably, we rely on that so that if we coalesce
6530b57cec5SDimitry Andric   // two PHINodes, the iteration over the old PHIs remains valid, and the
6540b57cec5SDimitry Andric   // mapping will just map us to the new node (which may not even be a PHI
6550b57cec5SDimitry Andric   // node).
6560b57cec5SDimitry Andric   const DataLayout &DL = NewFunc->getParent()->getDataLayout();
6570b57cec5SDimitry Andric   SmallSetVector<const Value *, 8> Worklist;
6580b57cec5SDimitry Andric   for (unsigned Idx = 0, Size = PHIToResolve.size(); Idx != Size; ++Idx)
6590b57cec5SDimitry Andric     if (isa<PHINode>(VMap[PHIToResolve[Idx]]))
6600b57cec5SDimitry Andric       Worklist.insert(PHIToResolve[Idx]);
6610b57cec5SDimitry Andric 
6620b57cec5SDimitry Andric   // Note that we must test the size on each iteration, the worklist can grow.
6630b57cec5SDimitry Andric   for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
6640b57cec5SDimitry Andric     const Value *OrigV = Worklist[Idx];
6650b57cec5SDimitry Andric     auto *I = dyn_cast_or_null<Instruction>(VMap.lookup(OrigV));
6660b57cec5SDimitry Andric     if (!I)
6670b57cec5SDimitry Andric       continue;
6680b57cec5SDimitry Andric 
6690b57cec5SDimitry Andric     // Skip over non-intrinsic callsites, we don't want to remove any nodes from
6700b57cec5SDimitry Andric     // the CGSCC.
6715ffd83dbSDimitry Andric     CallBase *CB = dyn_cast<CallBase>(I);
6725ffd83dbSDimitry Andric     if (CB && CB->getCalledFunction() &&
6735ffd83dbSDimitry Andric         !CB->getCalledFunction()->isIntrinsic())
6740b57cec5SDimitry Andric       continue;
6750b57cec5SDimitry Andric 
6760b57cec5SDimitry Andric     // See if this instruction simplifies.
6770b57cec5SDimitry Andric     Value *SimpleV = SimplifyInstruction(I, DL);
6780b57cec5SDimitry Andric     if (!SimpleV)
6790b57cec5SDimitry Andric       continue;
6800b57cec5SDimitry Andric 
6810b57cec5SDimitry Andric     // Stash away all the uses of the old instruction so we can check them for
6820b57cec5SDimitry Andric     // recursive simplifications after a RAUW. This is cheaper than checking all
6830b57cec5SDimitry Andric     // uses of To on the recursive step in most cases.
6840b57cec5SDimitry Andric     for (const User *U : OrigV->users())
6850b57cec5SDimitry Andric       Worklist.insert(cast<Instruction>(U));
6860b57cec5SDimitry Andric 
6870b57cec5SDimitry Andric     // Replace the instruction with its simplified value.
6880b57cec5SDimitry Andric     I->replaceAllUsesWith(SimpleV);
6890b57cec5SDimitry Andric 
6900b57cec5SDimitry Andric     // If the original instruction had no side effects, remove it.
6910b57cec5SDimitry Andric     if (isInstructionTriviallyDead(I))
6920b57cec5SDimitry Andric       I->eraseFromParent();
6930b57cec5SDimitry Andric     else
6940b57cec5SDimitry Andric       VMap[OrigV] = I;
6950b57cec5SDimitry Andric   }
6960b57cec5SDimitry Andric 
6970b57cec5SDimitry Andric   // Now that the inlined function body has been fully constructed, go through
6980b57cec5SDimitry Andric   // and zap unconditional fall-through branches. This happens all the time when
6990b57cec5SDimitry Andric   // specializing code: code specialization turns conditional branches into
7000b57cec5SDimitry Andric   // uncond branches, and this code folds them.
7010b57cec5SDimitry Andric   Function::iterator Begin = cast<BasicBlock>(VMap[StartingBB])->getIterator();
7020b57cec5SDimitry Andric   Function::iterator I = Begin;
7030b57cec5SDimitry Andric   while (I != NewFunc->end()) {
7040b57cec5SDimitry Andric     // We need to simplify conditional branches and switches with a constant
7050b57cec5SDimitry Andric     // operand. We try to prune these out when cloning, but if the
7060b57cec5SDimitry Andric     // simplification required looking through PHI nodes, those are only
7070b57cec5SDimitry Andric     // available after forming the full basic block. That may leave some here,
7080b57cec5SDimitry Andric     // and we still want to prune the dead code as early as possible.
7090b57cec5SDimitry Andric     //
7100b57cec5SDimitry Andric     // Do the folding before we check if the block is dead since we want code
7110b57cec5SDimitry Andric     // like
7120b57cec5SDimitry Andric     //  bb:
7130b57cec5SDimitry Andric     //    br i1 undef, label %bb, label %bb
7140b57cec5SDimitry Andric     // to be simplified to
7150b57cec5SDimitry Andric     //  bb:
7160b57cec5SDimitry Andric     //    br label %bb
7170b57cec5SDimitry Andric     // before we call I->getSinglePredecessor().
7180b57cec5SDimitry Andric     ConstantFoldTerminator(&*I);
7190b57cec5SDimitry Andric 
7200b57cec5SDimitry Andric     // Check if this block has become dead during inlining or other
7210b57cec5SDimitry Andric     // simplifications. Note that the first block will appear dead, as it has
7220b57cec5SDimitry Andric     // not yet been wired up properly.
723af732203SDimitry Andric     if (I != Begin && (pred_empty(&*I) || I->getSinglePredecessor() == &*I)) {
7240b57cec5SDimitry Andric       BasicBlock *DeadBB = &*I++;
7250b57cec5SDimitry Andric       DeleteDeadBlock(DeadBB);
7260b57cec5SDimitry Andric       continue;
7270b57cec5SDimitry Andric     }
7280b57cec5SDimitry Andric 
7290b57cec5SDimitry Andric     BranchInst *BI = dyn_cast<BranchInst>(I->getTerminator());
730*5f7ddb14SDimitry Andric     if (!BI || BI->isConditional()) {
731*5f7ddb14SDimitry Andric       ++I;
732*5f7ddb14SDimitry Andric       continue;
733*5f7ddb14SDimitry Andric     }
7340b57cec5SDimitry Andric 
7350b57cec5SDimitry Andric     BasicBlock *Dest = BI->getSuccessor(0);
7360b57cec5SDimitry Andric     if (!Dest->getSinglePredecessor()) {
737*5f7ddb14SDimitry Andric       ++I;
738*5f7ddb14SDimitry Andric       continue;
7390b57cec5SDimitry Andric     }
7400b57cec5SDimitry Andric 
7410b57cec5SDimitry Andric     // We shouldn't be able to get single-entry PHI nodes here, as instsimplify
7420b57cec5SDimitry Andric     // above should have zapped all of them..
7430b57cec5SDimitry Andric     assert(!isa<PHINode>(Dest->begin()));
7440b57cec5SDimitry Andric 
7450b57cec5SDimitry Andric     // We know all single-entry PHI nodes in the inlined function have been
7460b57cec5SDimitry Andric     // removed, so we just need to splice the blocks.
7470b57cec5SDimitry Andric     BI->eraseFromParent();
7480b57cec5SDimitry Andric 
7490b57cec5SDimitry Andric     // Make all PHI nodes that referred to Dest now refer to I as their source.
7500b57cec5SDimitry Andric     Dest->replaceAllUsesWith(&*I);
7510b57cec5SDimitry Andric 
7520b57cec5SDimitry Andric     // Move all the instructions in the succ to the pred.
7530b57cec5SDimitry Andric     I->getInstList().splice(I->end(), Dest->getInstList());
7540b57cec5SDimitry Andric 
7550b57cec5SDimitry Andric     // Remove the dest block.
7560b57cec5SDimitry Andric     Dest->eraseFromParent();
7570b57cec5SDimitry Andric 
7580b57cec5SDimitry Andric     // Do not increment I, iteratively merge all things this block branches to.
7590b57cec5SDimitry Andric   }
7600b57cec5SDimitry Andric 
7610b57cec5SDimitry Andric   // Make a final pass over the basic blocks from the old function to gather
7620b57cec5SDimitry Andric   // any return instructions which survived folding. We have to do this here
7630b57cec5SDimitry Andric   // because we can iteratively remove and merge returns above.
7640b57cec5SDimitry Andric   for (Function::iterator I = cast<BasicBlock>(VMap[StartingBB])->getIterator(),
7650b57cec5SDimitry Andric                           E = NewFunc->end();
7660b57cec5SDimitry Andric        I != E; ++I)
7670b57cec5SDimitry Andric     if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator()))
7680b57cec5SDimitry Andric       Returns.push_back(RI);
7690b57cec5SDimitry Andric }
7700b57cec5SDimitry Andric 
7710b57cec5SDimitry Andric /// This works exactly like CloneFunctionInto,
7720b57cec5SDimitry Andric /// except that it does some simple constant prop and DCE on the fly.  The
7730b57cec5SDimitry Andric /// effect of this is to copy significantly less code in cases where (for
7740b57cec5SDimitry Andric /// example) a function call with constant arguments is inlined, and those
7750b57cec5SDimitry Andric /// constant arguments cause a significant amount of code in the callee to be
7760b57cec5SDimitry Andric /// dead.  Since this doesn't produce an exact copy of the input, it can't be
7770b57cec5SDimitry Andric /// used for things like CloneFunction or CloneModule.
CloneAndPruneFunctionInto(Function * NewFunc,const Function * OldFunc,ValueToValueMapTy & VMap,bool ModuleLevelChanges,SmallVectorImpl<ReturnInst * > & Returns,const char * NameSuffix,ClonedCodeInfo * CodeInfo)778*5f7ddb14SDimitry Andric void llvm::CloneAndPruneFunctionInto(
779*5f7ddb14SDimitry Andric     Function *NewFunc, const Function *OldFunc, ValueToValueMapTy &VMap,
780*5f7ddb14SDimitry Andric     bool ModuleLevelChanges, SmallVectorImpl<ReturnInst *> &Returns,
781*5f7ddb14SDimitry Andric     const char *NameSuffix, ClonedCodeInfo *CodeInfo) {
7820b57cec5SDimitry Andric   CloneAndPruneIntoFromInst(NewFunc, OldFunc, &OldFunc->front().front(), VMap,
7830b57cec5SDimitry Andric                             ModuleLevelChanges, Returns, NameSuffix, CodeInfo);
7840b57cec5SDimitry Andric }
7850b57cec5SDimitry Andric 
7860b57cec5SDimitry Andric /// Remaps instructions in \p Blocks using the mapping in \p VMap.
remapInstructionsInBlocks(const SmallVectorImpl<BasicBlock * > & Blocks,ValueToValueMapTy & VMap)7870b57cec5SDimitry Andric void llvm::remapInstructionsInBlocks(
7880b57cec5SDimitry Andric     const SmallVectorImpl<BasicBlock *> &Blocks, ValueToValueMapTy &VMap) {
7890b57cec5SDimitry Andric   // Rewrite the code to refer to itself.
7900b57cec5SDimitry Andric   for (auto *BB : Blocks)
7910b57cec5SDimitry Andric     for (auto &Inst : *BB)
7920b57cec5SDimitry Andric       RemapInstruction(&Inst, VMap,
7930b57cec5SDimitry Andric                        RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
7940b57cec5SDimitry Andric }
7950b57cec5SDimitry Andric 
7960b57cec5SDimitry Andric /// Clones a loop \p OrigLoop.  Returns the loop and the blocks in \p
7970b57cec5SDimitry Andric /// Blocks.
7980b57cec5SDimitry Andric ///
7990b57cec5SDimitry Andric /// Updates LoopInfo and DominatorTree assuming the loop is dominated by block
8000b57cec5SDimitry Andric /// \p LoopDomBB.  Insert the new blocks before block specified in \p Before.
cloneLoopWithPreheader(BasicBlock * Before,BasicBlock * LoopDomBB,Loop * OrigLoop,ValueToValueMapTy & VMap,const Twine & NameSuffix,LoopInfo * LI,DominatorTree * DT,SmallVectorImpl<BasicBlock * > & Blocks)8010b57cec5SDimitry Andric Loop *llvm::cloneLoopWithPreheader(BasicBlock *Before, BasicBlock *LoopDomBB,
8020b57cec5SDimitry Andric                                    Loop *OrigLoop, ValueToValueMapTy &VMap,
8030b57cec5SDimitry Andric                                    const Twine &NameSuffix, LoopInfo *LI,
8040b57cec5SDimitry Andric                                    DominatorTree *DT,
8050b57cec5SDimitry Andric                                    SmallVectorImpl<BasicBlock *> &Blocks) {
8060b57cec5SDimitry Andric   Function *F = OrigLoop->getHeader()->getParent();
8070b57cec5SDimitry Andric   Loop *ParentLoop = OrigLoop->getParentLoop();
8080b57cec5SDimitry Andric   DenseMap<Loop *, Loop *> LMap;
8090b57cec5SDimitry Andric 
8100b57cec5SDimitry Andric   Loop *NewLoop = LI->AllocateLoop();
8110b57cec5SDimitry Andric   LMap[OrigLoop] = NewLoop;
8120b57cec5SDimitry Andric   if (ParentLoop)
8130b57cec5SDimitry Andric     ParentLoop->addChildLoop(NewLoop);
8140b57cec5SDimitry Andric   else
8150b57cec5SDimitry Andric     LI->addTopLevelLoop(NewLoop);
8160b57cec5SDimitry Andric 
8170b57cec5SDimitry Andric   BasicBlock *OrigPH = OrigLoop->getLoopPreheader();
8180b57cec5SDimitry Andric   assert(OrigPH && "No preheader");
8190b57cec5SDimitry Andric   BasicBlock *NewPH = CloneBasicBlock(OrigPH, VMap, NameSuffix, F);
8200b57cec5SDimitry Andric   // To rename the loop PHIs.
8210b57cec5SDimitry Andric   VMap[OrigPH] = NewPH;
8220b57cec5SDimitry Andric   Blocks.push_back(NewPH);
8230b57cec5SDimitry Andric 
8240b57cec5SDimitry Andric   // Update LoopInfo.
8250b57cec5SDimitry Andric   if (ParentLoop)
8260b57cec5SDimitry Andric     ParentLoop->addBasicBlockToLoop(NewPH, *LI);
8270b57cec5SDimitry Andric 
8280b57cec5SDimitry Andric   // Update DominatorTree.
8290b57cec5SDimitry Andric   DT->addNewBlock(NewPH, LoopDomBB);
8300b57cec5SDimitry Andric 
8310b57cec5SDimitry Andric   for (Loop *CurLoop : OrigLoop->getLoopsInPreorder()) {
8320b57cec5SDimitry Andric     Loop *&NewLoop = LMap[CurLoop];
8330b57cec5SDimitry Andric     if (!NewLoop) {
8340b57cec5SDimitry Andric       NewLoop = LI->AllocateLoop();
8350b57cec5SDimitry Andric 
8360b57cec5SDimitry Andric       // Establish the parent/child relationship.
8370b57cec5SDimitry Andric       Loop *OrigParent = CurLoop->getParentLoop();
8380b57cec5SDimitry Andric       assert(OrigParent && "Could not find the original parent loop");
8390b57cec5SDimitry Andric       Loop *NewParentLoop = LMap[OrigParent];
8400b57cec5SDimitry Andric       assert(NewParentLoop && "Could not find the new parent loop");
8410b57cec5SDimitry Andric 
8420b57cec5SDimitry Andric       NewParentLoop->addChildLoop(NewLoop);
8430b57cec5SDimitry Andric     }
8440b57cec5SDimitry Andric   }
8450b57cec5SDimitry Andric 
8460b57cec5SDimitry Andric   for (BasicBlock *BB : OrigLoop->getBlocks()) {
8470b57cec5SDimitry Andric     Loop *CurLoop = LI->getLoopFor(BB);
8480b57cec5SDimitry Andric     Loop *&NewLoop = LMap[CurLoop];
8490b57cec5SDimitry Andric     assert(NewLoop && "Expecting new loop to be allocated");
8500b57cec5SDimitry Andric 
8510b57cec5SDimitry Andric     BasicBlock *NewBB = CloneBasicBlock(BB, VMap, NameSuffix, F);
8520b57cec5SDimitry Andric     VMap[BB] = NewBB;
8530b57cec5SDimitry Andric 
8540b57cec5SDimitry Andric     // Update LoopInfo.
8550b57cec5SDimitry Andric     NewLoop->addBasicBlockToLoop(NewBB, *LI);
8560b57cec5SDimitry Andric 
8570b57cec5SDimitry Andric     // Add DominatorTree node. After seeing all blocks, update to correct
8580b57cec5SDimitry Andric     // IDom.
8590b57cec5SDimitry Andric     DT->addNewBlock(NewBB, NewPH);
8600b57cec5SDimitry Andric 
8610b57cec5SDimitry Andric     Blocks.push_back(NewBB);
8620b57cec5SDimitry Andric   }
8630b57cec5SDimitry Andric 
8640b57cec5SDimitry Andric   for (BasicBlock *BB : OrigLoop->getBlocks()) {
8655ffd83dbSDimitry Andric     // Update loop headers.
8665ffd83dbSDimitry Andric     Loop *CurLoop = LI->getLoopFor(BB);
8675ffd83dbSDimitry Andric     if (BB == CurLoop->getHeader())
8685ffd83dbSDimitry Andric       LMap[CurLoop]->moveToHeader(cast<BasicBlock>(VMap[BB]));
8695ffd83dbSDimitry Andric 
8700b57cec5SDimitry Andric     // Update DominatorTree.
8710b57cec5SDimitry Andric     BasicBlock *IDomBB = DT->getNode(BB)->getIDom()->getBlock();
8720b57cec5SDimitry Andric     DT->changeImmediateDominator(cast<BasicBlock>(VMap[BB]),
8730b57cec5SDimitry Andric                                  cast<BasicBlock>(VMap[IDomBB]));
8740b57cec5SDimitry Andric   }
8750b57cec5SDimitry Andric 
8760b57cec5SDimitry Andric   // Move them physically from the end of the block list.
8770b57cec5SDimitry Andric   F->getBasicBlockList().splice(Before->getIterator(), F->getBasicBlockList(),
8780b57cec5SDimitry Andric                                 NewPH);
8790b57cec5SDimitry Andric   F->getBasicBlockList().splice(Before->getIterator(), F->getBasicBlockList(),
8800b57cec5SDimitry Andric                                 NewLoop->getHeader()->getIterator(), F->end());
8810b57cec5SDimitry Andric 
8820b57cec5SDimitry Andric   return NewLoop;
8830b57cec5SDimitry Andric }
8840b57cec5SDimitry Andric 
8850b57cec5SDimitry Andric /// Duplicate non-Phi instructions from the beginning of block up to
8860b57cec5SDimitry Andric /// StopAt instruction into a split block between BB and its predecessor.
DuplicateInstructionsInSplitBetween(BasicBlock * BB,BasicBlock * PredBB,Instruction * StopAt,ValueToValueMapTy & ValueMapping,DomTreeUpdater & DTU)8870b57cec5SDimitry Andric BasicBlock *llvm::DuplicateInstructionsInSplitBetween(
8880b57cec5SDimitry Andric     BasicBlock *BB, BasicBlock *PredBB, Instruction *StopAt,
8890b57cec5SDimitry Andric     ValueToValueMapTy &ValueMapping, DomTreeUpdater &DTU) {
8900b57cec5SDimitry Andric 
8910b57cec5SDimitry Andric   assert(count(successors(PredBB), BB) == 1 &&
8920b57cec5SDimitry Andric          "There must be a single edge between PredBB and BB!");
8930b57cec5SDimitry Andric   // We are going to have to map operands from the original BB block to the new
8940b57cec5SDimitry Andric   // copy of the block 'NewBB'.  If there are PHI nodes in BB, evaluate them to
8950b57cec5SDimitry Andric   // account for entry from PredBB.
8960b57cec5SDimitry Andric   BasicBlock::iterator BI = BB->begin();
8970b57cec5SDimitry Andric   for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
8980b57cec5SDimitry Andric     ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
8990b57cec5SDimitry Andric 
9000b57cec5SDimitry Andric   BasicBlock *NewBB = SplitEdge(PredBB, BB);
9010b57cec5SDimitry Andric   NewBB->setName(PredBB->getName() + ".split");
9020b57cec5SDimitry Andric   Instruction *NewTerm = NewBB->getTerminator();
9030b57cec5SDimitry Andric 
9040b57cec5SDimitry Andric   // FIXME: SplitEdge does not yet take a DTU, so we include the split edge
9050b57cec5SDimitry Andric   //        in the update set here.
9060b57cec5SDimitry Andric   DTU.applyUpdates({{DominatorTree::Delete, PredBB, BB},
9070b57cec5SDimitry Andric                     {DominatorTree::Insert, PredBB, NewBB},
9080b57cec5SDimitry Andric                     {DominatorTree::Insert, NewBB, BB}});
9090b57cec5SDimitry Andric 
9100b57cec5SDimitry Andric   // Clone the non-phi instructions of BB into NewBB, keeping track of the
9110b57cec5SDimitry Andric   // mapping and using it to remap operands in the cloned instructions.
9120b57cec5SDimitry Andric   // Stop once we see the terminator too. This covers the case where BB's
9130b57cec5SDimitry Andric   // terminator gets replaced and StopAt == BB's terminator.
9140b57cec5SDimitry Andric   for (; StopAt != &*BI && BB->getTerminator() != &*BI; ++BI) {
9150b57cec5SDimitry Andric     Instruction *New = BI->clone();
9160b57cec5SDimitry Andric     New->setName(BI->getName());
9170b57cec5SDimitry Andric     New->insertBefore(NewTerm);
9180b57cec5SDimitry Andric     ValueMapping[&*BI] = New;
9190b57cec5SDimitry Andric 
9200b57cec5SDimitry Andric     // Remap operands to patch up intra-block references.
9210b57cec5SDimitry Andric     for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
9220b57cec5SDimitry Andric       if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
9230b57cec5SDimitry Andric         auto I = ValueMapping.find(Inst);
9240b57cec5SDimitry Andric         if (I != ValueMapping.end())
9250b57cec5SDimitry Andric           New->setOperand(i, I->second);
9260b57cec5SDimitry Andric       }
9270b57cec5SDimitry Andric   }
9280b57cec5SDimitry Andric 
9290b57cec5SDimitry Andric   return NewBB;
9300b57cec5SDimitry Andric }
931af732203SDimitry Andric 
cloneNoAliasScopes(ArrayRef<MDNode * > NoAliasDeclScopes,DenseMap<MDNode *,MDNode * > & ClonedScopes,StringRef Ext,LLVMContext & Context)932*5f7ddb14SDimitry Andric void llvm::cloneNoAliasScopes(ArrayRef<MDNode *> NoAliasDeclScopes,
933af732203SDimitry Andric                               DenseMap<MDNode *, MDNode *> &ClonedScopes,
934af732203SDimitry Andric                               StringRef Ext, LLVMContext &Context) {
935af732203SDimitry Andric   MDBuilder MDB(Context);
936af732203SDimitry Andric 
937af732203SDimitry Andric   for (auto *ScopeList : NoAliasDeclScopes) {
938af732203SDimitry Andric     for (auto &MDOperand : ScopeList->operands()) {
939af732203SDimitry Andric       if (MDNode *MD = dyn_cast<MDNode>(MDOperand)) {
940af732203SDimitry Andric         AliasScopeNode SNANode(MD);
941af732203SDimitry Andric 
942af732203SDimitry Andric         std::string Name;
943af732203SDimitry Andric         auto ScopeName = SNANode.getName();
944af732203SDimitry Andric         if (!ScopeName.empty())
945af732203SDimitry Andric           Name = (Twine(ScopeName) + ":" + Ext).str();
946af732203SDimitry Andric         else
947af732203SDimitry Andric           Name = std::string(Ext);
948af732203SDimitry Andric 
949af732203SDimitry Andric         MDNode *NewScope = MDB.createAnonymousAliasScope(
950af732203SDimitry Andric             const_cast<MDNode *>(SNANode.getDomain()), Name);
951af732203SDimitry Andric         ClonedScopes.insert(std::make_pair(MD, NewScope));
952af732203SDimitry Andric       }
953af732203SDimitry Andric     }
954af732203SDimitry Andric   }
955af732203SDimitry Andric }
956af732203SDimitry Andric 
adaptNoAliasScopes(Instruction * I,const DenseMap<MDNode *,MDNode * > & ClonedScopes,LLVMContext & Context)957*5f7ddb14SDimitry Andric void llvm::adaptNoAliasScopes(Instruction *I,
958*5f7ddb14SDimitry Andric                               const DenseMap<MDNode *, MDNode *> &ClonedScopes,
959af732203SDimitry Andric                               LLVMContext &Context) {
960af732203SDimitry Andric   auto CloneScopeList = [&](const MDNode *ScopeList) -> MDNode * {
961af732203SDimitry Andric     bool NeedsReplacement = false;
962af732203SDimitry Andric     SmallVector<Metadata *, 8> NewScopeList;
963af732203SDimitry Andric     for (auto &MDOp : ScopeList->operands()) {
964af732203SDimitry Andric       if (MDNode *MD = dyn_cast<MDNode>(MDOp)) {
965af732203SDimitry Andric         if (auto *NewMD = ClonedScopes.lookup(MD)) {
966af732203SDimitry Andric           NewScopeList.push_back(NewMD);
967af732203SDimitry Andric           NeedsReplacement = true;
968af732203SDimitry Andric           continue;
969af732203SDimitry Andric         }
970af732203SDimitry Andric         NewScopeList.push_back(MD);
971af732203SDimitry Andric       }
972af732203SDimitry Andric     }
973af732203SDimitry Andric     if (NeedsReplacement)
974af732203SDimitry Andric       return MDNode::get(Context, NewScopeList);
975af732203SDimitry Andric     return nullptr;
976af732203SDimitry Andric   };
977af732203SDimitry Andric 
978af732203SDimitry Andric   if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(I))
979af732203SDimitry Andric     if (auto *NewScopeList = CloneScopeList(Decl->getScopeList()))
980af732203SDimitry Andric       Decl->setScopeList(NewScopeList);
981af732203SDimitry Andric 
982af732203SDimitry Andric   auto replaceWhenNeeded = [&](unsigned MD_ID) {
983af732203SDimitry Andric     if (const MDNode *CSNoAlias = I->getMetadata(MD_ID))
984af732203SDimitry Andric       if (auto *NewScopeList = CloneScopeList(CSNoAlias))
985af732203SDimitry Andric         I->setMetadata(MD_ID, NewScopeList);
986af732203SDimitry Andric   };
987af732203SDimitry Andric   replaceWhenNeeded(LLVMContext::MD_noalias);
988af732203SDimitry Andric   replaceWhenNeeded(LLVMContext::MD_alias_scope);
989af732203SDimitry Andric }
990af732203SDimitry Andric 
cloneAndAdaptNoAliasScopes(ArrayRef<MDNode * > NoAliasDeclScopes,ArrayRef<BasicBlock * > NewBlocks,LLVMContext & Context,StringRef Ext)991*5f7ddb14SDimitry Andric void llvm::cloneAndAdaptNoAliasScopes(ArrayRef<MDNode *> NoAliasDeclScopes,
992*5f7ddb14SDimitry Andric                                       ArrayRef<BasicBlock *> NewBlocks,
993*5f7ddb14SDimitry Andric                                       LLVMContext &Context, StringRef Ext) {
994af732203SDimitry Andric   if (NoAliasDeclScopes.empty())
995af732203SDimitry Andric     return;
996af732203SDimitry Andric 
997af732203SDimitry Andric   DenseMap<MDNode *, MDNode *> ClonedScopes;
998af732203SDimitry Andric   LLVM_DEBUG(dbgs() << "cloneAndAdaptNoAliasScopes: cloning "
999af732203SDimitry Andric                     << NoAliasDeclScopes.size() << " node(s)\n");
1000af732203SDimitry Andric 
1001af732203SDimitry Andric   cloneNoAliasScopes(NoAliasDeclScopes, ClonedScopes, Ext, Context);
1002af732203SDimitry Andric   // Identify instructions using metadata that needs adaptation
1003af732203SDimitry Andric   for (BasicBlock *NewBlock : NewBlocks)
1004af732203SDimitry Andric     for (Instruction &I : *NewBlock)
1005af732203SDimitry Andric       adaptNoAliasScopes(&I, ClonedScopes, Context);
1006af732203SDimitry Andric }
1007af732203SDimitry Andric 
cloneAndAdaptNoAliasScopes(ArrayRef<MDNode * > NoAliasDeclScopes,Instruction * IStart,Instruction * IEnd,LLVMContext & Context,StringRef Ext)1008*5f7ddb14SDimitry Andric void llvm::cloneAndAdaptNoAliasScopes(ArrayRef<MDNode *> NoAliasDeclScopes,
1009*5f7ddb14SDimitry Andric                                       Instruction *IStart, Instruction *IEnd,
1010*5f7ddb14SDimitry Andric                                       LLVMContext &Context, StringRef Ext) {
1011af732203SDimitry Andric   if (NoAliasDeclScopes.empty())
1012af732203SDimitry Andric     return;
1013af732203SDimitry Andric 
1014af732203SDimitry Andric   DenseMap<MDNode *, MDNode *> ClonedScopes;
1015af732203SDimitry Andric   LLVM_DEBUG(dbgs() << "cloneAndAdaptNoAliasScopes: cloning "
1016af732203SDimitry Andric                     << NoAliasDeclScopes.size() << " node(s)\n");
1017af732203SDimitry Andric 
1018af732203SDimitry Andric   cloneNoAliasScopes(NoAliasDeclScopes, ClonedScopes, Ext, Context);
1019af732203SDimitry Andric   // Identify instructions using metadata that needs adaptation
1020af732203SDimitry Andric   assert(IStart->getParent() == IEnd->getParent() && "different basic block ?");
1021af732203SDimitry Andric   auto ItStart = IStart->getIterator();
1022af732203SDimitry Andric   auto ItEnd = IEnd->getIterator();
1023af732203SDimitry Andric   ++ItEnd; // IEnd is included, increment ItEnd to get the end of the range
1024af732203SDimitry Andric   for (auto &I : llvm::make_range(ItStart, ItEnd))
1025af732203SDimitry Andric     adaptNoAliasScopes(&I, ClonedScopes, Context);
1026af732203SDimitry Andric }
1027af732203SDimitry Andric 
identifyNoAliasScopesToClone(ArrayRef<BasicBlock * > BBs,SmallVectorImpl<MDNode * > & NoAliasDeclScopes)1028af732203SDimitry Andric void llvm::identifyNoAliasScopesToClone(
1029af732203SDimitry Andric     ArrayRef<BasicBlock *> BBs, SmallVectorImpl<MDNode *> &NoAliasDeclScopes) {
1030af732203SDimitry Andric   for (BasicBlock *BB : BBs)
1031af732203SDimitry Andric     for (Instruction &I : *BB)
1032af732203SDimitry Andric       if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(&I))
1033af732203SDimitry Andric         NoAliasDeclScopes.push_back(Decl->getScopeList());
1034af732203SDimitry Andric }
1035af732203SDimitry Andric 
identifyNoAliasScopesToClone(BasicBlock::iterator Start,BasicBlock::iterator End,SmallVectorImpl<MDNode * > & NoAliasDeclScopes)1036af732203SDimitry Andric void llvm::identifyNoAliasScopesToClone(
1037af732203SDimitry Andric     BasicBlock::iterator Start, BasicBlock::iterator End,
1038af732203SDimitry Andric     SmallVectorImpl<MDNode *> &NoAliasDeclScopes) {
1039af732203SDimitry Andric   for (Instruction &I : make_range(Start, End))
1040af732203SDimitry Andric     if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(&I))
1041af732203SDimitry Andric       NoAliasDeclScopes.push_back(Decl->getScopeList());
1042af732203SDimitry Andric }
1043