1009b1c42SEd Schouten //===- CloneFunction.cpp - Clone a function into another function ---------===//
2009b1c42SEd Schouten //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6009b1c42SEd Schouten //
7009b1c42SEd Schouten //===----------------------------------------------------------------------===//
8009b1c42SEd Schouten //
9009b1c42SEd Schouten // This file implements the CloneFunctionInto interface, which is used as the
10009b1c42SEd Schouten // low-level function cloner. This is used by the CloneFunction and function
11009b1c42SEd Schouten // inliner to do the dirty work of copying the body of a function around.
12009b1c42SEd Schouten //
13009b1c42SEd Schouten //===----------------------------------------------------------------------===//
14009b1c42SEd Schouten
15a7fe922bSDimitry Andric #include "llvm/ADT/SetVector.h"
164a16efa3SDimitry Andric #include "llvm/ADT/SmallVector.h"
17ac9a064cSDimitry Andric #include "llvm/Analysis/ConstantFolding.h"
18e6d15924SDimitry Andric #include "llvm/Analysis/DomTreeUpdater.h"
194a16efa3SDimitry Andric #include "llvm/Analysis/InstructionSimplify.h"
20ee8648bdSDimitry Andric #include "llvm/Analysis/LoopInfo.h"
21ac9a064cSDimitry Andric #include "llvm/IR/AttributeMask.h"
225ca98fd9SDimitry Andric #include "llvm/IR/CFG.h"
234a16efa3SDimitry Andric #include "llvm/IR/Constants.h"
245ca98fd9SDimitry Andric #include "llvm/IR/DebugInfo.h"
254a16efa3SDimitry Andric #include "llvm/IR/DerivedTypes.h"
264a16efa3SDimitry Andric #include "llvm/IR/Function.h"
274a16efa3SDimitry Andric #include "llvm/IR/Instructions.h"
284a16efa3SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
294a16efa3SDimitry Andric #include "llvm/IR/LLVMContext.h"
30b60736ecSDimitry Andric #include "llvm/IR/MDBuilder.h"
314a16efa3SDimitry Andric #include "llvm/IR/Metadata.h"
325ca98fd9SDimitry Andric #include "llvm/IR/Module.h"
3363faed5bSDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h"
347ab83427SDimitry Andric #include "llvm/Transforms/Utils/Cloning.h"
35d8e91e46SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
36d39c594dSDimitry Andric #include "llvm/Transforms/Utils/ValueMapper.h"
37009b1c42SEd Schouten #include <map>
38e3b55780SDimitry Andric #include <optional>
39009b1c42SEd Schouten using namespace llvm;
40009b1c42SEd Schouten
41b60736ecSDimitry Andric #define DEBUG_TYPE "clone-function"
42b60736ecSDimitry Andric
435a5ac124SDimitry Andric /// See comments in Cloning.h.
CloneBasicBlock(const BasicBlock * BB,ValueToValueMapTy & VMap,const Twine & NameSuffix,Function * F,ClonedCodeInfo * CodeInfo,DebugInfoFinder * DIFinder)44d288ef4cSDimitry Andric BasicBlock *llvm::CloneBasicBlock(const BasicBlock *BB, ValueToValueMapTy &VMap,
456fe5c7aaSRoman Divacky const Twine &NameSuffix, Function *F,
46d288ef4cSDimitry Andric ClonedCodeInfo *CodeInfo,
47d288ef4cSDimitry Andric DebugInfoFinder *DIFinder) {
4859850d08SRoman Divacky BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "", F);
49b1c73532SDimitry Andric NewBB->IsNewDbgInfoFormat = BB->IsNewDbgInfoFormat;
50eb11fae6SDimitry Andric if (BB->hasName())
51eb11fae6SDimitry Andric NewBB->setName(BB->getName() + NameSuffix);
52009b1c42SEd Schouten
53e3b55780SDimitry Andric bool hasCalls = false, hasDynamicAllocas = false, hasMemProfMetadata = false;
54ca089b24SDimitry Andric Module *TheModule = F ? F->getParent() : nullptr;
55009b1c42SEd Schouten
56009b1c42SEd Schouten // Loop over all instructions, and copy them over.
57eb11fae6SDimitry Andric for (const Instruction &I : *BB) {
58eb11fae6SDimitry Andric if (DIFinder && TheModule)
59eb11fae6SDimitry Andric DIFinder->processInstruction(*TheModule, I);
60d288ef4cSDimitry Andric
61eb11fae6SDimitry Andric Instruction *NewInst = I.clone();
62eb11fae6SDimitry Andric if (I.hasName())
63eb11fae6SDimitry Andric NewInst->setName(I.getName() + NameSuffix);
64b1c73532SDimitry Andric
65b1c73532SDimitry Andric NewInst->insertBefore(*NewBB, NewBB->end());
66b1c73532SDimitry Andric NewInst->cloneDebugInfoFrom(&I);
67b1c73532SDimitry Andric
68eb11fae6SDimitry Andric VMap[&I] = NewInst; // Add instruction map to value.
69009b1c42SEd Schouten
70e3b55780SDimitry Andric if (isa<CallInst>(I) && !I.isDebugOrPseudoInst()) {
71e3b55780SDimitry Andric hasCalls = true;
72e3b55780SDimitry Andric hasMemProfMetadata |= I.hasMetadata(LLVMContext::MD_memprof);
73e3b55780SDimitry Andric }
74eb11fae6SDimitry Andric if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
75cfca06d7SDimitry Andric if (!AI->isStaticAlloca()) {
76009b1c42SEd Schouten hasDynamicAllocas = true;
77009b1c42SEd Schouten }
78009b1c42SEd Schouten }
79cfca06d7SDimitry Andric }
80009b1c42SEd Schouten
81009b1c42SEd Schouten if (CodeInfo) {
82009b1c42SEd Schouten CodeInfo->ContainsCalls |= hasCalls;
83e3b55780SDimitry Andric CodeInfo->ContainsMemProfMetadata |= hasMemProfMetadata;
84009b1c42SEd Schouten CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
85009b1c42SEd Schouten }
86009b1c42SEd Schouten return NewBB;
87009b1c42SEd Schouten }
88009b1c42SEd Schouten
89009b1c42SEd Schouten // Clone OldFunc into NewFunc, transforming the old arguments into references to
90d39c594dSDimitry Andric // VMap values.
91009b1c42SEd Schouten //
CloneFunctionInto(Function * NewFunc,const Function * OldFunc,ValueToValueMapTy & VMap,CloneFunctionChangeType Changes,SmallVectorImpl<ReturnInst * > & Returns,const char * NameSuffix,ClonedCodeInfo * CodeInfo,ValueMapTypeRemapper * TypeMapper,ValueMaterializer * Materializer)92009b1c42SEd Schouten void llvm::CloneFunctionInto(Function *NewFunc, const Function *OldFunc,
9366e41e3cSRoman Divacky ValueToValueMapTy &VMap,
94344a3780SDimitry Andric CloneFunctionChangeType Changes,
9559850d08SRoman Divacky SmallVectorImpl<ReturnInst *> &Returns,
9663faed5bSDimitry Andric const char *NameSuffix, ClonedCodeInfo *CodeInfo,
97f8af5cf6SDimitry Andric ValueMapTypeRemapper *TypeMapper,
98f8af5cf6SDimitry Andric ValueMaterializer *Materializer) {
99b1c73532SDimitry Andric NewFunc->setIsNewDbgInfoFormat(OldFunc->IsNewDbgInfoFormat);
100009b1c42SEd Schouten assert(NameSuffix && "NameSuffix cannot be null!");
101009b1c42SEd Schouten
102009b1c42SEd Schouten #ifndef NDEBUG
103dd58ef01SDimitry Andric for (const Argument &I : OldFunc->args())
104dd58ef01SDimitry Andric assert(VMap.count(&I) && "No mapping from source argument specified!");
105009b1c42SEd Schouten #endif
106009b1c42SEd Schouten
107344a3780SDimitry Andric bool ModuleLevelChanges = Changes > CloneFunctionChangeType::LocalChangesOnly;
108344a3780SDimitry Andric
10971d5a254SDimitry Andric // Copy all attributes other than those stored in the AttributeList. We need
11071d5a254SDimitry Andric // to remap the parameter indices of the AttributeList.
11171d5a254SDimitry Andric AttributeList NewAttrs = NewFunc->getAttributes();
1125ca98fd9SDimitry Andric NewFunc->copyAttributesFrom(OldFunc);
1135ca98fd9SDimitry Andric NewFunc->setAttributes(NewAttrs);
1145ca98fd9SDimitry Andric
115e3b55780SDimitry Andric const RemapFlags FuncGlobalRefFlags =
116e3b55780SDimitry Andric ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges;
117e3b55780SDimitry Andric
118dd58ef01SDimitry Andric // Fix up the personality function that got copied over.
119dd58ef01SDimitry Andric if (OldFunc->hasPersonalityFn())
120e3b55780SDimitry Andric NewFunc->setPersonalityFn(MapValue(OldFunc->getPersonalityFn(), VMap,
121e3b55780SDimitry Andric FuncGlobalRefFlags, TypeMapper,
122e3b55780SDimitry Andric Materializer));
123e3b55780SDimitry Andric
124e3b55780SDimitry Andric if (OldFunc->hasPrefixData()) {
125e3b55780SDimitry Andric NewFunc->setPrefixData(MapValue(OldFunc->getPrefixData(), VMap,
126e3b55780SDimitry Andric FuncGlobalRefFlags, TypeMapper,
127e3b55780SDimitry Andric Materializer));
128e3b55780SDimitry Andric }
129e3b55780SDimitry Andric
130e3b55780SDimitry Andric if (OldFunc->hasPrologueData()) {
131e3b55780SDimitry Andric NewFunc->setPrologueData(MapValue(OldFunc->getPrologueData(), VMap,
132e3b55780SDimitry Andric FuncGlobalRefFlags, TypeMapper,
133e3b55780SDimitry Andric Materializer));
134e3b55780SDimitry Andric }
135dd58ef01SDimitry Andric
13671d5a254SDimitry Andric SmallVector<AttributeSet, 4> NewArgAttrs(NewFunc->arg_size());
13771d5a254SDimitry Andric AttributeList OldAttrs = OldFunc->getAttributes();
13871d5a254SDimitry Andric
13959d6cff9SDimitry Andric // Clone any argument attributes that are present in the VMap.
14071d5a254SDimitry Andric for (const Argument &OldArg : OldFunc->args()) {
1415ca98fd9SDimitry Andric if (Argument *NewArg = dyn_cast<Argument>(VMap[&OldArg])) {
14271d5a254SDimitry Andric NewArgAttrs[NewArg->getArgNo()] =
143c0981da4SDimitry Andric OldAttrs.getParamAttrs(OldArg.getArgNo());
14471d5a254SDimitry Andric }
1454a16efa3SDimitry Andric }
14659d6cff9SDimitry Andric
1475ca98fd9SDimitry Andric NewFunc->setAttributes(
148c0981da4SDimitry Andric AttributeList::get(NewFunc->getContext(), OldAttrs.getFnAttrs(),
149c0981da4SDimitry Andric OldAttrs.getRetAttrs(), NewArgAttrs));
150009b1c42SEd Schouten
151b60736ecSDimitry Andric // Everything else beyond this point deals with function instructions,
152b60736ecSDimitry Andric // so if we are dealing with a function declaration, we're done.
153b60736ecSDimitry Andric if (OldFunc->isDeclaration())
154b60736ecSDimitry Andric return;
15501095a5dSDimitry Andric
156344a3780SDimitry Andric // When we remap instructions within the same module, we want to avoid
157344a3780SDimitry Andric // duplicating inlined DISubprograms, so record all subprograms we find as we
158344a3780SDimitry Andric // duplicate instructions and then freeze them in the MD map. We also record
159344a3780SDimitry Andric // information about dbg.value and dbg.declare to avoid duplicating the
160344a3780SDimitry Andric // types.
161e3b55780SDimitry Andric std::optional<DebugInfoFinder> DIFinder;
162344a3780SDimitry Andric
163344a3780SDimitry Andric // Track the subprogram attachment that needs to be cloned to fine-tune the
164344a3780SDimitry Andric // mapping within the same module.
165344a3780SDimitry Andric DISubprogram *SPClonedWithinModule = nullptr;
166344a3780SDimitry Andric if (Changes < CloneFunctionChangeType::DifferentModule) {
167344a3780SDimitry Andric assert((NewFunc->getParent() == nullptr ||
168344a3780SDimitry Andric NewFunc->getParent() == OldFunc->getParent()) &&
169344a3780SDimitry Andric "Expected NewFunc to have the same parent, or no parent");
170344a3780SDimitry Andric
171344a3780SDimitry Andric // Need to find subprograms, types, and compile units.
172344a3780SDimitry Andric DIFinder.emplace();
173344a3780SDimitry Andric
174344a3780SDimitry Andric SPClonedWithinModule = OldFunc->getSubprogram();
175344a3780SDimitry Andric if (SPClonedWithinModule)
176344a3780SDimitry Andric DIFinder->processSubprogram(SPClonedWithinModule);
177344a3780SDimitry Andric } else {
178344a3780SDimitry Andric assert((NewFunc->getParent() == nullptr ||
179344a3780SDimitry Andric NewFunc->getParent() != OldFunc->getParent()) &&
180344a3780SDimitry Andric "Expected NewFunc to have different parents, or no parent");
181344a3780SDimitry Andric
182344a3780SDimitry Andric if (Changes == CloneFunctionChangeType::DifferentModule) {
183344a3780SDimitry Andric assert(NewFunc->getParent() &&
184344a3780SDimitry Andric "Need parent of new function to maintain debug info invariants");
185344a3780SDimitry Andric
186344a3780SDimitry Andric // Need to find all the compile units.
187344a3780SDimitry Andric DIFinder.emplace();
188344a3780SDimitry Andric }
189344a3780SDimitry Andric }
190d288ef4cSDimitry Andric
191009b1c42SEd Schouten // Loop over all of the basic blocks in the function, cloning them as
192009b1c42SEd Schouten // appropriate. Note that we save BE this way in order to handle cloning of
193009b1c42SEd Schouten // recursive functions into themselves.
194344a3780SDimitry Andric for (const BasicBlock &BB : *OldFunc) {
195009b1c42SEd Schouten
196009b1c42SEd Schouten // Create a new basic block and copy instructions into it!
197d288ef4cSDimitry Andric BasicBlock *CBB = CloneBasicBlock(&BB, VMap, NameSuffix, NewFunc, CodeInfo,
198344a3780SDimitry Andric DIFinder ? &*DIFinder : nullptr);
199009b1c42SEd Schouten
20063faed5bSDimitry Andric // Add basic block mapping.
20163faed5bSDimitry Andric VMap[&BB] = CBB;
20263faed5bSDimitry Andric
20363faed5bSDimitry Andric // It is only legal to clone a function if a block address within that
20463faed5bSDimitry Andric // function is never referenced outside of the function. Given that, we
20563faed5bSDimitry Andric // want to map block addresses from the old function to block addresses in
20663faed5bSDimitry Andric // the clone. (This is different from the generic ValueMapper
20763faed5bSDimitry Andric // implementation, which generates an invalid blockaddress when
20863faed5bSDimitry Andric // cloning a function.)
20963faed5bSDimitry Andric if (BB.hasAddressTaken()) {
21063faed5bSDimitry Andric Constant *OldBBAddr = BlockAddress::get(const_cast<Function *>(OldFunc),
21163faed5bSDimitry Andric const_cast<BasicBlock *>(&BB));
21263faed5bSDimitry Andric VMap[OldBBAddr] = BlockAddress::get(NewFunc, CBB);
21363faed5bSDimitry Andric }
21463faed5bSDimitry Andric
21563faed5bSDimitry Andric // Note return instructions for the caller.
216009b1c42SEd Schouten if (ReturnInst *RI = dyn_cast<ReturnInst>(CBB->getTerminator()))
217009b1c42SEd Schouten Returns.push_back(RI);
218009b1c42SEd Schouten }
219009b1c42SEd Schouten
220344a3780SDimitry Andric if (Changes < CloneFunctionChangeType::DifferentModule &&
221344a3780SDimitry Andric DIFinder->subprogram_count() > 0) {
222344a3780SDimitry Andric // Turn on module-level changes, since we need to clone (some of) the
223344a3780SDimitry Andric // debug info metadata.
224344a3780SDimitry Andric //
225344a3780SDimitry Andric // FIXME: Metadata effectively owned by a function should be made
226344a3780SDimitry Andric // local, and only that local metadata should be cloned.
227344a3780SDimitry Andric ModuleLevelChanges = true;
228d288ef4cSDimitry Andric
229344a3780SDimitry Andric auto mapToSelfIfNew = [&VMap](MDNode *N) {
230344a3780SDimitry Andric // Avoid clobbering an existing mapping.
231344a3780SDimitry Andric (void)VMap.MD().try_emplace(N, N);
232344a3780SDimitry Andric };
233eb11fae6SDimitry Andric
234344a3780SDimitry Andric // Avoid cloning types, compile units, and (other) subprograms.
2354b4fe385SDimitry Andric SmallPtrSet<const DISubprogram *, 16> MappedToSelfSPs;
2364b4fe385SDimitry Andric for (DISubprogram *ISP : DIFinder->subprograms()) {
2374b4fe385SDimitry Andric if (ISP != SPClonedWithinModule) {
238344a3780SDimitry Andric mapToSelfIfNew(ISP);
2394b4fe385SDimitry Andric MappedToSelfSPs.insert(ISP);
2404b4fe385SDimitry Andric }
2414b4fe385SDimitry Andric }
2424b4fe385SDimitry Andric
2434b4fe385SDimitry Andric // If a subprogram isn't going to be cloned skip its lexical blocks as well.
2444b4fe385SDimitry Andric for (DIScope *S : DIFinder->scopes()) {
2454b4fe385SDimitry Andric auto *LScope = dyn_cast<DILocalScope>(S);
2464b4fe385SDimitry Andric if (LScope && MappedToSelfSPs.count(LScope->getSubprogram()))
2474b4fe385SDimitry Andric mapToSelfIfNew(S);
2484b4fe385SDimitry Andric }
249ca089b24SDimitry Andric
250344a3780SDimitry Andric for (DICompileUnit *CU : DIFinder->compile_units())
251344a3780SDimitry Andric mapToSelfIfNew(CU);
252344a3780SDimitry Andric
253344a3780SDimitry Andric for (DIType *Type : DIFinder->types())
254344a3780SDimitry Andric mapToSelfIfNew(Type);
255344a3780SDimitry Andric } else {
256344a3780SDimitry Andric assert(!SPClonedWithinModule &&
257344a3780SDimitry Andric "Subprogram should be in DIFinder->subprogram_count()...");
258344a3780SDimitry Andric }
259344a3780SDimitry Andric
260344a3780SDimitry Andric const auto RemapFlag = ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges;
261b60736ecSDimitry Andric // Duplicate the metadata that is attached to the cloned function.
262b60736ecSDimitry Andric // Subprograms/CUs/types that were already mapped to themselves won't be
263b60736ecSDimitry Andric // duplicated.
264b60736ecSDimitry Andric SmallVector<std::pair<unsigned, MDNode *>, 1> MDs;
265b60736ecSDimitry Andric OldFunc->getAllMetadata(MDs);
266b60736ecSDimitry Andric for (auto MD : MDs) {
267344a3780SDimitry Andric NewFunc->addMetadata(MD.first, *MapMetadata(MD.second, VMap, RemapFlag,
268b60736ecSDimitry Andric TypeMapper, Materializer));
269b60736ecSDimitry Andric }
270b60736ecSDimitry Andric
271344a3780SDimitry Andric // Loop over all of the instructions in the new function, fixing up operand
27266e41e3cSRoman Divacky // references as we go. This uses VMap to do all the hard work.
273344a3780SDimitry Andric for (Function::iterator
274344a3780SDimitry Andric BB = cast<BasicBlock>(VMap[&OldFunc->front()])->getIterator(),
275dd58ef01SDimitry Andric BE = NewFunc->end();
276dd58ef01SDimitry Andric BB != BE; ++BB)
277b1c73532SDimitry Andric // Loop over all instructions, fixing each one as we find it, and any
278b1c73532SDimitry Andric // attached debug-info records.
279b1c73532SDimitry Andric for (Instruction &II : *BB) {
280344a3780SDimitry Andric RemapInstruction(&II, VMap, RemapFlag, TypeMapper, Materializer);
281ac9a064cSDimitry Andric RemapDbgRecordRange(II.getModule(), II.getDbgRecordRange(), VMap,
282ac9a064cSDimitry Andric RemapFlag, TypeMapper, Materializer);
283b1c73532SDimitry Andric }
2841d5ae102SDimitry Andric
285344a3780SDimitry Andric // Only update !llvm.dbg.cu for DifferentModule (not CloneModule). In the
286344a3780SDimitry Andric // same module, the compile unit will already be listed (or not). When
287344a3780SDimitry Andric // cloning a module, CloneModule() will handle creating the named metadata.
288344a3780SDimitry Andric if (Changes != CloneFunctionChangeType::DifferentModule)
289344a3780SDimitry Andric return;
290344a3780SDimitry Andric
291344a3780SDimitry Andric // Update !llvm.dbg.cu with compile units added to the new module if this
292344a3780SDimitry Andric // function is being cloned in isolation.
293344a3780SDimitry Andric //
294344a3780SDimitry Andric // FIXME: This is making global / module-level changes, which doesn't seem
295344a3780SDimitry Andric // like the right encapsulation Consider dropping the requirement to update
296344a3780SDimitry Andric // !llvm.dbg.cu (either obsoleting the node, or restricting it to
297344a3780SDimitry Andric // non-discardable compile units) instead of discovering compile units by
298344a3780SDimitry Andric // visiting the metadata attached to global values, which would allow this
299344a3780SDimitry Andric // code to be deleted. Alternatively, perhaps give responsibility for this
300344a3780SDimitry Andric // update to CloneFunctionInto's callers.
3011d5ae102SDimitry Andric auto *NewModule = NewFunc->getParent();
3021d5ae102SDimitry Andric auto *NMD = NewModule->getOrInsertNamedMetadata("llvm.dbg.cu");
3031d5ae102SDimitry Andric // Avoid multiple insertions of the same DICompileUnit to NMD.
3041d5ae102SDimitry Andric SmallPtrSet<const void *, 8> Visited;
3051d5ae102SDimitry Andric for (auto *Operand : NMD->operands())
3061d5ae102SDimitry Andric Visited.insert(Operand);
307344a3780SDimitry Andric for (auto *Unit : DIFinder->compile_units()) {
308344a3780SDimitry Andric MDNode *MappedUnit =
309344a3780SDimitry Andric MapMetadata(Unit, VMap, RF_None, TypeMapper, Materializer);
310344a3780SDimitry Andric if (Visited.insert(MappedUnit).second)
311344a3780SDimitry Andric NMD->addOperand(MappedUnit);
3121d5ae102SDimitry Andric }
313009b1c42SEd Schouten }
314009b1c42SEd Schouten
31501095a5dSDimitry Andric /// Return a copy of the specified function and add it to that function's
31601095a5dSDimitry Andric /// module. Also, any references specified in the VMap are changed to refer to
31701095a5dSDimitry Andric /// their mapped value instead of the original one. If any of the arguments to
31801095a5dSDimitry Andric /// the function are in the VMap, the arguments are deleted from the resultant
31901095a5dSDimitry Andric /// function. The VMap is updated to include mappings from all of the
32001095a5dSDimitry Andric /// instructions and basicblocks in the function from their old to new values.
321009b1c42SEd Schouten ///
CloneFunction(Function * F,ValueToValueMapTy & VMap,ClonedCodeInfo * CodeInfo)32201095a5dSDimitry Andric Function *llvm::CloneFunction(Function *F, ValueToValueMapTy &VMap,
323009b1c42SEd Schouten ClonedCodeInfo *CodeInfo) {
324411bd29eSDimitry Andric std::vector<Type *> ArgTypes;
325009b1c42SEd Schouten
326009b1c42SEd Schouten // The user might be deleting arguments to the function by specifying them in
32766e41e3cSRoman Divacky // the VMap. If so, we need to not add the arguments to the arg ty vector
328009b1c42SEd Schouten //
329dd58ef01SDimitry Andric for (const Argument &I : F->args())
330dd58ef01SDimitry Andric if (VMap.count(&I) == 0) // Haven't mapped the argument to anything yet?
331dd58ef01SDimitry Andric ArgTypes.push_back(I.getType());
332009b1c42SEd Schouten
333009b1c42SEd Schouten // Create a new function type...
334344a3780SDimitry Andric FunctionType *FTy =
335344a3780SDimitry Andric FunctionType::get(F->getFunctionType()->getReturnType(), ArgTypes,
336344a3780SDimitry Andric F->getFunctionType()->isVarArg());
337009b1c42SEd Schouten
338009b1c42SEd Schouten // Create the new function...
339d8e91e46SDimitry Andric Function *NewF = Function::Create(FTy, F->getLinkage(), F->getAddressSpace(),
340d8e91e46SDimitry Andric F->getName(), F->getParent());
341b1c73532SDimitry Andric NewF->setIsNewDbgInfoFormat(F->IsNewDbgInfoFormat);
342009b1c42SEd Schouten
343009b1c42SEd Schouten // Loop over the arguments, copying the names of the mapped arguments over...
344009b1c42SEd Schouten Function::arg_iterator DestI = NewF->arg_begin();
345dd58ef01SDimitry Andric for (const Argument &I : F->args())
346dd58ef01SDimitry Andric if (VMap.count(&I) == 0) { // Is this argument preserved?
347dd58ef01SDimitry Andric DestI->setName(I.getName()); // Copy the name over...
348dd58ef01SDimitry Andric VMap[&I] = &*DestI++; // Add mapping to VMap
349009b1c42SEd Schouten }
350009b1c42SEd Schouten
35159850d08SRoman Divacky SmallVector<ReturnInst *, 8> Returns; // Ignore returns cloned.
352344a3780SDimitry Andric CloneFunctionInto(NewF, F, VMap, CloneFunctionChangeType::LocalChangesOnly,
353344a3780SDimitry Andric Returns, "", CodeInfo);
35401095a5dSDimitry Andric
355009b1c42SEd Schouten return NewF;
356009b1c42SEd Schouten }
357009b1c42SEd Schouten
358009b1c42SEd Schouten namespace {
3595a5ac124SDimitry Andric /// This is a private class used to implement CloneAndPruneFunctionInto.
36036bf506aSRoman Divacky struct PruningFunctionCloner {
361009b1c42SEd Schouten Function *NewFunc;
362009b1c42SEd Schouten const Function *OldFunc;
36366e41e3cSRoman Divacky ValueToValueMapTy &VMap;
364d39c594dSDimitry Andric bool ModuleLevelChanges;
365009b1c42SEd Schouten const char *NameSuffix;
366009b1c42SEd Schouten ClonedCodeInfo *CodeInfo;
367145449b1SDimitry Andric bool HostFuncIsStrictFP;
368145449b1SDimitry Andric
369145449b1SDimitry Andric Instruction *cloneInstruction(BasicBlock::const_iterator II);
3705a5ac124SDimitry Andric
371009b1c42SEd Schouten public:
PruningFunctionCloner__anon078740ba0211::PruningFunctionCloner372009b1c42SEd Schouten PruningFunctionCloner(Function *newFunc, const Function *oldFunc,
3735a5ac124SDimitry Andric ValueToValueMapTy &valueMap, bool moduleLevelChanges,
374050e163aSDimitry Andric const char *nameSuffix, ClonedCodeInfo *codeInfo)
3755a5ac124SDimitry Andric : NewFunc(newFunc), OldFunc(oldFunc), VMap(valueMap),
3765a5ac124SDimitry Andric ModuleLevelChanges(moduleLevelChanges), NameSuffix(nameSuffix),
377145449b1SDimitry Andric CodeInfo(codeInfo) {
378145449b1SDimitry Andric HostFuncIsStrictFP =
379145449b1SDimitry Andric newFunc->getAttributes().hasFnAttr(Attribute::StrictFP);
380145449b1SDimitry Andric }
381009b1c42SEd Schouten
3825a5ac124SDimitry Andric /// The specified block is found to be reachable, clone it and
383009b1c42SEd Schouten /// anything that it can reach.
384344a3780SDimitry Andric void CloneBlock(const BasicBlock *BB, BasicBlock::const_iterator StartingInst,
385009b1c42SEd Schouten std::vector<const BasicBlock *> &ToClone);
386009b1c42SEd Schouten };
387344a3780SDimitry Andric } // namespace
388009b1c42SEd Schouten
389145449b1SDimitry Andric Instruction *
cloneInstruction(BasicBlock::const_iterator II)390145449b1SDimitry Andric PruningFunctionCloner::cloneInstruction(BasicBlock::const_iterator II) {
391145449b1SDimitry Andric const Instruction &OldInst = *II;
392145449b1SDimitry Andric Instruction *NewInst = nullptr;
393145449b1SDimitry Andric if (HostFuncIsStrictFP) {
394145449b1SDimitry Andric Intrinsic::ID CIID = getConstrainedIntrinsicID(OldInst);
395145449b1SDimitry Andric if (CIID != Intrinsic::not_intrinsic) {
396145449b1SDimitry Andric // Instead of cloning the instruction, a call to constrained intrinsic
397145449b1SDimitry Andric // should be created.
398145449b1SDimitry Andric // Assume the first arguments of constrained intrinsics are the same as
399145449b1SDimitry Andric // the operands of original instruction.
400145449b1SDimitry Andric
401145449b1SDimitry Andric // Determine overloaded types of the intrinsic.
402145449b1SDimitry Andric SmallVector<Type *, 2> TParams;
403145449b1SDimitry Andric SmallVector<Intrinsic::IITDescriptor, 8> Descriptor;
404145449b1SDimitry Andric getIntrinsicInfoTableEntries(CIID, Descriptor);
405145449b1SDimitry Andric for (unsigned I = 0, E = Descriptor.size(); I != E; ++I) {
406145449b1SDimitry Andric Intrinsic::IITDescriptor Operand = Descriptor[I];
407145449b1SDimitry Andric switch (Operand.Kind) {
408145449b1SDimitry Andric case Intrinsic::IITDescriptor::Argument:
409145449b1SDimitry Andric if (Operand.getArgumentKind() !=
410145449b1SDimitry Andric Intrinsic::IITDescriptor::AK_MatchType) {
411145449b1SDimitry Andric if (I == 0)
412145449b1SDimitry Andric TParams.push_back(OldInst.getType());
413145449b1SDimitry Andric else
414145449b1SDimitry Andric TParams.push_back(OldInst.getOperand(I - 1)->getType());
415145449b1SDimitry Andric }
416145449b1SDimitry Andric break;
417145449b1SDimitry Andric case Intrinsic::IITDescriptor::SameVecWidthArgument:
418145449b1SDimitry Andric ++I;
419145449b1SDimitry Andric break;
420145449b1SDimitry Andric default:
421145449b1SDimitry Andric break;
422145449b1SDimitry Andric }
423145449b1SDimitry Andric }
424145449b1SDimitry Andric
425145449b1SDimitry Andric // Create intrinsic call.
426145449b1SDimitry Andric LLVMContext &Ctx = NewFunc->getContext();
427145449b1SDimitry Andric Function *IFn =
428145449b1SDimitry Andric Intrinsic::getDeclaration(NewFunc->getParent(), CIID, TParams);
429145449b1SDimitry Andric SmallVector<Value *, 4> Args;
430145449b1SDimitry Andric unsigned NumOperands = OldInst.getNumOperands();
431145449b1SDimitry Andric if (isa<CallInst>(OldInst))
432145449b1SDimitry Andric --NumOperands;
433145449b1SDimitry Andric for (unsigned I = 0; I < NumOperands; ++I) {
434145449b1SDimitry Andric Value *Op = OldInst.getOperand(I);
435145449b1SDimitry Andric Args.push_back(Op);
436145449b1SDimitry Andric }
437145449b1SDimitry Andric if (const auto *CmpI = dyn_cast<FCmpInst>(&OldInst)) {
438145449b1SDimitry Andric FCmpInst::Predicate Pred = CmpI->getPredicate();
439145449b1SDimitry Andric StringRef PredName = FCmpInst::getPredicateName(Pred);
440145449b1SDimitry Andric Args.push_back(MetadataAsValue::get(Ctx, MDString::get(Ctx, PredName)));
441145449b1SDimitry Andric }
442145449b1SDimitry Andric
443145449b1SDimitry Andric // The last arguments of a constrained intrinsic are metadata that
444145449b1SDimitry Andric // represent rounding mode (absents in some intrinsics) and exception
445145449b1SDimitry Andric // behavior. The inlined function uses default settings.
446ac9a064cSDimitry Andric if (Intrinsic::hasConstrainedFPRoundingModeOperand(CIID))
447145449b1SDimitry Andric Args.push_back(
448145449b1SDimitry Andric MetadataAsValue::get(Ctx, MDString::get(Ctx, "round.tonearest")));
449145449b1SDimitry Andric Args.push_back(
450145449b1SDimitry Andric MetadataAsValue::get(Ctx, MDString::get(Ctx, "fpexcept.ignore")));
451145449b1SDimitry Andric
452145449b1SDimitry Andric NewInst = CallInst::Create(IFn, Args, OldInst.getName() + ".strict");
453145449b1SDimitry Andric }
454145449b1SDimitry Andric }
455145449b1SDimitry Andric if (!NewInst)
456145449b1SDimitry Andric NewInst = II->clone();
457145449b1SDimitry Andric return NewInst;
458145449b1SDimitry Andric }
459145449b1SDimitry Andric
4605a5ac124SDimitry Andric /// The specified block is found to be reachable, clone it and
461009b1c42SEd Schouten /// anything that it can reach.
CloneBlock(const BasicBlock * BB,BasicBlock::const_iterator StartingInst,std::vector<const BasicBlock * > & ToClone)462344a3780SDimitry Andric void PruningFunctionCloner::CloneBlock(
463344a3780SDimitry Andric const BasicBlock *BB, BasicBlock::const_iterator StartingInst,
464009b1c42SEd Schouten std::vector<const BasicBlock *> &ToClone) {
465a303c417SDimitry Andric WeakTrackingVH &BBEntry = VMap[BB];
466009b1c42SEd Schouten
467009b1c42SEd Schouten // Have we already cloned this block?
468344a3780SDimitry Andric if (BBEntry)
469344a3780SDimitry Andric return;
470009b1c42SEd Schouten
471009b1c42SEd Schouten // Nope, clone it now.
472009b1c42SEd Schouten BasicBlock *NewBB;
4737fa27ce4SDimitry Andric Twine NewName(BB->hasName() ? Twine(BB->getName()) + NameSuffix : "");
4747fa27ce4SDimitry Andric BBEntry = NewBB = BasicBlock::Create(BB->getContext(), NewName, NewFunc);
475b1c73532SDimitry Andric NewBB->IsNewDbgInfoFormat = BB->IsNewDbgInfoFormat;
476009b1c42SEd Schouten
47763faed5bSDimitry Andric // It is only legal to clone a function if a block address within that
47863faed5bSDimitry Andric // function is never referenced outside of the function. Given that, we
47963faed5bSDimitry Andric // want to map block addresses from the old function to block addresses in
48063faed5bSDimitry Andric // the clone. (This is different from the generic ValueMapper
48163faed5bSDimitry Andric // implementation, which generates an invalid blockaddress when
48263faed5bSDimitry Andric // cloning a function.)
48363faed5bSDimitry Andric //
48463faed5bSDimitry Andric // Note that we don't need to fix the mapping for unreachable blocks;
48563faed5bSDimitry Andric // the default mapping there is safe.
48663faed5bSDimitry Andric if (BB->hasAddressTaken()) {
48763faed5bSDimitry Andric Constant *OldBBAddr = BlockAddress::get(const_cast<Function *>(OldFunc),
48863faed5bSDimitry Andric const_cast<BasicBlock *>(BB));
48963faed5bSDimitry Andric VMap[OldBBAddr] = BlockAddress::get(NewFunc, NewBB);
49063faed5bSDimitry Andric }
49163faed5bSDimitry Andric
492009b1c42SEd Schouten bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false;
493e3b55780SDimitry Andric bool hasMemProfMetadata = false;
494009b1c42SEd Schouten
495b1c73532SDimitry Andric // Keep a cursor pointing at the last place we cloned debug-info records from.
496b1c73532SDimitry Andric BasicBlock::const_iterator DbgCursor = StartingInst;
497b1c73532SDimitry Andric auto CloneDbgRecordsToHere =
498b1c73532SDimitry Andric [NewBB, &DbgCursor](Instruction *NewInst, BasicBlock::const_iterator II) {
499b1c73532SDimitry Andric if (!NewBB->IsNewDbgInfoFormat)
500b1c73532SDimitry Andric return;
501b1c73532SDimitry Andric
502b1c73532SDimitry Andric // Clone debug-info records onto this instruction. Iterate through any
503b1c73532SDimitry Andric // source-instructions we've cloned and then subsequently optimised
504b1c73532SDimitry Andric // away, so that their debug-info doesn't go missing.
505b1c73532SDimitry Andric for (; DbgCursor != II; ++DbgCursor)
506b1c73532SDimitry Andric NewInst->cloneDebugInfoFrom(&*DbgCursor, std::nullopt, false);
507b1c73532SDimitry Andric NewInst->cloneDebugInfoFrom(&*II);
508b1c73532SDimitry Andric DbgCursor = std::next(II);
509b1c73532SDimitry Andric };
510b1c73532SDimitry Andric
511009b1c42SEd Schouten // Loop over all instructions, and copy them over, DCE'ing as we go. This
512009b1c42SEd Schouten // loop doesn't include the terminator.
513344a3780SDimitry Andric for (BasicBlock::const_iterator II = StartingInst, IE = --BB->end(); II != IE;
514344a3780SDimitry Andric ++II) {
5155a5ac124SDimitry Andric
516145449b1SDimitry Andric Instruction *NewInst = cloneInstruction(II);
5177fa27ce4SDimitry Andric NewInst->insertInto(NewBB, NewBB->end());
518145449b1SDimitry Andric
519145449b1SDimitry Andric if (HostFuncIsStrictFP) {
520145449b1SDimitry Andric // All function calls in the inlined function must get 'strictfp'
521145449b1SDimitry Andric // attribute to prevent undesirable optimizations.
522145449b1SDimitry Andric if (auto *Call = dyn_cast<CallInst>(NewInst))
523145449b1SDimitry Andric Call->addFnAttr(Attribute::StrictFP);
524145449b1SDimitry Andric }
52563faed5bSDimitry Andric
52663faed5bSDimitry Andric // Eagerly remap operands to the newly cloned instruction, except for PHI
527e3b55780SDimitry Andric // nodes for which we defer processing until we update the CFG. Also defer
528e3b55780SDimitry Andric // debug intrinsic processing because they may contain use-before-defs.
529e3b55780SDimitry Andric if (!isa<PHINode>(NewInst) && !isa<DbgVariableIntrinsic>(NewInst)) {
53063faed5bSDimitry Andric RemapInstruction(NewInst, VMap,
531050e163aSDimitry Andric ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
53263faed5bSDimitry Andric
533ac9a064cSDimitry Andric // Eagerly constant fold the newly cloned instruction. If successful, add
534ac9a064cSDimitry Andric // a mapping to the new value. Non-constant operands may be incomplete at
535ac9a064cSDimitry Andric // this stage, thus instruction simplification is performed after
536ac9a064cSDimitry Andric // processing phi-nodes.
537ac9a064cSDimitry Andric if (Value *V = ConstantFoldInstruction(
538ac9a064cSDimitry Andric NewInst, BB->getDataLayout())) {
539ac9a064cSDimitry Andric if (isInstructionTriviallyDead(NewInst)) {
540dd58ef01SDimitry Andric VMap[&*II] = V;
5417fa27ce4SDimitry Andric NewInst->eraseFromParent();
542009b1c42SEd Schouten continue;
543009b1c42SEd Schouten }
54463faed5bSDimitry Andric }
54501095a5dSDimitry Andric }
546009b1c42SEd Schouten
547009b1c42SEd Schouten if (II->hasName())
548009b1c42SEd Schouten NewInst->setName(II->getName() + NameSuffix);
549dd58ef01SDimitry Andric VMap[&*II] = NewInst; // Add instruction map to value.
550e3b55780SDimitry Andric if (isa<CallInst>(II) && !II->isDebugOrPseudoInst()) {
551e3b55780SDimitry Andric hasCalls = true;
552e3b55780SDimitry Andric hasMemProfMetadata |= II->hasMetadata(LLVMContext::MD_memprof);
553e3b55780SDimitry Andric }
554dd58ef01SDimitry Andric
555b1c73532SDimitry Andric CloneDbgRecordsToHere(NewInst, II);
556b1c73532SDimitry Andric
557344a3780SDimitry Andric if (CodeInfo) {
558344a3780SDimitry Andric CodeInfo->OrigVMap[&*II] = NewInst;
559cfca06d7SDimitry Andric if (auto *CB = dyn_cast<CallBase>(&*II))
560cfca06d7SDimitry Andric if (CB->hasOperandBundles())
561dd58ef01SDimitry Andric CodeInfo->OperandBundleCallSites.push_back(NewInst);
562344a3780SDimitry Andric }
563dd58ef01SDimitry Andric
564009b1c42SEd Schouten if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
565009b1c42SEd Schouten if (isa<ConstantInt>(AI->getArraySize()))
566009b1c42SEd Schouten hasStaticAllocas = true;
567009b1c42SEd Schouten else
568009b1c42SEd Schouten hasDynamicAllocas = true;
569009b1c42SEd Schouten }
570009b1c42SEd Schouten }
571009b1c42SEd Schouten
572009b1c42SEd Schouten // Finally, clone over the terminator.
573d8e91e46SDimitry Andric const Instruction *OldTI = BB->getTerminator();
574009b1c42SEd Schouten bool TerminatorDone = false;
575009b1c42SEd Schouten if (const BranchInst *BI = dyn_cast<BranchInst>(OldTI)) {
576009b1c42SEd Schouten if (BI->isConditional()) {
577009b1c42SEd Schouten // If the condition was a known constant in the callee...
578009b1c42SEd Schouten ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
579009b1c42SEd Schouten // Or is a known constant in the caller...
5805ca98fd9SDimitry Andric if (!Cond) {
58101095a5dSDimitry Andric Value *V = VMap.lookup(BI->getCondition());
582cf099d11SDimitry Andric Cond = dyn_cast_or_null<ConstantInt>(V);
583cf099d11SDimitry Andric }
584009b1c42SEd Schouten
585009b1c42SEd Schouten // Constant fold to uncond branch!
586009b1c42SEd Schouten if (Cond) {
587009b1c42SEd Schouten BasicBlock *Dest = BI->getSuccessor(!Cond->getZExtValue());
58866e41e3cSRoman Divacky VMap[OldTI] = BranchInst::Create(Dest, NewBB);
589009b1c42SEd Schouten ToClone.push_back(Dest);
590009b1c42SEd Schouten TerminatorDone = true;
591009b1c42SEd Schouten }
592009b1c42SEd Schouten }
593009b1c42SEd Schouten } else if (const SwitchInst *SI = dyn_cast<SwitchInst>(OldTI)) {
594009b1c42SEd Schouten // If switching on a value known constant in the caller.
595009b1c42SEd Schouten ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition());
5965ca98fd9SDimitry Andric if (!Cond) { // Or known constant after constant prop in the callee...
59701095a5dSDimitry Andric Value *V = VMap.lookup(SI->getCondition());
598cf099d11SDimitry Andric Cond = dyn_cast_or_null<ConstantInt>(V);
599cf099d11SDimitry Andric }
600009b1c42SEd Schouten if (Cond) { // Constant fold to uncond branch!
60171d5a254SDimitry Andric SwitchInst::ConstCaseHandle Case = *SI->findCaseValue(Cond);
60263faed5bSDimitry Andric BasicBlock *Dest = const_cast<BasicBlock *>(Case.getCaseSuccessor());
60366e41e3cSRoman Divacky VMap[OldTI] = BranchInst::Create(Dest, NewBB);
604009b1c42SEd Schouten ToClone.push_back(Dest);
605009b1c42SEd Schouten TerminatorDone = true;
606009b1c42SEd Schouten }
607009b1c42SEd Schouten }
608009b1c42SEd Schouten
609009b1c42SEd Schouten if (!TerminatorDone) {
610009b1c42SEd Schouten Instruction *NewInst = OldTI->clone();
611009b1c42SEd Schouten if (OldTI->hasName())
612009b1c42SEd Schouten NewInst->setName(OldTI->getName() + NameSuffix);
613e3b55780SDimitry Andric NewInst->insertInto(NewBB, NewBB->end());
614b1c73532SDimitry Andric
615b1c73532SDimitry Andric CloneDbgRecordsToHere(NewInst, OldTI->getIterator());
616b1c73532SDimitry Andric
61766e41e3cSRoman Divacky VMap[OldTI] = NewInst; // Add instruction map to value.
618009b1c42SEd Schouten
619344a3780SDimitry Andric if (CodeInfo) {
620344a3780SDimitry Andric CodeInfo->OrigVMap[OldTI] = NewInst;
621cfca06d7SDimitry Andric if (auto *CB = dyn_cast<CallBase>(OldTI))
622cfca06d7SDimitry Andric if (CB->hasOperandBundles())
623dd58ef01SDimitry Andric CodeInfo->OperandBundleCallSites.push_back(NewInst);
624344a3780SDimitry Andric }
625dd58ef01SDimitry Andric
626009b1c42SEd Schouten // Recursively clone any reachable successor blocks.
627b60736ecSDimitry Andric append_range(ToClone, successors(BB->getTerminator()));
628b1c73532SDimitry Andric } else {
629ac9a064cSDimitry Andric // If we didn't create a new terminator, clone DbgVariableRecords from the
630ac9a064cSDimitry Andric // old terminator onto the new terminator.
631b1c73532SDimitry Andric Instruction *NewInst = NewBB->getTerminator();
632b1c73532SDimitry Andric assert(NewInst);
633b1c73532SDimitry Andric
634b1c73532SDimitry Andric CloneDbgRecordsToHere(NewInst, OldTI->getIterator());
635009b1c42SEd Schouten }
636009b1c42SEd Schouten
637009b1c42SEd Schouten if (CodeInfo) {
638009b1c42SEd Schouten CodeInfo->ContainsCalls |= hasCalls;
639e3b55780SDimitry Andric CodeInfo->ContainsMemProfMetadata |= hasMemProfMetadata;
640009b1c42SEd Schouten CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
641344a3780SDimitry Andric CodeInfo->ContainsDynamicAllocas |=
642344a3780SDimitry Andric hasStaticAllocas && BB != &BB->getParent()->front();
643009b1c42SEd Schouten }
644907da171SRoman Divacky }
645907da171SRoman Divacky
6465a5ac124SDimitry Andric /// This works like CloneAndPruneFunctionInto, except that it does not clone the
6475a5ac124SDimitry Andric /// entire function. Instead it starts at an instruction provided by the caller
6485a5ac124SDimitry 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)6495a5ac124SDimitry Andric void llvm::CloneAndPruneIntoFromInst(Function *NewFunc, const Function *OldFunc,
6505a5ac124SDimitry Andric const Instruction *StartingInst,
65166e41e3cSRoman Divacky ValueToValueMapTy &VMap,
652d39c594dSDimitry Andric bool ModuleLevelChanges,
65359850d08SRoman Divacky SmallVectorImpl<ReturnInst *> &Returns,
654009b1c42SEd Schouten const char *NameSuffix,
655050e163aSDimitry Andric ClonedCodeInfo *CodeInfo) {
656009b1c42SEd Schouten assert(NameSuffix && "NameSuffix cannot be null!");
657009b1c42SEd Schouten
6585a5ac124SDimitry Andric ValueMapTypeRemapper *TypeMapper = nullptr;
6595a5ac124SDimitry Andric ValueMaterializer *Materializer = nullptr;
6605a5ac124SDimitry Andric
661009b1c42SEd Schouten #ifndef NDEBUG
662dd58ef01SDimitry Andric // If the cloning starts at the beginning of the function, verify that
6635a5ac124SDimitry Andric // the function arguments are mapped.
6645a5ac124SDimitry Andric if (!StartingInst)
665dd58ef01SDimitry Andric for (const Argument &II : OldFunc->args())
666dd58ef01SDimitry Andric assert(VMap.count(&II) && "No mapping from source argument specified!");
667009b1c42SEd Schouten #endif
668009b1c42SEd Schouten
669d39c594dSDimitry Andric PruningFunctionCloner PFC(NewFunc, OldFunc, VMap, ModuleLevelChanges,
670050e163aSDimitry Andric NameSuffix, CodeInfo);
6715a5ac124SDimitry Andric const BasicBlock *StartingBB;
6725a5ac124SDimitry Andric if (StartingInst)
6735a5ac124SDimitry Andric StartingBB = StartingInst->getParent();
6745a5ac124SDimitry Andric else {
6755a5ac124SDimitry Andric StartingBB = &OldFunc->getEntryBlock();
676dd58ef01SDimitry Andric StartingInst = &StartingBB->front();
6775a5ac124SDimitry Andric }
678009b1c42SEd Schouten
679e3b55780SDimitry Andric // Collect debug intrinsics for remapping later.
680e3b55780SDimitry Andric SmallVector<const DbgVariableIntrinsic *, 8> DbgIntrinsics;
681e3b55780SDimitry Andric for (const auto &BB : *OldFunc) {
682e3b55780SDimitry Andric for (const auto &I : BB) {
683e3b55780SDimitry Andric if (const auto *DVI = dyn_cast<DbgVariableIntrinsic>(&I))
684e3b55780SDimitry Andric DbgIntrinsics.push_back(DVI);
685e3b55780SDimitry Andric }
686e3b55780SDimitry Andric }
687e3b55780SDimitry Andric
688009b1c42SEd Schouten // Clone the entry block, and anything recursively reachable from it.
689009b1c42SEd Schouten std::vector<const BasicBlock *> CloneWorklist;
690dd58ef01SDimitry Andric PFC.CloneBlock(StartingBB, StartingInst->getIterator(), CloneWorklist);
691009b1c42SEd Schouten while (!CloneWorklist.empty()) {
692009b1c42SEd Schouten const BasicBlock *BB = CloneWorklist.back();
693009b1c42SEd Schouten CloneWorklist.pop_back();
6945a5ac124SDimitry Andric PFC.CloneBlock(BB, BB->begin(), CloneWorklist);
695009b1c42SEd Schouten }
696009b1c42SEd Schouten
697009b1c42SEd Schouten // Loop over all of the basic blocks in the old function. If the block was
698009b1c42SEd Schouten // reachable, we have cloned it and the old block is now in the value map:
699009b1c42SEd Schouten // insert it into the new function in the right order. If not, ignore it.
700009b1c42SEd Schouten //
701009b1c42SEd Schouten // Defer PHI resolution until rest of function is resolved.
70259850d08SRoman Divacky SmallVector<const PHINode *, 16> PHIToResolve;
703dd58ef01SDimitry Andric for (const BasicBlock &BI : *OldFunc) {
70401095a5dSDimitry Andric Value *V = VMap.lookup(&BI);
705cf099d11SDimitry Andric BasicBlock *NewBB = cast_or_null<BasicBlock>(V);
706344a3780SDimitry Andric if (!NewBB)
707344a3780SDimitry Andric continue; // Dead block.
708009b1c42SEd Schouten
7097fa27ce4SDimitry Andric // Move the new block to preserve the order in the original function.
7107fa27ce4SDimitry Andric NewBB->moveBefore(NewFunc->end());
711009b1c42SEd Schouten
712009b1c42SEd Schouten // Handle PHI nodes specially, as we have to remove references to dead
713009b1c42SEd Schouten // blocks.
714eb11fae6SDimitry Andric for (const PHINode &PN : BI.phis()) {
7155a5ac124SDimitry Andric // PHI nodes may have been remapped to non-PHI nodes by the caller or
7165a5ac124SDimitry Andric // during the cloning process.
717eb11fae6SDimitry Andric if (isa<PHINode>(VMap[&PN]))
718eb11fae6SDimitry Andric PHIToResolve.push_back(&PN);
71963faed5bSDimitry Andric else
72063faed5bSDimitry Andric break;
7215a5ac124SDimitry Andric }
7221e7804dbSRoman Divacky
72363faed5bSDimitry Andric // Finally, remap the terminator instructions, as those can't be remapped
72463faed5bSDimitry Andric // until all BBs are mapped.
72563faed5bSDimitry Andric RemapInstruction(NewBB->getTerminator(), VMap,
7265a5ac124SDimitry Andric ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
7275a5ac124SDimitry Andric TypeMapper, Materializer);
728009b1c42SEd Schouten }
729009b1c42SEd Schouten
730009b1c42SEd Schouten // Defer PHI resolution until rest of function is resolved, PHI resolution
731009b1c42SEd Schouten // requires the CFG to be up-to-date.
732009b1c42SEd Schouten for (unsigned phino = 0, e = PHIToResolve.size(); phino != e;) {
733009b1c42SEd Schouten const PHINode *OPN = PHIToResolve[phino];
734009b1c42SEd Schouten unsigned NumPreds = OPN->getNumIncomingValues();
735009b1c42SEd Schouten const BasicBlock *OldBB = OPN->getParent();
73666e41e3cSRoman Divacky BasicBlock *NewBB = cast<BasicBlock>(VMap[OldBB]);
737009b1c42SEd Schouten
738009b1c42SEd Schouten // Map operands for blocks that are live and remove operands for blocks
739009b1c42SEd Schouten // that are dead.
740009b1c42SEd Schouten for (; phino != PHIToResolve.size() &&
741344a3780SDimitry Andric PHIToResolve[phino]->getParent() == OldBB;
742344a3780SDimitry Andric ++phino) {
743009b1c42SEd Schouten OPN = PHIToResolve[phino];
74466e41e3cSRoman Divacky PHINode *PN = cast<PHINode>(VMap[OPN]);
745009b1c42SEd Schouten for (unsigned pred = 0, e = NumPreds; pred != e; ++pred) {
74601095a5dSDimitry Andric Value *V = VMap.lookup(PN->getIncomingBlock(pred));
747cf099d11SDimitry Andric if (BasicBlock *MappedBlock = cast_or_null<BasicBlock>(V)) {
748344a3780SDimitry Andric Value *InVal =
749344a3780SDimitry Andric MapValue(PN->getIncomingValue(pred), VMap,
750cf099d11SDimitry Andric ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
751009b1c42SEd Schouten assert(InVal && "Unknown input value?");
752009b1c42SEd Schouten PN->setIncomingValue(pred, InVal);
753009b1c42SEd Schouten PN->setIncomingBlock(pred, MappedBlock);
754009b1c42SEd Schouten } else {
755009b1c42SEd Schouten PN->removeIncomingValue(pred, false);
75601095a5dSDimitry Andric --pred; // Revisit the next entry.
75701095a5dSDimitry Andric --e;
758009b1c42SEd Schouten }
759009b1c42SEd Schouten }
760009b1c42SEd Schouten }
761009b1c42SEd Schouten
762009b1c42SEd Schouten // The loop above has removed PHI entries for those blocks that are dead
763009b1c42SEd Schouten // and has updated others. However, if a block is live (i.e. copied over)
764009b1c42SEd Schouten // but its terminator has been changed to not go to this block, then our
765009b1c42SEd Schouten // phi nodes will have invalid entries. Update the PHI nodes in this
766009b1c42SEd Schouten // case.
767009b1c42SEd Schouten PHINode *PN = cast<PHINode>(NewBB->begin());
768eb11fae6SDimitry Andric NumPreds = pred_size(NewBB);
769009b1c42SEd Schouten if (NumPreds != PN->getNumIncomingValues()) {
770009b1c42SEd Schouten assert(NumPreds < PN->getNumIncomingValues());
771009b1c42SEd Schouten // Count how many times each predecessor comes to this block.
772009b1c42SEd Schouten std::map<BasicBlock *, unsigned> PredCount;
773344a3780SDimitry Andric for (BasicBlock *Pred : predecessors(NewBB))
774344a3780SDimitry Andric --PredCount[Pred];
775009b1c42SEd Schouten
776009b1c42SEd Schouten // Figure out how many entries to remove from each PHI.
777009b1c42SEd Schouten for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
778009b1c42SEd Schouten ++PredCount[PN->getIncomingBlock(i)];
779009b1c42SEd Schouten
780009b1c42SEd Schouten // At this point, the excess predecessor entries are positive in the
781009b1c42SEd Schouten // map. Loop over all of the PHIs and remove excess predecessor
782009b1c42SEd Schouten // entries.
783009b1c42SEd Schouten BasicBlock::iterator I = NewBB->begin();
784009b1c42SEd Schouten for (; (PN = dyn_cast<PHINode>(I)); ++I) {
78501095a5dSDimitry Andric for (const auto &PCI : PredCount) {
78601095a5dSDimitry Andric BasicBlock *Pred = PCI.first;
78701095a5dSDimitry Andric for (unsigned NumToRemove = PCI.second; NumToRemove; --NumToRemove)
788009b1c42SEd Schouten PN->removeIncomingValue(Pred, false);
789009b1c42SEd Schouten }
790009b1c42SEd Schouten }
791009b1c42SEd Schouten }
792009b1c42SEd Schouten
793009b1c42SEd Schouten // If the loops above have made these phi nodes have 0 or 1 operand,
7944b4fe385SDimitry Andric // replace them with poison or the input value. We must do this for
795009b1c42SEd Schouten // correctness, because 0-operand phis are not valid.
796009b1c42SEd Schouten PN = cast<PHINode>(NewBB->begin());
797009b1c42SEd Schouten if (PN->getNumIncomingValues() == 0) {
798009b1c42SEd Schouten BasicBlock::iterator I = NewBB->begin();
799009b1c42SEd Schouten BasicBlock::const_iterator OldI = OldBB->begin();
800009b1c42SEd Schouten while ((PN = dyn_cast<PHINode>(I++))) {
8014b4fe385SDimitry Andric Value *NV = PoisonValue::get(PN->getType());
802009b1c42SEd Schouten PN->replaceAllUsesWith(NV);
803dd58ef01SDimitry Andric assert(VMap[&*OldI] == PN && "VMap mismatch");
804dd58ef01SDimitry Andric VMap[&*OldI] = NV;
805009b1c42SEd Schouten PN->eraseFromParent();
806009b1c42SEd Schouten ++OldI;
807009b1c42SEd Schouten }
808009b1c42SEd Schouten }
809009b1c42SEd Schouten }
810009b1c42SEd Schouten
811ac9a064cSDimitry Andric // Drop all incompatible return attributes that cannot be applied to NewFunc
812ac9a064cSDimitry Andric // during cloning, so as to allow instruction simplification to reason on the
813ac9a064cSDimitry Andric // old state of the function. The original attributes are restored later.
814ac9a064cSDimitry Andric AttributeMask IncompatibleAttrs =
815ac9a064cSDimitry Andric AttributeFuncs::typeIncompatible(OldFunc->getReturnType());
816ac9a064cSDimitry Andric AttributeList Attrs = NewFunc->getAttributes();
817ac9a064cSDimitry Andric NewFunc->removeRetAttrs(IncompatibleAttrs);
818a7fe922bSDimitry Andric
819ac9a064cSDimitry Andric // As phi-nodes have been now remapped, allow incremental simplification of
820ac9a064cSDimitry Andric // newly-cloned instructions.
821ac9a064cSDimitry Andric const DataLayout &DL = NewFunc->getDataLayout();
822ac9a064cSDimitry Andric for (const auto &BB : *OldFunc) {
823ac9a064cSDimitry Andric for (const auto &I : BB) {
824ac9a064cSDimitry Andric auto *NewI = dyn_cast_or_null<Instruction>(VMap.lookup(&I));
825ac9a064cSDimitry Andric if (!NewI)
826a7fe922bSDimitry Andric continue;
827a7fe922bSDimitry Andric
828ac9a064cSDimitry Andric if (Value *V = simplifyInstruction(NewI, DL)) {
829ac9a064cSDimitry Andric NewI->replaceAllUsesWith(V);
830887f1973SDimitry Andric
831ac9a064cSDimitry Andric if (isInstructionTriviallyDead(NewI)) {
832ac9a064cSDimitry Andric NewI->eraseFromParent();
833ac9a064cSDimitry Andric } else {
834ac9a064cSDimitry Andric // Did not erase it? Restore the new instruction into VMap previously
835ac9a064cSDimitry Andric // dropped by `ValueIsRAUWd`.
836ac9a064cSDimitry Andric VMap[&I] = NewI;
837a7fe922bSDimitry Andric }
838ac9a064cSDimitry Andric }
839ac9a064cSDimitry Andric }
840ac9a064cSDimitry Andric }
841ac9a064cSDimitry Andric
842ac9a064cSDimitry Andric // Restore attributes.
843ac9a064cSDimitry Andric NewFunc->setAttributes(Attrs);
84463faed5bSDimitry Andric
845e3b55780SDimitry Andric // Remap debug intrinsic operands now that all values have been mapped.
846e3b55780SDimitry Andric // Doing this now (late) preserves use-before-defs in debug intrinsics. If
847e3b55780SDimitry Andric // we didn't do this, ValueAsMetadata(use-before-def) operands would be
848e3b55780SDimitry Andric // replaced by empty metadata. This would signal later cleanup passes to
849e3b55780SDimitry Andric // remove the debug intrinsics, potentially causing incorrect locations.
850e3b55780SDimitry Andric for (const auto *DVI : DbgIntrinsics) {
851e3b55780SDimitry Andric if (DbgVariableIntrinsic *NewDVI =
852e3b55780SDimitry Andric cast_or_null<DbgVariableIntrinsic>(VMap.lookup(DVI)))
853e3b55780SDimitry Andric RemapInstruction(NewDVI, VMap,
854e3b55780SDimitry Andric ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
855e3b55780SDimitry Andric TypeMapper, Materializer);
856e3b55780SDimitry Andric }
857e3b55780SDimitry Andric
858ac9a064cSDimitry Andric // Do the same for DbgVariableRecords, touching all the instructions in the
859ac9a064cSDimitry Andric // cloned range of blocks.
860b1c73532SDimitry Andric Function::iterator Begin = cast<BasicBlock>(VMap[StartingBB])->getIterator();
861b1c73532SDimitry Andric for (BasicBlock &BB : make_range(Begin, NewFunc->end())) {
862b1c73532SDimitry Andric for (Instruction &I : BB) {
863ac9a064cSDimitry Andric RemapDbgRecordRange(I.getModule(), I.getDbgRecordRange(), VMap,
864ac9a064cSDimitry Andric ModuleLevelChanges ? RF_None
865ac9a064cSDimitry Andric : RF_NoModuleLevelChanges,
866b1c73532SDimitry Andric TypeMapper, Materializer);
867b1c73532SDimitry Andric }
868b1c73532SDimitry Andric }
869b1c73532SDimitry Andric
870ecbca9f5SDimitry Andric // Simplify conditional branches and switches with a constant operand. We try
871ecbca9f5SDimitry Andric // to prune these out when cloning, but if the simplification required
872ecbca9f5SDimitry Andric // looking through PHI nodes, those are only available after forming the full
873ecbca9f5SDimitry Andric // basic block. That may leave some here, and we still want to prune the dead
874ecbca9f5SDimitry Andric // code as early as possible.
875ecbca9f5SDimitry Andric for (BasicBlock &BB : make_range(Begin, NewFunc->end()))
876ecbca9f5SDimitry Andric ConstantFoldTerminator(&BB);
877ecbca9f5SDimitry Andric
878ecbca9f5SDimitry Andric // Some blocks may have become unreachable as a result. Find and delete them.
879ecbca9f5SDimitry Andric {
880ecbca9f5SDimitry Andric SmallPtrSet<BasicBlock *, 16> ReachableBlocks;
881ecbca9f5SDimitry Andric SmallVector<BasicBlock *, 16> Worklist;
882ecbca9f5SDimitry Andric Worklist.push_back(&*Begin);
883ecbca9f5SDimitry Andric while (!Worklist.empty()) {
884ecbca9f5SDimitry Andric BasicBlock *BB = Worklist.pop_back_val();
885ecbca9f5SDimitry Andric if (ReachableBlocks.insert(BB).second)
886ecbca9f5SDimitry Andric append_range(Worklist, successors(BB));
887ecbca9f5SDimitry Andric }
888ecbca9f5SDimitry Andric
889ecbca9f5SDimitry Andric SmallVector<BasicBlock *, 16> UnreachableBlocks;
890ecbca9f5SDimitry Andric for (BasicBlock &BB : make_range(Begin, NewFunc->end()))
891ecbca9f5SDimitry Andric if (!ReachableBlocks.contains(&BB))
892ecbca9f5SDimitry Andric UnreachableBlocks.push_back(&BB);
893ecbca9f5SDimitry Andric DeleteDeadBlocks(UnreachableBlocks);
894ecbca9f5SDimitry Andric }
895ecbca9f5SDimitry Andric
896009b1c42SEd Schouten // Now that the inlined function body has been fully constructed, go through
8975a5ac124SDimitry Andric // and zap unconditional fall-through branches. This happens all the time when
898009b1c42SEd Schouten // specializing code: code specialization turns conditional branches into
899009b1c42SEd Schouten // uncond branches, and this code folds them.
90063faed5bSDimitry Andric Function::iterator I = Begin;
901009b1c42SEd Schouten while (I != NewFunc->end()) {
902009b1c42SEd Schouten BranchInst *BI = dyn_cast<BranchInst>(I->getTerminator());
903344a3780SDimitry Andric if (!BI || BI->isConditional()) {
904344a3780SDimitry Andric ++I;
905344a3780SDimitry Andric continue;
906344a3780SDimitry Andric }
907009b1c42SEd Schouten
908009b1c42SEd Schouten BasicBlock *Dest = BI->getSuccessor(0);
90963faed5bSDimitry Andric if (!Dest->getSinglePredecessor()) {
910344a3780SDimitry Andric ++I;
911344a3780SDimitry Andric continue;
912009b1c42SEd Schouten }
913009b1c42SEd Schouten
91463faed5bSDimitry Andric // We shouldn't be able to get single-entry PHI nodes here, as instsimplify
91563faed5bSDimitry Andric // above should have zapped all of them..
91663faed5bSDimitry Andric assert(!isa<PHINode>(Dest->begin()));
91763faed5bSDimitry Andric
918009b1c42SEd Schouten // We know all single-entry PHI nodes in the inlined function have been
919009b1c42SEd Schouten // removed, so we just need to splice the blocks.
920009b1c42SEd Schouten BI->eraseFromParent();
921009b1c42SEd Schouten
922009b1c42SEd Schouten // Make all PHI nodes that referred to Dest now refer to I as their source.
923dd58ef01SDimitry Andric Dest->replaceAllUsesWith(&*I);
924009b1c42SEd Schouten
925411bd29eSDimitry Andric // Move all the instructions in the succ to the pred.
926e3b55780SDimitry Andric I->splice(I->end(), Dest);
927411bd29eSDimitry Andric
928009b1c42SEd Schouten // Remove the dest block.
929009b1c42SEd Schouten Dest->eraseFromParent();
930009b1c42SEd Schouten
931009b1c42SEd Schouten // Do not increment I, iteratively merge all things this block branches to.
932009b1c42SEd Schouten }
93363faed5bSDimitry Andric
9345a5ac124SDimitry Andric // Make a final pass over the basic blocks from the old function to gather
93563faed5bSDimitry Andric // any return instructions which survived folding. We have to do this here
93663faed5bSDimitry Andric // because we can iteratively remove and merge returns above.
937dd58ef01SDimitry Andric for (Function::iterator I = cast<BasicBlock>(VMap[StartingBB])->getIterator(),
93863faed5bSDimitry Andric E = NewFunc->end();
93963faed5bSDimitry Andric I != E; ++I)
94063faed5bSDimitry Andric if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator()))
94163faed5bSDimitry Andric Returns.push_back(RI);
942009b1c42SEd Schouten }
9435a5ac124SDimitry Andric
9445a5ac124SDimitry Andric /// This works exactly like CloneFunctionInto,
9455a5ac124SDimitry Andric /// except that it does some simple constant prop and DCE on the fly. The
9465a5ac124SDimitry Andric /// effect of this is to copy significantly less code in cases where (for
9475a5ac124SDimitry Andric /// example) a function call with constant arguments is inlined, and those
9485a5ac124SDimitry Andric /// constant arguments cause a significant amount of code in the callee to be
9495a5ac124SDimitry Andric /// dead. Since this doesn't produce an exact copy of the input, it can't be
9505a5ac124SDimitry 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)951344a3780SDimitry Andric void llvm::CloneAndPruneFunctionInto(
952344a3780SDimitry Andric Function *NewFunc, const Function *OldFunc, ValueToValueMapTy &VMap,
953344a3780SDimitry Andric bool ModuleLevelChanges, SmallVectorImpl<ReturnInst *> &Returns,
954344a3780SDimitry Andric const char *NameSuffix, ClonedCodeInfo *CodeInfo) {
955dd58ef01SDimitry Andric CloneAndPruneIntoFromInst(NewFunc, OldFunc, &OldFunc->front().front(), VMap,
956050e163aSDimitry Andric ModuleLevelChanges, Returns, NameSuffix, CodeInfo);
9575a5ac124SDimitry Andric }
958ee8648bdSDimitry Andric
959eb11fae6SDimitry Andric /// Remaps instructions in \p Blocks using the mapping in \p VMap.
remapInstructionsInBlocks(ArrayRef<BasicBlock * > Blocks,ValueToValueMapTy & VMap)9607fa27ce4SDimitry Andric void llvm::remapInstructionsInBlocks(ArrayRef<BasicBlock *> Blocks,
9617fa27ce4SDimitry Andric ValueToValueMapTy &VMap) {
962ee8648bdSDimitry Andric // Rewrite the code to refer to itself.
963b1c73532SDimitry Andric for (auto *BB : Blocks) {
964b1c73532SDimitry Andric for (auto &Inst : *BB) {
965ac9a064cSDimitry Andric RemapDbgRecordRange(Inst.getModule(), Inst.getDbgRecordRange(), VMap,
966b1c73532SDimitry Andric RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
967ee8648bdSDimitry Andric RemapInstruction(&Inst, VMap,
96801095a5dSDimitry Andric RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
969ee8648bdSDimitry Andric }
970b1c73532SDimitry Andric }
971b1c73532SDimitry Andric }
972ee8648bdSDimitry Andric
973eb11fae6SDimitry Andric /// Clones a loop \p OrigLoop. Returns the loop and the blocks in \p
974ee8648bdSDimitry Andric /// Blocks.
975ee8648bdSDimitry Andric ///
976ee8648bdSDimitry Andric /// Updates LoopInfo and DominatorTree assuming the loop is dominated by block
977ee8648bdSDimitry 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)978ee8648bdSDimitry Andric Loop *llvm::cloneLoopWithPreheader(BasicBlock *Before, BasicBlock *LoopDomBB,
979ee8648bdSDimitry Andric Loop *OrigLoop, ValueToValueMapTy &VMap,
980ee8648bdSDimitry Andric const Twine &NameSuffix, LoopInfo *LI,
981ee8648bdSDimitry Andric DominatorTree *DT,
982ee8648bdSDimitry Andric SmallVectorImpl<BasicBlock *> &Blocks) {
983ee8648bdSDimitry Andric Function *F = OrigLoop->getHeader()->getParent();
984ee8648bdSDimitry Andric Loop *ParentLoop = OrigLoop->getParentLoop();
985e6d15924SDimitry Andric DenseMap<Loop *, Loop *> LMap;
986ee8648bdSDimitry Andric
987044eb2f6SDimitry Andric Loop *NewLoop = LI->AllocateLoop();
988e6d15924SDimitry Andric LMap[OrigLoop] = NewLoop;
989ee8648bdSDimitry Andric if (ParentLoop)
990ee8648bdSDimitry Andric ParentLoop->addChildLoop(NewLoop);
991ee8648bdSDimitry Andric else
992ee8648bdSDimitry Andric LI->addTopLevelLoop(NewLoop);
993ee8648bdSDimitry Andric
994ee8648bdSDimitry Andric BasicBlock *OrigPH = OrigLoop->getLoopPreheader();
995ee8648bdSDimitry Andric assert(OrigPH && "No preheader");
996ee8648bdSDimitry Andric BasicBlock *NewPH = CloneBasicBlock(OrigPH, VMap, NameSuffix, F);
997ee8648bdSDimitry Andric // To rename the loop PHIs.
998ee8648bdSDimitry Andric VMap[OrigPH] = NewPH;
999ee8648bdSDimitry Andric Blocks.push_back(NewPH);
1000ee8648bdSDimitry Andric
1001ee8648bdSDimitry Andric // Update LoopInfo.
1002ee8648bdSDimitry Andric if (ParentLoop)
1003ee8648bdSDimitry Andric ParentLoop->addBasicBlockToLoop(NewPH, *LI);
1004ee8648bdSDimitry Andric
1005ee8648bdSDimitry Andric // Update DominatorTree.
1006ee8648bdSDimitry Andric DT->addNewBlock(NewPH, LoopDomBB);
1007ee8648bdSDimitry Andric
1008e6d15924SDimitry Andric for (Loop *CurLoop : OrigLoop->getLoopsInPreorder()) {
1009e6d15924SDimitry Andric Loop *&NewLoop = LMap[CurLoop];
1010e6d15924SDimitry Andric if (!NewLoop) {
1011e6d15924SDimitry Andric NewLoop = LI->AllocateLoop();
1012e6d15924SDimitry Andric
1013e6d15924SDimitry Andric // Establish the parent/child relationship.
1014e6d15924SDimitry Andric Loop *OrigParent = CurLoop->getParentLoop();
1015e6d15924SDimitry Andric assert(OrigParent && "Could not find the original parent loop");
1016e6d15924SDimitry Andric Loop *NewParentLoop = LMap[OrigParent];
1017e6d15924SDimitry Andric assert(NewParentLoop && "Could not find the new parent loop");
1018e6d15924SDimitry Andric
1019e6d15924SDimitry Andric NewParentLoop->addChildLoop(NewLoop);
1020e6d15924SDimitry Andric }
1021e6d15924SDimitry Andric }
1022e6d15924SDimitry Andric
1023ee8648bdSDimitry Andric for (BasicBlock *BB : OrigLoop->getBlocks()) {
1024e6d15924SDimitry Andric Loop *CurLoop = LI->getLoopFor(BB);
1025e6d15924SDimitry Andric Loop *&NewLoop = LMap[CurLoop];
1026e6d15924SDimitry Andric assert(NewLoop && "Expecting new loop to be allocated");
1027e6d15924SDimitry Andric
1028ee8648bdSDimitry Andric BasicBlock *NewBB = CloneBasicBlock(BB, VMap, NameSuffix, F);
1029ee8648bdSDimitry Andric VMap[BB] = NewBB;
1030ee8648bdSDimitry Andric
1031ee8648bdSDimitry Andric // Update LoopInfo.
1032ee8648bdSDimitry Andric NewLoop->addBasicBlockToLoop(NewBB, *LI);
1033ee8648bdSDimitry Andric
1034e6d15924SDimitry Andric // Add DominatorTree node. After seeing all blocks, update to correct
1035e6d15924SDimitry Andric // IDom.
103601095a5dSDimitry Andric DT->addNewBlock(NewBB, NewPH);
1037ee8648bdSDimitry Andric
1038ee8648bdSDimitry Andric Blocks.push_back(NewBB);
1039ee8648bdSDimitry Andric }
1040ee8648bdSDimitry Andric
104101095a5dSDimitry Andric for (BasicBlock *BB : OrigLoop->getBlocks()) {
1042cfca06d7SDimitry Andric // Update loop headers.
1043cfca06d7SDimitry Andric Loop *CurLoop = LI->getLoopFor(BB);
1044cfca06d7SDimitry Andric if (BB == CurLoop->getHeader())
1045cfca06d7SDimitry Andric LMap[CurLoop]->moveToHeader(cast<BasicBlock>(VMap[BB]));
1046cfca06d7SDimitry Andric
104701095a5dSDimitry Andric // Update DominatorTree.
104801095a5dSDimitry Andric BasicBlock *IDomBB = DT->getNode(BB)->getIDom()->getBlock();
104901095a5dSDimitry Andric DT->changeImmediateDominator(cast<BasicBlock>(VMap[BB]),
105001095a5dSDimitry Andric cast<BasicBlock>(VMap[IDomBB]));
105101095a5dSDimitry Andric }
105201095a5dSDimitry Andric
1053ee8648bdSDimitry Andric // Move them physically from the end of the block list.
1054e3b55780SDimitry Andric F->splice(Before->getIterator(), F, NewPH->getIterator());
1055e3b55780SDimitry Andric F->splice(Before->getIterator(), F, NewLoop->getHeader()->getIterator(),
1056e3b55780SDimitry Andric F->end());
1057ee8648bdSDimitry Andric
1058ee8648bdSDimitry Andric return NewLoop;
1059ee8648bdSDimitry Andric }
106071d5a254SDimitry Andric
1061eb11fae6SDimitry Andric /// Duplicate non-Phi instructions from the beginning of block up to
106271d5a254SDimitry Andric /// StopAt instruction into a split block between BB and its predecessor.
DuplicateInstructionsInSplitBetween(BasicBlock * BB,BasicBlock * PredBB,Instruction * StopAt,ValueToValueMapTy & ValueMapping,DomTreeUpdater & DTU)1063d8e91e46SDimitry Andric BasicBlock *llvm::DuplicateInstructionsInSplitBetween(
1064d8e91e46SDimitry Andric BasicBlock *BB, BasicBlock *PredBB, Instruction *StopAt,
1065d8e91e46SDimitry Andric ValueToValueMapTy &ValueMapping, DomTreeUpdater &DTU) {
1066d8e91e46SDimitry Andric
1067d8e91e46SDimitry Andric assert(count(successors(PredBB), BB) == 1 &&
1068d8e91e46SDimitry Andric "There must be a single edge between PredBB and BB!");
106971d5a254SDimitry Andric // We are going to have to map operands from the original BB block to the new
107071d5a254SDimitry Andric // copy of the block 'NewBB'. If there are PHI nodes in BB, evaluate them to
107171d5a254SDimitry Andric // account for entry from PredBB.
107271d5a254SDimitry Andric BasicBlock::iterator BI = BB->begin();
107371d5a254SDimitry Andric for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
107471d5a254SDimitry Andric ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
107571d5a254SDimitry Andric
1076d8e91e46SDimitry Andric BasicBlock *NewBB = SplitEdge(PredBB, BB);
107771d5a254SDimitry Andric NewBB->setName(PredBB->getName() + ".split");
107871d5a254SDimitry Andric Instruction *NewTerm = NewBB->getTerminator();
107971d5a254SDimitry Andric
1080d8e91e46SDimitry Andric // FIXME: SplitEdge does not yet take a DTU, so we include the split edge
1081d8e91e46SDimitry Andric // in the update set here.
1082d8e91e46SDimitry Andric DTU.applyUpdates({{DominatorTree::Delete, PredBB, BB},
1083d8e91e46SDimitry Andric {DominatorTree::Insert, PredBB, NewBB},
1084d8e91e46SDimitry Andric {DominatorTree::Insert, NewBB, BB}});
1085d8e91e46SDimitry Andric
108671d5a254SDimitry Andric // Clone the non-phi instructions of BB into NewBB, keeping track of the
108771d5a254SDimitry Andric // mapping and using it to remap operands in the cloned instructions.
1088eb11fae6SDimitry Andric // Stop once we see the terminator too. This covers the case where BB's
1089eb11fae6SDimitry Andric // terminator gets replaced and StopAt == BB's terminator.
1090eb11fae6SDimitry Andric for (; StopAt != &*BI && BB->getTerminator() != &*BI; ++BI) {
109171d5a254SDimitry Andric Instruction *New = BI->clone();
109271d5a254SDimitry Andric New->setName(BI->getName());
109371d5a254SDimitry Andric New->insertBefore(NewTerm);
1094b1c73532SDimitry Andric New->cloneDebugInfoFrom(&*BI);
109571d5a254SDimitry Andric ValueMapping[&*BI] = New;
109671d5a254SDimitry Andric
109771d5a254SDimitry Andric // Remap operands to patch up intra-block references.
109871d5a254SDimitry Andric for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
109971d5a254SDimitry Andric if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
110071d5a254SDimitry Andric auto I = ValueMapping.find(Inst);
110171d5a254SDimitry Andric if (I != ValueMapping.end())
110271d5a254SDimitry Andric New->setOperand(i, I->second);
110371d5a254SDimitry Andric }
1104ac9a064cSDimitry Andric
1105ac9a064cSDimitry Andric // Remap debug variable operands.
1106ac9a064cSDimitry Andric remapDebugVariable(ValueMapping, New);
110771d5a254SDimitry Andric }
110871d5a254SDimitry Andric
110971d5a254SDimitry Andric return NewBB;
111071d5a254SDimitry Andric }
1111b60736ecSDimitry Andric
cloneNoAliasScopes(ArrayRef<MDNode * > NoAliasDeclScopes,DenseMap<MDNode *,MDNode * > & ClonedScopes,StringRef Ext,LLVMContext & Context)1112344a3780SDimitry Andric void llvm::cloneNoAliasScopes(ArrayRef<MDNode *> NoAliasDeclScopes,
1113b60736ecSDimitry Andric DenseMap<MDNode *, MDNode *> &ClonedScopes,
1114b60736ecSDimitry Andric StringRef Ext, LLVMContext &Context) {
1115b60736ecSDimitry Andric MDBuilder MDB(Context);
1116b60736ecSDimitry Andric
1117b60736ecSDimitry Andric for (auto *ScopeList : NoAliasDeclScopes) {
1118e3b55780SDimitry Andric for (const auto &MDOperand : ScopeList->operands()) {
1119b60736ecSDimitry Andric if (MDNode *MD = dyn_cast<MDNode>(MDOperand)) {
1120b60736ecSDimitry Andric AliasScopeNode SNANode(MD);
1121b60736ecSDimitry Andric
1122b60736ecSDimitry Andric std::string Name;
1123b60736ecSDimitry Andric auto ScopeName = SNANode.getName();
1124b60736ecSDimitry Andric if (!ScopeName.empty())
1125b60736ecSDimitry Andric Name = (Twine(ScopeName) + ":" + Ext).str();
1126b60736ecSDimitry Andric else
1127b60736ecSDimitry Andric Name = std::string(Ext);
1128b60736ecSDimitry Andric
1129b60736ecSDimitry Andric MDNode *NewScope = MDB.createAnonymousAliasScope(
1130b60736ecSDimitry Andric const_cast<MDNode *>(SNANode.getDomain()), Name);
1131b60736ecSDimitry Andric ClonedScopes.insert(std::make_pair(MD, NewScope));
1132b60736ecSDimitry Andric }
1133b60736ecSDimitry Andric }
1134b60736ecSDimitry Andric }
1135b60736ecSDimitry Andric }
1136b60736ecSDimitry Andric
adaptNoAliasScopes(Instruction * I,const DenseMap<MDNode *,MDNode * > & ClonedScopes,LLVMContext & Context)1137344a3780SDimitry Andric void llvm::adaptNoAliasScopes(Instruction *I,
1138344a3780SDimitry Andric const DenseMap<MDNode *, MDNode *> &ClonedScopes,
1139b60736ecSDimitry Andric LLVMContext &Context) {
1140b60736ecSDimitry Andric auto CloneScopeList = [&](const MDNode *ScopeList) -> MDNode * {
1141b60736ecSDimitry Andric bool NeedsReplacement = false;
1142b60736ecSDimitry Andric SmallVector<Metadata *, 8> NewScopeList;
1143e3b55780SDimitry Andric for (const auto &MDOp : ScopeList->operands()) {
1144b60736ecSDimitry Andric if (MDNode *MD = dyn_cast<MDNode>(MDOp)) {
1145b60736ecSDimitry Andric if (auto *NewMD = ClonedScopes.lookup(MD)) {
1146b60736ecSDimitry Andric NewScopeList.push_back(NewMD);
1147b60736ecSDimitry Andric NeedsReplacement = true;
1148b60736ecSDimitry Andric continue;
1149b60736ecSDimitry Andric }
1150b60736ecSDimitry Andric NewScopeList.push_back(MD);
1151b60736ecSDimitry Andric }
1152b60736ecSDimitry Andric }
1153b60736ecSDimitry Andric if (NeedsReplacement)
1154b60736ecSDimitry Andric return MDNode::get(Context, NewScopeList);
1155b60736ecSDimitry Andric return nullptr;
1156b60736ecSDimitry Andric };
1157b60736ecSDimitry Andric
1158b60736ecSDimitry Andric if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(I))
1159b60736ecSDimitry Andric if (auto *NewScopeList = CloneScopeList(Decl->getScopeList()))
1160b60736ecSDimitry Andric Decl->setScopeList(NewScopeList);
1161b60736ecSDimitry Andric
1162b60736ecSDimitry Andric auto replaceWhenNeeded = [&](unsigned MD_ID) {
1163b60736ecSDimitry Andric if (const MDNode *CSNoAlias = I->getMetadata(MD_ID))
1164b60736ecSDimitry Andric if (auto *NewScopeList = CloneScopeList(CSNoAlias))
1165b60736ecSDimitry Andric I->setMetadata(MD_ID, NewScopeList);
1166b60736ecSDimitry Andric };
1167b60736ecSDimitry Andric replaceWhenNeeded(LLVMContext::MD_noalias);
1168b60736ecSDimitry Andric replaceWhenNeeded(LLVMContext::MD_alias_scope);
1169b60736ecSDimitry Andric }
1170b60736ecSDimitry Andric
cloneAndAdaptNoAliasScopes(ArrayRef<MDNode * > NoAliasDeclScopes,ArrayRef<BasicBlock * > NewBlocks,LLVMContext & Context,StringRef Ext)1171344a3780SDimitry Andric void llvm::cloneAndAdaptNoAliasScopes(ArrayRef<MDNode *> NoAliasDeclScopes,
1172344a3780SDimitry Andric ArrayRef<BasicBlock *> NewBlocks,
1173344a3780SDimitry Andric LLVMContext &Context, StringRef Ext) {
1174b60736ecSDimitry Andric if (NoAliasDeclScopes.empty())
1175b60736ecSDimitry Andric return;
1176b60736ecSDimitry Andric
1177b60736ecSDimitry Andric DenseMap<MDNode *, MDNode *> ClonedScopes;
1178b60736ecSDimitry Andric LLVM_DEBUG(dbgs() << "cloneAndAdaptNoAliasScopes: cloning "
1179b60736ecSDimitry Andric << NoAliasDeclScopes.size() << " node(s)\n");
1180b60736ecSDimitry Andric
1181b60736ecSDimitry Andric cloneNoAliasScopes(NoAliasDeclScopes, ClonedScopes, Ext, Context);
1182b60736ecSDimitry Andric // Identify instructions using metadata that needs adaptation
1183b60736ecSDimitry Andric for (BasicBlock *NewBlock : NewBlocks)
1184b60736ecSDimitry Andric for (Instruction &I : *NewBlock)
1185b60736ecSDimitry Andric adaptNoAliasScopes(&I, ClonedScopes, Context);
1186b60736ecSDimitry Andric }
1187b60736ecSDimitry Andric
cloneAndAdaptNoAliasScopes(ArrayRef<MDNode * > NoAliasDeclScopes,Instruction * IStart,Instruction * IEnd,LLVMContext & Context,StringRef Ext)1188344a3780SDimitry Andric void llvm::cloneAndAdaptNoAliasScopes(ArrayRef<MDNode *> NoAliasDeclScopes,
1189344a3780SDimitry Andric Instruction *IStart, Instruction *IEnd,
1190344a3780SDimitry Andric LLVMContext &Context, StringRef Ext) {
1191b60736ecSDimitry Andric if (NoAliasDeclScopes.empty())
1192b60736ecSDimitry Andric return;
1193b60736ecSDimitry Andric
1194b60736ecSDimitry Andric DenseMap<MDNode *, MDNode *> ClonedScopes;
1195b60736ecSDimitry Andric LLVM_DEBUG(dbgs() << "cloneAndAdaptNoAliasScopes: cloning "
1196b60736ecSDimitry Andric << NoAliasDeclScopes.size() << " node(s)\n");
1197b60736ecSDimitry Andric
1198b60736ecSDimitry Andric cloneNoAliasScopes(NoAliasDeclScopes, ClonedScopes, Ext, Context);
1199b60736ecSDimitry Andric // Identify instructions using metadata that needs adaptation
1200b60736ecSDimitry Andric assert(IStart->getParent() == IEnd->getParent() && "different basic block ?");
1201b60736ecSDimitry Andric auto ItStart = IStart->getIterator();
1202b60736ecSDimitry Andric auto ItEnd = IEnd->getIterator();
1203b60736ecSDimitry Andric ++ItEnd; // IEnd is included, increment ItEnd to get the end of the range
1204b60736ecSDimitry Andric for (auto &I : llvm::make_range(ItStart, ItEnd))
1205b60736ecSDimitry Andric adaptNoAliasScopes(&I, ClonedScopes, Context);
1206b60736ecSDimitry Andric }
1207b60736ecSDimitry Andric
identifyNoAliasScopesToClone(ArrayRef<BasicBlock * > BBs,SmallVectorImpl<MDNode * > & NoAliasDeclScopes)1208b60736ecSDimitry Andric void llvm::identifyNoAliasScopesToClone(
1209b60736ecSDimitry Andric ArrayRef<BasicBlock *> BBs, SmallVectorImpl<MDNode *> &NoAliasDeclScopes) {
1210b60736ecSDimitry Andric for (BasicBlock *BB : BBs)
1211b60736ecSDimitry Andric for (Instruction &I : *BB)
1212b60736ecSDimitry Andric if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(&I))
1213b60736ecSDimitry Andric NoAliasDeclScopes.push_back(Decl->getScopeList());
1214b60736ecSDimitry Andric }
1215344a3780SDimitry Andric
identifyNoAliasScopesToClone(BasicBlock::iterator Start,BasicBlock::iterator End,SmallVectorImpl<MDNode * > & NoAliasDeclScopes)1216344a3780SDimitry Andric void llvm::identifyNoAliasScopesToClone(
1217344a3780SDimitry Andric BasicBlock::iterator Start, BasicBlock::iterator End,
1218344a3780SDimitry Andric SmallVectorImpl<MDNode *> &NoAliasDeclScopes) {
1219344a3780SDimitry Andric for (Instruction &I : make_range(Start, End))
1220344a3780SDimitry Andric if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(&I))
1221344a3780SDimitry Andric NoAliasDeclScopes.push_back(Decl->getScopeList());
1222344a3780SDimitry Andric }
1223