CloneFunction.cpp revision 051a950000e21935165db56695e35bade668193b
1//===- CloneFunction.cpp - Clone a function into another function ---------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
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.
13//
14//===----------------------------------------------------------------------===//
15
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/Function.h"
21#include "llvm/Support/CFG.h"
22#include "llvm/Support/Compiler.h"
23#include "llvm/Transforms/Utils/ValueMapper.h"
24#include "llvm/Analysis/ConstantFolding.h"
25#include "llvm/ADT/SmallVector.h"
26#include <map>
27using namespace llvm;
28
29// CloneBasicBlock - See comments in Cloning.h
30BasicBlock *llvm::CloneBasicBlock(const BasicBlock *BB,
31                                  DenseMap<const Value*, Value*> &ValueMap,
32                                  const char *NameSuffix, Function *F,
33                                  ClonedCodeInfo *CodeInfo) {
34  BasicBlock *NewBB = BasicBlock::Create("", F);
35  if (BB->hasName()) NewBB->setName(BB->getName()+NameSuffix);
36  NewBB->setUnwindDest(const_cast<BasicBlock*>(BB->getUnwindDest()));
37
38  bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false;
39
40  // Loop over all instructions, and copy them over.
41  for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end();
42       II != IE; ++II) {
43    Instruction *NewInst = II->clone();
44    if (II->hasName())
45      NewInst->setName(II->getName()+NameSuffix);
46    NewBB->getInstList().push_back(NewInst);
47    ValueMap[II] = NewInst;                // Add instruction map to value.
48
49    hasCalls |= isa<CallInst>(II);
50    if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
51      if (isa<ConstantInt>(AI->getArraySize()))
52        hasStaticAllocas = true;
53      else
54        hasDynamicAllocas = true;
55    }
56  }
57
58  if (CodeInfo) {
59    CodeInfo->ContainsCalls          |= hasCalls;
60    CodeInfo->ContainsUnwinds        |= isa<UnwindInst>(BB->getTerminator());
61    CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
62    CodeInfo->ContainsDynamicAllocas |= hasStaticAllocas &&
63                                        BB != &BB->getParent()->getEntryBlock();
64  }
65  return NewBB;
66}
67
68// Clone OldFunc into NewFunc, transforming the old arguments into references to
69// ArgMap values.
70//
71void llvm::CloneFunctionInto(Function *NewFunc, const Function *OldFunc,
72                             DenseMap<const Value*, Value*> &ValueMap,
73                             std::vector<ReturnInst*> &Returns,
74                             const char *NameSuffix, ClonedCodeInfo *CodeInfo) {
75  assert(NameSuffix && "NameSuffix cannot be null!");
76
77#ifndef NDEBUG
78  for (Function::const_arg_iterator I = OldFunc->arg_begin(),
79       E = OldFunc->arg_end(); I != E; ++I)
80    assert(ValueMap.count(I) && "No mapping from source argument specified!");
81#endif
82
83  // Clone the parameter attributes
84  NewFunc->setParamAttrs(OldFunc->getParamAttrs());
85
86  // Clone the calling convention
87  NewFunc->setCallingConv(OldFunc->getCallingConv());
88
89  // Loop over all of the basic blocks in the function, cloning them as
90  // appropriate.  Note that we save BE this way in order to handle cloning of
91  // recursive functions into themselves.
92  //
93  for (Function::const_iterator BI = OldFunc->begin(), BE = OldFunc->end();
94       BI != BE; ++BI) {
95    const BasicBlock &BB = *BI;
96
97    // Create a new basic block and copy instructions into it!
98    BasicBlock *CBB = CloneBasicBlock(&BB, ValueMap, NameSuffix, NewFunc,
99                                      CodeInfo);
100    ValueMap[&BB] = CBB;                       // Add basic block mapping.
101
102    if (ReturnInst *RI = dyn_cast<ReturnInst>(CBB->getTerminator()))
103      Returns.push_back(RI);
104  }
105
106  // Loop over all of the instructions in the function, fixing up operand
107  // references as we go.  This uses ValueMap to do all the hard work.
108  //
109  for (Function::iterator BB = cast<BasicBlock>(ValueMap[OldFunc->begin()]),
110         BE = NewFunc->end(); BB != BE; ++BB) {
111    // Fix up the unwind destination.
112    if (BasicBlock *UnwindDest = BB->getUnwindDest())
113      BB->setUnwindDest(cast<BasicBlock>(ValueMap[UnwindDest]));
114
115    // Loop over all instructions, fixing each one as we find it...
116    for (BasicBlock::iterator II = BB->begin(); II != BB->end(); ++II)
117      RemapInstruction(II, ValueMap);
118  }
119}
120
121/// CloneFunction - Return a copy of the specified function, but without
122/// embedding the function into another module.  Also, any references specified
123/// in the ValueMap are changed to refer to their mapped value instead of the
124/// original one.  If any of the arguments to the function are in the ValueMap,
125/// the arguments are deleted from the resultant function.  The ValueMap is
126/// updated to include mappings from all of the instructions and basicblocks in
127/// the function from their old to new values.
128///
129Function *llvm::CloneFunction(const Function *F,
130                              DenseMap<const Value*, Value*> &ValueMap,
131                              ClonedCodeInfo *CodeInfo) {
132  std::vector<const Type*> ArgTypes;
133
134  // The user might be deleting arguments to the function by specifying them in
135  // the ValueMap.  If so, we need to not add the arguments to the arg ty vector
136  //
137  for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
138       I != E; ++I)
139    if (ValueMap.count(I) == 0)  // Haven't mapped the argument to anything yet?
140      ArgTypes.push_back(I->getType());
141
142  // Create a new function type...
143  FunctionType *FTy = FunctionType::get(F->getFunctionType()->getReturnType(),
144                                    ArgTypes, F->getFunctionType()->isVarArg());
145
146  // Create the new function...
147  Function *NewF = Function::Create(FTy, F->getLinkage(), F->getName());
148
149  // Loop over the arguments, copying the names of the mapped arguments over...
150  Function::arg_iterator DestI = NewF->arg_begin();
151  for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
152       I != E; ++I)
153    if (ValueMap.count(I) == 0) {   // Is this argument preserved?
154      DestI->setName(I->getName()); // Copy the name over...
155      ValueMap[I] = DestI++;        // Add mapping to ValueMap
156    }
157
158  std::vector<ReturnInst*> Returns;  // Ignore returns cloned...
159  CloneFunctionInto(NewF, F, ValueMap, Returns, "", CodeInfo);
160  return NewF;
161}
162
163
164
165namespace {
166  /// PruningFunctionCloner - This class is a private class used to implement
167  /// the CloneAndPruneFunctionInto method.
168  struct VISIBILITY_HIDDEN PruningFunctionCloner {
169    Function *NewFunc;
170    const Function *OldFunc;
171    DenseMap<const Value*, Value*> &ValueMap;
172    std::vector<ReturnInst*> &Returns;
173    const char *NameSuffix;
174    ClonedCodeInfo *CodeInfo;
175    const TargetData *TD;
176
177  public:
178    PruningFunctionCloner(Function *newFunc, const Function *oldFunc,
179                          DenseMap<const Value*, Value*> &valueMap,
180                          std::vector<ReturnInst*> &returns,
181                          const char *nameSuffix,
182                          ClonedCodeInfo *codeInfo,
183                          const TargetData *td)
184    : NewFunc(newFunc), OldFunc(oldFunc), ValueMap(valueMap), Returns(returns),
185      NameSuffix(nameSuffix), CodeInfo(codeInfo), TD(td) {
186    }
187
188    /// CloneBlock - The specified block is found to be reachable, clone it and
189    /// anything that it can reach.
190    void CloneBlock(const BasicBlock *BB,
191                    std::vector<const BasicBlock*> &ToClone);
192
193  public:
194    /// ConstantFoldMappedInstruction - Constant fold the specified instruction,
195    /// mapping its operands through ValueMap if they are available.
196    Constant *ConstantFoldMappedInstruction(const Instruction *I);
197  };
198}
199
200/// CloneBlock - The specified block is found to be reachable, clone it and
201/// anything that it can reach.
202void PruningFunctionCloner::CloneBlock(const BasicBlock *BB,
203                                       std::vector<const BasicBlock*> &ToClone){
204  Value *&BBEntry = ValueMap[BB];
205
206  // Have we already cloned this block?
207  if (BBEntry) return;
208
209  // Nope, clone it now.
210  BasicBlock *NewBB;
211  BBEntry = NewBB = BasicBlock::Create();
212  if (BB->hasName()) NewBB->setName(BB->getName()+NameSuffix);
213
214  bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false;
215
216  // Loop over all instructions, and copy them over, DCE'ing as we go.  This
217  // loop doesn't include the terminator.
218  for (BasicBlock::const_iterator II = BB->begin(), IE = --BB->end();
219       II != IE; ++II) {
220    // If this instruction constant folds, don't bother cloning the instruction,
221    // instead, just add the constant to the value map.
222    if (Constant *C = ConstantFoldMappedInstruction(II)) {
223      ValueMap[II] = C;
224      continue;
225    }
226
227    Instruction *NewInst = II->clone();
228    if (II->hasName())
229      NewInst->setName(II->getName()+NameSuffix);
230    NewBB->getInstList().push_back(NewInst);
231    ValueMap[II] = NewInst;                // Add instruction map to value.
232
233    hasCalls |= isa<CallInst>(II);
234    if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
235      if (isa<ConstantInt>(AI->getArraySize()))
236        hasStaticAllocas = true;
237      else
238        hasDynamicAllocas = true;
239    }
240  }
241
242  // Finally, clone over the terminator.
243  const TerminatorInst *OldTI = BB->getTerminator();
244  bool TerminatorDone = false;
245  if (const BranchInst *BI = dyn_cast<BranchInst>(OldTI)) {
246    if (BI->isConditional()) {
247      // If the condition was a known constant in the callee...
248      ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
249      // Or is a known constant in the caller...
250      if (Cond == 0)
251        Cond = dyn_cast_or_null<ConstantInt>(ValueMap[BI->getCondition()]);
252
253      // Constant fold to uncond branch!
254      if (Cond) {
255        BasicBlock *Dest = BI->getSuccessor(!Cond->getZExtValue());
256        ValueMap[OldTI] = BranchInst::Create(Dest, NewBB);
257        ToClone.push_back(Dest);
258        TerminatorDone = true;
259      }
260    }
261  } else if (const SwitchInst *SI = dyn_cast<SwitchInst>(OldTI)) {
262    // If switching on a value known constant in the caller.
263    ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition());
264    if (Cond == 0)  // Or known constant after constant prop in the callee...
265      Cond = dyn_cast_or_null<ConstantInt>(ValueMap[SI->getCondition()]);
266    if (Cond) {     // Constant fold to uncond branch!
267      BasicBlock *Dest = SI->getSuccessor(SI->findCaseValue(Cond));
268      ValueMap[OldTI] = BranchInst::Create(Dest, NewBB);
269      ToClone.push_back(Dest);
270      TerminatorDone = true;
271    }
272  }
273
274  if (!TerminatorDone) {
275    Instruction *NewInst = OldTI->clone();
276    if (OldTI->hasName())
277      NewInst->setName(OldTI->getName()+NameSuffix);
278    NewBB->getInstList().push_back(NewInst);
279    ValueMap[OldTI] = NewInst;             // Add instruction map to value.
280
281    // Recursively clone any reachable successor blocks.
282    const TerminatorInst *TI = BB->getTerminator();
283    for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
284      ToClone.push_back(TI->getSuccessor(i));
285  }
286
287  if (CodeInfo) {
288    CodeInfo->ContainsCalls          |= hasCalls;
289    CodeInfo->ContainsUnwinds        |= isa<UnwindInst>(OldTI);
290    CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
291    CodeInfo->ContainsDynamicAllocas |= hasStaticAllocas &&
292      BB != &BB->getParent()->front();
293  }
294
295  if (ReturnInst *RI = dyn_cast<ReturnInst>(NewBB->getTerminator()))
296    Returns.push_back(RI);
297}
298
299/// ConstantFoldMappedInstruction - Constant fold the specified instruction,
300/// mapping its operands through ValueMap if they are available.
301Constant *PruningFunctionCloner::
302ConstantFoldMappedInstruction(const Instruction *I) {
303  SmallVector<Constant*, 8> Ops;
304  for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
305    if (Constant *Op = dyn_cast_or_null<Constant>(MapValue(I->getOperand(i),
306                                                           ValueMap)))
307      Ops.push_back(Op);
308    else
309      return 0;  // All operands not constant!
310
311
312  if (const CmpInst *CI = dyn_cast<CmpInst>(I))
313    return ConstantFoldCompareInstOperands(CI->getPredicate(),
314                                           &Ops[0], Ops.size(), TD);
315  else
316    return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
317                                    &Ops[0], Ops.size(), TD);
318}
319
320/// CloneAndPruneFunctionInto - This works exactly like CloneFunctionInto,
321/// except that it does some simple constant prop and DCE on the fly.  The
322/// effect of this is to copy significantly less code in cases where (for
323/// example) a function call with constant arguments is inlined, and those
324/// constant arguments cause a significant amount of code in the callee to be
325/// dead.  Since this doesn't produce an exact copy of the input, it can't be
326/// used for things like CloneFunction or CloneModule.
327void llvm::CloneAndPruneFunctionInto(Function *NewFunc, const Function *OldFunc,
328                                     DenseMap<const Value*, Value*> &ValueMap,
329                                     std::vector<ReturnInst*> &Returns,
330                                     const char *NameSuffix,
331                                     ClonedCodeInfo *CodeInfo,
332                                     const TargetData *TD) {
333  assert(NameSuffix && "NameSuffix cannot be null!");
334
335#ifndef NDEBUG
336  for (Function::const_arg_iterator II = OldFunc->arg_begin(),
337       E = OldFunc->arg_end(); II != E; ++II)
338    assert(ValueMap.count(II) && "No mapping from source argument specified!");
339#endif
340
341  PruningFunctionCloner PFC(NewFunc, OldFunc, ValueMap, Returns,
342                            NameSuffix, CodeInfo, TD);
343
344  // Clone the entry block, and anything recursively reachable from it.
345  std::vector<const BasicBlock*> CloneWorklist;
346  CloneWorklist.push_back(&OldFunc->getEntryBlock());
347  while (!CloneWorklist.empty()) {
348    const BasicBlock *BB = CloneWorklist.back();
349    CloneWorklist.pop_back();
350    PFC.CloneBlock(BB, CloneWorklist);
351  }
352
353  // Loop over all of the basic blocks in the old function.  If the block was
354  // reachable, we have cloned it and the old block is now in the value map:
355  // insert it into the new function in the right order.  If not, ignore it.
356  //
357  // Defer PHI resolution until rest of function is resolved.
358  std::vector<const PHINode*> PHIToResolve;
359  for (Function::const_iterator BI = OldFunc->begin(), BE = OldFunc->end();
360       BI != BE; ++BI) {
361    BasicBlock *NewBB = cast_or_null<BasicBlock>(ValueMap[BI]);
362    if (NewBB == 0) continue;  // Dead block.
363
364    // Add the new block to the new function.
365    NewFunc->getBasicBlockList().push_back(NewBB);
366
367    // Loop over all of the instructions in the block, fixing up operand
368    // references as we go.  This uses ValueMap to do all the hard work.
369    //
370    BasicBlock::iterator I = NewBB->begin();
371
372    // Handle PHI nodes specially, as we have to remove references to dead
373    // blocks.
374    if (PHINode *PN = dyn_cast<PHINode>(I)) {
375      // Skip over all PHI nodes, remembering them for later.
376      BasicBlock::const_iterator OldI = BI->begin();
377      for (; (PN = dyn_cast<PHINode>(I)); ++I, ++OldI)
378        PHIToResolve.push_back(cast<PHINode>(OldI));
379    }
380
381    // Otherwise, remap the rest of the instructions normally.
382    for (; I != NewBB->end(); ++I)
383      RemapInstruction(I, ValueMap);
384  }
385
386  // Defer PHI resolution until rest of function is resolved, PHI resolution
387  // requires the CFG to be up-to-date.
388  for (unsigned phino = 0, e = PHIToResolve.size(); phino != e; ) {
389    const PHINode *OPN = PHIToResolve[phino];
390    unsigned NumPreds = OPN->getNumIncomingValues();
391    const BasicBlock *OldBB = OPN->getParent();
392    BasicBlock *NewBB = cast<BasicBlock>(ValueMap[OldBB]);
393
394    // Map operands for blocks that are live and remove operands for blocks
395    // that are dead.
396    for (; phino != PHIToResolve.size() &&
397         PHIToResolve[phino]->getParent() == OldBB; ++phino) {
398      OPN = PHIToResolve[phino];
399      PHINode *PN = cast<PHINode>(ValueMap[OPN]);
400      for (unsigned pred = 0, e = NumPreds; pred != e; ++pred) {
401        if (BasicBlock *MappedBlock =
402            cast_or_null<BasicBlock>(ValueMap[PN->getIncomingBlock(pred)])) {
403          Value *InVal = MapValue(PN->getIncomingValue(pred), ValueMap);
404          assert(InVal && "Unknown input value?");
405          PN->setIncomingValue(pred, InVal);
406          PN->setIncomingBlock(pred, MappedBlock);
407        } else {
408          PN->removeIncomingValue(pred, false);
409          --pred, --e;  // Revisit the next entry.
410        }
411      }
412    }
413
414    // The loop above has removed PHI entries for those blocks that are dead
415    // and has updated others.  However, if a block is live (i.e. copied over)
416    // but its terminator has been changed to not go to this block, then our
417    // phi nodes will have invalid entries.  Update the PHI nodes in this
418    // case.
419    PHINode *PN = cast<PHINode>(NewBB->begin());
420    NumPreds = std::distance(pred_begin(NewBB), pred_end(NewBB));
421    if (NumPreds != PN->getNumIncomingValues()) {
422      assert(NumPreds < PN->getNumIncomingValues());
423      // Count how many times each predecessor comes to this block.
424      std::map<BasicBlock*, unsigned> PredCount;
425      for (pred_iterator PI = pred_begin(NewBB), E = pred_end(NewBB);
426           PI != E; ++PI)
427        --PredCount[*PI];
428
429      // Figure out how many entries to remove from each PHI.
430      for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
431        ++PredCount[PN->getIncomingBlock(i)];
432
433      // At this point, the excess predecessor entries are positive in the
434      // map.  Loop over all of the PHIs and remove excess predecessor
435      // entries.
436      BasicBlock::iterator I = NewBB->begin();
437      for (; (PN = dyn_cast<PHINode>(I)); ++I) {
438        for (std::map<BasicBlock*, unsigned>::iterator PCI =PredCount.begin(),
439             E = PredCount.end(); PCI != E; ++PCI) {
440          BasicBlock *Pred     = PCI->first;
441          for (unsigned NumToRemove = PCI->second; NumToRemove; --NumToRemove)
442            PN->removeIncomingValue(Pred, false);
443        }
444      }
445    }
446
447    // If the loops above have made these phi nodes have 0 or 1 operand,
448    // replace them with undef or the input value.  We must do this for
449    // correctness, because 0-operand phis are not valid.
450    PN = cast<PHINode>(NewBB->begin());
451    if (PN->getNumIncomingValues() == 0) {
452      BasicBlock::iterator I = NewBB->begin();
453      BasicBlock::const_iterator OldI = OldBB->begin();
454      while ((PN = dyn_cast<PHINode>(I++))) {
455        Value *NV = UndefValue::get(PN->getType());
456        PN->replaceAllUsesWith(NV);
457        assert(ValueMap[OldI] == PN && "ValueMap mismatch");
458        ValueMap[OldI] = NV;
459        PN->eraseFromParent();
460        ++OldI;
461      }
462    }
463    // NOTE: We cannot eliminate single entry phi nodes here, because of
464    // ValueMap.  Single entry phi nodes can have multiple ValueMap entries
465    // pointing at them.  Thus, deleting one would require scanning the ValueMap
466    // to update any entries in it that would require that.  This would be
467    // really slow.
468  }
469
470  // Now that the inlined function body has been fully constructed, go through
471  // and zap unconditional fall-through branches.  This happen all the time when
472  // specializing code: code specialization turns conditional branches into
473  // uncond branches, and this code folds them.
474  Function::iterator I = cast<BasicBlock>(ValueMap[&OldFunc->getEntryBlock()]);
475  while (I != NewFunc->end()) {
476    BranchInst *BI = dyn_cast<BranchInst>(I->getTerminator());
477    if (!BI || BI->isConditional()) { ++I; continue; }
478
479    // Note that we can't eliminate uncond branches if the destination has
480    // single-entry PHI nodes.  Eliminating the single-entry phi nodes would
481    // require scanning the ValueMap to update any entries that point to the phi
482    // node.
483    BasicBlock *Dest = BI->getSuccessor(0);
484    if (!Dest->getSinglePredecessor() || isa<PHINode>(Dest->begin())) {
485      ++I; continue;
486    }
487
488    // We know all single-entry PHI nodes in the inlined function have been
489    // removed, so we just need to splice the blocks.
490    BI->eraseFromParent();
491
492    // Move all the instructions in the succ to the pred.
493    I->getInstList().splice(I->end(), Dest->getInstList());
494
495    // Make all PHI nodes that referred to Dest now refer to I as their source.
496    Dest->replaceAllUsesWith(I);
497
498    // Remove the dest block.
499    Dest->eraseFromParent();
500
501    // Do not increment I, iteratively merge all things this block branches to.
502  }
503}
504