4d81a820728cb680dca85ff0292b494ffca835a8
[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/ADT/SmallVector.h"
18 #include "llvm/Analysis/ConstantFolding.h"
19 #include "llvm/Analysis/InstructionSimplify.h"
20 #include "llvm/DebugInfo.h"
21 #include "llvm/IR/CFG.h"
22 #include "llvm/IR/Constants.h"
23 #include "llvm/IR/DerivedTypes.h"
24 #include "llvm/IR/Function.h"
25 #include "llvm/IR/GlobalVariable.h"
26 #include "llvm/IR/Instructions.h"
27 #include "llvm/IR/IntrinsicInst.h"
28 #include "llvm/IR/LLVMContext.h"
29 #include "llvm/IR/Metadata.h"
30 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
31 #include "llvm/Transforms/Utils/Local.h"
32 #include "llvm/Transforms/Utils/ValueMapper.h"
33 #include <map>
34 using namespace llvm;
35
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);
43
44   bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false;
45   
46   // Loop over all instructions, and copy them over.
47   for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end();
48        II != IE; ++II) {
49     Instruction *NewInst = II->clone();
50     if (II->hasName())
51       NewInst->setName(II->getName()+NameSuffix);
52     NewBB->getInstList().push_back(NewInst);
53     VMap[II] = NewInst;                // Add instruction map to value.
54     
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;
59       else
60         hasDynamicAllocas = true;
61     }
62   }
63   
64   if (CodeInfo) {
65     CodeInfo->ContainsCalls          |= hasCalls;
66     CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
67     CodeInfo->ContainsDynamicAllocas |= hasStaticAllocas && 
68                                         BB != &BB->getParent()->getEntryBlock();
69   }
70   return NewBB;
71 }
72
73 // Clone OldFunc into NewFunc, transforming the old arguments into references to
74 // VMap values.
75 //
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                              ValueMaterializer *Materializer) {
83   assert(NameSuffix && "NameSuffix cannot be null!");
84
85 #ifndef NDEBUG
86   for (Function::const_arg_iterator I = OldFunc->arg_begin(), 
87        E = OldFunc->arg_end(); I != E; ++I)
88     assert(VMap.count(I) && "No mapping from source argument specified!");
89 #endif
90
91   AttributeSet OldAttrs = OldFunc->getAttributes();
92   // Clone any argument attributes that are present in the VMap.
93   for (Function::const_arg_iterator I = OldFunc->arg_begin(),
94                                     E = OldFunc->arg_end();
95        I != E; ++I)
96     if (Argument *Anew = dyn_cast<Argument>(VMap[I])) {
97       AttributeSet attrs =
98           OldAttrs.getParamAttributes(I->getArgNo() + 1);
99       if (attrs.getNumSlots() > 0)
100         Anew->addAttr(attrs);
101     }
102
103   NewFunc->setAttributes(NewFunc->getAttributes()
104                          .addAttributes(NewFunc->getContext(),
105                                         AttributeSet::ReturnIndex,
106                                         OldAttrs.getRetAttributes()));
107   NewFunc->setAttributes(NewFunc->getAttributes()
108                          .addAttributes(NewFunc->getContext(),
109                                         AttributeSet::FunctionIndex,
110                                         OldAttrs.getFnAttributes()));
111
112   // Loop over all of the basic blocks in the function, cloning them as
113   // appropriate.  Note that we save BE this way in order to handle cloning of
114   // recursive functions into themselves.
115   //
116   for (Function::const_iterator BI = OldFunc->begin(), BE = OldFunc->end();
117        BI != BE; ++BI) {
118     const BasicBlock &BB = *BI;
119
120     // Create a new basic block and copy instructions into it!
121     BasicBlock *CBB = CloneBasicBlock(&BB, VMap, NameSuffix, NewFunc, CodeInfo);
122
123     // Add basic block mapping.
124     VMap[&BB] = CBB;
125
126     // It is only legal to clone a function if a block address within that
127     // function is never referenced outside of the function.  Given that, we
128     // want to map block addresses from the old function to block addresses in
129     // the clone. (This is different from the generic ValueMapper
130     // implementation, which generates an invalid blockaddress when
131     // cloning a function.)
132     if (BB.hasAddressTaken()) {
133       Constant *OldBBAddr = BlockAddress::get(const_cast<Function*>(OldFunc),
134                                               const_cast<BasicBlock*>(&BB));
135       VMap[OldBBAddr] = BlockAddress::get(NewFunc, CBB);                                         
136     }
137
138     // Note return instructions for the caller.
139     if (ReturnInst *RI = dyn_cast<ReturnInst>(CBB->getTerminator()))
140       Returns.push_back(RI);
141   }
142
143   // Loop over all of the instructions in the function, fixing up operand
144   // references as we go.  This uses VMap to do all the hard work.
145   for (Function::iterator BB = cast<BasicBlock>(VMap[OldFunc->begin()]),
146          BE = NewFunc->end(); BB != BE; ++BB)
147     // Loop over all instructions, fixing each one as we find it...
148     for (BasicBlock::iterator II = BB->begin(); II != BB->end(); ++II)
149       RemapInstruction(II, VMap,
150                        ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
151                        TypeMapper, Materializer);
152 }
153
154 /// CloneFunction - Return a copy of the specified function, but without
155 /// embedding the function into another module.  Also, any references specified
156 /// in the VMap are changed to refer to their mapped value instead of the
157 /// original one.  If any of the arguments to the function are in the VMap,
158 /// the arguments are deleted from the resultant function.  The VMap is
159 /// updated to include mappings from all of the instructions and basicblocks in
160 /// the function from their old to new values.
161 ///
162 Function *llvm::CloneFunction(const Function *F, ValueToValueMapTy &VMap,
163                               bool ModuleLevelChanges,
164                               ClonedCodeInfo *CodeInfo) {
165   std::vector<Type*> ArgTypes;
166
167   // The user might be deleting arguments to the function by specifying them in
168   // the VMap.  If so, we need to not add the arguments to the arg ty vector
169   //
170   for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
171        I != E; ++I)
172     if (VMap.count(I) == 0)  // Haven't mapped the argument to anything yet?
173       ArgTypes.push_back(I->getType());
174
175   // Create a new function type...
176   FunctionType *FTy = FunctionType::get(F->getFunctionType()->getReturnType(),
177                                     ArgTypes, F->getFunctionType()->isVarArg());
178
179   // Create the new function...
180   Function *NewF = Function::Create(FTy, F->getLinkage(), F->getName());
181
182   // Loop over the arguments, copying the names of the mapped arguments over...
183   Function::arg_iterator DestI = NewF->arg_begin();
184   for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
185        I != E; ++I)
186     if (VMap.count(I) == 0) {   // Is this argument preserved?
187       DestI->setName(I->getName()); // Copy the name over...
188       VMap[I] = DestI++;        // Add mapping to VMap
189     }
190
191   SmallVector<ReturnInst*, 8> Returns;  // Ignore returns cloned.
192   CloneFunctionInto(NewF, F, VMap, ModuleLevelChanges, Returns, "", CodeInfo);
193   return NewF;
194 }
195
196
197
198 namespace {
199   /// PruningFunctionCloner - This class is a private class used to implement
200   /// the CloneAndPruneFunctionInto method.
201   struct PruningFunctionCloner {
202     Function *NewFunc;
203     const Function *OldFunc;
204     ValueToValueMapTy &VMap;
205     bool ModuleLevelChanges;
206     const char *NameSuffix;
207     ClonedCodeInfo *CodeInfo;
208     const DataLayout *DL;
209   public:
210     PruningFunctionCloner(Function *newFunc, const Function *oldFunc,
211                           ValueToValueMapTy &valueMap,
212                           bool moduleLevelChanges,
213                           const char *nameSuffix, 
214                           ClonedCodeInfo *codeInfo,
215                           const DataLayout *DL)
216     : NewFunc(newFunc), OldFunc(oldFunc),
217       VMap(valueMap), ModuleLevelChanges(moduleLevelChanges),
218       NameSuffix(nameSuffix), CodeInfo(codeInfo), DL(DL) {
219     }
220
221     /// CloneBlock - The specified block is found to be reachable, clone it and
222     /// anything that it can reach.
223     void CloneBlock(const BasicBlock *BB,
224                     std::vector<const BasicBlock*> &ToClone);
225   };
226 }
227
228 /// CloneBlock - The specified block is found to be reachable, clone it and
229 /// anything that it can reach.
230 void PruningFunctionCloner::CloneBlock(const BasicBlock *BB,
231                                        std::vector<const BasicBlock*> &ToClone){
232   WeakVH &BBEntry = VMap[BB];
233
234   // Have we already cloned this block?
235   if (BBEntry) return;
236   
237   // Nope, clone it now.
238   BasicBlock *NewBB;
239   BBEntry = NewBB = BasicBlock::Create(BB->getContext());
240   if (BB->hasName()) NewBB->setName(BB->getName()+NameSuffix);
241
242   // It is only legal to clone a function if a block address within that
243   // function is never referenced outside of the function.  Given that, we
244   // want to map block addresses from the old function to block addresses in
245   // the clone. (This is different from the generic ValueMapper
246   // implementation, which generates an invalid blockaddress when
247   // cloning a function.)
248   //
249   // Note that we don't need to fix the mapping for unreachable blocks;
250   // the default mapping there is safe.
251   if (BB->hasAddressTaken()) {
252     Constant *OldBBAddr = BlockAddress::get(const_cast<Function*>(OldFunc),
253                                             const_cast<BasicBlock*>(BB));
254     VMap[OldBBAddr] = BlockAddress::get(NewFunc, NewBB);
255   }
256     
257
258   bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false;
259   
260   // Loop over all instructions, and copy them over, DCE'ing as we go.  This
261   // loop doesn't include the terminator.
262   for (BasicBlock::const_iterator II = BB->begin(), IE = --BB->end();
263        II != IE; ++II) {
264     Instruction *NewInst = II->clone();
265
266     // Eagerly remap operands to the newly cloned instruction, except for PHI
267     // nodes for which we defer processing until we update the CFG.
268     if (!isa<PHINode>(NewInst)) {
269       RemapInstruction(NewInst, VMap,
270                        ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
271
272       // If we can simplify this instruction to some other value, simply add
273       // a mapping to that value rather than inserting a new instruction into
274       // the basic block.
275       if (Value *V = SimplifyInstruction(NewInst, DL)) {
276         // On the off-chance that this simplifies to an instruction in the old
277         // function, map it back into the new function.
278         if (Value *MappedV = VMap.lookup(V))
279           V = MappedV;
280
281         VMap[II] = V;
282         delete NewInst;
283         continue;
284       }
285     }
286
287     if (II->hasName())
288       NewInst->setName(II->getName()+NameSuffix);
289     VMap[II] = NewInst;                // Add instruction map to value.
290     NewBB->getInstList().push_back(NewInst);
291     hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II));
292     if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
293       if (isa<ConstantInt>(AI->getArraySize()))
294         hasStaticAllocas = true;
295       else
296         hasDynamicAllocas = true;
297     }
298   }
299   
300   // Finally, clone over the terminator.
301   const TerminatorInst *OldTI = BB->getTerminator();
302   bool TerminatorDone = false;
303   if (const BranchInst *BI = dyn_cast<BranchInst>(OldTI)) {
304     if (BI->isConditional()) {
305       // If the condition was a known constant in the callee...
306       ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
307       // Or is a known constant in the caller...
308       if (Cond == 0) {
309         Value *V = VMap[BI->getCondition()];
310         Cond = dyn_cast_or_null<ConstantInt>(V);
311       }
312
313       // Constant fold to uncond branch!
314       if (Cond) {
315         BasicBlock *Dest = BI->getSuccessor(!Cond->getZExtValue());
316         VMap[OldTI] = BranchInst::Create(Dest, NewBB);
317         ToClone.push_back(Dest);
318         TerminatorDone = true;
319       }
320     }
321   } else if (const SwitchInst *SI = dyn_cast<SwitchInst>(OldTI)) {
322     // If switching on a value known constant in the caller.
323     ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition());
324     if (Cond == 0) { // Or known constant after constant prop in the callee...
325       Value *V = VMap[SI->getCondition()];
326       Cond = dyn_cast_or_null<ConstantInt>(V);
327     }
328     if (Cond) {     // Constant fold to uncond branch!
329       SwitchInst::ConstCaseIt Case = SI->findCaseValue(Cond);
330       BasicBlock *Dest = const_cast<BasicBlock*>(Case.getCaseSuccessor());
331       VMap[OldTI] = BranchInst::Create(Dest, NewBB);
332       ToClone.push_back(Dest);
333       TerminatorDone = true;
334     }
335   }
336   
337   if (!TerminatorDone) {
338     Instruction *NewInst = OldTI->clone();
339     if (OldTI->hasName())
340       NewInst->setName(OldTI->getName()+NameSuffix);
341     NewBB->getInstList().push_back(NewInst);
342     VMap[OldTI] = NewInst;             // Add instruction map to value.
343     
344     // Recursively clone any reachable successor blocks.
345     const TerminatorInst *TI = BB->getTerminator();
346     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
347       ToClone.push_back(TI->getSuccessor(i));
348   }
349   
350   if (CodeInfo) {
351     CodeInfo->ContainsCalls          |= hasCalls;
352     CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
353     CodeInfo->ContainsDynamicAllocas |= hasStaticAllocas && 
354       BB != &BB->getParent()->front();
355   }
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 DataLayout *DL,
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                             NameSuffix, CodeInfo, DL);
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     // Handle PHI nodes specially, as we have to remove references to dead
409     // blocks.
410     for (BasicBlock::const_iterator I = BI->begin(), E = BI->end(); I != E; ++I)
411       if (const PHINode *PN = dyn_cast<PHINode>(I))
412         PHIToResolve.push_back(PN);
413       else
414         break;
415
416     // Finally, remap the terminator instructions, as those can't be remapped
417     // until all BBs are mapped.
418     RemapInstruction(NewBB->getTerminator(), VMap,
419                      ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
420   }
421   
422   // Defer PHI resolution until rest of function is resolved, PHI resolution
423   // requires the CFG to be up-to-date.
424   for (unsigned phino = 0, e = PHIToResolve.size(); phino != e; ) {
425     const PHINode *OPN = PHIToResolve[phino];
426     unsigned NumPreds = OPN->getNumIncomingValues();
427     const BasicBlock *OldBB = OPN->getParent();
428     BasicBlock *NewBB = cast<BasicBlock>(VMap[OldBB]);
429
430     // Map operands for blocks that are live and remove operands for blocks
431     // that are dead.
432     for (; phino != PHIToResolve.size() &&
433          PHIToResolve[phino]->getParent() == OldBB; ++phino) {
434       OPN = PHIToResolve[phino];
435       PHINode *PN = cast<PHINode>(VMap[OPN]);
436       for (unsigned pred = 0, e = NumPreds; pred != e; ++pred) {
437         Value *V = VMap[PN->getIncomingBlock(pred)];
438         if (BasicBlock *MappedBlock = cast_or_null<BasicBlock>(V)) {
439           Value *InVal = MapValue(PN->getIncomingValue(pred),
440                                   VMap, 
441                         ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
442           assert(InVal && "Unknown input value?");
443           PN->setIncomingValue(pred, InVal);
444           PN->setIncomingBlock(pred, MappedBlock);
445         } else {
446           PN->removeIncomingValue(pred, false);
447           --pred, --e;  // Revisit the next entry.
448         }
449       } 
450     }
451     
452     // The loop above has removed PHI entries for those blocks that are dead
453     // and has updated others.  However, if a block is live (i.e. copied over)
454     // but its terminator has been changed to not go to this block, then our
455     // phi nodes will have invalid entries.  Update the PHI nodes in this
456     // case.
457     PHINode *PN = cast<PHINode>(NewBB->begin());
458     NumPreds = std::distance(pred_begin(NewBB), pred_end(NewBB));
459     if (NumPreds != PN->getNumIncomingValues()) {
460       assert(NumPreds < PN->getNumIncomingValues());
461       // Count how many times each predecessor comes to this block.
462       std::map<BasicBlock*, unsigned> PredCount;
463       for (pred_iterator PI = pred_begin(NewBB), E = pred_end(NewBB);
464            PI != E; ++PI)
465         --PredCount[*PI];
466       
467       // Figure out how many entries to remove from each PHI.
468       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
469         ++PredCount[PN->getIncomingBlock(i)];
470       
471       // At this point, the excess predecessor entries are positive in the
472       // map.  Loop over all of the PHIs and remove excess predecessor
473       // entries.
474       BasicBlock::iterator I = NewBB->begin();
475       for (; (PN = dyn_cast<PHINode>(I)); ++I) {
476         for (std::map<BasicBlock*, unsigned>::iterator PCI =PredCount.begin(),
477              E = PredCount.end(); PCI != E; ++PCI) {
478           BasicBlock *Pred     = PCI->first;
479           for (unsigned NumToRemove = PCI->second; NumToRemove; --NumToRemove)
480             PN->removeIncomingValue(Pred, false);
481         }
482       }
483     }
484     
485     // If the loops above have made these phi nodes have 0 or 1 operand,
486     // replace them with undef or the input value.  We must do this for
487     // correctness, because 0-operand phis are not valid.
488     PN = cast<PHINode>(NewBB->begin());
489     if (PN->getNumIncomingValues() == 0) {
490       BasicBlock::iterator I = NewBB->begin();
491       BasicBlock::const_iterator OldI = OldBB->begin();
492       while ((PN = dyn_cast<PHINode>(I++))) {
493         Value *NV = UndefValue::get(PN->getType());
494         PN->replaceAllUsesWith(NV);
495         assert(VMap[OldI] == PN && "VMap mismatch");
496         VMap[OldI] = NV;
497         PN->eraseFromParent();
498         ++OldI;
499       }
500     }
501   }
502
503   // Make a second pass over the PHINodes now that all of them have been
504   // remapped into the new function, simplifying the PHINode and performing any
505   // recursive simplifications exposed. This will transparently update the
506   // WeakVH in the VMap. Notably, we rely on that so that if we coalesce
507   // two PHINodes, the iteration over the old PHIs remains valid, and the
508   // mapping will just map us to the new node (which may not even be a PHI
509   // node).
510   for (unsigned Idx = 0, Size = PHIToResolve.size(); Idx != Size; ++Idx)
511     if (PHINode *PN = dyn_cast<PHINode>(VMap[PHIToResolve[Idx]]))
512       recursivelySimplifyInstruction(PN, DL);
513
514   // Now that the inlined function body has been fully constructed, go through
515   // and zap unconditional fall-through branches.  This happen all the time when
516   // specializing code: code specialization turns conditional branches into
517   // uncond branches, and this code folds them.
518   Function::iterator Begin = cast<BasicBlock>(VMap[&OldFunc->getEntryBlock()]);
519   Function::iterator I = Begin;
520   while (I != NewFunc->end()) {
521     // Check if this block has become dead during inlining or other
522     // simplifications. Note that the first block will appear dead, as it has
523     // not yet been wired up properly.
524     if (I != Begin && (pred_begin(I) == pred_end(I) ||
525                        I->getSinglePredecessor() == I)) {
526       BasicBlock *DeadBB = I++;
527       DeleteDeadBlock(DeadBB);
528       continue;
529     }
530
531     // We need to simplify conditional branches and switches with a constant
532     // operand. We try to prune these out when cloning, but if the
533     // simplification required looking through PHI nodes, those are only
534     // available after forming the full basic block. That may leave some here,
535     // and we still want to prune the dead code as early as possible.
536     ConstantFoldTerminator(I);
537
538     BranchInst *BI = dyn_cast<BranchInst>(I->getTerminator());
539     if (!BI || BI->isConditional()) { ++I; continue; }
540     
541     BasicBlock *Dest = BI->getSuccessor(0);
542     if (!Dest->getSinglePredecessor()) {
543       ++I; continue;
544     }
545
546     // We shouldn't be able to get single-entry PHI nodes here, as instsimplify
547     // above should have zapped all of them..
548     assert(!isa<PHINode>(Dest->begin()));
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
566   // Make a final pass over the basic blocks from theh old function to gather
567   // any return instructions which survived folding. We have to do this here
568   // because we can iteratively remove and merge returns above.
569   for (Function::iterator I = cast<BasicBlock>(VMap[&OldFunc->getEntryBlock()]),
570                           E = NewFunc->end();
571        I != E; ++I)
572     if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator()))
573       Returns.push_back(RI);
574 }