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