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