1 //===- CloneModule.cpp - Clone an entire module ---------------------------===// 2 // 3 // This file implements the CloneModule interface which makes a copy of an 4 // entire module. 5 // 6 //===----------------------------------------------------------------------===// 7 8 #include "llvm/Transforms/Utils/Cloning.h" 9 #include "llvm/Module.h" 10 #include "llvm/DerivedTypes.h" 11 #include "llvm/Constant.h" 12 #include "ValueMapper.h" 13 14 /// CloneModule - Return an exact copy of the specified module. This is not as 15 /// easy as it might seem because we have to worry about making copies of global 16 /// variables and functions, and making their (intializers and references, 17 /// respectively) refer to the right globals. 18 /// 19 Module *CloneModule(const Module *M) { 20 // First off, we need to create the new module... 21 Module *New = new Module(); 22 23 // Create the value map that maps things from the old module over to the new 24 // module. 25 std::map<const Value*, Value*> ValueMap; 26 27 // Loop over all of the global variables, making corresponding globals in the 28 // new module. Here we add them to the ValueMap and to the new Module. We 29 // don't worry about attributes or initializers, they will come later. 30 // 31 for (Module::const_giterator I = M->gbegin(), E = M->gend(); I != E; ++I) 32 ValueMap[I] = new GlobalVariable(I->getType()->getElementType(), 33 false, false, 0, I->getName(), New); 34 35 // Loop over the functions in the module, making external functions as before 36 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I) 37 ValueMap[I]=new Function(cast<FunctionType>(I->getType()->getElementType()), 38 false, I->getName(), New); 39 40 // Now that all of the things that global variable initializer can refer to 41 // have been created, loop through and copy the global variable referrers 42 // over... We also set the attributes on the global now. 43 // 44 for (Module::const_giterator I = M->gbegin(), E = M->gend(); I != E; ++I) { 45 GlobalVariable *GV = cast<GlobalVariable>(ValueMap[I]); 46 if (I->hasInitializer()) 47 GV->setInitializer(cast<Constant>(MapValue(I->getInitializer(), 48 ValueMap))); 49 if (I->hasInternalLinkage()) 50 GV->setInternalLinkage(true); 51 } 52 53 // Similarly, copy over function bodies now... 54 // 55 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I) { 56 Function *F = cast<Function>(ValueMap[I]); 57 if (!I->isExternal()) { 58 Function::aiterator DestI = F->abegin(); 59 for (Function::const_aiterator J = I->abegin(); J != I->aend(); ++J) { 60 DestI->setName(J->getName()); 61 ValueMap[J] = DestI++; 62 } 63 64 std::vector<ReturnInst*> Returns; // Ignore returns cloned... 65 CloneFunctionInto(F, I, ValueMap, Returns); 66 } 67 68 if (I->hasInternalLinkage()) 69 F->setInternalLinkage(true); 70 } 71 72 return New; 73 } 74