xref: /freebsd-src/contrib/llvm-project/llvm/lib/Transforms/Utils/CloneModule.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
10b57cec5SDimitry Andric //===- CloneModule.cpp - Clone an entire module ---------------------------===//
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 CloneModule interface which makes a copy of an
100b57cec5SDimitry Andric // entire module.
110b57cec5SDimitry Andric //
120b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
130b57cec5SDimitry Andric 
140b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h"
150b57cec5SDimitry Andric #include "llvm/IR/Module.h"
160b57cec5SDimitry Andric #include "llvm/Transforms/Utils/Cloning.h"
170b57cec5SDimitry Andric #include "llvm/Transforms/Utils/ValueMapper.h"
180b57cec5SDimitry Andric using namespace llvm;
190b57cec5SDimitry Andric 
2081ad6265SDimitry Andric namespace llvm {
2181ad6265SDimitry Andric class Constant;
2281ad6265SDimitry Andric }
2381ad6265SDimitry Andric 
240b57cec5SDimitry Andric static void copyComdat(GlobalObject *Dst, const GlobalObject *Src) {
250b57cec5SDimitry Andric   const Comdat *SC = Src->getComdat();
260b57cec5SDimitry Andric   if (!SC)
270b57cec5SDimitry Andric     return;
280b57cec5SDimitry Andric   Comdat *DC = Dst->getParent()->getOrInsertComdat(SC->getName());
290b57cec5SDimitry Andric   DC->setSelectionKind(SC->getSelectionKind());
300b57cec5SDimitry Andric   Dst->setComdat(DC);
310b57cec5SDimitry Andric }
320b57cec5SDimitry Andric 
330b57cec5SDimitry Andric /// This is not as easy as it might seem because we have to worry about making
340b57cec5SDimitry Andric /// copies of global variables and functions, and making their (initializers and
350b57cec5SDimitry Andric /// references, respectively) refer to the right globals.
360b57cec5SDimitry Andric ///
375f757f3fSDimitry Andric /// Cloning un-materialized modules is not currently supported, so any
385f757f3fSDimitry Andric /// modules initialized via lazy loading should be materialized before cloning
390b57cec5SDimitry Andric std::unique_ptr<Module> llvm::CloneModule(const Module &M) {
400b57cec5SDimitry Andric   // Create the value map that maps things from the old module over to the new
410b57cec5SDimitry Andric   // module.
420b57cec5SDimitry Andric   ValueToValueMapTy VMap;
430b57cec5SDimitry Andric   return CloneModule(M, VMap);
440b57cec5SDimitry Andric }
450b57cec5SDimitry Andric 
460b57cec5SDimitry Andric std::unique_ptr<Module> llvm::CloneModule(const Module &M,
470b57cec5SDimitry Andric                                           ValueToValueMapTy &VMap) {
480b57cec5SDimitry Andric   return CloneModule(M, VMap, [](const GlobalValue *GV) { return true; });
490b57cec5SDimitry Andric }
500b57cec5SDimitry Andric 
510b57cec5SDimitry Andric std::unique_ptr<Module> llvm::CloneModule(
520b57cec5SDimitry Andric     const Module &M, ValueToValueMapTy &VMap,
530b57cec5SDimitry Andric     function_ref<bool(const GlobalValue *)> ShouldCloneDefinition) {
545f757f3fSDimitry Andric 
555f757f3fSDimitry Andric   assert(M.isMaterialized() && "Module must be materialized before cloning!");
565f757f3fSDimitry Andric 
570b57cec5SDimitry Andric   // First off, we need to create the new module.
580b57cec5SDimitry Andric   std::unique_ptr<Module> New =
598bcb0991SDimitry Andric       std::make_unique<Module>(M.getModuleIdentifier(), M.getContext());
600b57cec5SDimitry Andric   New->setSourceFileName(M.getSourceFileName());
610b57cec5SDimitry Andric   New->setDataLayout(M.getDataLayout());
620b57cec5SDimitry Andric   New->setTargetTriple(M.getTargetTriple());
630b57cec5SDimitry Andric   New->setModuleInlineAsm(M.getModuleInlineAsm());
645f757f3fSDimitry Andric   New->IsNewDbgInfoFormat = M.IsNewDbgInfoFormat;
650b57cec5SDimitry Andric 
660b57cec5SDimitry Andric   // Loop over all of the global variables, making corresponding globals in the
670b57cec5SDimitry Andric   // new module.  Here we add them to the VMap and to the new Module.  We
680b57cec5SDimitry Andric   // don't worry about attributes or initializers, they will come later.
690b57cec5SDimitry Andric   //
705e801ac6SDimitry Andric   for (const GlobalVariable &I : M.globals()) {
715e801ac6SDimitry Andric     GlobalVariable *NewGV = new GlobalVariable(
725e801ac6SDimitry Andric         *New, I.getValueType(), I.isConstant(), I.getLinkage(),
735e801ac6SDimitry Andric         (Constant *)nullptr, I.getName(), (GlobalVariable *)nullptr,
745e801ac6SDimitry Andric         I.getThreadLocalMode(), I.getType()->getAddressSpace());
755e801ac6SDimitry Andric     NewGV->copyAttributesFrom(&I);
765e801ac6SDimitry Andric     VMap[&I] = NewGV;
770b57cec5SDimitry Andric   }
780b57cec5SDimitry Andric 
790b57cec5SDimitry Andric   // Loop over the functions in the module, making external functions as before
800b57cec5SDimitry Andric   for (const Function &I : M) {
810b57cec5SDimitry Andric     Function *NF =
820b57cec5SDimitry Andric         Function::Create(cast<FunctionType>(I.getValueType()), I.getLinkage(),
830b57cec5SDimitry Andric                          I.getAddressSpace(), I.getName(), New.get());
840b57cec5SDimitry Andric     NF->copyAttributesFrom(&I);
850b57cec5SDimitry Andric     VMap[&I] = NF;
860b57cec5SDimitry Andric   }
870b57cec5SDimitry Andric 
880b57cec5SDimitry Andric   // Loop over the aliases in the module
895e801ac6SDimitry Andric   for (const GlobalAlias &I : M.aliases()) {
905e801ac6SDimitry Andric     if (!ShouldCloneDefinition(&I)) {
910b57cec5SDimitry Andric       // An alias cannot act as an external reference, so we need to create
920b57cec5SDimitry Andric       // either a function or a global variable depending on the value type.
930b57cec5SDimitry Andric       // FIXME: Once pointee types are gone we can probably pick one or the
940b57cec5SDimitry Andric       // other.
950b57cec5SDimitry Andric       GlobalValue *GV;
965e801ac6SDimitry Andric       if (I.getValueType()->isFunctionTy())
975e801ac6SDimitry Andric         GV = Function::Create(cast<FunctionType>(I.getValueType()),
985e801ac6SDimitry Andric                               GlobalValue::ExternalLinkage, I.getAddressSpace(),
995e801ac6SDimitry Andric                               I.getName(), New.get());
1000b57cec5SDimitry Andric       else
1015e801ac6SDimitry Andric         GV = new GlobalVariable(*New, I.getValueType(), false,
1025e801ac6SDimitry Andric                                 GlobalValue::ExternalLinkage, nullptr,
1035e801ac6SDimitry Andric                                 I.getName(), nullptr, I.getThreadLocalMode(),
1045e801ac6SDimitry Andric                                 I.getType()->getAddressSpace());
1055e801ac6SDimitry Andric       VMap[&I] = GV;
1060b57cec5SDimitry Andric       // We do not copy attributes (mainly because copying between different
1070b57cec5SDimitry Andric       // kinds of globals is forbidden), but this is generally not required for
1080b57cec5SDimitry Andric       // correctness.
1090b57cec5SDimitry Andric       continue;
1100b57cec5SDimitry Andric     }
1115e801ac6SDimitry Andric     auto *GA = GlobalAlias::create(I.getValueType(),
1125e801ac6SDimitry Andric                                    I.getType()->getPointerAddressSpace(),
1135e801ac6SDimitry Andric                                    I.getLinkage(), I.getName(), New.get());
1145e801ac6SDimitry Andric     GA->copyAttributesFrom(&I);
1155e801ac6SDimitry Andric     VMap[&I] = GA;
1160b57cec5SDimitry Andric   }
1170b57cec5SDimitry Andric 
118bdd1243dSDimitry Andric   for (const GlobalIFunc &I : M.ifuncs()) {
119bdd1243dSDimitry Andric     // Defer setting the resolver function until after functions are cloned.
120bdd1243dSDimitry Andric     auto *GI =
121bdd1243dSDimitry Andric         GlobalIFunc::create(I.getValueType(), I.getAddressSpace(),
122bdd1243dSDimitry Andric                             I.getLinkage(), I.getName(), nullptr, New.get());
123bdd1243dSDimitry Andric     GI->copyAttributesFrom(&I);
124bdd1243dSDimitry Andric     VMap[&I] = GI;
125bdd1243dSDimitry Andric   }
126bdd1243dSDimitry Andric 
1270b57cec5SDimitry Andric   // Now that all of the things that global variable initializer can refer to
1280b57cec5SDimitry Andric   // have been created, loop through and copy the global variable referrers
1290b57cec5SDimitry Andric   // over...  We also set the attributes on the global now.
1300b57cec5SDimitry Andric   //
131fe6060f1SDimitry Andric   for (const GlobalVariable &G : M.globals()) {
132fe6060f1SDimitry Andric     GlobalVariable *GV = cast<GlobalVariable>(VMap[&G]);
133e8d8bef9SDimitry Andric 
134e8d8bef9SDimitry Andric     SmallVector<std::pair<unsigned, MDNode *>, 1> MDs;
135fe6060f1SDimitry Andric     G.getAllMetadata(MDs);
136e8d8bef9SDimitry Andric     for (auto MD : MDs)
137fe6060f1SDimitry Andric       GV->addMetadata(MD.first, *MapMetadata(MD.second, VMap));
138e8d8bef9SDimitry Andric 
139fe6060f1SDimitry Andric     if (G.isDeclaration())
1400b57cec5SDimitry Andric       continue;
1410b57cec5SDimitry Andric 
142fe6060f1SDimitry Andric     if (!ShouldCloneDefinition(&G)) {
1430b57cec5SDimitry Andric       // Skip after setting the correct linkage for an external reference.
1440b57cec5SDimitry Andric       GV->setLinkage(GlobalValue::ExternalLinkage);
1450b57cec5SDimitry Andric       continue;
1460b57cec5SDimitry Andric     }
147fe6060f1SDimitry Andric     if (G.hasInitializer())
148fe6060f1SDimitry Andric       GV->setInitializer(MapValue(G.getInitializer(), VMap));
1490b57cec5SDimitry Andric 
150fe6060f1SDimitry Andric     copyComdat(GV, &G);
1510b57cec5SDimitry Andric   }
1520b57cec5SDimitry Andric 
1530b57cec5SDimitry Andric   // Similarly, copy over function bodies now...
1540b57cec5SDimitry Andric   //
1550b57cec5SDimitry Andric   for (const Function &I : M) {
1560b57cec5SDimitry Andric     Function *F = cast<Function>(VMap[&I]);
1574824e7fdSDimitry Andric 
1584824e7fdSDimitry Andric     if (I.isDeclaration()) {
1594824e7fdSDimitry Andric       // Copy over metadata for declarations since we're not doing it below in
1604824e7fdSDimitry Andric       // CloneFunctionInto().
1614824e7fdSDimitry Andric       SmallVector<std::pair<unsigned, MDNode *>, 1> MDs;
1624824e7fdSDimitry Andric       I.getAllMetadata(MDs);
1634824e7fdSDimitry Andric       for (auto MD : MDs)
1644824e7fdSDimitry Andric         F->addMetadata(MD.first, *MapMetadata(MD.second, VMap));
1654824e7fdSDimitry Andric       continue;
1664824e7fdSDimitry Andric     }
1674824e7fdSDimitry Andric 
1680b57cec5SDimitry Andric     if (!ShouldCloneDefinition(&I)) {
1690b57cec5SDimitry Andric       // Skip after setting the correct linkage for an external reference.
1700b57cec5SDimitry Andric       F->setLinkage(GlobalValue::ExternalLinkage);
1710b57cec5SDimitry Andric       // Personality function is not valid on a declaration.
1720b57cec5SDimitry Andric       F->setPersonalityFn(nullptr);
1730b57cec5SDimitry Andric       continue;
1740b57cec5SDimitry Andric     }
1750b57cec5SDimitry Andric 
1760b57cec5SDimitry Andric     Function::arg_iterator DestI = F->arg_begin();
1775e801ac6SDimitry Andric     for (const Argument &J : I.args()) {
1785e801ac6SDimitry Andric       DestI->setName(J.getName());
1795e801ac6SDimitry Andric       VMap[&J] = &*DestI++;
1800b57cec5SDimitry Andric     }
1810b57cec5SDimitry Andric 
1820b57cec5SDimitry Andric     SmallVector<ReturnInst *, 8> Returns; // Ignore returns cloned.
183fe6060f1SDimitry Andric     CloneFunctionInto(F, &I, VMap, CloneFunctionChangeType::ClonedModule,
184fe6060f1SDimitry Andric                       Returns);
1850b57cec5SDimitry Andric 
1860b57cec5SDimitry Andric     if (I.hasPersonalityFn())
1870b57cec5SDimitry Andric       F->setPersonalityFn(MapValue(I.getPersonalityFn(), VMap));
1880b57cec5SDimitry Andric 
1890b57cec5SDimitry Andric     copyComdat(F, &I);
1900b57cec5SDimitry Andric   }
1910b57cec5SDimitry Andric 
1920b57cec5SDimitry Andric   // And aliases
1935e801ac6SDimitry Andric   for (const GlobalAlias &I : M.aliases()) {
1940b57cec5SDimitry Andric     // We already dealt with undefined aliases above.
1955e801ac6SDimitry Andric     if (!ShouldCloneDefinition(&I))
1960b57cec5SDimitry Andric       continue;
1975e801ac6SDimitry Andric     GlobalAlias *GA = cast<GlobalAlias>(VMap[&I]);
1985e801ac6SDimitry Andric     if (const Constant *C = I.getAliasee())
1990b57cec5SDimitry Andric       GA->setAliasee(MapValue(C, VMap));
2000b57cec5SDimitry Andric   }
2010b57cec5SDimitry Andric 
202bdd1243dSDimitry Andric   for (const GlobalIFunc &I : M.ifuncs()) {
203bdd1243dSDimitry Andric     GlobalIFunc *GI = cast<GlobalIFunc>(VMap[&I]);
204bdd1243dSDimitry Andric     if (const Constant *Resolver = I.getResolver())
205bdd1243dSDimitry Andric       GI->setResolver(MapValue(Resolver, VMap));
206bdd1243dSDimitry Andric   }
207bdd1243dSDimitry Andric 
2080b57cec5SDimitry Andric   // And named metadata....
2095e801ac6SDimitry Andric   for (const NamedMDNode &NMD : M.named_metadata()) {
2100b57cec5SDimitry Andric     NamedMDNode *NewNMD = New->getOrInsertNamedMetadata(NMD.getName());
211*0fca6ea1SDimitry Andric     for (const MDNode *N : NMD.operands())
212*0fca6ea1SDimitry Andric       NewNMD->addOperand(MapMetadata(N, VMap));
2130b57cec5SDimitry Andric   }
2140b57cec5SDimitry Andric 
2150b57cec5SDimitry Andric   return New;
2160b57cec5SDimitry Andric }
2170b57cec5SDimitry Andric 
2180b57cec5SDimitry Andric extern "C" {
2190b57cec5SDimitry Andric 
2200b57cec5SDimitry Andric LLVMModuleRef LLVMCloneModule(LLVMModuleRef M) {
2210b57cec5SDimitry Andric   return wrap(CloneModule(*unwrap(M)).release());
2220b57cec5SDimitry Andric }
2230b57cec5SDimitry Andric 
2240b57cec5SDimitry Andric }
225