4 #include "llvm/Transforms/CloneFunction.h"
5 #include "llvm/Function.h"
6 #include "llvm/BasicBlock.h"
7 #include "llvm/Instruction.h"
10 // FIXME: This should be merged with FunctionInlining
12 // RemapInstruction - Convert the instruction operands from referencing the
13 // current values into those specified by ValueMap.
15 static inline void RemapInstruction(Instruction *I,
16 std::map<const Value *, Value*> &ValueMap) {
17 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
18 const Value *Op = I->getOperand(op);
19 Value *V = ValueMap[Op];
20 if (!V && (isa<GlobalValue>(Op) || isa<Constant>(Op)))
21 continue; // Globals and constants don't get relocated
25 cerr << "Val = \n" << Op << "Addr = " << (void*)Op;
26 cerr << "\nInst = " << I;
29 assert(V && "Referenced value not in value map!");
34 // Clone OldFunc into NewFunc, transforming the old arguments into references to
37 void CloneFunctionInto(Function *NewFunc, const Function *OldFunc,
38 const std::vector<Value*> &ArgMap) {
39 assert(OldFunc->getArgumentList().empty() ||
40 !NewFunc->getArgumentList().empty() &&
41 "Synthesization of arguments is not implemented yet!");
42 assert(OldFunc->getArgumentList().size() == ArgMap.size() &&
43 "Improper number of argument values to map specified!");
45 // Keep a mapping between the original function's values and the new
46 // duplicated code's values. This includes all of: Function arguments,
47 // instruction values, constant pool entries, and basic blocks.
49 std::map<const Value *, Value*> ValueMap;
51 // Add all of the function arguments to the mapping...
52 for (unsigned i = 0, e = ArgMap.size(); i != e; ++i)
53 ValueMap[(Value*)OldFunc->getArgumentList()[i]] = ArgMap[i];
56 // Loop over all of the basic blocks in the function, cloning them as
59 for (Function::const_iterator BI = OldFunc->begin(), BE = OldFunc->end();
61 const BasicBlock *BB = *BI;
62 assert(BB->getTerminator() && "BasicBlock doesn't have terminator!?!?");
64 // Create a new basic block to copy instructions into!
65 BasicBlock *CBB = new BasicBlock(BB->getName(), NewFunc);
66 ValueMap[BB] = CBB; // Add basic block mapping.
68 // Loop over all instructions copying them over...
69 for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end();
71 Instruction *NewInst = (*II)->clone();
72 NewInst->setName((*II)->getName()); // Name is not cloned...
73 CBB->getInstList().push_back(NewInst);
74 ValueMap[*II] = NewInst; // Add instruction map to value.
78 // Loop over all of the instructions in the function, fixing up operand
79 // references as we go. This uses ValueMap to do all the hard work.
81 for (Function::const_iterator BI = OldFunc->begin(), BE = OldFunc->end();
83 const BasicBlock *BB = *BI;
84 BasicBlock *NBB = cast<BasicBlock>(ValueMap[BB]);
86 // Loop over all instructions, fixing each one as we find it...
87 for (BasicBlock::iterator II = NBB->begin(); II != NBB->end(); II++)
88 RemapInstruction(*II, ValueMap);