Revert commit r207302 since build failures
[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/IR/CFG.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/DebugInfo.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/IR/Module.h"
31 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
32 #include "llvm/Transforms/Utils/Local.h"
33 #include "llvm/Transforms/Utils/ValueMapper.h"
34 #include <map>
35 #include <set>
36 using namespace llvm;
37
38 // CloneBasicBlock - See comments in Cloning.h
39 BasicBlock *llvm::CloneBasicBlock(const BasicBlock *BB,
40                                   ValueToValueMapTy &VMap,
41                                   const Twine &NameSuffix, Function *F,
42                                   ClonedCodeInfo *CodeInfo) {
43   BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "", F);
44   if (BB->hasName()) NewBB->setName(BB->getName()+NameSuffix);
45
46   bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false;
47   
48   // Loop over all instructions, and copy them over.
49   for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end();
50        II != IE; ++II) {
51     Instruction *NewInst = II->clone();
52     if (II->hasName())
53       NewInst->setName(II->getName()+NameSuffix);
54     NewBB->getInstList().push_back(NewInst);
55     VMap[II] = NewInst;                // Add instruction map to value.
56     
57     hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II));
58     if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
59       if (isa<ConstantInt>(AI->getArraySize()))
60         hasStaticAllocas = true;
61       else
62         hasDynamicAllocas = true;
63     }
64   }
65   
66   if (CodeInfo) {
67     CodeInfo->ContainsCalls          |= hasCalls;
68     CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
69     CodeInfo->ContainsDynamicAllocas |= hasStaticAllocas && 
70                                         BB != &BB->getParent()->getEntryBlock();
71   }
72   return NewBB;
73 }
74
75 // Clone OldFunc into NewFunc, transforming the old arguments into references to
76 // VMap values.
77 //
78 void llvm::CloneFunctionInto(Function *NewFunc, const Function *OldFunc,
79                              ValueToValueMapTy &VMap,
80                              bool ModuleLevelChanges,
81                              SmallVectorImpl<ReturnInst*> &Returns,
82                              const char *NameSuffix, ClonedCodeInfo *CodeInfo,
83                              ValueMapTypeRemapper *TypeMapper,
84                              ValueMaterializer *Materializer) {
85   assert(NameSuffix && "NameSuffix cannot be null!");
86
87 #ifndef NDEBUG
88   for (Function::const_arg_iterator I = OldFunc->arg_begin(), 
89        E = OldFunc->arg_end(); I != E; ++I)
90     assert(VMap.count(I) && "No mapping from source argument specified!");
91 #endif
92
93   // Copy all attributes other than those stored in the AttributeSet.  We need
94   // to remap the parameter indices of the AttributeSet.
95   AttributeSet NewAttrs = NewFunc->getAttributes();
96   NewFunc->copyAttributesFrom(OldFunc);
97   NewFunc->setAttributes(NewAttrs);
98
99   AttributeSet OldAttrs = OldFunc->getAttributes();
100   // Clone any argument attributes that are present in the VMap.
101   for (const Argument &OldArg : OldFunc->args())
102     if (Argument *NewArg = dyn_cast<Argument>(VMap[&OldArg])) {
103       AttributeSet attrs =
104           OldAttrs.getParamAttributes(OldArg.getArgNo() + 1);
105       if (attrs.getNumSlots() > 0)
106         NewArg->addAttr(attrs);
107     }
108
109   NewFunc->setAttributes(
110       NewFunc->getAttributes()
111           .addAttributes(NewFunc->getContext(), AttributeSet::ReturnIndex,
112                          OldAttrs.getRetAttributes())
113           .addAttributes(NewFunc->getContext(), AttributeSet::FunctionIndex,
114                          OldAttrs.getFnAttributes()));
115
116   // Loop over all of the basic blocks in the function, cloning them as
117   // appropriate.  Note that we save BE this way in order to handle cloning of
118   // recursive functions into themselves.
119   //
120   for (Function::const_iterator BI = OldFunc->begin(), BE = OldFunc->end();
121        BI != BE; ++BI) {
122     const BasicBlock &BB = *BI;
123
124     // Create a new basic block and copy instructions into it!
125     BasicBlock *CBB = CloneBasicBlock(&BB, VMap, NameSuffix, NewFunc, CodeInfo);
126
127     // Add basic block mapping.
128     VMap[&BB] = CBB;
129
130     // It is only legal to clone a function if a block address within that
131     // function is never referenced outside of the function.  Given that, we
132     // want to map block addresses from the old function to block addresses in
133     // the clone. (This is different from the generic ValueMapper
134     // implementation, which generates an invalid blockaddress when
135     // cloning a function.)
136     if (BB.hasAddressTaken()) {
137       Constant *OldBBAddr = BlockAddress::get(const_cast<Function*>(OldFunc),
138                                               const_cast<BasicBlock*>(&BB));
139       VMap[OldBBAddr] = BlockAddress::get(NewFunc, CBB);                                         
140     }
141
142     // Note return instructions for the caller.
143     if (ReturnInst *RI = dyn_cast<ReturnInst>(CBB->getTerminator()))
144       Returns.push_back(RI);
145   }
146
147   // Loop over all of the instructions in the function, fixing up operand
148   // references as we go.  This uses VMap to do all the hard work.
149   for (Function::iterator BB = cast<BasicBlock>(VMap[OldFunc->begin()]),
150          BE = NewFunc->end(); BB != BE; ++BB)
151     // Loop over all instructions, fixing each one as we find it...
152     for (BasicBlock::iterator II = BB->begin(); II != BB->end(); ++II)
153       RemapInstruction(II, VMap,
154                        ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
155                        TypeMapper, Materializer);
156 }
157
158 // Find the MDNode which corresponds to the DISubprogram data that described F.
159 static MDNode* FindSubprogram(const Function *F, DebugInfoFinder &Finder) {
160   for (DISubprogram Subprogram : Finder.subprograms()) {
161     if (Subprogram.describes(F)) return Subprogram;
162   }
163   return nullptr;
164 }
165
166 // Add an operand to an existing MDNode. The new operand will be added at the
167 // back of the operand list.
168 static void AddOperand(MDNode *Node, Value *Operand) {
169   SmallVector<Value*, 16> Operands;
170   for (unsigned i = 0; i < Node->getNumOperands(); i++) {
171     Operands.push_back(Node->getOperand(i));
172   }
173   Operands.push_back(Operand);
174   MDNode *NewNode = MDNode::get(Node->getContext(), Operands);
175   Node->replaceAllUsesWith(NewNode);
176 }
177
178 // Clone the module-level debug info associated with OldFunc. The cloned data
179 // will point to NewFunc instead.
180 static void CloneDebugInfoMetadata(Function *NewFunc, const Function *OldFunc,
181                             ValueToValueMapTy &VMap) {
182   DebugInfoFinder Finder;
183   Finder.processModule(*OldFunc->getParent());
184
185   const MDNode *OldSubprogramMDNode = FindSubprogram(OldFunc, Finder);
186   if (!OldSubprogramMDNode) return;
187
188   // Ensure that OldFunc appears in the map.
189   // (if it's already there it must point to NewFunc anyway)
190   VMap[OldFunc] = NewFunc;
191   DISubprogram NewSubprogram(MapValue(OldSubprogramMDNode, VMap));
192
193   for (DICompileUnit CU : Finder.compile_units()) {
194     DIArray Subprograms(CU.getSubprograms());
195
196     // If the compile unit's function list contains the old function, it should
197     // also contain the new one.
198     for (unsigned i = 0; i < Subprograms.getNumElements(); i++) {
199       if ((MDNode*)Subprograms.getElement(i) == OldSubprogramMDNode) {
200         AddOperand(Subprograms, NewSubprogram);
201       }
202     }
203   }
204 }
205
206 /// CloneFunction - Return a copy of the specified function, but without
207 /// embedding the function into another module.  Also, any references specified
208 /// in the VMap are changed to refer to their mapped value instead of the
209 /// original one.  If any of the arguments to the function are in the VMap,
210 /// the arguments are deleted from the resultant function.  The VMap is
211 /// updated to include mappings from all of the instructions and basicblocks in
212 /// the function from their old to new values.
213 ///
214 Function *llvm::CloneFunction(const Function *F, ValueToValueMapTy &VMap,
215                               bool ModuleLevelChanges,
216                               ClonedCodeInfo *CodeInfo) {
217   std::vector<Type*> ArgTypes;
218
219   // The user might be deleting arguments to the function by specifying them in
220   // the VMap.  If so, we need to not add the arguments to the arg ty vector
221   //
222   for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
223        I != E; ++I)
224     if (VMap.count(I) == 0)  // Haven't mapped the argument to anything yet?
225       ArgTypes.push_back(I->getType());
226
227   // Create a new function type...
228   FunctionType *FTy = FunctionType::get(F->getFunctionType()->getReturnType(),
229                                     ArgTypes, F->getFunctionType()->isVarArg());
230
231   // Create the new function...
232   Function *NewF = Function::Create(FTy, F->getLinkage(), F->getName());
233
234   // Loop over the arguments, copying the names of the mapped arguments over...
235   Function::arg_iterator DestI = NewF->arg_begin();
236   for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
237        I != E; ++I)
238     if (VMap.count(I) == 0) {   // Is this argument preserved?
239       DestI->setName(I->getName()); // Copy the name over...
240       VMap[I] = DestI++;        // Add mapping to VMap
241     }
242
243   if (ModuleLevelChanges)
244     CloneDebugInfoMetadata(NewF, F, VMap);
245
246   SmallVector<ReturnInst*, 8> Returns;  // Ignore returns cloned.
247   CloneFunctionInto(NewF, F, VMap, ModuleLevelChanges, Returns, "", CodeInfo);
248   return NewF;
249 }
250
251
252
253 namespace {
254   /// PruningFunctionCloner - This class is a private class used to implement
255   /// the CloneAndPruneFunctionInto method.
256   struct PruningFunctionCloner {
257     Function *NewFunc;
258     const Function *OldFunc;
259     ValueToValueMapTy &VMap;
260     bool ModuleLevelChanges;
261     const char *NameSuffix;
262     ClonedCodeInfo *CodeInfo;
263     const DataLayout *DL;
264   public:
265     PruningFunctionCloner(Function *newFunc, const Function *oldFunc,
266                           ValueToValueMapTy &valueMap,
267                           bool moduleLevelChanges,
268                           const char *nameSuffix, 
269                           ClonedCodeInfo *codeInfo,
270                           const DataLayout *DL)
271     : NewFunc(newFunc), OldFunc(oldFunc),
272       VMap(valueMap), ModuleLevelChanges(moduleLevelChanges),
273       NameSuffix(nameSuffix), CodeInfo(codeInfo), DL(DL) {
274     }
275
276     /// CloneBlock - The specified block is found to be reachable, so clone it
277     /// into newBB.
278     void CloneBlock(const BasicBlock *BB,
279                     BasicBlock *NewBB,
280                     std::vector<const BasicBlock *> &ToClone,
281                     std::set<const BasicBlock *> &OrigBBs);
282   };
283 }
284
285 /// CloneBlock - The specified block is found to be reachable, so clone it
286 /// into newBB.
287 void PruningFunctionCloner::CloneBlock(const BasicBlock *BB,
288                                        BasicBlock *NewBB,
289                                        std::vector<const BasicBlock *> &ToClone,
290                                        std::set<const BasicBlock *> &OrigBBs) {
291   
292   // Remove BB from list of blocks to clone.
293   // When it was not in the list, it has been cloned already, so
294   // don't clone again.
295   if (!OrigBBs.erase(BB)) return;
296
297   // Nope, clone it now.
298
299   bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false;
300   
301   // Loop over all instructions, and copy them over, DCE'ing as we go.  This
302   // loop doesn't include the terminator.
303   for (BasicBlock::const_iterator II = BB->begin(), IE = --BB->end();
304        II != IE; ++II) {
305     Instruction *NewInst = II->clone();
306
307     // Eagerly remap operands to the newly cloned instruction, except for PHI
308     // nodes for which we defer processing until we update the CFG.
309     if (!isa<PHINode>(NewInst)) {
310       RemapInstruction(NewInst, VMap,
311                        ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
312
313       // If we can simplify this instruction to some other value, simply add
314       // a mapping to that value rather than inserting a new instruction into
315       // the basic block.
316       if (Value *V = SimplifyInstruction(NewInst, DL)) {
317         // On the off-chance that this simplifies to an instruction in the old
318         // function, map it back into the new function.
319         if (Value *MappedV = VMap.lookup(V))
320           V = MappedV;
321
322         VMap[II] = V;
323         delete NewInst;
324         continue;
325       }
326     }
327
328     if (II->hasName())
329       NewInst->setName(II->getName()+NameSuffix);
330     VMap[II] = NewInst;                // Add instruction map to value.
331     NewBB->getInstList().push_back(NewInst);
332     hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II));
333     if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
334       if (isa<ConstantInt>(AI->getArraySize()))
335         hasStaticAllocas = true;
336       else
337         hasDynamicAllocas = true;
338     }
339   }
340   
341   // Finally, clone over the terminator.
342   const TerminatorInst *OldTI = BB->getTerminator();
343   bool TerminatorDone = false;
344   if (const BranchInst *BI = dyn_cast<BranchInst>(OldTI)) {
345     if (BI->isConditional()) {
346       // If the condition was a known constant in the callee...
347       ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
348       // Or is a known constant in the caller...
349       if (!Cond) {
350         Value *V = VMap[BI->getCondition()];
351         Cond = dyn_cast_or_null<ConstantInt>(V);
352       }
353
354       // Constant fold to uncond branch!
355       if (Cond) {
356         BasicBlock *Dest = BI->getSuccessor(!Cond->getZExtValue());
357         VMap[OldTI] = BranchInst::Create(Dest, NewBB);
358         ToClone.push_back(Dest);
359         TerminatorDone = true;
360       }
361     }
362   } else if (const SwitchInst *SI = dyn_cast<SwitchInst>(OldTI)) {
363     // If switching on a value known constant in the caller.
364     ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition());
365     if (!Cond) { // Or known constant after constant prop in the callee...
366       Value *V = VMap[SI->getCondition()];
367       Cond = dyn_cast_or_null<ConstantInt>(V);
368     }
369     if (Cond) {     // Constant fold to uncond branch!
370       SwitchInst::ConstCaseIt Case = SI->findCaseValue(Cond);
371       BasicBlock *Dest = const_cast<BasicBlock*>(Case.getCaseSuccessor());
372       VMap[OldTI] = BranchInst::Create(Dest, NewBB);
373       ToClone.push_back(Dest);
374       TerminatorDone = true;
375     }
376   }
377   
378   if (!TerminatorDone) {
379     Instruction *NewInst = OldTI->clone();
380     if (OldTI->hasName())
381       NewInst->setName(OldTI->getName()+NameSuffix);
382     NewBB->getInstList().push_back(NewInst);
383     VMap[OldTI] = NewInst;             // Add instruction map to value.
384     
385     // Recursively clone any reachable successor blocks.
386     const TerminatorInst *TI = BB->getTerminator();
387     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
388       ToClone.push_back(TI->getSuccessor(i));
389   }
390   
391   if (CodeInfo) {
392     CodeInfo->ContainsCalls          |= hasCalls;
393     CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
394     CodeInfo->ContainsDynamicAllocas |= hasStaticAllocas && 
395       BB != &BB->getParent()->front();
396   }
397 }
398
399 /// CloneAndPruneFunctionInto - This works exactly like CloneFunctionInto,
400 /// except that it does some simple constant prop and DCE on the fly.  The
401 /// effect of this is to copy significantly less code in cases where (for
402 /// example) a function call with constant arguments is inlined, and those
403 /// constant arguments cause a significant amount of code in the callee to be
404 /// dead.  Since this doesn't produce an exact copy of the input, it can't be
405 /// used for things like CloneFunction or CloneModule.
406 void llvm::CloneAndPruneFunctionInto(Function *NewFunc, const Function *OldFunc,
407                                      ValueToValueMapTy &VMap,
408                                      bool ModuleLevelChanges,
409                                      SmallVectorImpl<ReturnInst*> &Returns,
410                                      const char *NameSuffix, 
411                                      ClonedCodeInfo *CodeInfo,
412                                      const DataLayout *DL,
413                                      Instruction *TheCall) {
414   assert(NameSuffix && "NameSuffix cannot be null!");
415
416 #ifndef NDEBUG
417   for (Function::const_arg_iterator II = OldFunc->arg_begin(), 
418        E = OldFunc->arg_end(); II != E; ++II)
419     assert(VMap.count(II) && "No mapping from source argument specified!");
420 #endif
421
422   PruningFunctionCloner PFC(NewFunc, OldFunc, VMap, ModuleLevelChanges,
423                             NameSuffix, CodeInfo, DL);
424
425   // Since all BB address references need to be known before block-by-block
426   // processing, we need to create all reachable blocks before processing
427   // them for instruction cloning and pruning. Some of these blocks may
428   // be removed due to later pruning.
429   std::vector<const BasicBlock*> CloneWorklist;
430   //
431   // OrigBBs consists of all blocks reachable from the entry
432   // block.
433   // This list will be pruned down by the CloneFunction() currently
434   // (March 2014) due to two optimizations:
435   // First, when a conditional branch target is known at compile-time,
436   // only the actual branch destination block needs to be cloned.
437   // Second, when a switch statement target is known at compile-time,
438   // only the actual case statement needs to be cloned.
439   std::set<const BasicBlock*> OrigBBs;
440
441   CloneWorklist.push_back(&OldFunc->getEntryBlock());
442   while (!CloneWorklist.empty()) {
443     const BasicBlock *BB = CloneWorklist.back();
444     CloneWorklist.pop_back();
445
446     // Don't revisit blocks.
447     if (VMap.count(BB))
448       continue;
449
450     BasicBlock *NewBB = BasicBlock::Create(BB->getContext());
451     if (BB->hasName()) NewBB->setName(BB->getName()+NameSuffix);
452
453     // It is only legal to clone a function if a block address within that
454     // function is never referenced outside of the function.  Given that, we
455     // want to map block addresses from the old function to block addresses in
456     // the clone. (This is different from the generic ValueMapper
457     // implementation, which generates an invalid blockaddress when
458     // cloning a function.)
459     //
460     // Note that we don't need to fix the mapping for unreachable blocks;
461     // the default mapping there is safe.
462     if (BB->hasAddressTaken()) {
463       Constant *OldBBAddr = BlockAddress::get(const_cast<Function*>(OldFunc),
464                                               const_cast<BasicBlock*>(BB));
465       VMap[OldBBAddr] = BlockAddress::get(NewFunc, NewBB);
466     }
467
468     OrigBBs.insert(BB);
469     VMap[BB] = NewBB;
470     // Iterate over all possible successors and add them to the CloneWorklist.
471     const TerminatorInst *Term = BB->getTerminator();
472     for (unsigned i = 0, e = Term->getNumSuccessors(); i != e; ++i) {
473       BasicBlock *Succ = Term->getSuccessor(i);
474       CloneWorklist.push_back(Succ);
475     }
476   }
477
478   // Now, fill only the reachable blocks with the cloned contents
479   // of the originals.
480   assert(CloneWorklist.empty() && "Dirty worklist before re-use\n");
481   CloneWorklist.push_back(&OldFunc->getEntryBlock());
482   while (!CloneWorklist.empty()) {
483     const BasicBlock *BB = CloneWorklist.back();
484     CloneWorklist.pop_back();
485     PFC.CloneBlock(BB, cast<BasicBlock>(VMap[BB]), CloneWorklist,
486                    OrigBBs);
487   }
488
489   // Removed BB's that were created that turned out to be prunable.
490   // Actual cloning may have found pruning opportunities since
491   // branch or switch statement target may have been known at compile-time.
492   // Alternatively we could write a routine CloneFunction and add a) a
493   // parameter to actually do the cloning and b) a return parameter that
494   // gives a list of blocks that need to be cloned also. Then we could
495   // call CloneFunction when we collect the blocks to call, but suppress
496   // cloning. And actually *do* the cloning in the while loop above. Also
497   // the cleanup here would become redundant, and so would be the OrigBBs.
498   for (std::set<const BasicBlock *>::iterator Oi = OrigBBs.begin(),
499        Oe = OrigBBs.end(); Oi != Oe; ++Oi) {
500     const BasicBlock *Orig = *Oi;
501     BasicBlock *NewBB = cast<BasicBlock>(VMap[Orig]);
502     delete NewBB;
503     VMap[Orig] = 0;
504   }
505
506   // Loop over all of the basic blocks in the old function.  If the block was
507   // reachable, we have cloned it and the old block is now in the value map:
508   // insert it into the new function in the right order.  If not, ignore it.
509   //
510   // Defer PHI resolution until rest of function is resolved.
511   SmallVector<const PHINode*, 16> PHIToResolve;
512   for (Function::const_iterator BI = OldFunc->begin(), BE = OldFunc->end();
513        BI != BE; ++BI) {
514     Value *V = VMap[BI];
515     BasicBlock *NewBB = cast_or_null<BasicBlock>(V);
516     if (!NewBB) continue;  // Dead block.
517
518     // Add the new block to the new function.
519     NewFunc->getBasicBlockList().push_back(NewBB);
520
521     // Handle PHI nodes specially, as we have to remove references to dead
522     // blocks.
523     for (BasicBlock::const_iterator I = BI->begin(), E = BI->end(); I != E; ++I)
524       if (const PHINode *PN = dyn_cast<PHINode>(I))
525         PHIToResolve.push_back(PN);
526       else
527         break;
528
529     // Finally, remap the terminator instructions, as those can't be remapped
530     // until all BBs are mapped.
531     RemapInstruction(NewBB->getTerminator(), VMap,
532                      ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
533   }
534   
535   // Defer PHI resolution until rest of function is resolved, PHI resolution
536   // requires the CFG to be up-to-date.
537   for (unsigned phino = 0, e = PHIToResolve.size(); phino != e; ) {
538     const PHINode *OPN = PHIToResolve[phino];
539     unsigned NumPreds = OPN->getNumIncomingValues();
540     const BasicBlock *OldBB = OPN->getParent();
541     BasicBlock *NewBB = cast<BasicBlock>(VMap[OldBB]);
542
543     // Map operands for blocks that are live and remove operands for blocks
544     // that are dead.
545     for (; phino != PHIToResolve.size() &&
546          PHIToResolve[phino]->getParent() == OldBB; ++phino) {
547       OPN = PHIToResolve[phino];
548       PHINode *PN = cast<PHINode>(VMap[OPN]);
549       for (unsigned pred = 0, e = NumPreds; pred != e; ++pred) {
550         Value *V = VMap[PN->getIncomingBlock(pred)];
551         if (BasicBlock *MappedBlock = cast_or_null<BasicBlock>(V)) {
552           Value *InVal = MapValue(PN->getIncomingValue(pred),
553                                   VMap, 
554                         ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
555           assert(InVal && "Unknown input value?");
556           PN->setIncomingValue(pred, InVal);
557           PN->setIncomingBlock(pred, MappedBlock);
558         } else {
559           PN->removeIncomingValue(pred, false);
560           --pred, --e;  // Revisit the next entry.
561         }
562       } 
563     }
564     
565     // The loop above has removed PHI entries for those blocks that are dead
566     // and has updated others.  However, if a block is live (i.e. copied over)
567     // but its terminator has been changed to not go to this block, then our
568     // phi nodes will have invalid entries.  Update the PHI nodes in this
569     // case.
570     PHINode *PN = cast<PHINode>(NewBB->begin());
571     NumPreds = std::distance(pred_begin(NewBB), pred_end(NewBB));
572     if (NumPreds != PN->getNumIncomingValues()) {
573       assert(NumPreds < PN->getNumIncomingValues());
574       // Count how many times each predecessor comes to this block.
575       std::map<BasicBlock*, unsigned> PredCount;
576       for (pred_iterator PI = pred_begin(NewBB), E = pred_end(NewBB);
577            PI != E; ++PI)
578         --PredCount[*PI];
579       
580       // Figure out how many entries to remove from each PHI.
581       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
582         ++PredCount[PN->getIncomingBlock(i)];
583       
584       // At this point, the excess predecessor entries are positive in the
585       // map.  Loop over all of the PHIs and remove excess predecessor
586       // entries.
587       BasicBlock::iterator I = NewBB->begin();
588       for (; (PN = dyn_cast<PHINode>(I)); ++I) {
589         for (std::map<BasicBlock*, unsigned>::iterator PCI =PredCount.begin(),
590              E = PredCount.end(); PCI != E; ++PCI) {
591           BasicBlock *Pred     = PCI->first;
592           for (unsigned NumToRemove = PCI->second; NumToRemove; --NumToRemove)
593             PN->removeIncomingValue(Pred, false);
594         }
595       }
596     }
597     
598     // If the loops above have made these phi nodes have 0 or 1 operand,
599     // replace them with undef or the input value.  We must do this for
600     // correctness, because 0-operand phis are not valid.
601     PN = cast<PHINode>(NewBB->begin());
602     if (PN->getNumIncomingValues() == 0) {
603       BasicBlock::iterator I = NewBB->begin();
604       BasicBlock::const_iterator OldI = OldBB->begin();
605       while ((PN = dyn_cast<PHINode>(I++))) {
606         Value *NV = UndefValue::get(PN->getType());
607         PN->replaceAllUsesWith(NV);
608         assert(VMap[OldI] == PN && "VMap mismatch");
609         VMap[OldI] = NV;
610         PN->eraseFromParent();
611         ++OldI;
612       }
613     }
614   }
615
616   // Make a second pass over the PHINodes now that all of them have been
617   // remapped into the new function, simplifying the PHINode and performing any
618   // recursive simplifications exposed. This will transparently update the
619   // WeakVH in the VMap. Notably, we rely on that so that if we coalesce
620   // two PHINodes, the iteration over the old PHIs remains valid, and the
621   // mapping will just map us to the new node (which may not even be a PHI
622   // node).
623   for (unsigned Idx = 0, Size = PHIToResolve.size(); Idx != Size; ++Idx)
624     if (PHINode *PN = dyn_cast<PHINode>(VMap[PHIToResolve[Idx]]))
625       recursivelySimplifyInstruction(PN, DL);
626
627   // Now that the inlined function body has been fully constructed, go through
628   // and zap unconditional fall-through branches.  This happen all the time when
629   // specializing code: code specialization turns conditional branches into
630   // uncond branches, and this code folds them.
631   Function::iterator Begin = cast<BasicBlock>(VMap[&OldFunc->getEntryBlock()]);
632   Function::iterator I = Begin;
633   while (I != NewFunc->end()) {
634     // Check if this block has become dead during inlining or other
635     // simplifications. Note that the first block will appear dead, as it has
636     // not yet been wired up properly.
637     if (I != Begin && (pred_begin(I) == pred_end(I) ||
638                        I->getSinglePredecessor() == I)) {
639       BasicBlock *DeadBB = I++;
640       DeleteDeadBlock(DeadBB);
641       continue;
642     }
643
644     // We need to simplify conditional branches and switches with a constant
645     // operand. We try to prune these out when cloning, but if the
646     // simplification required looking through PHI nodes, those are only
647     // available after forming the full basic block. That may leave some here,
648     // and we still want to prune the dead code as early as possible.
649     ConstantFoldTerminator(I);
650
651     BranchInst *BI = dyn_cast<BranchInst>(I->getTerminator());
652     if (!BI || BI->isConditional()) { ++I; continue; }
653     
654     BasicBlock *Dest = BI->getSuccessor(0);
655     if (!Dest->getSinglePredecessor()) {
656       ++I; continue;
657     }
658
659     // We shouldn't be able to get single-entry PHI nodes here, as instsimplify
660     // above should have zapped all of them..
661     assert(!isa<PHINode>(Dest->begin()));
662
663     // We know all single-entry PHI nodes in the inlined function have been
664     // removed, so we just need to splice the blocks.
665     BI->eraseFromParent();
666     
667     // Make all PHI nodes that referred to Dest now refer to I as their source.
668     Dest->replaceAllUsesWith(I);
669
670     // Move all the instructions in the succ to the pred.
671     I->getInstList().splice(I->end(), Dest->getInstList());
672     
673     // Remove the dest block.
674     Dest->eraseFromParent();
675     
676     // Do not increment I, iteratively merge all things this block branches to.
677   }
678
679   // Make a final pass over the basic blocks from theh old function to gather
680   // any return instructions which survived folding. We have to do this here
681   // because we can iteratively remove and merge returns above.
682   for (Function::iterator I = cast<BasicBlock>(VMap[&OldFunc->getEntryBlock()]),
683                           E = NewFunc->end();
684        I != E; ++I)
685     if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator()))
686       Returns.push_back(RI);
687 }