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/Constant.h"
150b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h"
160b57cec5SDimitry Andric #include "llvm/IR/Module.h"
170b57cec5SDimitry Andric #include "llvm/Transforms/Utils/Cloning.h"
180b57cec5SDimitry Andric #include "llvm/Transforms/Utils/ValueMapper.h"
190b57cec5SDimitry Andric using namespace llvm;
200b57cec5SDimitry Andric 
copyComdat(GlobalObject * Dst,const GlobalObject * Src)210b57cec5SDimitry Andric static void copyComdat(GlobalObject *Dst, const GlobalObject *Src) {
220b57cec5SDimitry Andric   const Comdat *SC = Src->getComdat();
230b57cec5SDimitry Andric   if (!SC)
240b57cec5SDimitry Andric     return;
250b57cec5SDimitry Andric   Comdat *DC = Dst->getParent()->getOrInsertComdat(SC->getName());
260b57cec5SDimitry Andric   DC->setSelectionKind(SC->getSelectionKind());
270b57cec5SDimitry Andric   Dst->setComdat(DC);
280b57cec5SDimitry Andric }
290b57cec5SDimitry Andric 
300b57cec5SDimitry Andric /// This is not as easy as it might seem because we have to worry about making
310b57cec5SDimitry Andric /// copies of global variables and functions, and making their (initializers and
320b57cec5SDimitry Andric /// references, respectively) refer to the right globals.
330b57cec5SDimitry Andric ///
CloneModule(const Module & M)340b57cec5SDimitry Andric std::unique_ptr<Module> llvm::CloneModule(const Module &M) {
350b57cec5SDimitry Andric   // Create the value map that maps things from the old module over to the new
360b57cec5SDimitry Andric   // module.
370b57cec5SDimitry Andric   ValueToValueMapTy VMap;
380b57cec5SDimitry Andric   return CloneModule(M, VMap);
390b57cec5SDimitry Andric }
400b57cec5SDimitry Andric 
CloneModule(const Module & M,ValueToValueMapTy & VMap)410b57cec5SDimitry Andric std::unique_ptr<Module> llvm::CloneModule(const Module &M,
420b57cec5SDimitry Andric                                           ValueToValueMapTy &VMap) {
430b57cec5SDimitry Andric   return CloneModule(M, VMap, [](const GlobalValue *GV) { return true; });
440b57cec5SDimitry Andric }
450b57cec5SDimitry Andric 
CloneModule(const Module & M,ValueToValueMapTy & VMap,function_ref<bool (const GlobalValue *)> ShouldCloneDefinition)460b57cec5SDimitry Andric std::unique_ptr<Module> llvm::CloneModule(
470b57cec5SDimitry Andric     const Module &M, ValueToValueMapTy &VMap,
480b57cec5SDimitry Andric     function_ref<bool(const GlobalValue *)> ShouldCloneDefinition) {
490b57cec5SDimitry Andric   // First off, we need to create the new module.
500b57cec5SDimitry Andric   std::unique_ptr<Module> New =
518bcb0991SDimitry Andric       std::make_unique<Module>(M.getModuleIdentifier(), M.getContext());
520b57cec5SDimitry Andric   New->setSourceFileName(M.getSourceFileName());
530b57cec5SDimitry Andric   New->setDataLayout(M.getDataLayout());
540b57cec5SDimitry Andric   New->setTargetTriple(M.getTargetTriple());
550b57cec5SDimitry Andric   New->setModuleInlineAsm(M.getModuleInlineAsm());
560b57cec5SDimitry Andric 
570b57cec5SDimitry Andric   // Loop over all of the global variables, making corresponding globals in the
580b57cec5SDimitry Andric   // new module.  Here we add them to the VMap and to the new Module.  We
590b57cec5SDimitry Andric   // don't worry about attributes or initializers, they will come later.
600b57cec5SDimitry Andric   //
610b57cec5SDimitry Andric   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
620b57cec5SDimitry Andric        I != E; ++I) {
630b57cec5SDimitry Andric     GlobalVariable *GV = new GlobalVariable(*New,
640b57cec5SDimitry Andric                                             I->getValueType(),
650b57cec5SDimitry Andric                                             I->isConstant(), I->getLinkage(),
660b57cec5SDimitry Andric                                             (Constant*) nullptr, I->getName(),
670b57cec5SDimitry Andric                                             (GlobalVariable*) nullptr,
680b57cec5SDimitry Andric                                             I->getThreadLocalMode(),
690b57cec5SDimitry Andric                                             I->getType()->getAddressSpace());
700b57cec5SDimitry Andric     GV->copyAttributesFrom(&*I);
710b57cec5SDimitry Andric     VMap[&*I] = GV;
720b57cec5SDimitry Andric   }
730b57cec5SDimitry Andric 
740b57cec5SDimitry Andric   // Loop over the functions in the module, making external functions as before
750b57cec5SDimitry Andric   for (const Function &I : M) {
760b57cec5SDimitry Andric     Function *NF =
770b57cec5SDimitry Andric         Function::Create(cast<FunctionType>(I.getValueType()), I.getLinkage(),
780b57cec5SDimitry Andric                          I.getAddressSpace(), I.getName(), New.get());
790b57cec5SDimitry Andric     NF->copyAttributesFrom(&I);
800b57cec5SDimitry Andric     VMap[&I] = NF;
810b57cec5SDimitry Andric   }
820b57cec5SDimitry Andric 
830b57cec5SDimitry Andric   // Loop over the aliases in the module
840b57cec5SDimitry Andric   for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
850b57cec5SDimitry Andric        I != E; ++I) {
860b57cec5SDimitry Andric     if (!ShouldCloneDefinition(&*I)) {
870b57cec5SDimitry Andric       // An alias cannot act as an external reference, so we need to create
880b57cec5SDimitry Andric       // either a function or a global variable depending on the value type.
890b57cec5SDimitry Andric       // FIXME: Once pointee types are gone we can probably pick one or the
900b57cec5SDimitry Andric       // other.
910b57cec5SDimitry Andric       GlobalValue *GV;
920b57cec5SDimitry Andric       if (I->getValueType()->isFunctionTy())
930b57cec5SDimitry Andric         GV = Function::Create(cast<FunctionType>(I->getValueType()),
940b57cec5SDimitry Andric                               GlobalValue::ExternalLinkage,
950b57cec5SDimitry Andric                               I->getAddressSpace(), I->getName(), New.get());
960b57cec5SDimitry Andric       else
970b57cec5SDimitry Andric         GV = new GlobalVariable(
980b57cec5SDimitry Andric             *New, I->getValueType(), false, GlobalValue::ExternalLinkage,
990b57cec5SDimitry Andric             nullptr, I->getName(), nullptr,
1000b57cec5SDimitry Andric             I->getThreadLocalMode(), I->getType()->getAddressSpace());
1010b57cec5SDimitry Andric       VMap[&*I] = GV;
1020b57cec5SDimitry Andric       // We do not copy attributes (mainly because copying between different
1030b57cec5SDimitry Andric       // kinds of globals is forbidden), but this is generally not required for
1040b57cec5SDimitry Andric       // correctness.
1050b57cec5SDimitry Andric       continue;
1060b57cec5SDimitry Andric     }
1070b57cec5SDimitry Andric     auto *GA = GlobalAlias::create(I->getValueType(),
1080b57cec5SDimitry Andric                                    I->getType()->getPointerAddressSpace(),
1090b57cec5SDimitry Andric                                    I->getLinkage(), I->getName(), New.get());
1100b57cec5SDimitry Andric     GA->copyAttributesFrom(&*I);
1110b57cec5SDimitry Andric     VMap[&*I] = GA;
1120b57cec5SDimitry Andric   }
1130b57cec5SDimitry Andric 
1140b57cec5SDimitry Andric   // Now that all of the things that global variable initializer can refer to
1150b57cec5SDimitry Andric   // have been created, loop through and copy the global variable referrers
1160b57cec5SDimitry Andric   // over...  We also set the attributes on the global now.
1170b57cec5SDimitry Andric   //
118*5f7ddb14SDimitry Andric   for (const GlobalVariable &G : M.globals()) {
119*5f7ddb14SDimitry Andric     GlobalVariable *GV = cast<GlobalVariable>(VMap[&G]);
120af732203SDimitry Andric 
121af732203SDimitry Andric     SmallVector<std::pair<unsigned, MDNode *>, 1> MDs;
122*5f7ddb14SDimitry Andric     G.getAllMetadata(MDs);
123af732203SDimitry Andric     for (auto MD : MDs)
124*5f7ddb14SDimitry Andric       GV->addMetadata(MD.first, *MapMetadata(MD.second, VMap));
125af732203SDimitry Andric 
126*5f7ddb14SDimitry Andric     if (G.isDeclaration())
1270b57cec5SDimitry Andric       continue;
1280b57cec5SDimitry Andric 
129*5f7ddb14SDimitry Andric     if (!ShouldCloneDefinition(&G)) {
1300b57cec5SDimitry Andric       // Skip after setting the correct linkage for an external reference.
1310b57cec5SDimitry Andric       GV->setLinkage(GlobalValue::ExternalLinkage);
1320b57cec5SDimitry Andric       continue;
1330b57cec5SDimitry Andric     }
134*5f7ddb14SDimitry Andric     if (G.hasInitializer())
135*5f7ddb14SDimitry Andric       GV->setInitializer(MapValue(G.getInitializer(), VMap));
1360b57cec5SDimitry Andric 
137*5f7ddb14SDimitry Andric     copyComdat(GV, &G);
1380b57cec5SDimitry Andric   }
1390b57cec5SDimitry Andric 
1400b57cec5SDimitry Andric   // Similarly, copy over function bodies now...
1410b57cec5SDimitry Andric   //
1420b57cec5SDimitry Andric   for (const Function &I : M) {
1430b57cec5SDimitry Andric     if (I.isDeclaration())
1440b57cec5SDimitry Andric       continue;
1450b57cec5SDimitry Andric 
1460b57cec5SDimitry Andric     Function *F = cast<Function>(VMap[&I]);
1470b57cec5SDimitry Andric     if (!ShouldCloneDefinition(&I)) {
1480b57cec5SDimitry Andric       // Skip after setting the correct linkage for an external reference.
1490b57cec5SDimitry Andric       F->setLinkage(GlobalValue::ExternalLinkage);
1500b57cec5SDimitry Andric       // Personality function is not valid on a declaration.
1510b57cec5SDimitry Andric       F->setPersonalityFn(nullptr);
1520b57cec5SDimitry Andric       continue;
1530b57cec5SDimitry Andric     }
1540b57cec5SDimitry Andric 
1550b57cec5SDimitry Andric     Function::arg_iterator DestI = F->arg_begin();
1560b57cec5SDimitry Andric     for (Function::const_arg_iterator J = I.arg_begin(); J != I.arg_end();
1570b57cec5SDimitry Andric          ++J) {
1580b57cec5SDimitry Andric       DestI->setName(J->getName());
1590b57cec5SDimitry Andric       VMap[&*J] = &*DestI++;
1600b57cec5SDimitry Andric     }
1610b57cec5SDimitry Andric 
1620b57cec5SDimitry Andric     SmallVector<ReturnInst *, 8> Returns; // Ignore returns cloned.
163*5f7ddb14SDimitry Andric     CloneFunctionInto(F, &I, VMap, CloneFunctionChangeType::ClonedModule,
164*5f7ddb14SDimitry Andric                       Returns);
1650b57cec5SDimitry Andric 
1660b57cec5SDimitry Andric     if (I.hasPersonalityFn())
1670b57cec5SDimitry Andric       F->setPersonalityFn(MapValue(I.getPersonalityFn(), VMap));
1680b57cec5SDimitry Andric 
1690b57cec5SDimitry Andric     copyComdat(F, &I);
1700b57cec5SDimitry Andric   }
1710b57cec5SDimitry Andric 
1720b57cec5SDimitry Andric   // And aliases
1730b57cec5SDimitry Andric   for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
1740b57cec5SDimitry Andric        I != E; ++I) {
1750b57cec5SDimitry Andric     // We already dealt with undefined aliases above.
1760b57cec5SDimitry Andric     if (!ShouldCloneDefinition(&*I))
1770b57cec5SDimitry Andric       continue;
1780b57cec5SDimitry Andric     GlobalAlias *GA = cast<GlobalAlias>(VMap[&*I]);
1790b57cec5SDimitry Andric     if (const Constant *C = I->getAliasee())
1800b57cec5SDimitry Andric       GA->setAliasee(MapValue(C, VMap));
1810b57cec5SDimitry Andric   }
1820b57cec5SDimitry Andric 
1830b57cec5SDimitry Andric   // And named metadata....
1840b57cec5SDimitry Andric   for (Module::const_named_metadata_iterator I = M.named_metadata_begin(),
1850b57cec5SDimitry Andric                                              E = M.named_metadata_end();
1860b57cec5SDimitry Andric        I != E; ++I) {
1870b57cec5SDimitry Andric     const NamedMDNode &NMD = *I;
1880b57cec5SDimitry Andric     NamedMDNode *NewNMD = New->getOrInsertNamedMetadata(NMD.getName());
1890b57cec5SDimitry Andric     for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i)
1900b57cec5SDimitry Andric       NewNMD->addOperand(MapMetadata(NMD.getOperand(i), VMap));
1910b57cec5SDimitry Andric   }
1920b57cec5SDimitry Andric 
1930b57cec5SDimitry Andric   return New;
1940b57cec5SDimitry Andric }
1950b57cec5SDimitry Andric 
1960b57cec5SDimitry Andric extern "C" {
1970b57cec5SDimitry Andric 
LLVMCloneModule(LLVMModuleRef M)1980b57cec5SDimitry Andric LLVMModuleRef LLVMCloneModule(LLVMModuleRef M) {
1990b57cec5SDimitry Andric   return wrap(CloneModule(*unwrap(M)).release());
2000b57cec5SDimitry Andric }
2010b57cec5SDimitry Andric 
2020b57cec5SDimitry Andric }
203