xref: /freebsd-src/contrib/llvm-project/llvm/lib/Transforms/Utils/CloneFunction.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
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"
17*0fca6ea1SDimitry 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"
21*0fca6ea1SDimitry Andric #include "llvm/IR/AttributeMask.h"
220b57cec5SDimitry Andric #include "llvm/IR/CFG.h"
230b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
240b57cec5SDimitry Andric #include "llvm/IR/DebugInfo.h"
250b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h"
260b57cec5SDimitry Andric #include "llvm/IR/Function.h"
270b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
280b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
290b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h"
30e8d8bef9SDimitry 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>
38bdd1243dSDimitry Andric #include <optional>
390b57cec5SDimitry Andric using namespace llvm;
400b57cec5SDimitry Andric 
41e8d8bef9SDimitry Andric #define DEBUG_TYPE "clone-function"
42e8d8bef9SDimitry Andric 
430b57cec5SDimitry Andric /// See comments in Cloning.h.
440b57cec5SDimitry Andric BasicBlock *llvm::CloneBasicBlock(const BasicBlock *BB, ValueToValueMapTy &VMap,
450b57cec5SDimitry Andric                                   const Twine &NameSuffix, Function *F,
460b57cec5SDimitry Andric                                   ClonedCodeInfo *CodeInfo,
470b57cec5SDimitry Andric                                   DebugInfoFinder *DIFinder) {
480b57cec5SDimitry Andric   BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "", F);
495f757f3fSDimitry Andric   NewBB->IsNewDbgInfoFormat = BB->IsNewDbgInfoFormat;
500b57cec5SDimitry Andric   if (BB->hasName())
510b57cec5SDimitry Andric     NewBB->setName(BB->getName() + NameSuffix);
520b57cec5SDimitry Andric 
53bdd1243dSDimitry Andric   bool hasCalls = false, hasDynamicAllocas = false, hasMemProfMetadata = false;
540b57cec5SDimitry Andric   Module *TheModule = F ? F->getParent() : nullptr;
550b57cec5SDimitry Andric 
560b57cec5SDimitry Andric   // Loop over all instructions, and copy them over.
570b57cec5SDimitry Andric   for (const Instruction &I : *BB) {
580b57cec5SDimitry Andric     if (DIFinder && TheModule)
590b57cec5SDimitry Andric       DIFinder->processInstruction(*TheModule, I);
600b57cec5SDimitry Andric 
610b57cec5SDimitry Andric     Instruction *NewInst = I.clone();
620b57cec5SDimitry Andric     if (I.hasName())
630b57cec5SDimitry Andric       NewInst->setName(I.getName() + NameSuffix);
645f757f3fSDimitry Andric 
655f757f3fSDimitry Andric     NewInst->insertBefore(*NewBB, NewBB->end());
665f757f3fSDimitry Andric     NewInst->cloneDebugInfoFrom(&I);
675f757f3fSDimitry Andric 
680b57cec5SDimitry Andric     VMap[&I] = NewInst; // Add instruction map to value.
690b57cec5SDimitry Andric 
70bdd1243dSDimitry Andric     if (isa<CallInst>(I) && !I.isDebugOrPseudoInst()) {
71bdd1243dSDimitry Andric       hasCalls = true;
72bdd1243dSDimitry Andric       hasMemProfMetadata |= I.hasMetadata(LLVMContext::MD_memprof);
73bdd1243dSDimitry Andric     }
740b57cec5SDimitry Andric     if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
755ffd83dbSDimitry Andric       if (!AI->isStaticAlloca()) {
760b57cec5SDimitry Andric         hasDynamicAllocas = true;
770b57cec5SDimitry Andric       }
780b57cec5SDimitry Andric     }
795ffd83dbSDimitry Andric   }
800b57cec5SDimitry Andric 
810b57cec5SDimitry Andric   if (CodeInfo) {
820b57cec5SDimitry Andric     CodeInfo->ContainsCalls |= hasCalls;
83bdd1243dSDimitry Andric     CodeInfo->ContainsMemProfMetadata |= hasMemProfMetadata;
840b57cec5SDimitry Andric     CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
850b57cec5SDimitry Andric   }
860b57cec5SDimitry Andric   return NewBB;
870b57cec5SDimitry Andric }
880b57cec5SDimitry Andric 
890b57cec5SDimitry Andric // Clone OldFunc into NewFunc, transforming the old arguments into references to
900b57cec5SDimitry Andric // VMap values.
910b57cec5SDimitry Andric //
920b57cec5SDimitry Andric void llvm::CloneFunctionInto(Function *NewFunc, const Function *OldFunc,
930b57cec5SDimitry Andric                              ValueToValueMapTy &VMap,
94fe6060f1SDimitry Andric                              CloneFunctionChangeType Changes,
950b57cec5SDimitry Andric                              SmallVectorImpl<ReturnInst *> &Returns,
960b57cec5SDimitry Andric                              const char *NameSuffix, ClonedCodeInfo *CodeInfo,
970b57cec5SDimitry Andric                              ValueMapTypeRemapper *TypeMapper,
980b57cec5SDimitry Andric                              ValueMaterializer *Materializer) {
995f757f3fSDimitry Andric   NewFunc->setIsNewDbgInfoFormat(OldFunc->IsNewDbgInfoFormat);
1000b57cec5SDimitry Andric   assert(NameSuffix && "NameSuffix cannot be null!");
1010b57cec5SDimitry Andric 
1020b57cec5SDimitry Andric #ifndef NDEBUG
1030b57cec5SDimitry Andric   for (const Argument &I : OldFunc->args())
1040b57cec5SDimitry Andric     assert(VMap.count(&I) && "No mapping from source argument specified!");
1050b57cec5SDimitry Andric #endif
1060b57cec5SDimitry Andric 
107fe6060f1SDimitry Andric   bool ModuleLevelChanges = Changes > CloneFunctionChangeType::LocalChangesOnly;
108fe6060f1SDimitry Andric 
1090b57cec5SDimitry Andric   // Copy all attributes other than those stored in the AttributeList.  We need
1100b57cec5SDimitry Andric   // to remap the parameter indices of the AttributeList.
1110b57cec5SDimitry Andric   AttributeList NewAttrs = NewFunc->getAttributes();
1120b57cec5SDimitry Andric   NewFunc->copyAttributesFrom(OldFunc);
1130b57cec5SDimitry Andric   NewFunc->setAttributes(NewAttrs);
1140b57cec5SDimitry Andric 
115bdd1243dSDimitry Andric   const RemapFlags FuncGlobalRefFlags =
116bdd1243dSDimitry Andric       ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges;
117bdd1243dSDimitry Andric 
1180b57cec5SDimitry Andric   // Fix up the personality function that got copied over.
1190b57cec5SDimitry Andric   if (OldFunc->hasPersonalityFn())
120bdd1243dSDimitry Andric     NewFunc->setPersonalityFn(MapValue(OldFunc->getPersonalityFn(), VMap,
121bdd1243dSDimitry Andric                                        FuncGlobalRefFlags, TypeMapper,
122bdd1243dSDimitry Andric                                        Materializer));
123bdd1243dSDimitry Andric 
124bdd1243dSDimitry Andric   if (OldFunc->hasPrefixData()) {
125bdd1243dSDimitry Andric     NewFunc->setPrefixData(MapValue(OldFunc->getPrefixData(), VMap,
126bdd1243dSDimitry Andric                                     FuncGlobalRefFlags, TypeMapper,
127bdd1243dSDimitry Andric                                     Materializer));
128bdd1243dSDimitry Andric   }
129bdd1243dSDimitry Andric 
130bdd1243dSDimitry Andric   if (OldFunc->hasPrologueData()) {
131bdd1243dSDimitry Andric     NewFunc->setPrologueData(MapValue(OldFunc->getPrologueData(), VMap,
132bdd1243dSDimitry Andric                                       FuncGlobalRefFlags, TypeMapper,
133bdd1243dSDimitry Andric                                       Materializer));
134bdd1243dSDimitry Andric   }
1350b57cec5SDimitry Andric 
1360b57cec5SDimitry Andric   SmallVector<AttributeSet, 4> NewArgAttrs(NewFunc->arg_size());
1370b57cec5SDimitry Andric   AttributeList OldAttrs = OldFunc->getAttributes();
1380b57cec5SDimitry Andric 
1390b57cec5SDimitry Andric   // Clone any argument attributes that are present in the VMap.
1400b57cec5SDimitry Andric   for (const Argument &OldArg : OldFunc->args()) {
1410b57cec5SDimitry Andric     if (Argument *NewArg = dyn_cast<Argument>(VMap[&OldArg])) {
1420b57cec5SDimitry Andric       NewArgAttrs[NewArg->getArgNo()] =
143349cc55cSDimitry Andric           OldAttrs.getParamAttrs(OldArg.getArgNo());
1440b57cec5SDimitry Andric     }
1450b57cec5SDimitry Andric   }
1460b57cec5SDimitry Andric 
1470b57cec5SDimitry Andric   NewFunc->setAttributes(
148349cc55cSDimitry Andric       AttributeList::get(NewFunc->getContext(), OldAttrs.getFnAttrs(),
149349cc55cSDimitry Andric                          OldAttrs.getRetAttrs(), NewArgAttrs));
1500b57cec5SDimitry Andric 
151e8d8bef9SDimitry Andric   // Everything else beyond this point deals with function instructions,
152e8d8bef9SDimitry Andric   // so if we are dealing with a function declaration, we're done.
153e8d8bef9SDimitry Andric   if (OldFunc->isDeclaration())
154e8d8bef9SDimitry Andric     return;
1550b57cec5SDimitry Andric 
156fe6060f1SDimitry Andric   // When we remap instructions within the same module, we want to avoid
157fe6060f1SDimitry Andric   // duplicating inlined DISubprograms, so record all subprograms we find as we
158fe6060f1SDimitry Andric   // duplicate instructions and then freeze them in the MD map. We also record
159fe6060f1SDimitry Andric   // information about dbg.value and dbg.declare to avoid duplicating the
160fe6060f1SDimitry Andric   // types.
161bdd1243dSDimitry Andric   std::optional<DebugInfoFinder> DIFinder;
162fe6060f1SDimitry Andric 
163fe6060f1SDimitry Andric   // Track the subprogram attachment that needs to be cloned to fine-tune the
164fe6060f1SDimitry Andric   // mapping within the same module.
165fe6060f1SDimitry Andric   DISubprogram *SPClonedWithinModule = nullptr;
166fe6060f1SDimitry Andric   if (Changes < CloneFunctionChangeType::DifferentModule) {
167fe6060f1SDimitry Andric     assert((NewFunc->getParent() == nullptr ||
168fe6060f1SDimitry Andric             NewFunc->getParent() == OldFunc->getParent()) &&
169fe6060f1SDimitry Andric            "Expected NewFunc to have the same parent, or no parent");
170fe6060f1SDimitry Andric 
171fe6060f1SDimitry Andric     // Need to find subprograms, types, and compile units.
172fe6060f1SDimitry Andric     DIFinder.emplace();
173fe6060f1SDimitry Andric 
174fe6060f1SDimitry Andric     SPClonedWithinModule = OldFunc->getSubprogram();
175fe6060f1SDimitry Andric     if (SPClonedWithinModule)
176fe6060f1SDimitry Andric       DIFinder->processSubprogram(SPClonedWithinModule);
177fe6060f1SDimitry Andric   } else {
178fe6060f1SDimitry Andric     assert((NewFunc->getParent() == nullptr ||
179fe6060f1SDimitry Andric             NewFunc->getParent() != OldFunc->getParent()) &&
180fe6060f1SDimitry Andric            "Expected NewFunc to have different parents, or no parent");
181fe6060f1SDimitry Andric 
182fe6060f1SDimitry Andric     if (Changes == CloneFunctionChangeType::DifferentModule) {
183fe6060f1SDimitry Andric       assert(NewFunc->getParent() &&
184fe6060f1SDimitry Andric              "Need parent of new function to maintain debug info invariants");
185fe6060f1SDimitry Andric 
186fe6060f1SDimitry Andric       // Need to find all the compile units.
187fe6060f1SDimitry Andric       DIFinder.emplace();
188fe6060f1SDimitry Andric     }
189fe6060f1SDimitry Andric   }
1900b57cec5SDimitry Andric 
1910b57cec5SDimitry Andric   // Loop over all of the basic blocks in the function, cloning them as
1920b57cec5SDimitry Andric   // appropriate.  Note that we save BE this way in order to handle cloning of
1930b57cec5SDimitry Andric   // recursive functions into themselves.
194fe6060f1SDimitry Andric   for (const BasicBlock &BB : *OldFunc) {
1950b57cec5SDimitry Andric 
1960b57cec5SDimitry Andric     // Create a new basic block and copy instructions into it!
1970b57cec5SDimitry Andric     BasicBlock *CBB = CloneBasicBlock(&BB, VMap, NameSuffix, NewFunc, CodeInfo,
198fe6060f1SDimitry Andric                                       DIFinder ? &*DIFinder : nullptr);
1990b57cec5SDimitry Andric 
2000b57cec5SDimitry Andric     // Add basic block mapping.
2010b57cec5SDimitry Andric     VMap[&BB] = CBB;
2020b57cec5SDimitry Andric 
2030b57cec5SDimitry Andric     // It is only legal to clone a function if a block address within that
2040b57cec5SDimitry Andric     // function is never referenced outside of the function.  Given that, we
2050b57cec5SDimitry Andric     // want to map block addresses from the old function to block addresses in
2060b57cec5SDimitry Andric     // the clone. (This is different from the generic ValueMapper
2070b57cec5SDimitry Andric     // implementation, which generates an invalid blockaddress when
2080b57cec5SDimitry Andric     // cloning a function.)
2090b57cec5SDimitry Andric     if (BB.hasAddressTaken()) {
2100b57cec5SDimitry Andric       Constant *OldBBAddr = BlockAddress::get(const_cast<Function *>(OldFunc),
2110b57cec5SDimitry Andric                                               const_cast<BasicBlock *>(&BB));
2120b57cec5SDimitry Andric       VMap[OldBBAddr] = BlockAddress::get(NewFunc, CBB);
2130b57cec5SDimitry Andric     }
2140b57cec5SDimitry Andric 
2150b57cec5SDimitry Andric     // Note return instructions for the caller.
2160b57cec5SDimitry Andric     if (ReturnInst *RI = dyn_cast<ReturnInst>(CBB->getTerminator()))
2170b57cec5SDimitry Andric       Returns.push_back(RI);
2180b57cec5SDimitry Andric   }
2190b57cec5SDimitry Andric 
220fe6060f1SDimitry Andric   if (Changes < CloneFunctionChangeType::DifferentModule &&
221fe6060f1SDimitry Andric       DIFinder->subprogram_count() > 0) {
222fe6060f1SDimitry Andric     // Turn on module-level changes, since we need to clone (some of) the
223fe6060f1SDimitry Andric     // debug info metadata.
224fe6060f1SDimitry Andric     //
225fe6060f1SDimitry Andric     // FIXME: Metadata effectively owned by a function should be made
226fe6060f1SDimitry Andric     // local, and only that local metadata should be cloned.
227fe6060f1SDimitry Andric     ModuleLevelChanges = true;
2280b57cec5SDimitry Andric 
229fe6060f1SDimitry Andric     auto mapToSelfIfNew = [&VMap](MDNode *N) {
230fe6060f1SDimitry Andric       // Avoid clobbering an existing mapping.
231fe6060f1SDimitry Andric       (void)VMap.MD().try_emplace(N, N);
232fe6060f1SDimitry Andric     };
2330b57cec5SDimitry Andric 
234fe6060f1SDimitry Andric     // Avoid cloning types, compile units, and (other) subprograms.
235fcaf7f86SDimitry Andric     SmallPtrSet<const DISubprogram *, 16> MappedToSelfSPs;
236fcaf7f86SDimitry Andric     for (DISubprogram *ISP : DIFinder->subprograms()) {
237fcaf7f86SDimitry Andric       if (ISP != SPClonedWithinModule) {
238fe6060f1SDimitry Andric         mapToSelfIfNew(ISP);
239fcaf7f86SDimitry Andric         MappedToSelfSPs.insert(ISP);
240fcaf7f86SDimitry Andric       }
241fcaf7f86SDimitry Andric     }
242fcaf7f86SDimitry Andric 
243fcaf7f86SDimitry Andric     // If a subprogram isn't going to be cloned skip its lexical blocks as well.
244fcaf7f86SDimitry Andric     for (DIScope *S : DIFinder->scopes()) {
245fcaf7f86SDimitry Andric       auto *LScope = dyn_cast<DILocalScope>(S);
246fcaf7f86SDimitry Andric       if (LScope && MappedToSelfSPs.count(LScope->getSubprogram()))
247fcaf7f86SDimitry Andric         mapToSelfIfNew(S);
248fcaf7f86SDimitry Andric     }
2490b57cec5SDimitry Andric 
250fe6060f1SDimitry Andric     for (DICompileUnit *CU : DIFinder->compile_units())
251fe6060f1SDimitry Andric       mapToSelfIfNew(CU);
252fe6060f1SDimitry Andric 
253fe6060f1SDimitry Andric     for (DIType *Type : DIFinder->types())
254fe6060f1SDimitry Andric       mapToSelfIfNew(Type);
255fe6060f1SDimitry Andric   } else {
256fe6060f1SDimitry Andric     assert(!SPClonedWithinModule &&
257fe6060f1SDimitry Andric            "Subprogram should be in DIFinder->subprogram_count()...");
258fe6060f1SDimitry Andric   }
259fe6060f1SDimitry Andric 
260fe6060f1SDimitry Andric   const auto RemapFlag = ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges;
261e8d8bef9SDimitry Andric   // Duplicate the metadata that is attached to the cloned function.
262e8d8bef9SDimitry Andric   // Subprograms/CUs/types that were already mapped to themselves won't be
263e8d8bef9SDimitry Andric   // duplicated.
264e8d8bef9SDimitry Andric   SmallVector<std::pair<unsigned, MDNode *>, 1> MDs;
265e8d8bef9SDimitry Andric   OldFunc->getAllMetadata(MDs);
266e8d8bef9SDimitry Andric   for (auto MD : MDs) {
267fe6060f1SDimitry Andric     NewFunc->addMetadata(MD.first, *MapMetadata(MD.second, VMap, RemapFlag,
268e8d8bef9SDimitry Andric                                                 TypeMapper, Materializer));
269e8d8bef9SDimitry Andric   }
270e8d8bef9SDimitry Andric 
271fe6060f1SDimitry Andric   // Loop over all of the instructions in the new function, fixing up operand
2720b57cec5SDimitry Andric   // references as we go. This uses VMap to do all the hard work.
273fe6060f1SDimitry Andric   for (Function::iterator
274fe6060f1SDimitry Andric            BB = cast<BasicBlock>(VMap[&OldFunc->front()])->getIterator(),
2750b57cec5SDimitry Andric            BE = NewFunc->end();
2760b57cec5SDimitry Andric        BB != BE; ++BB)
2775f757f3fSDimitry Andric     // Loop over all instructions, fixing each one as we find it, and any
2785f757f3fSDimitry Andric     // attached debug-info records.
2795f757f3fSDimitry Andric     for (Instruction &II : *BB) {
280fe6060f1SDimitry Andric       RemapInstruction(&II, VMap, RemapFlag, TypeMapper, Materializer);
281*0fca6ea1SDimitry Andric       RemapDbgRecordRange(II.getModule(), II.getDbgRecordRange(), VMap,
282*0fca6ea1SDimitry Andric                           RemapFlag, TypeMapper, Materializer);
2835f757f3fSDimitry Andric     }
2848bcb0991SDimitry Andric 
285fe6060f1SDimitry Andric   // Only update !llvm.dbg.cu for DifferentModule (not CloneModule). In the
286fe6060f1SDimitry Andric   // same module, the compile unit will already be listed (or not). When
287fe6060f1SDimitry Andric   // cloning a module, CloneModule() will handle creating the named metadata.
288fe6060f1SDimitry Andric   if (Changes != CloneFunctionChangeType::DifferentModule)
289fe6060f1SDimitry Andric     return;
290fe6060f1SDimitry Andric 
291fe6060f1SDimitry Andric   // Update !llvm.dbg.cu with compile units added to the new module if this
292fe6060f1SDimitry Andric   // function is being cloned in isolation.
293fe6060f1SDimitry Andric   //
294fe6060f1SDimitry Andric   // FIXME: This is making global / module-level changes, which doesn't seem
295fe6060f1SDimitry Andric   // like the right encapsulation  Consider dropping the requirement to update
296fe6060f1SDimitry Andric   // !llvm.dbg.cu (either obsoleting the node, or restricting it to
297fe6060f1SDimitry Andric   // non-discardable compile units) instead of discovering compile units by
298fe6060f1SDimitry Andric   // visiting the metadata attached to global values, which would allow this
299fe6060f1SDimitry Andric   // code to be deleted. Alternatively, perhaps give responsibility for this
300fe6060f1SDimitry Andric   // update to CloneFunctionInto's callers.
3018bcb0991SDimitry Andric   auto *NewModule = NewFunc->getParent();
3028bcb0991SDimitry Andric   auto *NMD = NewModule->getOrInsertNamedMetadata("llvm.dbg.cu");
3038bcb0991SDimitry Andric   // Avoid multiple insertions of the same DICompileUnit to NMD.
3048bcb0991SDimitry Andric   SmallPtrSet<const void *, 8> Visited;
3058bcb0991SDimitry Andric   for (auto *Operand : NMD->operands())
3068bcb0991SDimitry Andric     Visited.insert(Operand);
307fe6060f1SDimitry Andric   for (auto *Unit : DIFinder->compile_units()) {
308fe6060f1SDimitry Andric     MDNode *MappedUnit =
309fe6060f1SDimitry Andric         MapMetadata(Unit, VMap, RF_None, TypeMapper, Materializer);
310fe6060f1SDimitry Andric     if (Visited.insert(MappedUnit).second)
311fe6060f1SDimitry Andric       NMD->addOperand(MappedUnit);
3128bcb0991SDimitry Andric   }
3130b57cec5SDimitry Andric }
3140b57cec5SDimitry Andric 
3150b57cec5SDimitry Andric /// Return a copy of the specified function and add it to that function's
3160b57cec5SDimitry Andric /// module.  Also, any references specified in the VMap are changed to refer to
3170b57cec5SDimitry Andric /// their mapped value instead of the original one.  If any of the arguments to
3180b57cec5SDimitry Andric /// the function are in the VMap, the arguments are deleted from the resultant
3190b57cec5SDimitry Andric /// function.  The VMap is updated to include mappings from all of the
3200b57cec5SDimitry Andric /// instructions and basicblocks in the function from their old to new values.
3210b57cec5SDimitry Andric ///
3220b57cec5SDimitry Andric Function *llvm::CloneFunction(Function *F, ValueToValueMapTy &VMap,
3230b57cec5SDimitry Andric                               ClonedCodeInfo *CodeInfo) {
3240b57cec5SDimitry Andric   std::vector<Type *> ArgTypes;
3250b57cec5SDimitry Andric 
3260b57cec5SDimitry Andric   // The user might be deleting arguments to the function by specifying them in
3270b57cec5SDimitry Andric   // the VMap.  If so, we need to not add the arguments to the arg ty vector
3280b57cec5SDimitry Andric   //
3290b57cec5SDimitry Andric   for (const Argument &I : F->args())
3300b57cec5SDimitry Andric     if (VMap.count(&I) == 0) // Haven't mapped the argument to anything yet?
3310b57cec5SDimitry Andric       ArgTypes.push_back(I.getType());
3320b57cec5SDimitry Andric 
3330b57cec5SDimitry Andric   // Create a new function type...
334fe6060f1SDimitry Andric   FunctionType *FTy =
335fe6060f1SDimitry Andric       FunctionType::get(F->getFunctionType()->getReturnType(), ArgTypes,
336fe6060f1SDimitry Andric                         F->getFunctionType()->isVarArg());
3370b57cec5SDimitry Andric 
3380b57cec5SDimitry Andric   // Create the new function...
3390b57cec5SDimitry Andric   Function *NewF = Function::Create(FTy, F->getLinkage(), F->getAddressSpace(),
3400b57cec5SDimitry Andric                                     F->getName(), F->getParent());
3415f757f3fSDimitry Andric   NewF->setIsNewDbgInfoFormat(F->IsNewDbgInfoFormat);
3420b57cec5SDimitry Andric 
3430b57cec5SDimitry Andric   // Loop over the arguments, copying the names of the mapped arguments over...
3440b57cec5SDimitry Andric   Function::arg_iterator DestI = NewF->arg_begin();
3450b57cec5SDimitry Andric   for (const Argument &I : F->args())
3460b57cec5SDimitry Andric     if (VMap.count(&I) == 0) {     // Is this argument preserved?
3470b57cec5SDimitry Andric       DestI->setName(I.getName()); // Copy the name over...
3480b57cec5SDimitry Andric       VMap[&I] = &*DestI++;        // Add mapping to VMap
3490b57cec5SDimitry Andric     }
3500b57cec5SDimitry Andric 
3510b57cec5SDimitry Andric   SmallVector<ReturnInst *, 8> Returns; // Ignore returns cloned.
352fe6060f1SDimitry Andric   CloneFunctionInto(NewF, F, VMap, CloneFunctionChangeType::LocalChangesOnly,
353fe6060f1SDimitry Andric                     Returns, "", CodeInfo);
3540b57cec5SDimitry Andric 
3550b57cec5SDimitry Andric   return NewF;
3560b57cec5SDimitry Andric }
3570b57cec5SDimitry Andric 
3580b57cec5SDimitry Andric namespace {
3590b57cec5SDimitry Andric /// This is a private class used to implement CloneAndPruneFunctionInto.
3600b57cec5SDimitry Andric struct PruningFunctionCloner {
3610b57cec5SDimitry Andric   Function *NewFunc;
3620b57cec5SDimitry Andric   const Function *OldFunc;
3630b57cec5SDimitry Andric   ValueToValueMapTy &VMap;
3640b57cec5SDimitry Andric   bool ModuleLevelChanges;
3650b57cec5SDimitry Andric   const char *NameSuffix;
3660b57cec5SDimitry Andric   ClonedCodeInfo *CodeInfo;
36781ad6265SDimitry Andric   bool HostFuncIsStrictFP;
36881ad6265SDimitry Andric 
36981ad6265SDimitry Andric   Instruction *cloneInstruction(BasicBlock::const_iterator II);
3700b57cec5SDimitry Andric 
3710b57cec5SDimitry Andric public:
3720b57cec5SDimitry Andric   PruningFunctionCloner(Function *newFunc, const Function *oldFunc,
3730b57cec5SDimitry Andric                         ValueToValueMapTy &valueMap, bool moduleLevelChanges,
3740b57cec5SDimitry Andric                         const char *nameSuffix, ClonedCodeInfo *codeInfo)
3750b57cec5SDimitry Andric       : NewFunc(newFunc), OldFunc(oldFunc), VMap(valueMap),
3760b57cec5SDimitry Andric         ModuleLevelChanges(moduleLevelChanges), NameSuffix(nameSuffix),
37781ad6265SDimitry Andric         CodeInfo(codeInfo) {
37881ad6265SDimitry Andric     HostFuncIsStrictFP =
37981ad6265SDimitry Andric         newFunc->getAttributes().hasFnAttr(Attribute::StrictFP);
38081ad6265SDimitry Andric   }
3810b57cec5SDimitry Andric 
3820b57cec5SDimitry Andric   /// The specified block is found to be reachable, clone it and
3830b57cec5SDimitry Andric   /// anything that it can reach.
384fe6060f1SDimitry Andric   void CloneBlock(const BasicBlock *BB, BasicBlock::const_iterator StartingInst,
3850b57cec5SDimitry Andric                   std::vector<const BasicBlock *> &ToClone);
3860b57cec5SDimitry Andric };
387fe6060f1SDimitry Andric } // namespace
3880b57cec5SDimitry Andric 
38981ad6265SDimitry Andric Instruction *
39081ad6265SDimitry Andric PruningFunctionCloner::cloneInstruction(BasicBlock::const_iterator II) {
39181ad6265SDimitry Andric   const Instruction &OldInst = *II;
39281ad6265SDimitry Andric   Instruction *NewInst = nullptr;
39381ad6265SDimitry Andric   if (HostFuncIsStrictFP) {
39481ad6265SDimitry Andric     Intrinsic::ID CIID = getConstrainedIntrinsicID(OldInst);
39581ad6265SDimitry Andric     if (CIID != Intrinsic::not_intrinsic) {
39681ad6265SDimitry Andric       // Instead of cloning the instruction, a call to constrained intrinsic
39781ad6265SDimitry Andric       // should be created.
39881ad6265SDimitry Andric       // Assume the first arguments of constrained intrinsics are the same as
39981ad6265SDimitry Andric       // the operands of original instruction.
40081ad6265SDimitry Andric 
40181ad6265SDimitry Andric       // Determine overloaded types of the intrinsic.
40281ad6265SDimitry Andric       SmallVector<Type *, 2> TParams;
40381ad6265SDimitry Andric       SmallVector<Intrinsic::IITDescriptor, 8> Descriptor;
40481ad6265SDimitry Andric       getIntrinsicInfoTableEntries(CIID, Descriptor);
40581ad6265SDimitry Andric       for (unsigned I = 0, E = Descriptor.size(); I != E; ++I) {
40681ad6265SDimitry Andric         Intrinsic::IITDescriptor Operand = Descriptor[I];
40781ad6265SDimitry Andric         switch (Operand.Kind) {
40881ad6265SDimitry Andric         case Intrinsic::IITDescriptor::Argument:
40981ad6265SDimitry Andric           if (Operand.getArgumentKind() !=
41081ad6265SDimitry Andric               Intrinsic::IITDescriptor::AK_MatchType) {
41181ad6265SDimitry Andric             if (I == 0)
41281ad6265SDimitry Andric               TParams.push_back(OldInst.getType());
41381ad6265SDimitry Andric             else
41481ad6265SDimitry Andric               TParams.push_back(OldInst.getOperand(I - 1)->getType());
41581ad6265SDimitry Andric           }
41681ad6265SDimitry Andric           break;
41781ad6265SDimitry Andric         case Intrinsic::IITDescriptor::SameVecWidthArgument:
41881ad6265SDimitry Andric           ++I;
41981ad6265SDimitry Andric           break;
42081ad6265SDimitry Andric         default:
42181ad6265SDimitry Andric           break;
42281ad6265SDimitry Andric         }
42381ad6265SDimitry Andric       }
42481ad6265SDimitry Andric 
42581ad6265SDimitry Andric       // Create intrinsic call.
42681ad6265SDimitry Andric       LLVMContext &Ctx = NewFunc->getContext();
42781ad6265SDimitry Andric       Function *IFn =
42881ad6265SDimitry Andric           Intrinsic::getDeclaration(NewFunc->getParent(), CIID, TParams);
42981ad6265SDimitry Andric       SmallVector<Value *, 4> Args;
43081ad6265SDimitry Andric       unsigned NumOperands = OldInst.getNumOperands();
43181ad6265SDimitry Andric       if (isa<CallInst>(OldInst))
43281ad6265SDimitry Andric         --NumOperands;
43381ad6265SDimitry Andric       for (unsigned I = 0; I < NumOperands; ++I) {
43481ad6265SDimitry Andric         Value *Op = OldInst.getOperand(I);
43581ad6265SDimitry Andric         Args.push_back(Op);
43681ad6265SDimitry Andric       }
43781ad6265SDimitry Andric       if (const auto *CmpI = dyn_cast<FCmpInst>(&OldInst)) {
43881ad6265SDimitry Andric         FCmpInst::Predicate Pred = CmpI->getPredicate();
43981ad6265SDimitry Andric         StringRef PredName = FCmpInst::getPredicateName(Pred);
44081ad6265SDimitry Andric         Args.push_back(MetadataAsValue::get(Ctx, MDString::get(Ctx, PredName)));
44181ad6265SDimitry Andric       }
44281ad6265SDimitry Andric 
44381ad6265SDimitry Andric       // The last arguments of a constrained intrinsic are metadata that
44481ad6265SDimitry Andric       // represent rounding mode (absents in some intrinsics) and exception
44581ad6265SDimitry Andric       // behavior. The inlined function uses default settings.
446*0fca6ea1SDimitry Andric       if (Intrinsic::hasConstrainedFPRoundingModeOperand(CIID))
44781ad6265SDimitry Andric         Args.push_back(
44881ad6265SDimitry Andric             MetadataAsValue::get(Ctx, MDString::get(Ctx, "round.tonearest")));
44981ad6265SDimitry Andric       Args.push_back(
45081ad6265SDimitry Andric           MetadataAsValue::get(Ctx, MDString::get(Ctx, "fpexcept.ignore")));
45181ad6265SDimitry Andric 
45281ad6265SDimitry Andric       NewInst = CallInst::Create(IFn, Args, OldInst.getName() + ".strict");
45381ad6265SDimitry Andric     }
45481ad6265SDimitry Andric   }
45581ad6265SDimitry Andric   if (!NewInst)
45681ad6265SDimitry Andric     NewInst = II->clone();
45781ad6265SDimitry Andric   return NewInst;
45881ad6265SDimitry Andric }
45981ad6265SDimitry Andric 
4600b57cec5SDimitry Andric /// The specified block is found to be reachable, clone it and
4610b57cec5SDimitry Andric /// anything that it can reach.
462fe6060f1SDimitry Andric void PruningFunctionCloner::CloneBlock(
463fe6060f1SDimitry Andric     const BasicBlock *BB, BasicBlock::const_iterator StartingInst,
4640b57cec5SDimitry Andric     std::vector<const BasicBlock *> &ToClone) {
4650b57cec5SDimitry Andric   WeakTrackingVH &BBEntry = VMap[BB];
4660b57cec5SDimitry Andric 
4670b57cec5SDimitry Andric   // Have we already cloned this block?
468fe6060f1SDimitry Andric   if (BBEntry)
469fe6060f1SDimitry Andric     return;
4700b57cec5SDimitry Andric 
4710b57cec5SDimitry Andric   // Nope, clone it now.
4720b57cec5SDimitry Andric   BasicBlock *NewBB;
47306c3fb27SDimitry Andric   Twine NewName(BB->hasName() ? Twine(BB->getName()) + NameSuffix : "");
47406c3fb27SDimitry Andric   BBEntry = NewBB = BasicBlock::Create(BB->getContext(), NewName, NewFunc);
4755f757f3fSDimitry Andric   NewBB->IsNewDbgInfoFormat = BB->IsNewDbgInfoFormat;
4760b57cec5SDimitry Andric 
4770b57cec5SDimitry Andric   // It is only legal to clone a function if a block address within that
4780b57cec5SDimitry Andric   // function is never referenced outside of the function.  Given that, we
4790b57cec5SDimitry Andric   // want to map block addresses from the old function to block addresses in
4800b57cec5SDimitry Andric   // the clone. (This is different from the generic ValueMapper
4810b57cec5SDimitry Andric   // implementation, which generates an invalid blockaddress when
4820b57cec5SDimitry Andric   // cloning a function.)
4830b57cec5SDimitry Andric   //
4840b57cec5SDimitry Andric   // Note that we don't need to fix the mapping for unreachable blocks;
4850b57cec5SDimitry Andric   // the default mapping there is safe.
4860b57cec5SDimitry Andric   if (BB->hasAddressTaken()) {
4870b57cec5SDimitry Andric     Constant *OldBBAddr = BlockAddress::get(const_cast<Function *>(OldFunc),
4880b57cec5SDimitry Andric                                             const_cast<BasicBlock *>(BB));
4890b57cec5SDimitry Andric     VMap[OldBBAddr] = BlockAddress::get(NewFunc, NewBB);
4900b57cec5SDimitry Andric   }
4910b57cec5SDimitry Andric 
4920b57cec5SDimitry Andric   bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false;
493bdd1243dSDimitry Andric   bool hasMemProfMetadata = false;
4940b57cec5SDimitry Andric 
4955f757f3fSDimitry Andric   // Keep a cursor pointing at the last place we cloned debug-info records from.
4965f757f3fSDimitry Andric   BasicBlock::const_iterator DbgCursor = StartingInst;
4975f757f3fSDimitry Andric   auto CloneDbgRecordsToHere =
4985f757f3fSDimitry Andric       [NewBB, &DbgCursor](Instruction *NewInst, BasicBlock::const_iterator II) {
4995f757f3fSDimitry Andric         if (!NewBB->IsNewDbgInfoFormat)
5005f757f3fSDimitry Andric           return;
5015f757f3fSDimitry Andric 
5025f757f3fSDimitry Andric         // Clone debug-info records onto this instruction. Iterate through any
5035f757f3fSDimitry Andric         // source-instructions we've cloned and then subsequently optimised
5045f757f3fSDimitry Andric         // away, so that their debug-info doesn't go missing.
5055f757f3fSDimitry Andric         for (; DbgCursor != II; ++DbgCursor)
5065f757f3fSDimitry Andric           NewInst->cloneDebugInfoFrom(&*DbgCursor, std::nullopt, false);
5075f757f3fSDimitry Andric         NewInst->cloneDebugInfoFrom(&*II);
5085f757f3fSDimitry Andric         DbgCursor = std::next(II);
5095f757f3fSDimitry Andric       };
5105f757f3fSDimitry Andric 
5110b57cec5SDimitry Andric   // Loop over all instructions, and copy them over, DCE'ing as we go.  This
5120b57cec5SDimitry Andric   // loop doesn't include the terminator.
513fe6060f1SDimitry Andric   for (BasicBlock::const_iterator II = StartingInst, IE = --BB->end(); II != IE;
514fe6060f1SDimitry Andric        ++II) {
5150b57cec5SDimitry Andric 
51681ad6265SDimitry Andric     Instruction *NewInst = cloneInstruction(II);
51706c3fb27SDimitry Andric     NewInst->insertInto(NewBB, NewBB->end());
51881ad6265SDimitry Andric 
51981ad6265SDimitry Andric     if (HostFuncIsStrictFP) {
52081ad6265SDimitry Andric       // All function calls in the inlined function must get 'strictfp'
52181ad6265SDimitry Andric       // attribute to prevent undesirable optimizations.
52281ad6265SDimitry Andric       if (auto *Call = dyn_cast<CallInst>(NewInst))
52381ad6265SDimitry Andric         Call->addFnAttr(Attribute::StrictFP);
52481ad6265SDimitry Andric     }
5250b57cec5SDimitry Andric 
5260b57cec5SDimitry Andric     // Eagerly remap operands to the newly cloned instruction, except for PHI
527bdd1243dSDimitry Andric     // nodes for which we defer processing until we update the CFG. Also defer
528bdd1243dSDimitry Andric     // debug intrinsic processing because they may contain use-before-defs.
529bdd1243dSDimitry Andric     if (!isa<PHINode>(NewInst) && !isa<DbgVariableIntrinsic>(NewInst)) {
5300b57cec5SDimitry Andric       RemapInstruction(NewInst, VMap,
5310b57cec5SDimitry Andric                        ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
5320b57cec5SDimitry Andric 
533*0fca6ea1SDimitry Andric       // Eagerly constant fold the newly cloned instruction. If successful, add
534*0fca6ea1SDimitry Andric       // a mapping to the new value. Non-constant operands may be incomplete at
535*0fca6ea1SDimitry Andric       // this stage, thus instruction simplification is performed after
536*0fca6ea1SDimitry Andric       // processing phi-nodes.
537*0fca6ea1SDimitry Andric       if (Value *V = ConstantFoldInstruction(
538*0fca6ea1SDimitry Andric               NewInst, BB->getDataLayout())) {
539*0fca6ea1SDimitry Andric         if (isInstructionTriviallyDead(NewInst)) {
5400b57cec5SDimitry Andric           VMap[&*II] = V;
54106c3fb27SDimitry Andric           NewInst->eraseFromParent();
5420b57cec5SDimitry Andric           continue;
5430b57cec5SDimitry Andric         }
5440b57cec5SDimitry Andric       }
5450b57cec5SDimitry Andric     }
5460b57cec5SDimitry Andric 
5470b57cec5SDimitry Andric     if (II->hasName())
5480b57cec5SDimitry Andric       NewInst->setName(II->getName() + NameSuffix);
5490b57cec5SDimitry Andric     VMap[&*II] = NewInst; // Add instruction map to value.
550bdd1243dSDimitry Andric     if (isa<CallInst>(II) && !II->isDebugOrPseudoInst()) {
551bdd1243dSDimitry Andric       hasCalls = true;
552bdd1243dSDimitry Andric       hasMemProfMetadata |= II->hasMetadata(LLVMContext::MD_memprof);
553bdd1243dSDimitry Andric     }
5540b57cec5SDimitry Andric 
5555f757f3fSDimitry Andric     CloneDbgRecordsToHere(NewInst, II);
5565f757f3fSDimitry Andric 
557fe6060f1SDimitry Andric     if (CodeInfo) {
558fe6060f1SDimitry Andric       CodeInfo->OrigVMap[&*II] = NewInst;
5595ffd83dbSDimitry Andric       if (auto *CB = dyn_cast<CallBase>(&*II))
5605ffd83dbSDimitry Andric         if (CB->hasOperandBundles())
5610b57cec5SDimitry Andric           CodeInfo->OperandBundleCallSites.push_back(NewInst);
562fe6060f1SDimitry Andric     }
5630b57cec5SDimitry Andric 
5640b57cec5SDimitry Andric     if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
5650b57cec5SDimitry Andric       if (isa<ConstantInt>(AI->getArraySize()))
5660b57cec5SDimitry Andric         hasStaticAllocas = true;
5670b57cec5SDimitry Andric       else
5680b57cec5SDimitry Andric         hasDynamicAllocas = true;
5690b57cec5SDimitry Andric     }
5700b57cec5SDimitry Andric   }
5710b57cec5SDimitry Andric 
5720b57cec5SDimitry Andric   // Finally, clone over the terminator.
5730b57cec5SDimitry Andric   const Instruction *OldTI = BB->getTerminator();
5740b57cec5SDimitry Andric   bool TerminatorDone = false;
5750b57cec5SDimitry Andric   if (const BranchInst *BI = dyn_cast<BranchInst>(OldTI)) {
5760b57cec5SDimitry Andric     if (BI->isConditional()) {
5770b57cec5SDimitry Andric       // If the condition was a known constant in the callee...
5780b57cec5SDimitry Andric       ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
5790b57cec5SDimitry Andric       // Or is a known constant in the caller...
5800b57cec5SDimitry Andric       if (!Cond) {
5810b57cec5SDimitry Andric         Value *V = VMap.lookup(BI->getCondition());
5820b57cec5SDimitry Andric         Cond = dyn_cast_or_null<ConstantInt>(V);
5830b57cec5SDimitry Andric       }
5840b57cec5SDimitry Andric 
5850b57cec5SDimitry Andric       // Constant fold to uncond branch!
5860b57cec5SDimitry Andric       if (Cond) {
5870b57cec5SDimitry Andric         BasicBlock *Dest = BI->getSuccessor(!Cond->getZExtValue());
5880b57cec5SDimitry Andric         VMap[OldTI] = BranchInst::Create(Dest, NewBB);
5890b57cec5SDimitry Andric         ToClone.push_back(Dest);
5900b57cec5SDimitry Andric         TerminatorDone = true;
5910b57cec5SDimitry Andric       }
5920b57cec5SDimitry Andric     }
5930b57cec5SDimitry Andric   } else if (const SwitchInst *SI = dyn_cast<SwitchInst>(OldTI)) {
5940b57cec5SDimitry Andric     // If switching on a value known constant in the caller.
5950b57cec5SDimitry Andric     ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition());
5960b57cec5SDimitry Andric     if (!Cond) { // Or known constant after constant prop in the callee...
5970b57cec5SDimitry Andric       Value *V = VMap.lookup(SI->getCondition());
5980b57cec5SDimitry Andric       Cond = dyn_cast_or_null<ConstantInt>(V);
5990b57cec5SDimitry Andric     }
6000b57cec5SDimitry Andric     if (Cond) { // Constant fold to uncond branch!
6010b57cec5SDimitry Andric       SwitchInst::ConstCaseHandle Case = *SI->findCaseValue(Cond);
6020b57cec5SDimitry Andric       BasicBlock *Dest = const_cast<BasicBlock *>(Case.getCaseSuccessor());
6030b57cec5SDimitry Andric       VMap[OldTI] = BranchInst::Create(Dest, NewBB);
6040b57cec5SDimitry Andric       ToClone.push_back(Dest);
6050b57cec5SDimitry Andric       TerminatorDone = true;
6060b57cec5SDimitry Andric     }
6070b57cec5SDimitry Andric   }
6080b57cec5SDimitry Andric 
6090b57cec5SDimitry Andric   if (!TerminatorDone) {
6100b57cec5SDimitry Andric     Instruction *NewInst = OldTI->clone();
6110b57cec5SDimitry Andric     if (OldTI->hasName())
6120b57cec5SDimitry Andric       NewInst->setName(OldTI->getName() + NameSuffix);
613bdd1243dSDimitry Andric     NewInst->insertInto(NewBB, NewBB->end());
6145f757f3fSDimitry Andric 
6155f757f3fSDimitry Andric     CloneDbgRecordsToHere(NewInst, OldTI->getIterator());
6165f757f3fSDimitry Andric 
6170b57cec5SDimitry Andric     VMap[OldTI] = NewInst; // Add instruction map to value.
6180b57cec5SDimitry Andric 
619fe6060f1SDimitry Andric     if (CodeInfo) {
620fe6060f1SDimitry Andric       CodeInfo->OrigVMap[OldTI] = NewInst;
6215ffd83dbSDimitry Andric       if (auto *CB = dyn_cast<CallBase>(OldTI))
6225ffd83dbSDimitry Andric         if (CB->hasOperandBundles())
6230b57cec5SDimitry Andric           CodeInfo->OperandBundleCallSites.push_back(NewInst);
624fe6060f1SDimitry Andric     }
6250b57cec5SDimitry Andric 
6260b57cec5SDimitry Andric     // Recursively clone any reachable successor blocks.
627e8d8bef9SDimitry Andric     append_range(ToClone, successors(BB->getTerminator()));
6285f757f3fSDimitry Andric   } else {
629*0fca6ea1SDimitry Andric     // If we didn't create a new terminator, clone DbgVariableRecords from the
630*0fca6ea1SDimitry Andric     // old terminator onto the new terminator.
6315f757f3fSDimitry Andric     Instruction *NewInst = NewBB->getTerminator();
6325f757f3fSDimitry Andric     assert(NewInst);
6335f757f3fSDimitry Andric 
6345f757f3fSDimitry Andric     CloneDbgRecordsToHere(NewInst, OldTI->getIterator());
6350b57cec5SDimitry Andric   }
6360b57cec5SDimitry Andric 
6370b57cec5SDimitry Andric   if (CodeInfo) {
6380b57cec5SDimitry Andric     CodeInfo->ContainsCalls |= hasCalls;
639bdd1243dSDimitry Andric     CodeInfo->ContainsMemProfMetadata |= hasMemProfMetadata;
6400b57cec5SDimitry Andric     CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
641fe6060f1SDimitry Andric     CodeInfo->ContainsDynamicAllocas |=
642fe6060f1SDimitry Andric         hasStaticAllocas && BB != &BB->getParent()->front();
6430b57cec5SDimitry Andric   }
6440b57cec5SDimitry Andric }
6450b57cec5SDimitry Andric 
6460b57cec5SDimitry Andric /// This works like CloneAndPruneFunctionInto, except that it does not clone the
6470b57cec5SDimitry Andric /// entire function. Instead it starts at an instruction provided by the caller
6480b57cec5SDimitry Andric /// and copies (and prunes) only the code reachable from that instruction.
6490b57cec5SDimitry Andric void llvm::CloneAndPruneIntoFromInst(Function *NewFunc, const Function *OldFunc,
6500b57cec5SDimitry Andric                                      const Instruction *StartingInst,
6510b57cec5SDimitry Andric                                      ValueToValueMapTy &VMap,
6520b57cec5SDimitry Andric                                      bool ModuleLevelChanges,
6530b57cec5SDimitry Andric                                      SmallVectorImpl<ReturnInst *> &Returns,
6540b57cec5SDimitry Andric                                      const char *NameSuffix,
6550b57cec5SDimitry Andric                                      ClonedCodeInfo *CodeInfo) {
6560b57cec5SDimitry Andric   assert(NameSuffix && "NameSuffix cannot be null!");
6570b57cec5SDimitry Andric 
6580b57cec5SDimitry Andric   ValueMapTypeRemapper *TypeMapper = nullptr;
6590b57cec5SDimitry Andric   ValueMaterializer *Materializer = nullptr;
6600b57cec5SDimitry Andric 
6610b57cec5SDimitry Andric #ifndef NDEBUG
6620b57cec5SDimitry Andric   // If the cloning starts at the beginning of the function, verify that
6630b57cec5SDimitry Andric   // the function arguments are mapped.
6640b57cec5SDimitry Andric   if (!StartingInst)
6650b57cec5SDimitry Andric     for (const Argument &II : OldFunc->args())
6660b57cec5SDimitry Andric       assert(VMap.count(&II) && "No mapping from source argument specified!");
6670b57cec5SDimitry Andric #endif
6680b57cec5SDimitry Andric 
6690b57cec5SDimitry Andric   PruningFunctionCloner PFC(NewFunc, OldFunc, VMap, ModuleLevelChanges,
6700b57cec5SDimitry Andric                             NameSuffix, CodeInfo);
6710b57cec5SDimitry Andric   const BasicBlock *StartingBB;
6720b57cec5SDimitry Andric   if (StartingInst)
6730b57cec5SDimitry Andric     StartingBB = StartingInst->getParent();
6740b57cec5SDimitry Andric   else {
6750b57cec5SDimitry Andric     StartingBB = &OldFunc->getEntryBlock();
6760b57cec5SDimitry Andric     StartingInst = &StartingBB->front();
6770b57cec5SDimitry Andric   }
6780b57cec5SDimitry Andric 
679bdd1243dSDimitry Andric   // Collect debug intrinsics for remapping later.
680bdd1243dSDimitry Andric   SmallVector<const DbgVariableIntrinsic *, 8> DbgIntrinsics;
681bdd1243dSDimitry Andric   for (const auto &BB : *OldFunc) {
682bdd1243dSDimitry Andric     for (const auto &I : BB) {
683bdd1243dSDimitry Andric       if (const auto *DVI = dyn_cast<DbgVariableIntrinsic>(&I))
684bdd1243dSDimitry Andric         DbgIntrinsics.push_back(DVI);
685bdd1243dSDimitry Andric     }
686bdd1243dSDimitry Andric   }
687bdd1243dSDimitry Andric 
6880b57cec5SDimitry Andric   // Clone the entry block, and anything recursively reachable from it.
6890b57cec5SDimitry Andric   std::vector<const BasicBlock *> CloneWorklist;
6900b57cec5SDimitry Andric   PFC.CloneBlock(StartingBB, StartingInst->getIterator(), CloneWorklist);
6910b57cec5SDimitry Andric   while (!CloneWorklist.empty()) {
6920b57cec5SDimitry Andric     const BasicBlock *BB = CloneWorklist.back();
6930b57cec5SDimitry Andric     CloneWorklist.pop_back();
6940b57cec5SDimitry Andric     PFC.CloneBlock(BB, BB->begin(), CloneWorklist);
6950b57cec5SDimitry Andric   }
6960b57cec5SDimitry Andric 
6970b57cec5SDimitry Andric   // Loop over all of the basic blocks in the old function.  If the block was
6980b57cec5SDimitry Andric   // reachable, we have cloned it and the old block is now in the value map:
6990b57cec5SDimitry Andric   // insert it into the new function in the right order.  If not, ignore it.
7000b57cec5SDimitry Andric   //
7010b57cec5SDimitry Andric   // Defer PHI resolution until rest of function is resolved.
7020b57cec5SDimitry Andric   SmallVector<const PHINode *, 16> PHIToResolve;
7030b57cec5SDimitry Andric   for (const BasicBlock &BI : *OldFunc) {
7040b57cec5SDimitry Andric     Value *V = VMap.lookup(&BI);
7050b57cec5SDimitry Andric     BasicBlock *NewBB = cast_or_null<BasicBlock>(V);
706fe6060f1SDimitry Andric     if (!NewBB)
707fe6060f1SDimitry Andric       continue; // Dead block.
7080b57cec5SDimitry Andric 
70906c3fb27SDimitry Andric     // Move the new block to preserve the order in the original function.
71006c3fb27SDimitry Andric     NewBB->moveBefore(NewFunc->end());
7110b57cec5SDimitry Andric 
7120b57cec5SDimitry Andric     // Handle PHI nodes specially, as we have to remove references to dead
7130b57cec5SDimitry Andric     // blocks.
7140b57cec5SDimitry Andric     for (const PHINode &PN : BI.phis()) {
7150b57cec5SDimitry Andric       // PHI nodes may have been remapped to non-PHI nodes by the caller or
7160b57cec5SDimitry Andric       // during the cloning process.
7170b57cec5SDimitry Andric       if (isa<PHINode>(VMap[&PN]))
7180b57cec5SDimitry Andric         PHIToResolve.push_back(&PN);
7190b57cec5SDimitry Andric       else
7200b57cec5SDimitry Andric         break;
7210b57cec5SDimitry Andric     }
7220b57cec5SDimitry Andric 
7230b57cec5SDimitry Andric     // Finally, remap the terminator instructions, as those can't be remapped
7240b57cec5SDimitry Andric     // until all BBs are mapped.
7250b57cec5SDimitry Andric     RemapInstruction(NewBB->getTerminator(), VMap,
7260b57cec5SDimitry Andric                      ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
7270b57cec5SDimitry Andric                      TypeMapper, Materializer);
7280b57cec5SDimitry Andric   }
7290b57cec5SDimitry Andric 
7300b57cec5SDimitry Andric   // Defer PHI resolution until rest of function is resolved, PHI resolution
7310b57cec5SDimitry Andric   // requires the CFG to be up-to-date.
7320b57cec5SDimitry Andric   for (unsigned phino = 0, e = PHIToResolve.size(); phino != e;) {
7330b57cec5SDimitry Andric     const PHINode *OPN = PHIToResolve[phino];
7340b57cec5SDimitry Andric     unsigned NumPreds = OPN->getNumIncomingValues();
7350b57cec5SDimitry Andric     const BasicBlock *OldBB = OPN->getParent();
7360b57cec5SDimitry Andric     BasicBlock *NewBB = cast<BasicBlock>(VMap[OldBB]);
7370b57cec5SDimitry Andric 
7380b57cec5SDimitry Andric     // Map operands for blocks that are live and remove operands for blocks
7390b57cec5SDimitry Andric     // that are dead.
7400b57cec5SDimitry Andric     for (; phino != PHIToResolve.size() &&
741fe6060f1SDimitry Andric            PHIToResolve[phino]->getParent() == OldBB;
742fe6060f1SDimitry Andric          ++phino) {
7430b57cec5SDimitry Andric       OPN = PHIToResolve[phino];
7440b57cec5SDimitry Andric       PHINode *PN = cast<PHINode>(VMap[OPN]);
7450b57cec5SDimitry Andric       for (unsigned pred = 0, e = NumPreds; pred != e; ++pred) {
7460b57cec5SDimitry Andric         Value *V = VMap.lookup(PN->getIncomingBlock(pred));
7470b57cec5SDimitry Andric         if (BasicBlock *MappedBlock = cast_or_null<BasicBlock>(V)) {
748fe6060f1SDimitry Andric           Value *InVal =
749fe6060f1SDimitry Andric               MapValue(PN->getIncomingValue(pred), VMap,
7500b57cec5SDimitry Andric                        ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
7510b57cec5SDimitry Andric           assert(InVal && "Unknown input value?");
7520b57cec5SDimitry Andric           PN->setIncomingValue(pred, InVal);
7530b57cec5SDimitry Andric           PN->setIncomingBlock(pred, MappedBlock);
7540b57cec5SDimitry Andric         } else {
7550b57cec5SDimitry Andric           PN->removeIncomingValue(pred, false);
7560b57cec5SDimitry Andric           --pred; // Revisit the next entry.
7570b57cec5SDimitry Andric           --e;
7580b57cec5SDimitry Andric         }
7590b57cec5SDimitry Andric       }
7600b57cec5SDimitry Andric     }
7610b57cec5SDimitry Andric 
7620b57cec5SDimitry Andric     // The loop above has removed PHI entries for those blocks that are dead
7630b57cec5SDimitry Andric     // and has updated others.  However, if a block is live (i.e. copied over)
7640b57cec5SDimitry Andric     // but its terminator has been changed to not go to this block, then our
7650b57cec5SDimitry Andric     // phi nodes will have invalid entries.  Update the PHI nodes in this
7660b57cec5SDimitry Andric     // case.
7670b57cec5SDimitry Andric     PHINode *PN = cast<PHINode>(NewBB->begin());
7680b57cec5SDimitry Andric     NumPreds = pred_size(NewBB);
7690b57cec5SDimitry Andric     if (NumPreds != PN->getNumIncomingValues()) {
7700b57cec5SDimitry Andric       assert(NumPreds < PN->getNumIncomingValues());
7710b57cec5SDimitry Andric       // Count how many times each predecessor comes to this block.
7720b57cec5SDimitry Andric       std::map<BasicBlock *, unsigned> PredCount;
773fe6060f1SDimitry Andric       for (BasicBlock *Pred : predecessors(NewBB))
774fe6060f1SDimitry Andric         --PredCount[Pred];
7750b57cec5SDimitry Andric 
7760b57cec5SDimitry Andric       // Figure out how many entries to remove from each PHI.
7770b57cec5SDimitry Andric       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7780b57cec5SDimitry Andric         ++PredCount[PN->getIncomingBlock(i)];
7790b57cec5SDimitry Andric 
7800b57cec5SDimitry Andric       // At this point, the excess predecessor entries are positive in the
7810b57cec5SDimitry Andric       // map.  Loop over all of the PHIs and remove excess predecessor
7820b57cec5SDimitry Andric       // entries.
7830b57cec5SDimitry Andric       BasicBlock::iterator I = NewBB->begin();
7840b57cec5SDimitry Andric       for (; (PN = dyn_cast<PHINode>(I)); ++I) {
7850b57cec5SDimitry Andric         for (const auto &PCI : PredCount) {
7860b57cec5SDimitry Andric           BasicBlock *Pred = PCI.first;
7870b57cec5SDimitry Andric           for (unsigned NumToRemove = PCI.second; NumToRemove; --NumToRemove)
7880b57cec5SDimitry Andric             PN->removeIncomingValue(Pred, false);
7890b57cec5SDimitry Andric         }
7900b57cec5SDimitry Andric       }
7910b57cec5SDimitry Andric     }
7920b57cec5SDimitry Andric 
7930b57cec5SDimitry Andric     // If the loops above have made these phi nodes have 0 or 1 operand,
794fcaf7f86SDimitry Andric     // replace them with poison or the input value.  We must do this for
7950b57cec5SDimitry Andric     // correctness, because 0-operand phis are not valid.
7960b57cec5SDimitry Andric     PN = cast<PHINode>(NewBB->begin());
7970b57cec5SDimitry Andric     if (PN->getNumIncomingValues() == 0) {
7980b57cec5SDimitry Andric       BasicBlock::iterator I = NewBB->begin();
7990b57cec5SDimitry Andric       BasicBlock::const_iterator OldI = OldBB->begin();
8000b57cec5SDimitry Andric       while ((PN = dyn_cast<PHINode>(I++))) {
801fcaf7f86SDimitry Andric         Value *NV = PoisonValue::get(PN->getType());
8020b57cec5SDimitry Andric         PN->replaceAllUsesWith(NV);
8030b57cec5SDimitry Andric         assert(VMap[&*OldI] == PN && "VMap mismatch");
8040b57cec5SDimitry Andric         VMap[&*OldI] = NV;
8050b57cec5SDimitry Andric         PN->eraseFromParent();
8060b57cec5SDimitry Andric         ++OldI;
8070b57cec5SDimitry Andric       }
8080b57cec5SDimitry Andric     }
8090b57cec5SDimitry Andric   }
8100b57cec5SDimitry Andric 
811*0fca6ea1SDimitry Andric   // Drop all incompatible return attributes that cannot be applied to NewFunc
812*0fca6ea1SDimitry Andric   // during cloning, so as to allow instruction simplification to reason on the
813*0fca6ea1SDimitry Andric   // old state of the function. The original attributes are restored later.
814*0fca6ea1SDimitry Andric   AttributeMask IncompatibleAttrs =
815*0fca6ea1SDimitry Andric       AttributeFuncs::typeIncompatible(OldFunc->getReturnType());
816*0fca6ea1SDimitry Andric   AttributeList Attrs = NewFunc->getAttributes();
817*0fca6ea1SDimitry Andric   NewFunc->removeRetAttrs(IncompatibleAttrs);
8180b57cec5SDimitry Andric 
819*0fca6ea1SDimitry Andric   // As phi-nodes have been now remapped, allow incremental simplification of
820*0fca6ea1SDimitry Andric   // newly-cloned instructions.
821*0fca6ea1SDimitry Andric   const DataLayout &DL = NewFunc->getDataLayout();
822*0fca6ea1SDimitry Andric   for (const auto &BB : *OldFunc) {
823*0fca6ea1SDimitry Andric     for (const auto &I : BB) {
824*0fca6ea1SDimitry Andric       auto *NewI = dyn_cast_or_null<Instruction>(VMap.lookup(&I));
825*0fca6ea1SDimitry Andric       if (!NewI)
8260b57cec5SDimitry Andric         continue;
8270b57cec5SDimitry Andric 
828*0fca6ea1SDimitry Andric       if (Value *V = simplifyInstruction(NewI, DL)) {
829*0fca6ea1SDimitry Andric         NewI->replaceAllUsesWith(V);
8300b57cec5SDimitry Andric 
831*0fca6ea1SDimitry Andric         if (isInstructionTriviallyDead(NewI)) {
832*0fca6ea1SDimitry Andric           NewI->eraseFromParent();
833*0fca6ea1SDimitry Andric         } else {
834*0fca6ea1SDimitry Andric           // Did not erase it? Restore the new instruction into VMap previously
835*0fca6ea1SDimitry Andric           // dropped by `ValueIsRAUWd`.
836*0fca6ea1SDimitry Andric           VMap[&I] = NewI;
8370b57cec5SDimitry Andric         }
838*0fca6ea1SDimitry Andric       }
839*0fca6ea1SDimitry Andric     }
840*0fca6ea1SDimitry Andric   }
841*0fca6ea1SDimitry Andric 
842*0fca6ea1SDimitry Andric   // Restore attributes.
843*0fca6ea1SDimitry Andric   NewFunc->setAttributes(Attrs);
8440b57cec5SDimitry Andric 
845bdd1243dSDimitry Andric   // Remap debug intrinsic operands now that all values have been mapped.
846bdd1243dSDimitry Andric   // Doing this now (late) preserves use-before-defs in debug intrinsics. If
847bdd1243dSDimitry Andric   // we didn't do this, ValueAsMetadata(use-before-def) operands would be
848bdd1243dSDimitry Andric   // replaced by empty metadata. This would signal later cleanup passes to
849bdd1243dSDimitry Andric   // remove the debug intrinsics, potentially causing incorrect locations.
850bdd1243dSDimitry Andric   for (const auto *DVI : DbgIntrinsics) {
851bdd1243dSDimitry Andric     if (DbgVariableIntrinsic *NewDVI =
852bdd1243dSDimitry Andric             cast_or_null<DbgVariableIntrinsic>(VMap.lookup(DVI)))
853bdd1243dSDimitry Andric       RemapInstruction(NewDVI, VMap,
854bdd1243dSDimitry Andric                        ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
855bdd1243dSDimitry Andric                        TypeMapper, Materializer);
856bdd1243dSDimitry Andric   }
857bdd1243dSDimitry Andric 
858*0fca6ea1SDimitry Andric   // Do the same for DbgVariableRecords, touching all the instructions in the
859*0fca6ea1SDimitry Andric   // cloned range of blocks.
8605f757f3fSDimitry Andric   Function::iterator Begin = cast<BasicBlock>(VMap[StartingBB])->getIterator();
8615f757f3fSDimitry Andric   for (BasicBlock &BB : make_range(Begin, NewFunc->end())) {
8625f757f3fSDimitry Andric     for (Instruction &I : BB) {
863*0fca6ea1SDimitry Andric       RemapDbgRecordRange(I.getModule(), I.getDbgRecordRange(), VMap,
864*0fca6ea1SDimitry Andric                           ModuleLevelChanges ? RF_None
865*0fca6ea1SDimitry Andric                                              : RF_NoModuleLevelChanges,
8665f757f3fSDimitry Andric                           TypeMapper, Materializer);
8675f757f3fSDimitry Andric     }
8685f757f3fSDimitry Andric   }
8695f757f3fSDimitry Andric 
8701fd87a68SDimitry Andric   // Simplify conditional branches and switches with a constant operand. We try
8711fd87a68SDimitry Andric   // to prune these out when cloning, but if the simplification required
8721fd87a68SDimitry Andric   // looking through PHI nodes, those are only available after forming the full
8731fd87a68SDimitry Andric   // basic block. That may leave some here, and we still want to prune the dead
8741fd87a68SDimitry Andric   // code as early as possible.
8751fd87a68SDimitry Andric   for (BasicBlock &BB : make_range(Begin, NewFunc->end()))
8761fd87a68SDimitry Andric     ConstantFoldTerminator(&BB);
8771fd87a68SDimitry Andric 
8781fd87a68SDimitry Andric   // Some blocks may have become unreachable as a result. Find and delete them.
8791fd87a68SDimitry Andric   {
8801fd87a68SDimitry Andric     SmallPtrSet<BasicBlock *, 16> ReachableBlocks;
8811fd87a68SDimitry Andric     SmallVector<BasicBlock *, 16> Worklist;
8821fd87a68SDimitry Andric     Worklist.push_back(&*Begin);
8831fd87a68SDimitry Andric     while (!Worklist.empty()) {
8841fd87a68SDimitry Andric       BasicBlock *BB = Worklist.pop_back_val();
8851fd87a68SDimitry Andric       if (ReachableBlocks.insert(BB).second)
8861fd87a68SDimitry Andric         append_range(Worklist, successors(BB));
8871fd87a68SDimitry Andric     }
8881fd87a68SDimitry Andric 
8891fd87a68SDimitry Andric     SmallVector<BasicBlock *, 16> UnreachableBlocks;
8901fd87a68SDimitry Andric     for (BasicBlock &BB : make_range(Begin, NewFunc->end()))
8911fd87a68SDimitry Andric       if (!ReachableBlocks.contains(&BB))
8921fd87a68SDimitry Andric         UnreachableBlocks.push_back(&BB);
8931fd87a68SDimitry Andric     DeleteDeadBlocks(UnreachableBlocks);
8941fd87a68SDimitry Andric   }
8951fd87a68SDimitry Andric 
8960b57cec5SDimitry Andric   // Now that the inlined function body has been fully constructed, go through
8970b57cec5SDimitry Andric   // and zap unconditional fall-through branches. This happens all the time when
8980b57cec5SDimitry Andric   // specializing code: code specialization turns conditional branches into
8990b57cec5SDimitry Andric   // uncond branches, and this code folds them.
9000b57cec5SDimitry Andric   Function::iterator I = Begin;
9010b57cec5SDimitry Andric   while (I != NewFunc->end()) {
9020b57cec5SDimitry Andric     BranchInst *BI = dyn_cast<BranchInst>(I->getTerminator());
903fe6060f1SDimitry Andric     if (!BI || BI->isConditional()) {
904fe6060f1SDimitry Andric       ++I;
905fe6060f1SDimitry Andric       continue;
906fe6060f1SDimitry Andric     }
9070b57cec5SDimitry Andric 
9080b57cec5SDimitry Andric     BasicBlock *Dest = BI->getSuccessor(0);
9090b57cec5SDimitry Andric     if (!Dest->getSinglePredecessor()) {
910fe6060f1SDimitry Andric       ++I;
911fe6060f1SDimitry Andric       continue;
9120b57cec5SDimitry Andric     }
9130b57cec5SDimitry Andric 
9140b57cec5SDimitry Andric     // We shouldn't be able to get single-entry PHI nodes here, as instsimplify
9150b57cec5SDimitry Andric     // above should have zapped all of them..
9160b57cec5SDimitry Andric     assert(!isa<PHINode>(Dest->begin()));
9170b57cec5SDimitry Andric 
9180b57cec5SDimitry Andric     // We know all single-entry PHI nodes in the inlined function have been
9190b57cec5SDimitry Andric     // removed, so we just need to splice the blocks.
9200b57cec5SDimitry Andric     BI->eraseFromParent();
9210b57cec5SDimitry Andric 
9220b57cec5SDimitry Andric     // Make all PHI nodes that referred to Dest now refer to I as their source.
9230b57cec5SDimitry Andric     Dest->replaceAllUsesWith(&*I);
9240b57cec5SDimitry Andric 
9250b57cec5SDimitry Andric     // Move all the instructions in the succ to the pred.
926bdd1243dSDimitry Andric     I->splice(I->end(), Dest);
9270b57cec5SDimitry Andric 
9280b57cec5SDimitry Andric     // Remove the dest block.
9290b57cec5SDimitry Andric     Dest->eraseFromParent();
9300b57cec5SDimitry Andric 
9310b57cec5SDimitry Andric     // Do not increment I, iteratively merge all things this block branches to.
9320b57cec5SDimitry Andric   }
9330b57cec5SDimitry Andric 
9340b57cec5SDimitry Andric   // Make a final pass over the basic blocks from the old function to gather
9350b57cec5SDimitry Andric   // any return instructions which survived folding. We have to do this here
9360b57cec5SDimitry Andric   // because we can iteratively remove and merge returns above.
9370b57cec5SDimitry Andric   for (Function::iterator I = cast<BasicBlock>(VMap[StartingBB])->getIterator(),
9380b57cec5SDimitry Andric                           E = NewFunc->end();
9390b57cec5SDimitry Andric        I != E; ++I)
9400b57cec5SDimitry Andric     if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator()))
9410b57cec5SDimitry Andric       Returns.push_back(RI);
9420b57cec5SDimitry Andric }
9430b57cec5SDimitry Andric 
9440b57cec5SDimitry Andric /// This works exactly like CloneFunctionInto,
9450b57cec5SDimitry Andric /// except that it does some simple constant prop and DCE on the fly.  The
9460b57cec5SDimitry Andric /// effect of this is to copy significantly less code in cases where (for
9470b57cec5SDimitry Andric /// example) a function call with constant arguments is inlined, and those
9480b57cec5SDimitry Andric /// constant arguments cause a significant amount of code in the callee to be
9490b57cec5SDimitry Andric /// dead.  Since this doesn't produce an exact copy of the input, it can't be
9500b57cec5SDimitry Andric /// used for things like CloneFunction or CloneModule.
951fe6060f1SDimitry Andric void llvm::CloneAndPruneFunctionInto(
952fe6060f1SDimitry Andric     Function *NewFunc, const Function *OldFunc, ValueToValueMapTy &VMap,
953fe6060f1SDimitry Andric     bool ModuleLevelChanges, SmallVectorImpl<ReturnInst *> &Returns,
954fe6060f1SDimitry Andric     const char *NameSuffix, ClonedCodeInfo *CodeInfo) {
9550b57cec5SDimitry Andric   CloneAndPruneIntoFromInst(NewFunc, OldFunc, &OldFunc->front().front(), VMap,
9560b57cec5SDimitry Andric                             ModuleLevelChanges, Returns, NameSuffix, CodeInfo);
9570b57cec5SDimitry Andric }
9580b57cec5SDimitry Andric 
9590b57cec5SDimitry Andric /// Remaps instructions in \p Blocks using the mapping in \p VMap.
96006c3fb27SDimitry Andric void llvm::remapInstructionsInBlocks(ArrayRef<BasicBlock *> Blocks,
96106c3fb27SDimitry Andric                                      ValueToValueMapTy &VMap) {
9620b57cec5SDimitry Andric   // Rewrite the code to refer to itself.
9635f757f3fSDimitry Andric   for (auto *BB : Blocks) {
9645f757f3fSDimitry Andric     for (auto &Inst : *BB) {
965*0fca6ea1SDimitry Andric       RemapDbgRecordRange(Inst.getModule(), Inst.getDbgRecordRange(), VMap,
9665f757f3fSDimitry Andric                           RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
9670b57cec5SDimitry Andric       RemapInstruction(&Inst, VMap,
9680b57cec5SDimitry Andric                        RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
9690b57cec5SDimitry Andric     }
9705f757f3fSDimitry Andric   }
9715f757f3fSDimitry Andric }
9720b57cec5SDimitry Andric 
9730b57cec5SDimitry Andric /// Clones a loop \p OrigLoop.  Returns the loop and the blocks in \p
9740b57cec5SDimitry Andric /// Blocks.
9750b57cec5SDimitry Andric ///
9760b57cec5SDimitry Andric /// Updates LoopInfo and DominatorTree assuming the loop is dominated by block
9770b57cec5SDimitry Andric /// \p LoopDomBB.  Insert the new blocks before block specified in \p Before.
9780b57cec5SDimitry Andric Loop *llvm::cloneLoopWithPreheader(BasicBlock *Before, BasicBlock *LoopDomBB,
9790b57cec5SDimitry Andric                                    Loop *OrigLoop, ValueToValueMapTy &VMap,
9800b57cec5SDimitry Andric                                    const Twine &NameSuffix, LoopInfo *LI,
9810b57cec5SDimitry Andric                                    DominatorTree *DT,
9820b57cec5SDimitry Andric                                    SmallVectorImpl<BasicBlock *> &Blocks) {
9830b57cec5SDimitry Andric   Function *F = OrigLoop->getHeader()->getParent();
9840b57cec5SDimitry Andric   Loop *ParentLoop = OrigLoop->getParentLoop();
9850b57cec5SDimitry Andric   DenseMap<Loop *, Loop *> LMap;
9860b57cec5SDimitry Andric 
9870b57cec5SDimitry Andric   Loop *NewLoop = LI->AllocateLoop();
9880b57cec5SDimitry Andric   LMap[OrigLoop] = NewLoop;
9890b57cec5SDimitry Andric   if (ParentLoop)
9900b57cec5SDimitry Andric     ParentLoop->addChildLoop(NewLoop);
9910b57cec5SDimitry Andric   else
9920b57cec5SDimitry Andric     LI->addTopLevelLoop(NewLoop);
9930b57cec5SDimitry Andric 
9940b57cec5SDimitry Andric   BasicBlock *OrigPH = OrigLoop->getLoopPreheader();
9950b57cec5SDimitry Andric   assert(OrigPH && "No preheader");
9960b57cec5SDimitry Andric   BasicBlock *NewPH = CloneBasicBlock(OrigPH, VMap, NameSuffix, F);
9970b57cec5SDimitry Andric   // To rename the loop PHIs.
9980b57cec5SDimitry Andric   VMap[OrigPH] = NewPH;
9990b57cec5SDimitry Andric   Blocks.push_back(NewPH);
10000b57cec5SDimitry Andric 
10010b57cec5SDimitry Andric   // Update LoopInfo.
10020b57cec5SDimitry Andric   if (ParentLoop)
10030b57cec5SDimitry Andric     ParentLoop->addBasicBlockToLoop(NewPH, *LI);
10040b57cec5SDimitry Andric 
10050b57cec5SDimitry Andric   // Update DominatorTree.
10060b57cec5SDimitry Andric   DT->addNewBlock(NewPH, LoopDomBB);
10070b57cec5SDimitry Andric 
10080b57cec5SDimitry Andric   for (Loop *CurLoop : OrigLoop->getLoopsInPreorder()) {
10090b57cec5SDimitry Andric     Loop *&NewLoop = LMap[CurLoop];
10100b57cec5SDimitry Andric     if (!NewLoop) {
10110b57cec5SDimitry Andric       NewLoop = LI->AllocateLoop();
10120b57cec5SDimitry Andric 
10130b57cec5SDimitry Andric       // Establish the parent/child relationship.
10140b57cec5SDimitry Andric       Loop *OrigParent = CurLoop->getParentLoop();
10150b57cec5SDimitry Andric       assert(OrigParent && "Could not find the original parent loop");
10160b57cec5SDimitry Andric       Loop *NewParentLoop = LMap[OrigParent];
10170b57cec5SDimitry Andric       assert(NewParentLoop && "Could not find the new parent loop");
10180b57cec5SDimitry Andric 
10190b57cec5SDimitry Andric       NewParentLoop->addChildLoop(NewLoop);
10200b57cec5SDimitry Andric     }
10210b57cec5SDimitry Andric   }
10220b57cec5SDimitry Andric 
10230b57cec5SDimitry Andric   for (BasicBlock *BB : OrigLoop->getBlocks()) {
10240b57cec5SDimitry Andric     Loop *CurLoop = LI->getLoopFor(BB);
10250b57cec5SDimitry Andric     Loop *&NewLoop = LMap[CurLoop];
10260b57cec5SDimitry Andric     assert(NewLoop && "Expecting new loop to be allocated");
10270b57cec5SDimitry Andric 
10280b57cec5SDimitry Andric     BasicBlock *NewBB = CloneBasicBlock(BB, VMap, NameSuffix, F);
10290b57cec5SDimitry Andric     VMap[BB] = NewBB;
10300b57cec5SDimitry Andric 
10310b57cec5SDimitry Andric     // Update LoopInfo.
10320b57cec5SDimitry Andric     NewLoop->addBasicBlockToLoop(NewBB, *LI);
10330b57cec5SDimitry Andric 
10340b57cec5SDimitry Andric     // Add DominatorTree node. After seeing all blocks, update to correct
10350b57cec5SDimitry Andric     // IDom.
10360b57cec5SDimitry Andric     DT->addNewBlock(NewBB, NewPH);
10370b57cec5SDimitry Andric 
10380b57cec5SDimitry Andric     Blocks.push_back(NewBB);
10390b57cec5SDimitry Andric   }
10400b57cec5SDimitry Andric 
10410b57cec5SDimitry Andric   for (BasicBlock *BB : OrigLoop->getBlocks()) {
10425ffd83dbSDimitry Andric     // Update loop headers.
10435ffd83dbSDimitry Andric     Loop *CurLoop = LI->getLoopFor(BB);
10445ffd83dbSDimitry Andric     if (BB == CurLoop->getHeader())
10455ffd83dbSDimitry Andric       LMap[CurLoop]->moveToHeader(cast<BasicBlock>(VMap[BB]));
10465ffd83dbSDimitry Andric 
10470b57cec5SDimitry Andric     // Update DominatorTree.
10480b57cec5SDimitry Andric     BasicBlock *IDomBB = DT->getNode(BB)->getIDom()->getBlock();
10490b57cec5SDimitry Andric     DT->changeImmediateDominator(cast<BasicBlock>(VMap[BB]),
10500b57cec5SDimitry Andric                                  cast<BasicBlock>(VMap[IDomBB]));
10510b57cec5SDimitry Andric   }
10520b57cec5SDimitry Andric 
10530b57cec5SDimitry Andric   // Move them physically from the end of the block list.
1054bdd1243dSDimitry Andric   F->splice(Before->getIterator(), F, NewPH->getIterator());
1055bdd1243dSDimitry Andric   F->splice(Before->getIterator(), F, NewLoop->getHeader()->getIterator(),
1056bdd1243dSDimitry Andric             F->end());
10570b57cec5SDimitry Andric 
10580b57cec5SDimitry Andric   return NewLoop;
10590b57cec5SDimitry Andric }
10600b57cec5SDimitry Andric 
10610b57cec5SDimitry Andric /// Duplicate non-Phi instructions from the beginning of block up to
10620b57cec5SDimitry Andric /// StopAt instruction into a split block between BB and its predecessor.
10630b57cec5SDimitry Andric BasicBlock *llvm::DuplicateInstructionsInSplitBetween(
10640b57cec5SDimitry Andric     BasicBlock *BB, BasicBlock *PredBB, Instruction *StopAt,
10650b57cec5SDimitry Andric     ValueToValueMapTy &ValueMapping, DomTreeUpdater &DTU) {
10660b57cec5SDimitry Andric 
10670b57cec5SDimitry Andric   assert(count(successors(PredBB), BB) == 1 &&
10680b57cec5SDimitry Andric          "There must be a single edge between PredBB and BB!");
10690b57cec5SDimitry Andric   // We are going to have to map operands from the original BB block to the new
10700b57cec5SDimitry Andric   // copy of the block 'NewBB'.  If there are PHI nodes in BB, evaluate them to
10710b57cec5SDimitry Andric   // account for entry from PredBB.
10720b57cec5SDimitry Andric   BasicBlock::iterator BI = BB->begin();
10730b57cec5SDimitry Andric   for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
10740b57cec5SDimitry Andric     ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
10750b57cec5SDimitry Andric 
10760b57cec5SDimitry Andric   BasicBlock *NewBB = SplitEdge(PredBB, BB);
10770b57cec5SDimitry Andric   NewBB->setName(PredBB->getName() + ".split");
10780b57cec5SDimitry Andric   Instruction *NewTerm = NewBB->getTerminator();
10790b57cec5SDimitry Andric 
10800b57cec5SDimitry Andric   // FIXME: SplitEdge does not yet take a DTU, so we include the split edge
10810b57cec5SDimitry Andric   //        in the update set here.
10820b57cec5SDimitry Andric   DTU.applyUpdates({{DominatorTree::Delete, PredBB, BB},
10830b57cec5SDimitry Andric                     {DominatorTree::Insert, PredBB, NewBB},
10840b57cec5SDimitry Andric                     {DominatorTree::Insert, NewBB, BB}});
10850b57cec5SDimitry Andric 
10860b57cec5SDimitry Andric   // Clone the non-phi instructions of BB into NewBB, keeping track of the
10870b57cec5SDimitry Andric   // mapping and using it to remap operands in the cloned instructions.
10880b57cec5SDimitry Andric   // Stop once we see the terminator too. This covers the case where BB's
10890b57cec5SDimitry Andric   // terminator gets replaced and StopAt == BB's terminator.
10900b57cec5SDimitry Andric   for (; StopAt != &*BI && BB->getTerminator() != &*BI; ++BI) {
10910b57cec5SDimitry Andric     Instruction *New = BI->clone();
10920b57cec5SDimitry Andric     New->setName(BI->getName());
10930b57cec5SDimitry Andric     New->insertBefore(NewTerm);
10945f757f3fSDimitry Andric     New->cloneDebugInfoFrom(&*BI);
10950b57cec5SDimitry Andric     ValueMapping[&*BI] = New;
10960b57cec5SDimitry Andric 
10970b57cec5SDimitry Andric     // Remap operands to patch up intra-block references.
10980b57cec5SDimitry Andric     for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
10990b57cec5SDimitry Andric       if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
11000b57cec5SDimitry Andric         auto I = ValueMapping.find(Inst);
11010b57cec5SDimitry Andric         if (I != ValueMapping.end())
11020b57cec5SDimitry Andric           New->setOperand(i, I->second);
11030b57cec5SDimitry Andric       }
1104*0fca6ea1SDimitry Andric 
1105*0fca6ea1SDimitry Andric     // Remap debug variable operands.
1106*0fca6ea1SDimitry Andric     remapDebugVariable(ValueMapping, New);
11070b57cec5SDimitry Andric   }
11080b57cec5SDimitry Andric 
11090b57cec5SDimitry Andric   return NewBB;
11100b57cec5SDimitry Andric }
1111e8d8bef9SDimitry Andric 
1112fe6060f1SDimitry Andric void llvm::cloneNoAliasScopes(ArrayRef<MDNode *> NoAliasDeclScopes,
1113e8d8bef9SDimitry Andric                               DenseMap<MDNode *, MDNode *> &ClonedScopes,
1114e8d8bef9SDimitry Andric                               StringRef Ext, LLVMContext &Context) {
1115e8d8bef9SDimitry Andric   MDBuilder MDB(Context);
1116e8d8bef9SDimitry Andric 
1117e8d8bef9SDimitry Andric   for (auto *ScopeList : NoAliasDeclScopes) {
1118bdd1243dSDimitry Andric     for (const auto &MDOperand : ScopeList->operands()) {
1119e8d8bef9SDimitry Andric       if (MDNode *MD = dyn_cast<MDNode>(MDOperand)) {
1120e8d8bef9SDimitry Andric         AliasScopeNode SNANode(MD);
1121e8d8bef9SDimitry Andric 
1122e8d8bef9SDimitry Andric         std::string Name;
1123e8d8bef9SDimitry Andric         auto ScopeName = SNANode.getName();
1124e8d8bef9SDimitry Andric         if (!ScopeName.empty())
1125e8d8bef9SDimitry Andric           Name = (Twine(ScopeName) + ":" + Ext).str();
1126e8d8bef9SDimitry Andric         else
1127e8d8bef9SDimitry Andric           Name = std::string(Ext);
1128e8d8bef9SDimitry Andric 
1129e8d8bef9SDimitry Andric         MDNode *NewScope = MDB.createAnonymousAliasScope(
1130e8d8bef9SDimitry Andric             const_cast<MDNode *>(SNANode.getDomain()), Name);
1131e8d8bef9SDimitry Andric         ClonedScopes.insert(std::make_pair(MD, NewScope));
1132e8d8bef9SDimitry Andric       }
1133e8d8bef9SDimitry Andric     }
1134e8d8bef9SDimitry Andric   }
1135e8d8bef9SDimitry Andric }
1136e8d8bef9SDimitry Andric 
1137fe6060f1SDimitry Andric void llvm::adaptNoAliasScopes(Instruction *I,
1138fe6060f1SDimitry Andric                               const DenseMap<MDNode *, MDNode *> &ClonedScopes,
1139e8d8bef9SDimitry Andric                               LLVMContext &Context) {
1140e8d8bef9SDimitry Andric   auto CloneScopeList = [&](const MDNode *ScopeList) -> MDNode * {
1141e8d8bef9SDimitry Andric     bool NeedsReplacement = false;
1142e8d8bef9SDimitry Andric     SmallVector<Metadata *, 8> NewScopeList;
1143bdd1243dSDimitry Andric     for (const auto &MDOp : ScopeList->operands()) {
1144e8d8bef9SDimitry Andric       if (MDNode *MD = dyn_cast<MDNode>(MDOp)) {
1145e8d8bef9SDimitry Andric         if (auto *NewMD = ClonedScopes.lookup(MD)) {
1146e8d8bef9SDimitry Andric           NewScopeList.push_back(NewMD);
1147e8d8bef9SDimitry Andric           NeedsReplacement = true;
1148e8d8bef9SDimitry Andric           continue;
1149e8d8bef9SDimitry Andric         }
1150e8d8bef9SDimitry Andric         NewScopeList.push_back(MD);
1151e8d8bef9SDimitry Andric       }
1152e8d8bef9SDimitry Andric     }
1153e8d8bef9SDimitry Andric     if (NeedsReplacement)
1154e8d8bef9SDimitry Andric       return MDNode::get(Context, NewScopeList);
1155e8d8bef9SDimitry Andric     return nullptr;
1156e8d8bef9SDimitry Andric   };
1157e8d8bef9SDimitry Andric 
1158e8d8bef9SDimitry Andric   if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(I))
1159e8d8bef9SDimitry Andric     if (auto *NewScopeList = CloneScopeList(Decl->getScopeList()))
1160e8d8bef9SDimitry Andric       Decl->setScopeList(NewScopeList);
1161e8d8bef9SDimitry Andric 
1162e8d8bef9SDimitry Andric   auto replaceWhenNeeded = [&](unsigned MD_ID) {
1163e8d8bef9SDimitry Andric     if (const MDNode *CSNoAlias = I->getMetadata(MD_ID))
1164e8d8bef9SDimitry Andric       if (auto *NewScopeList = CloneScopeList(CSNoAlias))
1165e8d8bef9SDimitry Andric         I->setMetadata(MD_ID, NewScopeList);
1166e8d8bef9SDimitry Andric   };
1167e8d8bef9SDimitry Andric   replaceWhenNeeded(LLVMContext::MD_noalias);
1168e8d8bef9SDimitry Andric   replaceWhenNeeded(LLVMContext::MD_alias_scope);
1169e8d8bef9SDimitry Andric }
1170e8d8bef9SDimitry Andric 
1171fe6060f1SDimitry Andric void llvm::cloneAndAdaptNoAliasScopes(ArrayRef<MDNode *> NoAliasDeclScopes,
1172fe6060f1SDimitry Andric                                       ArrayRef<BasicBlock *> NewBlocks,
1173fe6060f1SDimitry Andric                                       LLVMContext &Context, StringRef Ext) {
1174e8d8bef9SDimitry Andric   if (NoAliasDeclScopes.empty())
1175e8d8bef9SDimitry Andric     return;
1176e8d8bef9SDimitry Andric 
1177e8d8bef9SDimitry Andric   DenseMap<MDNode *, MDNode *> ClonedScopes;
1178e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "cloneAndAdaptNoAliasScopes: cloning "
1179e8d8bef9SDimitry Andric                     << NoAliasDeclScopes.size() << " node(s)\n");
1180e8d8bef9SDimitry Andric 
1181e8d8bef9SDimitry Andric   cloneNoAliasScopes(NoAliasDeclScopes, ClonedScopes, Ext, Context);
1182e8d8bef9SDimitry Andric   // Identify instructions using metadata that needs adaptation
1183e8d8bef9SDimitry Andric   for (BasicBlock *NewBlock : NewBlocks)
1184e8d8bef9SDimitry Andric     for (Instruction &I : *NewBlock)
1185e8d8bef9SDimitry Andric       adaptNoAliasScopes(&I, ClonedScopes, Context);
1186e8d8bef9SDimitry Andric }
1187e8d8bef9SDimitry Andric 
1188fe6060f1SDimitry Andric void llvm::cloneAndAdaptNoAliasScopes(ArrayRef<MDNode *> NoAliasDeclScopes,
1189fe6060f1SDimitry Andric                                       Instruction *IStart, Instruction *IEnd,
1190fe6060f1SDimitry Andric                                       LLVMContext &Context, StringRef Ext) {
1191e8d8bef9SDimitry Andric   if (NoAliasDeclScopes.empty())
1192e8d8bef9SDimitry Andric     return;
1193e8d8bef9SDimitry Andric 
1194e8d8bef9SDimitry Andric   DenseMap<MDNode *, MDNode *> ClonedScopes;
1195e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "cloneAndAdaptNoAliasScopes: cloning "
1196e8d8bef9SDimitry Andric                     << NoAliasDeclScopes.size() << " node(s)\n");
1197e8d8bef9SDimitry Andric 
1198e8d8bef9SDimitry Andric   cloneNoAliasScopes(NoAliasDeclScopes, ClonedScopes, Ext, Context);
1199e8d8bef9SDimitry Andric   // Identify instructions using metadata that needs adaptation
1200e8d8bef9SDimitry Andric   assert(IStart->getParent() == IEnd->getParent() && "different basic block ?");
1201e8d8bef9SDimitry Andric   auto ItStart = IStart->getIterator();
1202e8d8bef9SDimitry Andric   auto ItEnd = IEnd->getIterator();
1203e8d8bef9SDimitry Andric   ++ItEnd; // IEnd is included, increment ItEnd to get the end of the range
1204e8d8bef9SDimitry Andric   for (auto &I : llvm::make_range(ItStart, ItEnd))
1205e8d8bef9SDimitry Andric     adaptNoAliasScopes(&I, ClonedScopes, Context);
1206e8d8bef9SDimitry Andric }
1207e8d8bef9SDimitry Andric 
1208e8d8bef9SDimitry Andric void llvm::identifyNoAliasScopesToClone(
1209e8d8bef9SDimitry Andric     ArrayRef<BasicBlock *> BBs, SmallVectorImpl<MDNode *> &NoAliasDeclScopes) {
1210e8d8bef9SDimitry Andric   for (BasicBlock *BB : BBs)
1211e8d8bef9SDimitry Andric     for (Instruction &I : *BB)
1212e8d8bef9SDimitry Andric       if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(&I))
1213e8d8bef9SDimitry Andric         NoAliasDeclScopes.push_back(Decl->getScopeList());
1214e8d8bef9SDimitry Andric }
1215d409305fSDimitry Andric 
1216d409305fSDimitry Andric void llvm::identifyNoAliasScopesToClone(
1217d409305fSDimitry Andric     BasicBlock::iterator Start, BasicBlock::iterator End,
1218d409305fSDimitry Andric     SmallVectorImpl<MDNode *> &NoAliasDeclScopes) {
1219d409305fSDimitry Andric   for (Instruction &I : make_range(Start, End))
1220d409305fSDimitry Andric     if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(&I))
1221d409305fSDimitry Andric       NoAliasDeclScopes.push_back(Decl->getScopeList());
1222d409305fSDimitry Andric }
1223