1 //===- CloneFunction.cpp - Clone a function into another function ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
14 //===----------------------------------------------------------------------===//
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"
37 // CloneBasicBlock - See comments in Cloning.h
38 BasicBlock *llvm::CloneBasicBlock(const BasicBlock *BB,
39 ValueToValueMapTy &VMap,
40 const Twine &NameSuffix, Function *F,
41 ClonedCodeInfo *CodeInfo) {
42 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "", F);
43 if (BB->hasName()) NewBB->setName(BB->getName()+NameSuffix);
45 bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false;
47 // Loop over all instructions, and copy them over.
48 for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end();
50 Instruction *NewInst = II->clone();
52 NewInst->setName(II->getName()+NameSuffix);
53 NewBB->getInstList().push_back(NewInst);
54 VMap[II] = NewInst; // Add instruction map to value.
56 hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II));
57 if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
58 if (isa<ConstantInt>(AI->getArraySize()))
59 hasStaticAllocas = true;
61 hasDynamicAllocas = true;
66 CodeInfo->ContainsCalls |= hasCalls;
67 CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
68 CodeInfo->ContainsDynamicAllocas |= hasStaticAllocas &&
69 BB != &BB->getParent()->getEntryBlock();
74 // Clone OldFunc into NewFunc, transforming the old arguments into references to
77 void llvm::CloneFunctionInto(Function *NewFunc, const Function *OldFunc,
78 ValueToValueMapTy &VMap,
79 bool ModuleLevelChanges,
80 SmallVectorImpl<ReturnInst*> &Returns,
81 const char *NameSuffix, ClonedCodeInfo *CodeInfo,
82 ValueMapTypeRemapper *TypeMapper,
83 ValueMaterializer *Materializer) {
84 assert(NameSuffix && "NameSuffix cannot be null!");
87 for (Function::const_arg_iterator I = OldFunc->arg_begin(),
88 E = OldFunc->arg_end(); I != E; ++I)
89 assert(VMap.count(I) && "No mapping from source argument specified!");
92 AttributeSet OldAttrs = OldFunc->getAttributes();
93 // Clone any argument attributes that are present in the VMap.
94 for (Function::const_arg_iterator I = OldFunc->arg_begin(),
95 E = OldFunc->arg_end();
97 if (Argument *Anew = dyn_cast<Argument>(VMap[I])) {
99 OldAttrs.getParamAttributes(I->getArgNo() + 1);
100 if (attrs.getNumSlots() > 0)
101 Anew->addAttr(attrs);
104 NewFunc->setAttributes(NewFunc->getAttributes()
105 .addAttributes(NewFunc->getContext(),
106 AttributeSet::ReturnIndex,
107 OldAttrs.getRetAttributes()));
108 NewFunc->setAttributes(NewFunc->getAttributes()
109 .addAttributes(NewFunc->getContext(),
110 AttributeSet::FunctionIndex,
111 OldAttrs.getFnAttributes()));
113 // Loop over all of the basic blocks in the function, cloning them as
114 // appropriate. Note that we save BE this way in order to handle cloning of
115 // recursive functions into themselves.
117 for (Function::const_iterator BI = OldFunc->begin(), BE = OldFunc->end();
119 const BasicBlock &BB = *BI;
121 // Create a new basic block and copy instructions into it!
122 BasicBlock *CBB = CloneBasicBlock(&BB, VMap, NameSuffix, NewFunc, CodeInfo);
124 // Add basic block mapping.
127 // It is only legal to clone a function if a block address within that
128 // function is never referenced outside of the function. Given that, we
129 // want to map block addresses from the old function to block addresses in
130 // the clone. (This is different from the generic ValueMapper
131 // implementation, which generates an invalid blockaddress when
132 // cloning a function.)
133 if (BB.hasAddressTaken()) {
134 Constant *OldBBAddr = BlockAddress::get(const_cast<Function*>(OldFunc),
135 const_cast<BasicBlock*>(&BB));
136 VMap[OldBBAddr] = BlockAddress::get(NewFunc, CBB);
139 // Note return instructions for the caller.
140 if (ReturnInst *RI = dyn_cast<ReturnInst>(CBB->getTerminator()))
141 Returns.push_back(RI);
144 // Loop over all of the instructions in the function, fixing up operand
145 // references as we go. This uses VMap to do all the hard work.
146 for (Function::iterator BB = cast<BasicBlock>(VMap[OldFunc->begin()]),
147 BE = NewFunc->end(); BB != BE; ++BB)
148 // Loop over all instructions, fixing each one as we find it...
149 for (BasicBlock::iterator II = BB->begin(); II != BB->end(); ++II)
150 RemapInstruction(II, VMap,
151 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
152 TypeMapper, Materializer);
155 // Find the MDNode which corresponds to the DISubprogram data that described F.
156 static MDNode* FindSubprogram(const Function *F, DebugInfoFinder &Finder) {
157 for (DebugInfoFinder::iterator I = Finder.subprogram_begin(),
158 E = Finder.subprogram_end();
160 DISubprogram Subprogram(*I);
161 if (Subprogram.describes(F)) return Subprogram;
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));
173 Operands.push_back(Operand);
174 MDNode *NewNode = MDNode::get(Node->getContext(), Operands);
175 Node->replaceAllUsesWith(NewNode);
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());
185 const MDNode *OldSubprogramMDNode = FindSubprogram(OldFunc, Finder);
186 if (!OldSubprogramMDNode) return;
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));
193 for (DebugInfoFinder::iterator CUIter = Finder.compile_unit_begin(),
194 CUEnd = Finder.compile_unit_end(); CUIter != CUEnd; ++CUIter) {
195 DICompileUnit CU(*CUIter);
197 DIArray Subprograms(CU.getSubprograms());
199 // If the compile unit's function list contains the old function, it should
200 // also contain the new one.
201 for (unsigned i = 0; i < Subprograms.getNumElements(); i++) {
202 if ((MDNode*)Subprograms.getElement(i) == OldSubprogramMDNode) {
203 AddOperand(Subprograms, NewSubprogram);
209 /// CloneFunction - Return a copy of the specified function, but without
210 /// embedding the function into another module. Also, any references specified
211 /// in the VMap are changed to refer to their mapped value instead of the
212 /// original one. If any of the arguments to the function are in the VMap,
213 /// the arguments are deleted from the resultant function. The VMap is
214 /// updated to include mappings from all of the instructions and basicblocks in
215 /// the function from their old to new values.
217 Function *llvm::CloneFunction(const Function *F, ValueToValueMapTy &VMap,
218 bool ModuleLevelChanges,
219 ClonedCodeInfo *CodeInfo) {
220 std::vector<Type*> ArgTypes;
222 // The user might be deleting arguments to the function by specifying them in
223 // the VMap. If so, we need to not add the arguments to the arg ty vector
225 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
227 if (VMap.count(I) == 0) // Haven't mapped the argument to anything yet?
228 ArgTypes.push_back(I->getType());
230 // Create a new function type...
231 FunctionType *FTy = FunctionType::get(F->getFunctionType()->getReturnType(),
232 ArgTypes, F->getFunctionType()->isVarArg());
234 // Create the new function...
235 Function *NewF = Function::Create(FTy, F->getLinkage(), F->getName());
237 // Loop over the arguments, copying the names of the mapped arguments over...
238 Function::arg_iterator DestI = NewF->arg_begin();
239 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
241 if (VMap.count(I) == 0) { // Is this argument preserved?
242 DestI->setName(I->getName()); // Copy the name over...
243 VMap[I] = DestI++; // Add mapping to VMap
246 if (ModuleLevelChanges)
247 CloneDebugInfoMetadata(NewF, F, VMap);
249 SmallVector<ReturnInst*, 8> Returns; // Ignore returns cloned.
250 CloneFunctionInto(NewF, F, VMap, ModuleLevelChanges, Returns, "", CodeInfo);
257 /// PruningFunctionCloner - This class is a private class used to implement
258 /// the CloneAndPruneFunctionInto method.
259 struct PruningFunctionCloner {
261 const Function *OldFunc;
262 ValueToValueMapTy &VMap;
263 bool ModuleLevelChanges;
264 const char *NameSuffix;
265 ClonedCodeInfo *CodeInfo;
266 const DataLayout *DL;
268 PruningFunctionCloner(Function *newFunc, const Function *oldFunc,
269 ValueToValueMapTy &valueMap,
270 bool moduleLevelChanges,
271 const char *nameSuffix,
272 ClonedCodeInfo *codeInfo,
273 const DataLayout *DL)
274 : NewFunc(newFunc), OldFunc(oldFunc),
275 VMap(valueMap), ModuleLevelChanges(moduleLevelChanges),
276 NameSuffix(nameSuffix), CodeInfo(codeInfo), DL(DL) {
279 /// CloneBlock - The specified block is found to be reachable, clone it and
280 /// anything that it can reach.
281 void CloneBlock(const BasicBlock *BB,
282 std::vector<const BasicBlock*> &ToClone);
286 /// CloneBlock - The specified block is found to be reachable, clone it and
287 /// anything that it can reach.
288 void PruningFunctionCloner::CloneBlock(const BasicBlock *BB,
289 std::vector<const BasicBlock*> &ToClone){
290 WeakVH &BBEntry = VMap[BB];
292 // Have we already cloned this block?
295 // Nope, clone it now.
297 BBEntry = NewBB = BasicBlock::Create(BB->getContext());
298 if (BB->hasName()) NewBB->setName(BB->getName()+NameSuffix);
300 // It is only legal to clone a function if a block address within that
301 // function is never referenced outside of the function. Given that, we
302 // want to map block addresses from the old function to block addresses in
303 // the clone. (This is different from the generic ValueMapper
304 // implementation, which generates an invalid blockaddress when
305 // cloning a function.)
307 // Note that we don't need to fix the mapping for unreachable blocks;
308 // the default mapping there is safe.
309 if (BB->hasAddressTaken()) {
310 Constant *OldBBAddr = BlockAddress::get(const_cast<Function*>(OldFunc),
311 const_cast<BasicBlock*>(BB));
312 VMap[OldBBAddr] = BlockAddress::get(NewFunc, NewBB);
316 bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false;
318 // Loop over all instructions, and copy them over, DCE'ing as we go. This
319 // loop doesn't include the terminator.
320 for (BasicBlock::const_iterator II = BB->begin(), IE = --BB->end();
322 Instruction *NewInst = II->clone();
324 // Eagerly remap operands to the newly cloned instruction, except for PHI
325 // nodes for which we defer processing until we update the CFG.
326 if (!isa<PHINode>(NewInst)) {
327 RemapInstruction(NewInst, VMap,
328 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
330 // If we can simplify this instruction to some other value, simply add
331 // a mapping to that value rather than inserting a new instruction into
333 if (Value *V = SimplifyInstruction(NewInst, DL)) {
334 // On the off-chance that this simplifies to an instruction in the old
335 // function, map it back into the new function.
336 if (Value *MappedV = VMap.lookup(V))
346 NewInst->setName(II->getName()+NameSuffix);
347 VMap[II] = NewInst; // Add instruction map to value.
348 NewBB->getInstList().push_back(NewInst);
349 hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II));
350 if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
351 if (isa<ConstantInt>(AI->getArraySize()))
352 hasStaticAllocas = true;
354 hasDynamicAllocas = true;
358 // Finally, clone over the terminator.
359 const TerminatorInst *OldTI = BB->getTerminator();
360 bool TerminatorDone = false;
361 if (const BranchInst *BI = dyn_cast<BranchInst>(OldTI)) {
362 if (BI->isConditional()) {
363 // If the condition was a known constant in the callee...
364 ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
365 // Or is a known constant in the caller...
367 Value *V = VMap[BI->getCondition()];
368 Cond = dyn_cast_or_null<ConstantInt>(V);
371 // Constant fold to uncond branch!
373 BasicBlock *Dest = BI->getSuccessor(!Cond->getZExtValue());
374 VMap[OldTI] = BranchInst::Create(Dest, NewBB);
375 ToClone.push_back(Dest);
376 TerminatorDone = true;
379 } else if (const SwitchInst *SI = dyn_cast<SwitchInst>(OldTI)) {
380 // If switching on a value known constant in the caller.
381 ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition());
382 if (Cond == 0) { // Or known constant after constant prop in the callee...
383 Value *V = VMap[SI->getCondition()];
384 Cond = dyn_cast_or_null<ConstantInt>(V);
386 if (Cond) { // Constant fold to uncond branch!
387 SwitchInst::ConstCaseIt Case = SI->findCaseValue(Cond);
388 BasicBlock *Dest = const_cast<BasicBlock*>(Case.getCaseSuccessor());
389 VMap[OldTI] = BranchInst::Create(Dest, NewBB);
390 ToClone.push_back(Dest);
391 TerminatorDone = true;
395 if (!TerminatorDone) {
396 Instruction *NewInst = OldTI->clone();
397 if (OldTI->hasName())
398 NewInst->setName(OldTI->getName()+NameSuffix);
399 NewBB->getInstList().push_back(NewInst);
400 VMap[OldTI] = NewInst; // Add instruction map to value.
402 // Recursively clone any reachable successor blocks.
403 const TerminatorInst *TI = BB->getTerminator();
404 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
405 ToClone.push_back(TI->getSuccessor(i));
409 CodeInfo->ContainsCalls |= hasCalls;
410 CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
411 CodeInfo->ContainsDynamicAllocas |= hasStaticAllocas &&
412 BB != &BB->getParent()->front();
416 /// CloneAndPruneFunctionInto - This works exactly like CloneFunctionInto,
417 /// except that it does some simple constant prop and DCE on the fly. The
418 /// effect of this is to copy significantly less code in cases where (for
419 /// example) a function call with constant arguments is inlined, and those
420 /// constant arguments cause a significant amount of code in the callee to be
421 /// dead. Since this doesn't produce an exact copy of the input, it can't be
422 /// used for things like CloneFunction or CloneModule.
423 void llvm::CloneAndPruneFunctionInto(Function *NewFunc, const Function *OldFunc,
424 ValueToValueMapTy &VMap,
425 bool ModuleLevelChanges,
426 SmallVectorImpl<ReturnInst*> &Returns,
427 const char *NameSuffix,
428 ClonedCodeInfo *CodeInfo,
429 const DataLayout *DL,
430 Instruction *TheCall) {
431 assert(NameSuffix && "NameSuffix cannot be null!");
434 for (Function::const_arg_iterator II = OldFunc->arg_begin(),
435 E = OldFunc->arg_end(); II != E; ++II)
436 assert(VMap.count(II) && "No mapping from source argument specified!");
439 PruningFunctionCloner PFC(NewFunc, OldFunc, VMap, ModuleLevelChanges,
440 NameSuffix, CodeInfo, DL);
442 // Clone the entry block, and anything recursively reachable from it.
443 std::vector<const BasicBlock*> CloneWorklist;
444 CloneWorklist.push_back(&OldFunc->getEntryBlock());
445 while (!CloneWorklist.empty()) {
446 const BasicBlock *BB = CloneWorklist.back();
447 CloneWorklist.pop_back();
448 PFC.CloneBlock(BB, CloneWorklist);
451 // Loop over all of the basic blocks in the old function. If the block was
452 // reachable, we have cloned it and the old block is now in the value map:
453 // insert it into the new function in the right order. If not, ignore it.
455 // Defer PHI resolution until rest of function is resolved.
456 SmallVector<const PHINode*, 16> PHIToResolve;
457 for (Function::const_iterator BI = OldFunc->begin(), BE = OldFunc->end();
460 BasicBlock *NewBB = cast_or_null<BasicBlock>(V);
461 if (NewBB == 0) continue; // Dead block.
463 // Add the new block to the new function.
464 NewFunc->getBasicBlockList().push_back(NewBB);
466 // Handle PHI nodes specially, as we have to remove references to dead
468 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end(); I != E; ++I)
469 if (const PHINode *PN = dyn_cast<PHINode>(I))
470 PHIToResolve.push_back(PN);
474 // Finally, remap the terminator instructions, as those can't be remapped
475 // until all BBs are mapped.
476 RemapInstruction(NewBB->getTerminator(), VMap,
477 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
480 // Defer PHI resolution until rest of function is resolved, PHI resolution
481 // requires the CFG to be up-to-date.
482 for (unsigned phino = 0, e = PHIToResolve.size(); phino != e; ) {
483 const PHINode *OPN = PHIToResolve[phino];
484 unsigned NumPreds = OPN->getNumIncomingValues();
485 const BasicBlock *OldBB = OPN->getParent();
486 BasicBlock *NewBB = cast<BasicBlock>(VMap[OldBB]);
488 // Map operands for blocks that are live and remove operands for blocks
490 for (; phino != PHIToResolve.size() &&
491 PHIToResolve[phino]->getParent() == OldBB; ++phino) {
492 OPN = PHIToResolve[phino];
493 PHINode *PN = cast<PHINode>(VMap[OPN]);
494 for (unsigned pred = 0, e = NumPreds; pred != e; ++pred) {
495 Value *V = VMap[PN->getIncomingBlock(pred)];
496 if (BasicBlock *MappedBlock = cast_or_null<BasicBlock>(V)) {
497 Value *InVal = MapValue(PN->getIncomingValue(pred),
499 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
500 assert(InVal && "Unknown input value?");
501 PN->setIncomingValue(pred, InVal);
502 PN->setIncomingBlock(pred, MappedBlock);
504 PN->removeIncomingValue(pred, false);
505 --pred, --e; // Revisit the next entry.
510 // The loop above has removed PHI entries for those blocks that are dead
511 // and has updated others. However, if a block is live (i.e. copied over)
512 // but its terminator has been changed to not go to this block, then our
513 // phi nodes will have invalid entries. Update the PHI nodes in this
515 PHINode *PN = cast<PHINode>(NewBB->begin());
516 NumPreds = std::distance(pred_begin(NewBB), pred_end(NewBB));
517 if (NumPreds != PN->getNumIncomingValues()) {
518 assert(NumPreds < PN->getNumIncomingValues());
519 // Count how many times each predecessor comes to this block.
520 std::map<BasicBlock*, unsigned> PredCount;
521 for (pred_iterator PI = pred_begin(NewBB), E = pred_end(NewBB);
525 // Figure out how many entries to remove from each PHI.
526 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
527 ++PredCount[PN->getIncomingBlock(i)];
529 // At this point, the excess predecessor entries are positive in the
530 // map. Loop over all of the PHIs and remove excess predecessor
532 BasicBlock::iterator I = NewBB->begin();
533 for (; (PN = dyn_cast<PHINode>(I)); ++I) {
534 for (std::map<BasicBlock*, unsigned>::iterator PCI =PredCount.begin(),
535 E = PredCount.end(); PCI != E; ++PCI) {
536 BasicBlock *Pred = PCI->first;
537 for (unsigned NumToRemove = PCI->second; NumToRemove; --NumToRemove)
538 PN->removeIncomingValue(Pred, false);
543 // If the loops above have made these phi nodes have 0 or 1 operand,
544 // replace them with undef or the input value. We must do this for
545 // correctness, because 0-operand phis are not valid.
546 PN = cast<PHINode>(NewBB->begin());
547 if (PN->getNumIncomingValues() == 0) {
548 BasicBlock::iterator I = NewBB->begin();
549 BasicBlock::const_iterator OldI = OldBB->begin();
550 while ((PN = dyn_cast<PHINode>(I++))) {
551 Value *NV = UndefValue::get(PN->getType());
552 PN->replaceAllUsesWith(NV);
553 assert(VMap[OldI] == PN && "VMap mismatch");
555 PN->eraseFromParent();
561 // Make a second pass over the PHINodes now that all of them have been
562 // remapped into the new function, simplifying the PHINode and performing any
563 // recursive simplifications exposed. This will transparently update the
564 // WeakVH in the VMap. Notably, we rely on that so that if we coalesce
565 // two PHINodes, the iteration over the old PHIs remains valid, and the
566 // mapping will just map us to the new node (which may not even be a PHI
568 for (unsigned Idx = 0, Size = PHIToResolve.size(); Idx != Size; ++Idx)
569 if (PHINode *PN = dyn_cast<PHINode>(VMap[PHIToResolve[Idx]]))
570 recursivelySimplifyInstruction(PN, DL);
572 // Now that the inlined function body has been fully constructed, go through
573 // and zap unconditional fall-through branches. This happen all the time when
574 // specializing code: code specialization turns conditional branches into
575 // uncond branches, and this code folds them.
576 Function::iterator Begin = cast<BasicBlock>(VMap[&OldFunc->getEntryBlock()]);
577 Function::iterator I = Begin;
578 while (I != NewFunc->end()) {
579 // Check if this block has become dead during inlining or other
580 // simplifications. Note that the first block will appear dead, as it has
581 // not yet been wired up properly.
582 if (I != Begin && (pred_begin(I) == pred_end(I) ||
583 I->getSinglePredecessor() == I)) {
584 BasicBlock *DeadBB = I++;
585 DeleteDeadBlock(DeadBB);
589 // We need to simplify conditional branches and switches with a constant
590 // operand. We try to prune these out when cloning, but if the
591 // simplification required looking through PHI nodes, those are only
592 // available after forming the full basic block. That may leave some here,
593 // and we still want to prune the dead code as early as possible.
594 ConstantFoldTerminator(I);
596 BranchInst *BI = dyn_cast<BranchInst>(I->getTerminator());
597 if (!BI || BI->isConditional()) { ++I; continue; }
599 BasicBlock *Dest = BI->getSuccessor(0);
600 if (!Dest->getSinglePredecessor()) {
604 // We shouldn't be able to get single-entry PHI nodes here, as instsimplify
605 // above should have zapped all of them..
606 assert(!isa<PHINode>(Dest->begin()));
608 // We know all single-entry PHI nodes in the inlined function have been
609 // removed, so we just need to splice the blocks.
610 BI->eraseFromParent();
612 // Make all PHI nodes that referred to Dest now refer to I as their source.
613 Dest->replaceAllUsesWith(I);
615 // Move all the instructions in the succ to the pred.
616 I->getInstList().splice(I->end(), Dest->getInstList());
618 // Remove the dest block.
619 Dest->eraseFromParent();
621 // Do not increment I, iteratively merge all things this block branches to.
624 // Make a final pass over the basic blocks from theh old function to gather
625 // any return instructions which survived folding. We have to do this here
626 // because we can iteratively remove and merge returns above.
627 for (Function::iterator I = cast<BasicBlock>(VMap[&OldFunc->getEntryBlock()]),
630 if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator()))
631 Returns.push_back(RI);