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/ADT/SmallVector.h"
18 #include "llvm/Analysis/ConstantFolding.h"
19 #include "llvm/Analysis/InstructionSimplify.h"
20 #include "llvm/Constants.h"
21 #include "llvm/DebugInfo.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/Function.h"
24 #include "llvm/GlobalVariable.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/IntrinsicInst.h"
27 #include "llvm/LLVMContext.h"
28 #include "llvm/Metadata.h"
29 #include "llvm/Support/CFG.h"
30 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
31 #include "llvm/Transforms/Utils/Local.h"
32 #include "llvm/Transforms/Utils/ValueMapper.h"
36 // CloneBasicBlock - See comments in Cloning.h
37 BasicBlock *llvm::CloneBasicBlock(const BasicBlock *BB,
38 ValueToValueMapTy &VMap,
39 const Twine &NameSuffix, Function *F,
40 ClonedCodeInfo *CodeInfo) {
41 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "", F);
42 if (BB->hasName()) NewBB->setName(BB->getName()+NameSuffix);
44 bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false;
46 // Loop over all instructions, and copy them over.
47 for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end();
49 Instruction *NewInst = II->clone();
51 NewInst->setName(II->getName()+NameSuffix);
52 NewBB->getInstList().push_back(NewInst);
53 VMap[II] = NewInst; // Add instruction map to value.
55 hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II));
56 if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
57 if (isa<ConstantInt>(AI->getArraySize()))
58 hasStaticAllocas = true;
60 hasDynamicAllocas = true;
65 CodeInfo->ContainsCalls |= hasCalls;
66 CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
67 CodeInfo->ContainsDynamicAllocas |= hasStaticAllocas &&
68 BB != &BB->getParent()->getEntryBlock();
73 // Clone OldFunc into NewFunc, transforming the old arguments into references to
76 void llvm::CloneFunctionInto(Function *NewFunc, const Function *OldFunc,
77 ValueToValueMapTy &VMap,
78 bool ModuleLevelChanges,
79 SmallVectorImpl<ReturnInst*> &Returns,
80 const char *NameSuffix, ClonedCodeInfo *CodeInfo,
81 ValueMapTypeRemapper *TypeMapper) {
82 assert(NameSuffix && "NameSuffix cannot be null!");
85 for (Function::const_arg_iterator I = OldFunc->arg_begin(),
86 E = OldFunc->arg_end(); I != E; ++I)
87 assert(VMap.count(I) && "No mapping from source argument specified!");
90 // Clone any attributes.
91 if (NewFunc->arg_size() == OldFunc->arg_size())
92 NewFunc->copyAttributesFrom(OldFunc);
94 //Some arguments were deleted with the VMap. Copy arguments one by one
95 for (Function::const_arg_iterator I = OldFunc->arg_begin(),
96 E = OldFunc->arg_end(); I != E; ++I)
97 if (Argument* Anew = dyn_cast<Argument>(VMap[I]))
98 Anew->addAttr( OldFunc->getAttributes()
99 .getParamAttributes(I->getArgNo() + 1));
100 NewFunc->setAttributes(NewFunc->getAttributes()
101 .addAttr(NewFunc->getContext(),
102 AttributeSet::ReturnIndex,
103 OldFunc->getAttributes()
104 .getRetAttributes()));
105 NewFunc->setAttributes(NewFunc->getAttributes()
106 .addAttr(NewFunc->getContext(),
107 AttributeSet::FunctionIndex,
108 OldFunc->getAttributes()
109 .getFnAttributes()));
113 // Loop over all of the basic blocks in the function, cloning them as
114 // appropriate. Note that we save BE this way in order to handle cloning of
115 // recursive functions into themselves.
117 for (Function::const_iterator BI = OldFunc->begin(), BE = OldFunc->end();
119 const BasicBlock &BB = *BI;
121 // Create a new basic block and copy instructions into it!
122 BasicBlock *CBB = CloneBasicBlock(&BB, VMap, NameSuffix, NewFunc, CodeInfo);
124 // Add basic block mapping.
127 // It is only legal to clone a function if a block address within that
128 // function is never referenced outside of the function. Given that, we
129 // want to map block addresses from the old function to block addresses in
130 // the clone. (This is different from the generic ValueMapper
131 // implementation, which generates an invalid blockaddress when
132 // cloning a function.)
133 if (BB.hasAddressTaken()) {
134 Constant *OldBBAddr = BlockAddress::get(const_cast<Function*>(OldFunc),
135 const_cast<BasicBlock*>(&BB));
136 VMap[OldBBAddr] = BlockAddress::get(NewFunc, CBB);
139 // Note return instructions for the caller.
140 if (ReturnInst *RI = dyn_cast<ReturnInst>(CBB->getTerminator()))
141 Returns.push_back(RI);
144 // Loop over all of the instructions in the function, fixing up operand
145 // references as we go. This uses VMap to do all the hard work.
146 for (Function::iterator BB = cast<BasicBlock>(VMap[OldFunc->begin()]),
147 BE = NewFunc->end(); BB != BE; ++BB)
148 // Loop over all instructions, fixing each one as we find it...
149 for (BasicBlock::iterator II = BB->begin(); II != BB->end(); ++II)
150 RemapInstruction(II, VMap,
151 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
155 /// CloneFunction - Return a copy of the specified function, but without
156 /// embedding the function into another module. Also, any references specified
157 /// in the VMap are changed to refer to their mapped value instead of the
158 /// original one. If any of the arguments to the function are in the VMap,
159 /// the arguments are deleted from the resultant function. The VMap is
160 /// updated to include mappings from all of the instructions and basicblocks in
161 /// the function from their old to new values.
163 Function *llvm::CloneFunction(const Function *F, ValueToValueMapTy &VMap,
164 bool ModuleLevelChanges,
165 ClonedCodeInfo *CodeInfo) {
166 std::vector<Type*> ArgTypes;
168 // The user might be deleting arguments to the function by specifying them in
169 // the VMap. If so, we need to not add the arguments to the arg ty vector
171 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
173 if (VMap.count(I) == 0) // Haven't mapped the argument to anything yet?
174 ArgTypes.push_back(I->getType());
176 // Create a new function type...
177 FunctionType *FTy = FunctionType::get(F->getFunctionType()->getReturnType(),
178 ArgTypes, F->getFunctionType()->isVarArg());
180 // Create the new function...
181 Function *NewF = Function::Create(FTy, F->getLinkage(), F->getName());
183 // Loop over the arguments, copying the names of the mapped arguments over...
184 Function::arg_iterator DestI = NewF->arg_begin();
185 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
187 if (VMap.count(I) == 0) { // Is this argument preserved?
188 DestI->setName(I->getName()); // Copy the name over...
189 VMap[I] = DestI++; // Add mapping to VMap
192 SmallVector<ReturnInst*, 8> Returns; // Ignore returns cloned.
193 CloneFunctionInto(NewF, F, VMap, ModuleLevelChanges, Returns, "", CodeInfo);
200 /// PruningFunctionCloner - This class is a private class used to implement
201 /// the CloneAndPruneFunctionInto method.
202 struct PruningFunctionCloner {
204 const Function *OldFunc;
205 ValueToValueMapTy &VMap;
206 bool ModuleLevelChanges;
207 const char *NameSuffix;
208 ClonedCodeInfo *CodeInfo;
209 const DataLayout *TD;
211 PruningFunctionCloner(Function *newFunc, const Function *oldFunc,
212 ValueToValueMapTy &valueMap,
213 bool moduleLevelChanges,
214 const char *nameSuffix,
215 ClonedCodeInfo *codeInfo,
216 const DataLayout *td)
217 : NewFunc(newFunc), OldFunc(oldFunc),
218 VMap(valueMap), ModuleLevelChanges(moduleLevelChanges),
219 NameSuffix(nameSuffix), CodeInfo(codeInfo), TD(td) {
222 /// CloneBlock - The specified block is found to be reachable, clone it and
223 /// anything that it can reach.
224 void CloneBlock(const BasicBlock *BB,
225 std::vector<const BasicBlock*> &ToClone);
229 /// CloneBlock - The specified block is found to be reachable, clone it and
230 /// anything that it can reach.
231 void PruningFunctionCloner::CloneBlock(const BasicBlock *BB,
232 std::vector<const BasicBlock*> &ToClone){
233 WeakVH &BBEntry = VMap[BB];
235 // Have we already cloned this block?
238 // Nope, clone it now.
240 BBEntry = NewBB = BasicBlock::Create(BB->getContext());
241 if (BB->hasName()) NewBB->setName(BB->getName()+NameSuffix);
243 // It is only legal to clone a function if a block address within that
244 // function is never referenced outside of the function. Given that, we
245 // want to map block addresses from the old function to block addresses in
246 // the clone. (This is different from the generic ValueMapper
247 // implementation, which generates an invalid blockaddress when
248 // cloning a function.)
250 // Note that we don't need to fix the mapping for unreachable blocks;
251 // the default mapping there is safe.
252 if (BB->hasAddressTaken()) {
253 Constant *OldBBAddr = BlockAddress::get(const_cast<Function*>(OldFunc),
254 const_cast<BasicBlock*>(BB));
255 VMap[OldBBAddr] = BlockAddress::get(NewFunc, NewBB);
259 bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false;
261 // Loop over all instructions, and copy them over, DCE'ing as we go. This
262 // loop doesn't include the terminator.
263 for (BasicBlock::const_iterator II = BB->begin(), IE = --BB->end();
265 Instruction *NewInst = II->clone();
267 // Eagerly remap operands to the newly cloned instruction, except for PHI
268 // nodes for which we defer processing until we update the CFG.
269 if (!isa<PHINode>(NewInst)) {
270 RemapInstruction(NewInst, VMap,
271 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
273 // If we can simplify this instruction to some other value, simply add
274 // a mapping to that value rather than inserting a new instruction into
276 if (Value *V = SimplifyInstruction(NewInst, TD)) {
277 // On the off-chance that this simplifies to an instruction in the old
278 // function, map it back into the new function.
279 if (Value *MappedV = VMap.lookup(V))
289 NewInst->setName(II->getName()+NameSuffix);
290 VMap[II] = NewInst; // Add instruction map to value.
291 NewBB->getInstList().push_back(NewInst);
292 hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II));
293 if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
294 if (isa<ConstantInt>(AI->getArraySize()))
295 hasStaticAllocas = true;
297 hasDynamicAllocas = true;
301 // Finally, clone over the terminator.
302 const TerminatorInst *OldTI = BB->getTerminator();
303 bool TerminatorDone = false;
304 if (const BranchInst *BI = dyn_cast<BranchInst>(OldTI)) {
305 if (BI->isConditional()) {
306 // If the condition was a known constant in the callee...
307 ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
308 // Or is a known constant in the caller...
310 Value *V = VMap[BI->getCondition()];
311 Cond = dyn_cast_or_null<ConstantInt>(V);
314 // Constant fold to uncond branch!
316 BasicBlock *Dest = BI->getSuccessor(!Cond->getZExtValue());
317 VMap[OldTI] = BranchInst::Create(Dest, NewBB);
318 ToClone.push_back(Dest);
319 TerminatorDone = true;
322 } else if (const SwitchInst *SI = dyn_cast<SwitchInst>(OldTI)) {
323 // If switching on a value known constant in the caller.
324 ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition());
325 if (Cond == 0) { // Or known constant after constant prop in the callee...
326 Value *V = VMap[SI->getCondition()];
327 Cond = dyn_cast_or_null<ConstantInt>(V);
329 if (Cond) { // Constant fold to uncond branch!
330 SwitchInst::ConstCaseIt Case = SI->findCaseValue(Cond);
331 BasicBlock *Dest = const_cast<BasicBlock*>(Case.getCaseSuccessor());
332 VMap[OldTI] = BranchInst::Create(Dest, NewBB);
333 ToClone.push_back(Dest);
334 TerminatorDone = true;
338 if (!TerminatorDone) {
339 Instruction *NewInst = OldTI->clone();
340 if (OldTI->hasName())
341 NewInst->setName(OldTI->getName()+NameSuffix);
342 NewBB->getInstList().push_back(NewInst);
343 VMap[OldTI] = NewInst; // Add instruction map to value.
345 // Recursively clone any reachable successor blocks.
346 const TerminatorInst *TI = BB->getTerminator();
347 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
348 ToClone.push_back(TI->getSuccessor(i));
352 CodeInfo->ContainsCalls |= hasCalls;
353 CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
354 CodeInfo->ContainsDynamicAllocas |= hasStaticAllocas &&
355 BB != &BB->getParent()->front();
359 /// CloneAndPruneFunctionInto - This works exactly like CloneFunctionInto,
360 /// except that it does some simple constant prop and DCE on the fly. The
361 /// effect of this is to copy significantly less code in cases where (for
362 /// example) a function call with constant arguments is inlined, and those
363 /// constant arguments cause a significant amount of code in the callee to be
364 /// dead. Since this doesn't produce an exact copy of the input, it can't be
365 /// used for things like CloneFunction or CloneModule.
366 void llvm::CloneAndPruneFunctionInto(Function *NewFunc, const Function *OldFunc,
367 ValueToValueMapTy &VMap,
368 bool ModuleLevelChanges,
369 SmallVectorImpl<ReturnInst*> &Returns,
370 const char *NameSuffix,
371 ClonedCodeInfo *CodeInfo,
372 const DataLayout *TD,
373 Instruction *TheCall) {
374 assert(NameSuffix && "NameSuffix cannot be null!");
377 for (Function::const_arg_iterator II = OldFunc->arg_begin(),
378 E = OldFunc->arg_end(); II != E; ++II)
379 assert(VMap.count(II) && "No mapping from source argument specified!");
382 PruningFunctionCloner PFC(NewFunc, OldFunc, VMap, ModuleLevelChanges,
383 NameSuffix, CodeInfo, TD);
385 // Clone the entry block, and anything recursively reachable from it.
386 std::vector<const BasicBlock*> CloneWorklist;
387 CloneWorklist.push_back(&OldFunc->getEntryBlock());
388 while (!CloneWorklist.empty()) {
389 const BasicBlock *BB = CloneWorklist.back();
390 CloneWorklist.pop_back();
391 PFC.CloneBlock(BB, CloneWorklist);
394 // Loop over all of the basic blocks in the old function. If the block was
395 // reachable, we have cloned it and the old block is now in the value map:
396 // insert it into the new function in the right order. If not, ignore it.
398 // Defer PHI resolution until rest of function is resolved.
399 SmallVector<const PHINode*, 16> PHIToResolve;
400 for (Function::const_iterator BI = OldFunc->begin(), BE = OldFunc->end();
403 BasicBlock *NewBB = cast_or_null<BasicBlock>(V);
404 if (NewBB == 0) continue; // Dead block.
406 // Add the new block to the new function.
407 NewFunc->getBasicBlockList().push_back(NewBB);
409 // Handle PHI nodes specially, as we have to remove references to dead
411 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end(); I != E; ++I)
412 if (const PHINode *PN = dyn_cast<PHINode>(I))
413 PHIToResolve.push_back(PN);
417 // Finally, remap the terminator instructions, as those can't be remapped
418 // until all BBs are mapped.
419 RemapInstruction(NewBB->getTerminator(), VMap,
420 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
423 // Defer PHI resolution until rest of function is resolved, PHI resolution
424 // requires the CFG to be up-to-date.
425 for (unsigned phino = 0, e = PHIToResolve.size(); phino != e; ) {
426 const PHINode *OPN = PHIToResolve[phino];
427 unsigned NumPreds = OPN->getNumIncomingValues();
428 const BasicBlock *OldBB = OPN->getParent();
429 BasicBlock *NewBB = cast<BasicBlock>(VMap[OldBB]);
431 // Map operands for blocks that are live and remove operands for blocks
433 for (; phino != PHIToResolve.size() &&
434 PHIToResolve[phino]->getParent() == OldBB; ++phino) {
435 OPN = PHIToResolve[phino];
436 PHINode *PN = cast<PHINode>(VMap[OPN]);
437 for (unsigned pred = 0, e = NumPreds; pred != e; ++pred) {
438 Value *V = VMap[PN->getIncomingBlock(pred)];
439 if (BasicBlock *MappedBlock = cast_or_null<BasicBlock>(V)) {
440 Value *InVal = MapValue(PN->getIncomingValue(pred),
442 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
443 assert(InVal && "Unknown input value?");
444 PN->setIncomingValue(pred, InVal);
445 PN->setIncomingBlock(pred, MappedBlock);
447 PN->removeIncomingValue(pred, false);
448 --pred, --e; // Revisit the next entry.
453 // The loop above has removed PHI entries for those blocks that are dead
454 // and has updated others. However, if a block is live (i.e. copied over)
455 // but its terminator has been changed to not go to this block, then our
456 // phi nodes will have invalid entries. Update the PHI nodes in this
458 PHINode *PN = cast<PHINode>(NewBB->begin());
459 NumPreds = std::distance(pred_begin(NewBB), pred_end(NewBB));
460 if (NumPreds != PN->getNumIncomingValues()) {
461 assert(NumPreds < PN->getNumIncomingValues());
462 // Count how many times each predecessor comes to this block.
463 std::map<BasicBlock*, unsigned> PredCount;
464 for (pred_iterator PI = pred_begin(NewBB), E = pred_end(NewBB);
468 // Figure out how many entries to remove from each PHI.
469 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
470 ++PredCount[PN->getIncomingBlock(i)];
472 // At this point, the excess predecessor entries are positive in the
473 // map. Loop over all of the PHIs and remove excess predecessor
475 BasicBlock::iterator I = NewBB->begin();
476 for (; (PN = dyn_cast<PHINode>(I)); ++I) {
477 for (std::map<BasicBlock*, unsigned>::iterator PCI =PredCount.begin(),
478 E = PredCount.end(); PCI != E; ++PCI) {
479 BasicBlock *Pred = PCI->first;
480 for (unsigned NumToRemove = PCI->second; NumToRemove; --NumToRemove)
481 PN->removeIncomingValue(Pred, false);
486 // If the loops above have made these phi nodes have 0 or 1 operand,
487 // replace them with undef or the input value. We must do this for
488 // correctness, because 0-operand phis are not valid.
489 PN = cast<PHINode>(NewBB->begin());
490 if (PN->getNumIncomingValues() == 0) {
491 BasicBlock::iterator I = NewBB->begin();
492 BasicBlock::const_iterator OldI = OldBB->begin();
493 while ((PN = dyn_cast<PHINode>(I++))) {
494 Value *NV = UndefValue::get(PN->getType());
495 PN->replaceAllUsesWith(NV);
496 assert(VMap[OldI] == PN && "VMap mismatch");
498 PN->eraseFromParent();
504 // Make a second pass over the PHINodes now that all of them have been
505 // remapped into the new function, simplifying the PHINode and performing any
506 // recursive simplifications exposed. This will transparently update the
507 // WeakVH in the VMap. Notably, we rely on that so that if we coalesce
508 // two PHINodes, the iteration over the old PHIs remains valid, and the
509 // mapping will just map us to the new node (which may not even be a PHI
511 for (unsigned Idx = 0, Size = PHIToResolve.size(); Idx != Size; ++Idx)
512 if (PHINode *PN = dyn_cast<PHINode>(VMap[PHIToResolve[Idx]]))
513 recursivelySimplifyInstruction(PN, TD);
515 // Now that the inlined function body has been fully constructed, go through
516 // and zap unconditional fall-through branches. This happen all the time when
517 // specializing code: code specialization turns conditional branches into
518 // uncond branches, and this code folds them.
519 Function::iterator Begin = cast<BasicBlock>(VMap[&OldFunc->getEntryBlock()]);
520 Function::iterator I = Begin;
521 while (I != NewFunc->end()) {
522 // Check if this block has become dead during inlining or other
523 // simplifications. Note that the first block will appear dead, as it has
524 // not yet been wired up properly.
525 if (I != Begin && (pred_begin(I) == pred_end(I) ||
526 I->getSinglePredecessor() == I)) {
527 BasicBlock *DeadBB = I++;
528 DeleteDeadBlock(DeadBB);
532 // We need to simplify conditional branches and switches with a constant
533 // operand. We try to prune these out when cloning, but if the
534 // simplification required looking through PHI nodes, those are only
535 // available after forming the full basic block. That may leave some here,
536 // and we still want to prune the dead code as early as possible.
537 ConstantFoldTerminator(I);
539 BranchInst *BI = dyn_cast<BranchInst>(I->getTerminator());
540 if (!BI || BI->isConditional()) { ++I; continue; }
542 BasicBlock *Dest = BI->getSuccessor(0);
543 if (!Dest->getSinglePredecessor()) {
547 // We shouldn't be able to get single-entry PHI nodes here, as instsimplify
548 // above should have zapped all of them..
549 assert(!isa<PHINode>(Dest->begin()));
551 // We know all single-entry PHI nodes in the inlined function have been
552 // removed, so we just need to splice the blocks.
553 BI->eraseFromParent();
555 // Make all PHI nodes that referred to Dest now refer to I as their source.
556 Dest->replaceAllUsesWith(I);
558 // Move all the instructions in the succ to the pred.
559 I->getInstList().splice(I->end(), Dest->getInstList());
561 // Remove the dest block.
562 Dest->eraseFromParent();
564 // Do not increment I, iteratively merge all things this block branches to.
567 // Make a final pass over the basic blocks from theh old function to gather
568 // any return instructions which survived folding. We have to do this here
569 // because we can iteratively remove and merge returns above.
570 for (Function::iterator I = cast<BasicBlock>(VMap[&OldFunc->getEntryBlock()]),
573 if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator()))
574 Returns.push_back(RI);