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