1 //===- CloneFunction.cpp - Clone a function into another function ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the CloneFunctionInto interface, which is used as the
11 // low-level function cloner. This is used by the CloneFunction and function
12 // inliner to do the dirty work of copying the body of a function around.
14 //===----------------------------------------------------------------------===//
16 #include "llvm/Transforms/Utils/Cloning.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/IntrinsicInst.h"
21 #include "llvm/GlobalVariable.h"
22 #include "llvm/Function.h"
23 #include "llvm/LLVMContext.h"
24 #include "llvm/Metadata.h"
25 #include "llvm/Support/CFG.h"
26 #include "llvm/Transforms/Utils/ValueMapper.h"
27 #include "llvm/Analysis/ConstantFolding.h"
28 #include "llvm/Analysis/DebugInfo.h"
29 #include "llvm/ADT/SmallVector.h"
33 // CloneBasicBlock - See comments in Cloning.h
34 BasicBlock *llvm::CloneBasicBlock(const BasicBlock *BB,
35 ValueToValueMapTy &VMap,
36 const Twine &NameSuffix, Function *F,
37 ClonedCodeInfo *CodeInfo) {
38 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "", F);
39 if (BB->hasName()) NewBB->setName(BB->getName()+NameSuffix);
41 bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false;
43 // Loop over all instructions, and copy them over.
44 for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end();
46 Instruction *NewInst = II->clone();
48 NewInst->setName(II->getName()+NameSuffix);
49 NewBB->getInstList().push_back(NewInst);
50 VMap[II] = NewInst; // Add instruction map to value.
52 hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II));
53 if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
54 if (isa<ConstantInt>(AI->getArraySize()))
55 hasStaticAllocas = true;
57 hasDynamicAllocas = true;
62 CodeInfo->ContainsCalls |= hasCalls;
63 CodeInfo->ContainsUnwinds |= isa<UnwindInst>(BB->getTerminator());
64 CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
65 CodeInfo->ContainsDynamicAllocas |= hasStaticAllocas &&
66 BB != &BB->getParent()->getEntryBlock();
71 // Clone OldFunc into NewFunc, transforming the old arguments into references to
74 void llvm::CloneFunctionInto(Function *NewFunc, const Function *OldFunc,
75 ValueToValueMapTy &VMap,
76 bool ModuleLevelChanges,
77 SmallVectorImpl<ReturnInst*> &Returns,
78 const char *NameSuffix, ClonedCodeInfo *CodeInfo) {
79 assert(NameSuffix && "NameSuffix cannot be null!");
82 for (Function::const_arg_iterator I = OldFunc->arg_begin(),
83 E = OldFunc->arg_end(); I != E; ++I)
84 assert(VMap.count(I) && "No mapping from source argument specified!");
87 // Clone any attributes.
88 if (NewFunc->arg_size() == OldFunc->arg_size())
89 NewFunc->copyAttributesFrom(OldFunc);
91 //Some arguments were deleted with the VMap. Copy arguments one by one
92 for (Function::const_arg_iterator I = OldFunc->arg_begin(),
93 E = OldFunc->arg_end(); I != E; ++I)
94 if (Argument* Anew = dyn_cast<Argument>(VMap[I]))
95 Anew->addAttr( OldFunc->getAttributes()
96 .getParamAttributes(I->getArgNo() + 1));
97 NewFunc->setAttributes(NewFunc->getAttributes()
98 .addAttr(0, OldFunc->getAttributes()
99 .getRetAttributes()));
100 NewFunc->setAttributes(NewFunc->getAttributes()
101 .addAttr(~0, OldFunc->getAttributes()
102 .getFnAttributes()));
106 // Loop over all of the basic blocks in the function, cloning them as
107 // appropriate. Note that we save BE this way in order to handle cloning of
108 // recursive functions into themselves.
110 for (Function::const_iterator BI = OldFunc->begin(), BE = OldFunc->end();
112 const BasicBlock &BB = *BI;
114 // Create a new basic block and copy instructions into it!
115 BasicBlock *CBB = CloneBasicBlock(&BB, VMap, NameSuffix, NewFunc, CodeInfo);
117 // Add basic block mapping.
120 // It is only legal to clone a function if a block address within that
121 // function is never referenced outside of the function. Given that, we
122 // want to map block addresses from the old function to block addresses in
123 // the clone. (This is different from the generic ValueMapper
124 // implementation, which generates an invalid blockaddress when
125 // cloning a function.)
126 if (BB.hasAddressTaken()) {
127 Constant *OldBBAddr = BlockAddress::get(const_cast<Function*>(OldFunc),
128 const_cast<BasicBlock*>(&BB));
129 VMap[OldBBAddr] = BlockAddress::get(NewFunc, CBB);
132 // Note return instructions for the caller.
133 if (ReturnInst *RI = dyn_cast<ReturnInst>(CBB->getTerminator()))
134 Returns.push_back(RI);
137 // Loop over all of the instructions in the function, fixing up operand
138 // references as we go. This uses VMap to do all the hard work.
139 for (Function::iterator BB = cast<BasicBlock>(VMap[OldFunc->begin()]),
140 BE = NewFunc->end(); BB != BE; ++BB)
141 // Loop over all instructions, fixing each one as we find it...
142 for (BasicBlock::iterator II = BB->begin(); II != BB->end(); ++II)
143 RemapInstruction(II, VMap,
144 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
147 /// CloneFunction - Return a copy of the specified function, but without
148 /// embedding the function into another module. Also, any references specified
149 /// in the VMap are changed to refer to their mapped value instead of the
150 /// original one. If any of the arguments to the function are in the VMap,
151 /// the arguments are deleted from the resultant function. The VMap is
152 /// updated to include mappings from all of the instructions and basicblocks in
153 /// the function from their old to new values.
155 Function *llvm::CloneFunction(const Function *F, ValueToValueMapTy &VMap,
156 bool ModuleLevelChanges,
157 ClonedCodeInfo *CodeInfo) {
158 std::vector<Type*> ArgTypes;
160 // The user might be deleting arguments to the function by specifying them in
161 // the VMap. If so, we need to not add the arguments to the arg ty vector
163 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
165 if (VMap.count(I) == 0) // Haven't mapped the argument to anything yet?
166 ArgTypes.push_back(I->getType());
168 // Create a new function type...
169 FunctionType *FTy = FunctionType::get(F->getFunctionType()->getReturnType(),
170 ArgTypes, F->getFunctionType()->isVarArg());
172 // Create the new function...
173 Function *NewF = Function::Create(FTy, F->getLinkage(), F->getName());
175 // Loop over the arguments, copying the names of the mapped arguments over...
176 Function::arg_iterator DestI = NewF->arg_begin();
177 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
179 if (VMap.count(I) == 0) { // Is this argument preserved?
180 DestI->setName(I->getName()); // Copy the name over...
181 VMap[I] = DestI++; // Add mapping to VMap
184 SmallVector<ReturnInst*, 8> Returns; // Ignore returns cloned.
185 CloneFunctionInto(NewF, F, VMap, ModuleLevelChanges, Returns, "", CodeInfo);
192 /// PruningFunctionCloner - This class is a private class used to implement
193 /// the CloneAndPruneFunctionInto method.
194 struct PruningFunctionCloner {
196 const Function *OldFunc;
197 ValueToValueMapTy &VMap;
198 bool ModuleLevelChanges;
199 SmallVectorImpl<ReturnInst*> &Returns;
200 const char *NameSuffix;
201 ClonedCodeInfo *CodeInfo;
202 const TargetData *TD;
204 PruningFunctionCloner(Function *newFunc, const Function *oldFunc,
205 ValueToValueMapTy &valueMap,
206 bool moduleLevelChanges,
207 SmallVectorImpl<ReturnInst*> &returns,
208 const char *nameSuffix,
209 ClonedCodeInfo *codeInfo,
210 const TargetData *td)
211 : NewFunc(newFunc), OldFunc(oldFunc),
212 VMap(valueMap), ModuleLevelChanges(moduleLevelChanges),
213 Returns(returns), NameSuffix(nameSuffix), CodeInfo(codeInfo), TD(td) {
216 /// CloneBlock - The specified block is found to be reachable, clone it and
217 /// anything that it can reach.
218 void CloneBlock(const BasicBlock *BB,
219 std::vector<const BasicBlock*> &ToClone);
222 /// ConstantFoldMappedInstruction - Constant fold the specified instruction,
223 /// mapping its operands through VMap if they are available.
224 Constant *ConstantFoldMappedInstruction(const Instruction *I);
228 /// CloneBlock - The specified block is found to be reachable, clone it and
229 /// anything that it can reach.
230 void PruningFunctionCloner::CloneBlock(const BasicBlock *BB,
231 std::vector<const BasicBlock*> &ToClone){
232 TrackingVH<Value> &BBEntry = VMap[BB];
234 // Have we already cloned this block?
237 // Nope, clone it now.
239 BBEntry = NewBB = BasicBlock::Create(BB->getContext());
240 if (BB->hasName()) NewBB->setName(BB->getName()+NameSuffix);
242 // It is only legal to clone a function if a block address within that
243 // function is never referenced outside of the function. Given that, we
244 // want to map block addresses from the old function to block addresses in
245 // the clone. (This is different from the generic ValueMapper
246 // implementation, which generates an invalid blockaddress when
247 // cloning a function.)
249 // Note that we don't need to fix the mapping for unreachable blocks;
250 // the default mapping there is safe.
251 if (BB->hasAddressTaken()) {
252 Constant *OldBBAddr = BlockAddress::get(const_cast<Function*>(OldFunc),
253 const_cast<BasicBlock*>(BB));
254 VMap[OldBBAddr] = BlockAddress::get(NewFunc, NewBB);
258 bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false;
260 // Loop over all instructions, and copy them over, DCE'ing as we go. This
261 // loop doesn't include the terminator.
262 for (BasicBlock::const_iterator II = BB->begin(), IE = --BB->end();
264 // If this instruction constant folds, don't bother cloning the instruction,
265 // instead, just add the constant to the value map.
266 if (Constant *C = ConstantFoldMappedInstruction(II)) {
271 Instruction *NewInst = II->clone();
273 NewInst->setName(II->getName()+NameSuffix);
274 NewBB->getInstList().push_back(NewInst);
275 VMap[II] = NewInst; // Add instruction map to value.
277 hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II));
278 if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
279 if (isa<ConstantInt>(AI->getArraySize()))
280 hasStaticAllocas = true;
282 hasDynamicAllocas = true;
286 // Finally, clone over the terminator.
287 const TerminatorInst *OldTI = BB->getTerminator();
288 bool TerminatorDone = false;
289 if (const BranchInst *BI = dyn_cast<BranchInst>(OldTI)) {
290 if (BI->isConditional()) {
291 // If the condition was a known constant in the callee...
292 ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
293 // Or is a known constant in the caller...
295 Value *V = VMap[BI->getCondition()];
296 Cond = dyn_cast_or_null<ConstantInt>(V);
299 // Constant fold to uncond branch!
301 BasicBlock *Dest = BI->getSuccessor(!Cond->getZExtValue());
302 VMap[OldTI] = BranchInst::Create(Dest, NewBB);
303 ToClone.push_back(Dest);
304 TerminatorDone = true;
307 } else if (const SwitchInst *SI = dyn_cast<SwitchInst>(OldTI)) {
308 // If switching on a value known constant in the caller.
309 ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition());
310 if (Cond == 0) { // Or known constant after constant prop in the callee...
311 Value *V = VMap[SI->getCondition()];
312 Cond = dyn_cast_or_null<ConstantInt>(V);
314 if (Cond) { // Constant fold to uncond branch!
315 BasicBlock *Dest = SI->getSuccessor(SI->findCaseValue(Cond));
316 VMap[OldTI] = BranchInst::Create(Dest, NewBB);
317 ToClone.push_back(Dest);
318 TerminatorDone = true;
322 if (!TerminatorDone) {
323 Instruction *NewInst = OldTI->clone();
324 if (OldTI->hasName())
325 NewInst->setName(OldTI->getName()+NameSuffix);
326 NewBB->getInstList().push_back(NewInst);
327 VMap[OldTI] = NewInst; // Add instruction map to value.
329 // Recursively clone any reachable successor blocks.
330 const TerminatorInst *TI = BB->getTerminator();
331 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
332 ToClone.push_back(TI->getSuccessor(i));
336 CodeInfo->ContainsCalls |= hasCalls;
337 CodeInfo->ContainsUnwinds |= isa<UnwindInst>(OldTI);
338 CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
339 CodeInfo->ContainsDynamicAllocas |= hasStaticAllocas &&
340 BB != &BB->getParent()->front();
343 if (ReturnInst *RI = dyn_cast<ReturnInst>(NewBB->getTerminator()))
344 Returns.push_back(RI);
347 /// ConstantFoldMappedInstruction - Constant fold the specified instruction,
348 /// mapping its operands through VMap if they are available.
349 Constant *PruningFunctionCloner::
350 ConstantFoldMappedInstruction(const Instruction *I) {
351 SmallVector<Constant*, 8> Ops;
352 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
353 if (Constant *Op = dyn_cast_or_null<Constant>(MapValue(I->getOperand(i),
355 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges)))
358 return 0; // All operands not constant!
360 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
361 return ConstantFoldCompareInstOperands(CI->getPredicate(), Ops[0], Ops[1],
364 if (const LoadInst *LI = dyn_cast<LoadInst>(I))
365 if (!LI->isVolatile())
366 return ConstantFoldLoadFromConstPtr(Ops[0], TD);
368 return ConstantFoldInstOperands(I->getOpcode(), I->getType(), Ops, TD);
371 /// CloneAndPruneFunctionInto - This works exactly like CloneFunctionInto,
372 /// except that it does some simple constant prop and DCE on the fly. The
373 /// effect of this is to copy significantly less code in cases where (for
374 /// example) a function call with constant arguments is inlined, and those
375 /// constant arguments cause a significant amount of code in the callee to be
376 /// dead. Since this doesn't produce an exact copy of the input, it can't be
377 /// used for things like CloneFunction or CloneModule.
378 void llvm::CloneAndPruneFunctionInto(Function *NewFunc, const Function *OldFunc,
379 ValueToValueMapTy &VMap,
380 bool ModuleLevelChanges,
381 SmallVectorImpl<ReturnInst*> &Returns,
382 const char *NameSuffix,
383 ClonedCodeInfo *CodeInfo,
384 const TargetData *TD,
385 Instruction *TheCall) {
386 assert(NameSuffix && "NameSuffix cannot be null!");
389 for (Function::const_arg_iterator II = OldFunc->arg_begin(),
390 E = OldFunc->arg_end(); II != E; ++II)
391 assert(VMap.count(II) && "No mapping from source argument specified!");
394 PruningFunctionCloner PFC(NewFunc, OldFunc, VMap, ModuleLevelChanges,
395 Returns, NameSuffix, CodeInfo, TD);
397 // Clone the entry block, and anything recursively reachable from it.
398 std::vector<const BasicBlock*> CloneWorklist;
399 CloneWorklist.push_back(&OldFunc->getEntryBlock());
400 while (!CloneWorklist.empty()) {
401 const BasicBlock *BB = CloneWorklist.back();
402 CloneWorklist.pop_back();
403 PFC.CloneBlock(BB, CloneWorklist);
406 // Loop over all of the basic blocks in the old function. If the block was
407 // reachable, we have cloned it and the old block is now in the value map:
408 // insert it into the new function in the right order. If not, ignore it.
410 // Defer PHI resolution until rest of function is resolved.
411 SmallVector<const PHINode*, 16> PHIToResolve;
412 for (Function::const_iterator BI = OldFunc->begin(), BE = OldFunc->end();
415 BasicBlock *NewBB = cast_or_null<BasicBlock>(V);
416 if (NewBB == 0) continue; // Dead block.
418 // Add the new block to the new function.
419 NewFunc->getBasicBlockList().push_back(NewBB);
421 // Loop over all of the instructions in the block, fixing up operand
422 // references as we go. This uses VMap to do all the hard work.
424 BasicBlock::iterator I = NewBB->begin();
428 TheCallDL = TheCall->getDebugLoc();
430 // Handle PHI nodes specially, as we have to remove references to dead
432 if (PHINode *PN = dyn_cast<PHINode>(I)) {
433 // Skip over all PHI nodes, remembering them for later.
434 BasicBlock::const_iterator OldI = BI->begin();
435 for (; (PN = dyn_cast<PHINode>(I)); ++I, ++OldI)
436 PHIToResolve.push_back(cast<PHINode>(OldI));
439 // Otherwise, remap the rest of the instructions normally.
440 for (; I != NewBB->end(); ++I)
441 RemapInstruction(I, VMap,
442 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
445 // Defer PHI resolution until rest of function is resolved, PHI resolution
446 // requires the CFG to be up-to-date.
447 for (unsigned phino = 0, e = PHIToResolve.size(); phino != e; ) {
448 const PHINode *OPN = PHIToResolve[phino];
449 unsigned NumPreds = OPN->getNumIncomingValues();
450 const BasicBlock *OldBB = OPN->getParent();
451 BasicBlock *NewBB = cast<BasicBlock>(VMap[OldBB]);
453 // Map operands for blocks that are live and remove operands for blocks
455 for (; phino != PHIToResolve.size() &&
456 PHIToResolve[phino]->getParent() == OldBB; ++phino) {
457 OPN = PHIToResolve[phino];
458 PHINode *PN = cast<PHINode>(VMap[OPN]);
459 for (unsigned pred = 0, e = NumPreds; pred != e; ++pred) {
460 Value *V = VMap[PN->getIncomingBlock(pred)];
461 if (BasicBlock *MappedBlock = cast_or_null<BasicBlock>(V)) {
462 Value *InVal = MapValue(PN->getIncomingValue(pred),
464 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
465 assert(InVal && "Unknown input value?");
466 PN->setIncomingValue(pred, InVal);
467 PN->setIncomingBlock(pred, MappedBlock);
469 PN->removeIncomingValue(pred, false);
470 --pred, --e; // Revisit the next entry.
475 // The loop above has removed PHI entries for those blocks that are dead
476 // and has updated others. However, if a block is live (i.e. copied over)
477 // but its terminator has been changed to not go to this block, then our
478 // phi nodes will have invalid entries. Update the PHI nodes in this
480 PHINode *PN = cast<PHINode>(NewBB->begin());
481 NumPreds = std::distance(pred_begin(NewBB), pred_end(NewBB));
482 if (NumPreds != PN->getNumIncomingValues()) {
483 assert(NumPreds < PN->getNumIncomingValues());
484 // Count how many times each predecessor comes to this block.
485 std::map<BasicBlock*, unsigned> PredCount;
486 for (pred_iterator PI = pred_begin(NewBB), E = pred_end(NewBB);
490 // Figure out how many entries to remove from each PHI.
491 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
492 ++PredCount[PN->getIncomingBlock(i)];
494 // At this point, the excess predecessor entries are positive in the
495 // map. Loop over all of the PHIs and remove excess predecessor
497 BasicBlock::iterator I = NewBB->begin();
498 for (; (PN = dyn_cast<PHINode>(I)); ++I) {
499 for (std::map<BasicBlock*, unsigned>::iterator PCI =PredCount.begin(),
500 E = PredCount.end(); PCI != E; ++PCI) {
501 BasicBlock *Pred = PCI->first;
502 for (unsigned NumToRemove = PCI->second; NumToRemove; --NumToRemove)
503 PN->removeIncomingValue(Pred, false);
508 // If the loops above have made these phi nodes have 0 or 1 operand,
509 // replace them with undef or the input value. We must do this for
510 // correctness, because 0-operand phis are not valid.
511 PN = cast<PHINode>(NewBB->begin());
512 if (PN->getNumIncomingValues() == 0) {
513 BasicBlock::iterator I = NewBB->begin();
514 BasicBlock::const_iterator OldI = OldBB->begin();
515 while ((PN = dyn_cast<PHINode>(I++))) {
516 Value *NV = UndefValue::get(PN->getType());
517 PN->replaceAllUsesWith(NV);
518 assert(VMap[OldI] == PN && "VMap mismatch");
520 PN->eraseFromParent();
524 // NOTE: We cannot eliminate single entry phi nodes here, because of
525 // VMap. Single entry phi nodes can have multiple VMap entries
526 // pointing at them. Thus, deleting one would require scanning the VMap
527 // to update any entries in it that would require that. This would be
531 // Now that the inlined function body has been fully constructed, go through
532 // and zap unconditional fall-through branches. This happen all the time when
533 // specializing code: code specialization turns conditional branches into
534 // uncond branches, and this code folds them.
535 Function::iterator I = cast<BasicBlock>(VMap[&OldFunc->getEntryBlock()]);
536 while (I != NewFunc->end()) {
537 BranchInst *BI = dyn_cast<BranchInst>(I->getTerminator());
538 if (!BI || BI->isConditional()) { ++I; continue; }
540 // Note that we can't eliminate uncond branches if the destination has
541 // single-entry PHI nodes. Eliminating the single-entry phi nodes would
542 // require scanning the VMap to update any entries that point to the phi
544 BasicBlock *Dest = BI->getSuccessor(0);
545 if (!Dest->getSinglePredecessor() || isa<PHINode>(Dest->begin())) {
549 // We know all single-entry PHI nodes in the inlined function have been
550 // removed, so we just need to splice the blocks.
551 BI->eraseFromParent();
553 // Make all PHI nodes that referred to Dest now refer to I as their source.
554 Dest->replaceAllUsesWith(I);
556 // Move all the instructions in the succ to the pred.
557 I->getInstList().splice(I->end(), Dest->getInstList());
559 // Remove the dest block.
560 Dest->eraseFromParent();
562 // Do not increment I, iteratively merge all things this block branches to.