CloneFunction.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  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. #include "llvm/Transforms/Utils/Cloning.h"
  16. #include "llvm/Constants.h"
  17. #include "llvm/DerivedTypes.h"
  18. #include "llvm/Instructions.h"
  19. #include "llvm/IntrinsicInst.h"
  20. #include "llvm/GlobalVariable.h"
  21. #include "llvm/Function.h"
  22. #include "llvm/Support/CFG.h"
  23. #include "llvm/Transforms/Utils/ValueMapper.h"
  24. #include "llvm/Analysis/ConstantFolding.h"
  25. #include "llvm/Analysis/DebugInfo.h"
  26. #include "llvm/ADT/SmallVector.h"
  27. #include <map>
  28. using namespace llvm;
  29. // CloneBasicBlock - See comments in Cloning.h
  30. BasicBlock *llvm::CloneBasicBlock(const BasicBlock *BB,
  31. DenseMap<const Value*, Value*> &ValueMap,
  32. const char *NameSuffix, Function *F,
  33. ClonedCodeInfo *CodeInfo) {
  34. BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "", F);
  35. if (BB->hasName()) NewBB->setName(BB->getName()+NameSuffix);
  36. bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false;
  37. // Loop over all instructions, and copy them over.
  38. for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end();
  39. II != IE; ++II) {
  40. Instruction *NewInst = II->clone();
  41. if (II->hasName())
  42. NewInst->setName(II->getName()+NameSuffix);
  43. NewBB->getInstList().push_back(NewInst);
  44. ValueMap[II] = NewInst; // Add instruction map to value.
  45. hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II));
  46. if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
  47. if (isa<ConstantInt>(AI->getArraySize()))
  48. hasStaticAllocas = true;
  49. else
  50. hasDynamicAllocas = true;
  51. }
  52. }
  53. if (CodeInfo) {
  54. CodeInfo->ContainsCalls |= hasCalls;
  55. CodeInfo->ContainsUnwinds |= isa<UnwindInst>(BB->getTerminator());
  56. CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
  57. CodeInfo->ContainsDynamicAllocas |= hasStaticAllocas &&
  58. BB != &BB->getParent()->getEntryBlock();
  59. }
  60. return NewBB;
  61. }
  62. // Clone OldFunc into NewFunc, transforming the old arguments into references to
  63. // ArgMap values.
  64. //
  65. void llvm::CloneFunctionInto(Function *NewFunc, const Function *OldFunc,
  66. DenseMap<const Value*, Value*> &ValueMap,
  67. SmallVectorImpl<ReturnInst*> &Returns,
  68. const char *NameSuffix, ClonedCodeInfo *CodeInfo) {
  69. assert(NameSuffix && "NameSuffix cannot be null!");
  70. #ifndef NDEBUG
  71. for (Function::const_arg_iterator I = OldFunc->arg_begin(),
  72. E = OldFunc->arg_end(); I != E; ++I)
  73. assert(ValueMap.count(I) && "No mapping from source argument specified!");
  74. #endif
  75. // Clone any attributes.
  76. if (NewFunc->arg_size() == OldFunc->arg_size())
  77. NewFunc->copyAttributesFrom(OldFunc);
  78. else {
  79. //Some arguments were deleted with the ValueMap. Copy arguments one by one
  80. for (Function::const_arg_iterator I = OldFunc->arg_begin(),
  81. E = OldFunc->arg_end(); I != E; ++I)
  82. if (Argument* Anew = dyn_cast<Argument>(ValueMap[I]))
  83. Anew->addAttr( OldFunc->getAttributes()
  84. .getParamAttributes(I->getArgNo() + 1));
  85. NewFunc->setAttributes(NewFunc->getAttributes()
  86. .addAttr(0, OldFunc->getAttributes()
  87. .getRetAttributes()));
  88. NewFunc->setAttributes(NewFunc->getAttributes()
  89. .addAttr(~0, OldFunc->getAttributes()
  90. .getFnAttributes()));
  91. }
  92. // Loop over all of the basic blocks in the function, cloning them as
  93. // appropriate. Note that we save BE this way in order to handle cloning of
  94. // recursive functions into themselves.
  95. //
  96. for (Function::const_iterator BI = OldFunc->begin(), BE = OldFunc->end();
  97. BI != BE; ++BI) {
  98. const BasicBlock &BB = *BI;
  99. // Create a new basic block and copy instructions into it!
  100. BasicBlock *CBB = CloneBasicBlock(&BB, ValueMap, NameSuffix, NewFunc,
  101. CodeInfo);
  102. ValueMap[&BB] = CBB; // Add basic block mapping.
  103. if (ReturnInst *RI = dyn_cast<ReturnInst>(CBB->getTerminator()))
  104. Returns.push_back(RI);
  105. }
  106. // Loop over all of the instructions in the function, fixing up operand
  107. // references as we go. This uses ValueMap to do all the hard work.
  108. //
  109. for (Function::iterator BB = cast<BasicBlock>(ValueMap[OldFunc->begin()]),
  110. BE = NewFunc->end(); BB != BE; ++BB)
  111. // Loop over all instructions, fixing each one as we find it...
  112. for (BasicBlock::iterator II = BB->begin(); II != BB->end(); ++II)
  113. RemapInstruction(II, ValueMap);
  114. }
  115. /// CloneFunction - Return a copy of the specified function, but without
  116. /// embedding the function into another module. Also, any references specified
  117. /// in the ValueMap are changed to refer to their mapped value instead of the
  118. /// original one. If any of the arguments to the function are in the ValueMap,
  119. /// the arguments are deleted from the resultant function. The ValueMap is
  120. /// updated to include mappings from all of the instructions and basicblocks in
  121. /// the function from their old to new values.
  122. ///
  123. Function *llvm::CloneFunction(const Function *F,
  124. DenseMap<const Value*, Value*> &ValueMap,
  125. ClonedCodeInfo *CodeInfo) {
  126. std::vector<const Type*> ArgTypes;
  127. // The user might be deleting arguments to the function by specifying them in
  128. // the ValueMap. If so, we need to not add the arguments to the arg ty vector
  129. //
  130. for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
  131. I != E; ++I)
  132. if (ValueMap.count(I) == 0) // Haven't mapped the argument to anything yet?
  133. ArgTypes.push_back(I->getType());
  134. // Create a new function type...
  135. FunctionType *FTy = FunctionType::get(F->getFunctionType()->getReturnType(),
  136. ArgTypes, F->getFunctionType()->isVarArg());
  137. // Create the new function...
  138. Function *NewF = Function::Create(FTy, F->getLinkage(), F->getName());
  139. // Loop over the arguments, copying the names of the mapped arguments over...
  140. Function::arg_iterator DestI = NewF->arg_begin();
  141. for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
  142. I != E; ++I)
  143. if (ValueMap.count(I) == 0) { // Is this argument preserved?
  144. DestI->setName(I->getName()); // Copy the name over...
  145. ValueMap[I] = DestI++; // Add mapping to ValueMap
  146. }
  147. SmallVector<ReturnInst*, 8> Returns; // Ignore returns cloned.
  148. CloneFunctionInto(NewF, F, ValueMap, Returns, "", CodeInfo);
  149. return NewF;
  150. }
  151. namespace {
  152. /// PruningFunctionCloner - This class is a private class used to implement
  153. /// the CloneAndPruneFunctionInto method.
  154. struct PruningFunctionCloner {
  155. Function *NewFunc;
  156. const Function *OldFunc;
  157. DenseMap<const Value*, Value*> &ValueMap;
  158. SmallVectorImpl<ReturnInst*> &Returns;
  159. const char *NameSuffix;
  160. ClonedCodeInfo *CodeInfo;
  161. const TargetData *TD;
  162. Value *DbgFnStart;
  163. public:
  164. PruningFunctionCloner(Function *newFunc, const Function *oldFunc,
  165. DenseMap<const Value*, Value*> &valueMap,
  166. SmallVectorImpl<ReturnInst*> &returns,
  167. const char *nameSuffix,
  168. ClonedCodeInfo *codeInfo,
  169. const TargetData *td)
  170. : NewFunc(newFunc), OldFunc(oldFunc), ValueMap(valueMap), Returns(returns),
  171. NameSuffix(nameSuffix), CodeInfo(codeInfo), TD(td), DbgFnStart(NULL) {
  172. }
  173. /// CloneBlock - The specified block is found to be reachable, clone it and
  174. /// anything that it can reach.
  175. void CloneBlock(const BasicBlock *BB,
  176. std::vector<const BasicBlock*> &ToClone);
  177. public:
  178. /// ConstantFoldMappedInstruction - Constant fold the specified instruction,
  179. /// mapping its operands through ValueMap if they are available.
  180. Constant *ConstantFoldMappedInstruction(const Instruction *I);
  181. };
  182. }
  183. /// CloneBlock - The specified block is found to be reachable, clone it and
  184. /// anything that it can reach.
  185. void PruningFunctionCloner::CloneBlock(const BasicBlock *BB,
  186. std::vector<const BasicBlock*> &ToClone){
  187. Value *&BBEntry = ValueMap[BB];
  188. // Have we already cloned this block?
  189. if (BBEntry) return;
  190. // Nope, clone it now.
  191. BasicBlock *NewBB;
  192. BBEntry = NewBB = BasicBlock::Create(BB->getContext());
  193. if (BB->hasName()) NewBB->setName(BB->getName()+NameSuffix);
  194. bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false;
  195. // Loop over all instructions, and copy them over, DCE'ing as we go. This
  196. // loop doesn't include the terminator.
  197. for (BasicBlock::const_iterator II = BB->begin(), IE = --BB->end();
  198. II != IE; ++II) {
  199. // If this instruction constant folds, don't bother cloning the instruction,
  200. // instead, just add the constant to the value map.
  201. if (Constant *C = ConstantFoldMappedInstruction(II)) {
  202. ValueMap[II] = C;
  203. continue;
  204. }
  205. // Do not clone llvm.dbg.region.end. It will be adjusted by the inliner.
  206. if (const DbgFuncStartInst *DFSI = dyn_cast<DbgFuncStartInst>(II)) {
  207. if (DbgFnStart == NULL) {
  208. DISubprogram SP(DFSI->getSubprogram());
  209. if (SP.describes(BB->getParent()))
  210. DbgFnStart = DFSI->getSubprogram();
  211. }
  212. }
  213. if (const DbgRegionEndInst *DREIS = dyn_cast<DbgRegionEndInst>(II)) {
  214. if (DREIS->getContext() == DbgFnStart)
  215. continue;
  216. }
  217. Instruction *NewInst = II->clone();
  218. if (II->hasName())
  219. NewInst->setName(II->getName()+NameSuffix);
  220. NewBB->getInstList().push_back(NewInst);
  221. ValueMap[II] = NewInst; // Add instruction map to value.
  222. hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II));
  223. if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
  224. if (isa<ConstantInt>(AI->getArraySize()))
  225. hasStaticAllocas = true;
  226. else
  227. hasDynamicAllocas = true;
  228. }
  229. }
  230. // Finally, clone over the terminator.
  231. const TerminatorInst *OldTI = BB->getTerminator();
  232. bool TerminatorDone = false;
  233. if (const BranchInst *BI = dyn_cast<BranchInst>(OldTI)) {
  234. if (BI->isConditional()) {
  235. // If the condition was a known constant in the callee...
  236. ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
  237. // Or is a known constant in the caller...
  238. if (Cond == 0)
  239. Cond = dyn_cast_or_null<ConstantInt>(ValueMap[BI->getCondition()]);
  240. // Constant fold to uncond branch!
  241. if (Cond) {
  242. BasicBlock *Dest = BI->getSuccessor(!Cond->getZExtValue());
  243. ValueMap[OldTI] = BranchInst::Create(Dest, NewBB);
  244. ToClone.push_back(Dest);
  245. TerminatorDone = true;
  246. }
  247. }
  248. } else if (const SwitchInst *SI = dyn_cast<SwitchInst>(OldTI)) {
  249. // If switching on a value known constant in the caller.
  250. ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition());
  251. if (Cond == 0) // Or known constant after constant prop in the callee...
  252. Cond = dyn_cast_or_null<ConstantInt>(ValueMap[SI->getCondition()]);
  253. if (Cond) { // Constant fold to uncond branch!
  254. BasicBlock *Dest = SI->getSuccessor(SI->findCaseValue(Cond));
  255. ValueMap[OldTI] = BranchInst::Create(Dest, NewBB);
  256. ToClone.push_back(Dest);
  257. TerminatorDone = true;
  258. }
  259. }
  260. if (!TerminatorDone) {
  261. Instruction *NewInst = OldTI->clone();
  262. if (OldTI->hasName())
  263. NewInst->setName(OldTI->getName()+NameSuffix);
  264. NewBB->getInstList().push_back(NewInst);
  265. ValueMap[OldTI] = NewInst; // Add instruction map to value.
  266. // Recursively clone any reachable successor blocks.
  267. const TerminatorInst *TI = BB->getTerminator();
  268. for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
  269. ToClone.push_back(TI->getSuccessor(i));
  270. }
  271. if (CodeInfo) {
  272. CodeInfo->ContainsCalls |= hasCalls;
  273. CodeInfo->ContainsUnwinds |= isa<UnwindInst>(OldTI);
  274. CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
  275. CodeInfo->ContainsDynamicAllocas |= hasStaticAllocas &&
  276. BB != &BB->getParent()->front();
  277. }
  278. if (ReturnInst *RI = dyn_cast<ReturnInst>(NewBB->getTerminator()))
  279. Returns.push_back(RI);
  280. }
  281. /// ConstantFoldMappedInstruction - Constant fold the specified instruction,
  282. /// mapping its operands through ValueMap if they are available.
  283. Constant *PruningFunctionCloner::
  284. ConstantFoldMappedInstruction(const Instruction *I) {
  285. LLVMContext &Context = I->getContext();
  286. SmallVector<Constant*, 8> Ops;
  287. for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
  288. if (Constant *Op = dyn_cast_or_null<Constant>(MapValue(I->getOperand(i),
  289. ValueMap)))
  290. Ops.push_back(Op);
  291. else
  292. return 0; // All operands not constant!
  293. if (const CmpInst *CI = dyn_cast<CmpInst>(I))
  294. return ConstantFoldCompareInstOperands(CI->getPredicate(),
  295. &Ops[0], Ops.size(),
  296. Context, TD);
  297. if (const LoadInst *LI = dyn_cast<LoadInst>(I))
  298. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0]))
  299. if (!LI->isVolatile() && CE->getOpcode() == Instruction::GetElementPtr)
  300. if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
  301. if (GV->isConstant() && GV->hasDefinitiveInitializer())
  302. return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(),
  303. CE);
  304. return ConstantFoldInstOperands(I->getOpcode(), I->getType(), &Ops[0],
  305. Ops.size(), Context, TD);
  306. }
  307. /// CloneAndPruneFunctionInto - This works exactly like CloneFunctionInto,
  308. /// except that it does some simple constant prop and DCE on the fly. The
  309. /// effect of this is to copy significantly less code in cases where (for
  310. /// example) a function call with constant arguments is inlined, and those
  311. /// constant arguments cause a significant amount of code in the callee to be
  312. /// dead. Since this doesn't produce an exact copy of the input, it can't be
  313. /// used for things like CloneFunction or CloneModule.
  314. void llvm::CloneAndPruneFunctionInto(Function *NewFunc, const Function *OldFunc,
  315. DenseMap<const Value*, Value*> &ValueMap,
  316. SmallVectorImpl<ReturnInst*> &Returns,
  317. const char *NameSuffix,
  318. ClonedCodeInfo *CodeInfo,
  319. const TargetData *TD) {
  320. assert(NameSuffix && "NameSuffix cannot be null!");
  321. #ifndef NDEBUG
  322. for (Function::const_arg_iterator II = OldFunc->arg_begin(),
  323. E = OldFunc->arg_end(); II != E; ++II)
  324. assert(ValueMap.count(II) && "No mapping from source argument specified!");
  325. #endif
  326. PruningFunctionCloner PFC(NewFunc, OldFunc, ValueMap, Returns,
  327. NameSuffix, CodeInfo, TD);
  328. // Clone the entry block, and anything recursively reachable from it.
  329. std::vector<const BasicBlock*> CloneWorklist;
  330. CloneWorklist.push_back(&OldFunc->getEntryBlock());
  331. while (!CloneWorklist.empty()) {
  332. const BasicBlock *BB = CloneWorklist.back();
  333. CloneWorklist.pop_back();
  334. PFC.CloneBlock(BB, CloneWorklist);
  335. }
  336. // Loop over all of the basic blocks in the old function. If the block was
  337. // reachable, we have cloned it and the old block is now in the value map:
  338. // insert it into the new function in the right order. If not, ignore it.
  339. //
  340. // Defer PHI resolution until rest of function is resolved.
  341. SmallVector<const PHINode*, 16> PHIToResolve;
  342. for (Function::const_iterator BI = OldFunc->begin(), BE = OldFunc->end();
  343. BI != BE; ++BI) {
  344. BasicBlock *NewBB = cast_or_null<BasicBlock>(ValueMap[BI]);
  345. if (NewBB == 0) continue; // Dead block.
  346. // Add the new block to the new function.
  347. NewFunc->getBasicBlockList().push_back(NewBB);
  348. // Loop over all of the instructions in the block, fixing up operand
  349. // references as we go. This uses ValueMap to do all the hard work.
  350. //
  351. BasicBlock::iterator I = NewBB->begin();
  352. // Handle PHI nodes specially, as we have to remove references to dead
  353. // blocks.
  354. if (PHINode *PN = dyn_cast<PHINode>(I)) {
  355. // Skip over all PHI nodes, remembering them for later.
  356. BasicBlock::const_iterator OldI = BI->begin();
  357. for (; (PN = dyn_cast<PHINode>(I)); ++I, ++OldI)
  358. PHIToResolve.push_back(cast<PHINode>(OldI));
  359. }
  360. // Otherwise, remap the rest of the instructions normally.
  361. for (; I != NewBB->end(); ++I)
  362. RemapInstruction(I, ValueMap);
  363. }
  364. // Defer PHI resolution until rest of function is resolved, PHI resolution
  365. // requires the CFG to be up-to-date.
  366. for (unsigned phino = 0, e = PHIToResolve.size(); phino != e; ) {
  367. const PHINode *OPN = PHIToResolve[phino];
  368. unsigned NumPreds = OPN->getNumIncomingValues();
  369. const BasicBlock *OldBB = OPN->getParent();
  370. BasicBlock *NewBB = cast<BasicBlock>(ValueMap[OldBB]);
  371. // Map operands for blocks that are live and remove operands for blocks
  372. // that are dead.
  373. for (; phino != PHIToResolve.size() &&
  374. PHIToResolve[phino]->getParent() == OldBB; ++phino) {
  375. OPN = PHIToResolve[phino];
  376. PHINode *PN = cast<PHINode>(ValueMap[OPN]);
  377. for (unsigned pred = 0, e = NumPreds; pred != e; ++pred) {
  378. if (BasicBlock *MappedBlock =
  379. cast_or_null<BasicBlock>(ValueMap[PN->getIncomingBlock(pred)])) {
  380. Value *InVal = MapValue(PN->getIncomingValue(pred),
  381. ValueMap);
  382. assert(InVal && "Unknown input value?");
  383. PN->setIncomingValue(pred, InVal);
  384. PN->setIncomingBlock(pred, MappedBlock);
  385. } else {
  386. PN->removeIncomingValue(pred, false);
  387. --pred, --e; // Revisit the next entry.
  388. }
  389. }
  390. }
  391. // The loop above has removed PHI entries for those blocks that are dead
  392. // and has updated others. However, if a block is live (i.e. copied over)
  393. // but its terminator has been changed to not go to this block, then our
  394. // phi nodes will have invalid entries. Update the PHI nodes in this
  395. // case.
  396. PHINode *PN = cast<PHINode>(NewBB->begin());
  397. NumPreds = std::distance(pred_begin(NewBB), pred_end(NewBB));
  398. if (NumPreds != PN->getNumIncomingValues()) {
  399. assert(NumPreds < PN->getNumIncomingValues());
  400. // Count how many times each predecessor comes to this block.
  401. std::map<BasicBlock*, unsigned> PredCount;
  402. for (pred_iterator PI = pred_begin(NewBB), E = pred_end(NewBB);
  403. PI != E; ++PI)
  404. --PredCount[*PI];
  405. // Figure out how many entries to remove from each PHI.
  406. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
  407. ++PredCount[PN->getIncomingBlock(i)];
  408. // At this point, the excess predecessor entries are positive in the
  409. // map. Loop over all of the PHIs and remove excess predecessor
  410. // entries.
  411. BasicBlock::iterator I = NewBB->begin();
  412. for (; (PN = dyn_cast<PHINode>(I)); ++I) {
  413. for (std::map<BasicBlock*, unsigned>::iterator PCI =PredCount.begin(),
  414. E = PredCount.end(); PCI != E; ++PCI) {
  415. BasicBlock *Pred = PCI->first;
  416. for (unsigned NumToRemove = PCI->second; NumToRemove; --NumToRemove)
  417. PN->removeIncomingValue(Pred, false);
  418. }
  419. }
  420. }
  421. // If the loops above have made these phi nodes have 0 or 1 operand,
  422. // replace them with undef or the input value. We must do this for
  423. // correctness, because 0-operand phis are not valid.
  424. PN = cast<PHINode>(NewBB->begin());
  425. if (PN->getNumIncomingValues() == 0) {
  426. BasicBlock::iterator I = NewBB->begin();
  427. BasicBlock::const_iterator OldI = OldBB->begin();
  428. while ((PN = dyn_cast<PHINode>(I++))) {
  429. Value *NV = UndefValue::get(PN->getType());
  430. PN->replaceAllUsesWith(NV);
  431. assert(ValueMap[OldI] == PN && "ValueMap mismatch");
  432. ValueMap[OldI] = NV;
  433. PN->eraseFromParent();
  434. ++OldI;
  435. }
  436. }
  437. // NOTE: We cannot eliminate single entry phi nodes here, because of
  438. // ValueMap. Single entry phi nodes can have multiple ValueMap entries
  439. // pointing at them. Thus, deleting one would require scanning the ValueMap
  440. // to update any entries in it that would require that. This would be
  441. // really slow.
  442. }
  443. // Now that the inlined function body has been fully constructed, go through
  444. // and zap unconditional fall-through branches. This happen all the time when
  445. // specializing code: code specialization turns conditional branches into
  446. // uncond branches, and this code folds them.
  447. Function::iterator I = cast<BasicBlock>(ValueMap[&OldFunc->getEntryBlock()]);
  448. while (I != NewFunc->end()) {
  449. BranchInst *BI = dyn_cast<BranchInst>(I->getTerminator());
  450. if (!BI || BI->isConditional()) { ++I; continue; }
  451. // Note that we can't eliminate uncond branches if the destination has
  452. // single-entry PHI nodes. Eliminating the single-entry phi nodes would
  453. // require scanning the ValueMap to update any entries that point to the phi
  454. // node.
  455. BasicBlock *Dest = BI->getSuccessor(0);
  456. if (!Dest->getSinglePredecessor() || isa<PHINode>(Dest->begin())) {
  457. ++I; continue;
  458. }
  459. // We know all single-entry PHI nodes in the inlined function have been
  460. // removed, so we just need to splice the blocks.
  461. BI->eraseFromParent();
  462. // Move all the instructions in the succ to the pred.
  463. I->getInstList().splice(I->end(), Dest->getInstList());
  464. // Make all PHI nodes that referred to Dest now refer to I as their source.
  465. Dest->replaceAllUsesWith(I);
  466. // Remove the dest block.
  467. Dest->eraseFromParent();
  468. // Do not increment I, iteratively merge all things this block branches to.
  469. }
  470. }