Local.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  1. //===-- Local.cpp - Functions to perform local transformations ------------===//
  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 family of functions perform various local transformations to the
  11. // program.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/Transforms/Utils/Local.h"
  15. #include "llvm/Constants.h"
  16. #include "llvm/GlobalAlias.h"
  17. #include "llvm/GlobalVariable.h"
  18. #include "llvm/DerivedTypes.h"
  19. #include "llvm/Instructions.h"
  20. #include "llvm/Intrinsics.h"
  21. #include "llvm/IntrinsicInst.h"
  22. #include "llvm/ADT/DenseMap.h"
  23. #include "llvm/ADT/SmallPtrSet.h"
  24. #include "llvm/Analysis/ConstantFolding.h"
  25. #include "llvm/Analysis/InstructionSimplify.h"
  26. #include "llvm/Analysis/ProfileInfo.h"
  27. #include "llvm/Target/TargetData.h"
  28. #include "llvm/Support/CFG.h"
  29. #include "llvm/Support/Debug.h"
  30. #include "llvm/Support/GetElementPtrTypeIterator.h"
  31. #include "llvm/Support/MathExtras.h"
  32. #include "llvm/Support/ValueHandle.h"
  33. #include "llvm/Support/raw_ostream.h"
  34. using namespace llvm;
  35. //===----------------------------------------------------------------------===//
  36. // Local constant propagation.
  37. //
  38. // ConstantFoldTerminator - If a terminator instruction is predicated on a
  39. // constant value, convert it into an unconditional branch to the constant
  40. // destination.
  41. //
  42. bool llvm::ConstantFoldTerminator(BasicBlock *BB) {
  43. TerminatorInst *T = BB->getTerminator();
  44. // Branch - See if we are conditional jumping on constant
  45. if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
  46. if (BI->isUnconditional()) return false; // Can't optimize uncond branch
  47. BasicBlock *Dest1 = BI->getSuccessor(0);
  48. BasicBlock *Dest2 = BI->getSuccessor(1);
  49. if (ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
  50. // Are we branching on constant?
  51. // YES. Change to unconditional branch...
  52. BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2;
  53. BasicBlock *OldDest = Cond->getZExtValue() ? Dest2 : Dest1;
  54. //cerr << "Function: " << T->getParent()->getParent()
  55. // << "\nRemoving branch from " << T->getParent()
  56. // << "\n\nTo: " << OldDest << endl;
  57. // Let the basic block know that we are letting go of it. Based on this,
  58. // it will adjust it's PHI nodes.
  59. assert(BI->getParent() && "Terminator not inserted in block!");
  60. OldDest->removePredecessor(BI->getParent());
  61. // Set the unconditional destination, and change the insn to be an
  62. // unconditional branch.
  63. BI->setUnconditionalDest(Destination);
  64. return true;
  65. }
  66. if (Dest2 == Dest1) { // Conditional branch to same location?
  67. // This branch matches something like this:
  68. // br bool %cond, label %Dest, label %Dest
  69. // and changes it into: br label %Dest
  70. // Let the basic block know that we are letting go of one copy of it.
  71. assert(BI->getParent() && "Terminator not inserted in block!");
  72. Dest1->removePredecessor(BI->getParent());
  73. // Change a conditional branch to unconditional.
  74. BI->setUnconditionalDest(Dest1);
  75. return true;
  76. }
  77. return false;
  78. }
  79. if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
  80. // If we are switching on a constant, we can convert the switch into a
  81. // single branch instruction!
  82. ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
  83. BasicBlock *TheOnlyDest = SI->getSuccessor(0); // The default dest
  84. BasicBlock *DefaultDest = TheOnlyDest;
  85. assert(TheOnlyDest == SI->getDefaultDest() &&
  86. "Default destination is not successor #0?");
  87. // Figure out which case it goes to.
  88. for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
  89. // Found case matching a constant operand?
  90. if (SI->getSuccessorValue(i) == CI) {
  91. TheOnlyDest = SI->getSuccessor(i);
  92. break;
  93. }
  94. // Check to see if this branch is going to the same place as the default
  95. // dest. If so, eliminate it as an explicit compare.
  96. if (SI->getSuccessor(i) == DefaultDest) {
  97. // Remove this entry.
  98. DefaultDest->removePredecessor(SI->getParent());
  99. SI->removeCase(i);
  100. --i; --e; // Don't skip an entry...
  101. continue;
  102. }
  103. // Otherwise, check to see if the switch only branches to one destination.
  104. // We do this by reseting "TheOnlyDest" to null when we find two non-equal
  105. // destinations.
  106. if (SI->getSuccessor(i) != TheOnlyDest) TheOnlyDest = 0;
  107. }
  108. if (CI && !TheOnlyDest) {
  109. // Branching on a constant, but not any of the cases, go to the default
  110. // successor.
  111. TheOnlyDest = SI->getDefaultDest();
  112. }
  113. // If we found a single destination that we can fold the switch into, do so
  114. // now.
  115. if (TheOnlyDest) {
  116. // Insert the new branch.
  117. BranchInst::Create(TheOnlyDest, SI);
  118. BasicBlock *BB = SI->getParent();
  119. // Remove entries from PHI nodes which we no longer branch to...
  120. for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
  121. // Found case matching a constant operand?
  122. BasicBlock *Succ = SI->getSuccessor(i);
  123. if (Succ == TheOnlyDest)
  124. TheOnlyDest = 0; // Don't modify the first branch to TheOnlyDest
  125. else
  126. Succ->removePredecessor(BB);
  127. }
  128. // Delete the old switch.
  129. BB->getInstList().erase(SI);
  130. return true;
  131. }
  132. if (SI->getNumSuccessors() == 2) {
  133. // Otherwise, we can fold this switch into a conditional branch
  134. // instruction if it has only one non-default destination.
  135. Value *Cond = new ICmpInst(SI, ICmpInst::ICMP_EQ, SI->getCondition(),
  136. SI->getSuccessorValue(1), "cond");
  137. // Insert the new branch.
  138. BranchInst::Create(SI->getSuccessor(1), SI->getSuccessor(0), Cond, SI);
  139. // Delete the old switch.
  140. SI->eraseFromParent();
  141. return true;
  142. }
  143. return false;
  144. }
  145. if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(T)) {
  146. // indirectbr blockaddress(@F, @BB) -> br label @BB
  147. if (BlockAddress *BA =
  148. dyn_cast<BlockAddress>(IBI->getAddress()->stripPointerCasts())) {
  149. BasicBlock *TheOnlyDest = BA->getBasicBlock();
  150. // Insert the new branch.
  151. BranchInst::Create(TheOnlyDest, IBI);
  152. for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
  153. if (IBI->getDestination(i) == TheOnlyDest)
  154. TheOnlyDest = 0;
  155. else
  156. IBI->getDestination(i)->removePredecessor(IBI->getParent());
  157. }
  158. IBI->eraseFromParent();
  159. // If we didn't find our destination in the IBI successor list, then we
  160. // have undefined behavior. Replace the unconditional branch with an
  161. // 'unreachable' instruction.
  162. if (TheOnlyDest) {
  163. BB->getTerminator()->eraseFromParent();
  164. new UnreachableInst(BB->getContext(), BB);
  165. }
  166. return true;
  167. }
  168. }
  169. return false;
  170. }
  171. //===----------------------------------------------------------------------===//
  172. // Local dead code elimination.
  173. //
  174. /// isInstructionTriviallyDead - Return true if the result produced by the
  175. /// instruction is not used, and the instruction has no side effects.
  176. ///
  177. bool llvm::isInstructionTriviallyDead(Instruction *I) {
  178. if (!I->use_empty() || isa<TerminatorInst>(I)) return false;
  179. // We don't want debug info removed by anything this general.
  180. if (isa<DbgInfoIntrinsic>(I)) return false;
  181. // Likewise for memory use markers.
  182. if (isa<MemoryUseIntrinsic>(I)) return false;
  183. if (!I->mayHaveSideEffects()) return true;
  184. // Special case intrinsics that "may have side effects" but can be deleted
  185. // when dead.
  186. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
  187. // Safe to delete llvm.stacksave if dead.
  188. if (II->getIntrinsicID() == Intrinsic::stacksave)
  189. return true;
  190. return false;
  191. }
  192. /// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
  193. /// trivially dead instruction, delete it. If that makes any of its operands
  194. /// trivially dead, delete them too, recursively. Return true if any
  195. /// instructions were deleted.
  196. bool llvm::RecursivelyDeleteTriviallyDeadInstructions(Value *V) {
  197. Instruction *I = dyn_cast<Instruction>(V);
  198. if (!I || !I->use_empty() || !isInstructionTriviallyDead(I))
  199. return false;
  200. SmallVector<Instruction*, 16> DeadInsts;
  201. DeadInsts.push_back(I);
  202. do {
  203. I = DeadInsts.pop_back_val();
  204. // Null out all of the instruction's operands to see if any operand becomes
  205. // dead as we go.
  206. for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
  207. Value *OpV = I->getOperand(i);
  208. I->setOperand(i, 0);
  209. if (!OpV->use_empty()) continue;
  210. // If the operand is an instruction that became dead as we nulled out the
  211. // operand, and if it is 'trivially' dead, delete it in a future loop
  212. // iteration.
  213. if (Instruction *OpI = dyn_cast<Instruction>(OpV))
  214. if (isInstructionTriviallyDead(OpI))
  215. DeadInsts.push_back(OpI);
  216. }
  217. I->eraseFromParent();
  218. } while (!DeadInsts.empty());
  219. return true;
  220. }
  221. /// RecursivelyDeleteDeadPHINode - If the specified value is an effectively
  222. /// dead PHI node, due to being a def-use chain of single-use nodes that
  223. /// either forms a cycle or is terminated by a trivially dead instruction,
  224. /// delete it. If that makes any of its operands trivially dead, delete them
  225. /// too, recursively. Return true if the PHI node is actually deleted.
  226. bool
  227. llvm::RecursivelyDeleteDeadPHINode(PHINode *PN) {
  228. // We can remove a PHI if it is on a cycle in the def-use graph
  229. // where each node in the cycle has degree one, i.e. only one use,
  230. // and is an instruction with no side effects.
  231. if (!PN->hasOneUse())
  232. return false;
  233. bool Changed = false;
  234. SmallPtrSet<PHINode *, 4> PHIs;
  235. PHIs.insert(PN);
  236. for (Instruction *J = cast<Instruction>(*PN->use_begin());
  237. J->hasOneUse() && !J->mayHaveSideEffects();
  238. J = cast<Instruction>(*J->use_begin()))
  239. // If we find a PHI more than once, we're on a cycle that
  240. // won't prove fruitful.
  241. if (PHINode *JP = dyn_cast<PHINode>(J))
  242. if (!PHIs.insert(cast<PHINode>(JP))) {
  243. // Break the cycle and delete the PHI and its operands.
  244. JP->replaceAllUsesWith(UndefValue::get(JP->getType()));
  245. (void)RecursivelyDeleteTriviallyDeadInstructions(JP);
  246. Changed = true;
  247. break;
  248. }
  249. return Changed;
  250. }
  251. /// SimplifyInstructionsInBlock - Scan the specified basic block and try to
  252. /// simplify any instructions in it and recursively delete dead instructions.
  253. ///
  254. /// This returns true if it changed the code, note that it can delete
  255. /// instructions in other blocks as well in this block.
  256. bool llvm::SimplifyInstructionsInBlock(BasicBlock *BB, const TargetData *TD) {
  257. bool MadeChange = false;
  258. for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
  259. Instruction *Inst = BI++;
  260. if (Value *V = SimplifyInstruction(Inst, TD)) {
  261. WeakVH BIHandle(BI);
  262. ReplaceAndSimplifyAllUses(Inst, V, TD);
  263. MadeChange = true;
  264. if (BIHandle != BI)
  265. BI = BB->begin();
  266. continue;
  267. }
  268. MadeChange |= RecursivelyDeleteTriviallyDeadInstructions(Inst);
  269. }
  270. return MadeChange;
  271. }
  272. //===----------------------------------------------------------------------===//
  273. // Control Flow Graph Restructuring.
  274. //
  275. /// RemovePredecessorAndSimplify - Like BasicBlock::removePredecessor, this
  276. /// method is called when we're about to delete Pred as a predecessor of BB. If
  277. /// BB contains any PHI nodes, this drops the entries in the PHI nodes for Pred.
  278. ///
  279. /// Unlike the removePredecessor method, this attempts to simplify uses of PHI
  280. /// nodes that collapse into identity values. For example, if we have:
  281. /// x = phi(1, 0, 0, 0)
  282. /// y = and x, z
  283. ///
  284. /// .. and delete the predecessor corresponding to the '1', this will attempt to
  285. /// recursively fold the and to 0.
  286. void llvm::RemovePredecessorAndSimplify(BasicBlock *BB, BasicBlock *Pred,
  287. TargetData *TD) {
  288. // This only adjusts blocks with PHI nodes.
  289. if (!isa<PHINode>(BB->begin()))
  290. return;
  291. // Remove the entries for Pred from the PHI nodes in BB, but do not simplify
  292. // them down. This will leave us with single entry phi nodes and other phis
  293. // that can be removed.
  294. BB->removePredecessor(Pred, true);
  295. WeakVH PhiIt = &BB->front();
  296. while (PHINode *PN = dyn_cast<PHINode>(PhiIt)) {
  297. PhiIt = &*++BasicBlock::iterator(cast<Instruction>(PhiIt));
  298. Value *PNV = PN->hasConstantValue();
  299. if (PNV == 0) continue;
  300. // If we're able to simplify the phi to a single value, substitute the new
  301. // value into all of its uses.
  302. assert(PNV != PN && "hasConstantValue broken");
  303. Value *OldPhiIt = PhiIt;
  304. ReplaceAndSimplifyAllUses(PN, PNV, TD);
  305. // If recursive simplification ended up deleting the next PHI node we would
  306. // iterate to, then our iterator is invalid, restart scanning from the top
  307. // of the block.
  308. if (PhiIt != OldPhiIt) PhiIt = &BB->front();
  309. }
  310. }
  311. /// MergeBasicBlockIntoOnlyPred - DestBB is a block with one predecessor and its
  312. /// predecessor is known to have one successor (DestBB!). Eliminate the edge
  313. /// between them, moving the instructions in the predecessor into DestBB and
  314. /// deleting the predecessor block.
  315. ///
  316. void llvm::MergeBasicBlockIntoOnlyPred(BasicBlock *DestBB, Pass *P) {
  317. // If BB has single-entry PHI nodes, fold them.
  318. while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
  319. Value *NewVal = PN->getIncomingValue(0);
  320. // Replace self referencing PHI with undef, it must be dead.
  321. if (NewVal == PN) NewVal = UndefValue::get(PN->getType());
  322. PN->replaceAllUsesWith(NewVal);
  323. PN->eraseFromParent();
  324. }
  325. BasicBlock *PredBB = DestBB->getSinglePredecessor();
  326. assert(PredBB && "Block doesn't have a single predecessor!");
  327. // Splice all the instructions from PredBB to DestBB.
  328. PredBB->getTerminator()->eraseFromParent();
  329. DestBB->getInstList().splice(DestBB->begin(), PredBB->getInstList());
  330. // Zap anything that took the address of DestBB. Not doing this will give the
  331. // address an invalid value.
  332. if (DestBB->hasAddressTaken()) {
  333. BlockAddress *BA = BlockAddress::get(DestBB);
  334. Constant *Replacement =
  335. ConstantInt::get(llvm::Type::getInt32Ty(BA->getContext()), 1);
  336. BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
  337. BA->getType()));
  338. BA->destroyConstant();
  339. }
  340. // Anything that branched to PredBB now branches to DestBB.
  341. PredBB->replaceAllUsesWith(DestBB);
  342. if (P) {
  343. ProfileInfo *PI = P->getAnalysisIfAvailable<ProfileInfo>();
  344. if (PI) {
  345. PI->replaceAllUses(PredBB, DestBB);
  346. PI->removeEdge(ProfileInfo::getEdge(PredBB, DestBB));
  347. }
  348. }
  349. // Nuke BB.
  350. PredBB->eraseFromParent();
  351. }
  352. /// CanPropagatePredecessorsForPHIs - Return true if we can fold BB, an
  353. /// almost-empty BB ending in an unconditional branch to Succ, into succ.
  354. ///
  355. /// Assumption: Succ is the single successor for BB.
  356. ///
  357. static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
  358. assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
  359. DEBUG(dbgs() << "Looking to fold " << BB->getName() << " into "
  360. << Succ->getName() << "\n");
  361. // Shortcut, if there is only a single predecessor it must be BB and merging
  362. // is always safe
  363. if (Succ->getSinglePredecessor()) return true;
  364. // Make a list of the predecessors of BB
  365. typedef SmallPtrSet<BasicBlock*, 16> BlockSet;
  366. BlockSet BBPreds(pred_begin(BB), pred_end(BB));
  367. // Use that list to make another list of common predecessors of BB and Succ
  368. BlockSet CommonPreds;
  369. for (pred_iterator PI = pred_begin(Succ), PE = pred_end(Succ);
  370. PI != PE; ++PI) {
  371. BasicBlock *P = *PI;
  372. if (BBPreds.count(P))
  373. CommonPreds.insert(P);
  374. }
  375. // Shortcut, if there are no common predecessors, merging is always safe
  376. if (CommonPreds.empty())
  377. return true;
  378. // Look at all the phi nodes in Succ, to see if they present a conflict when
  379. // merging these blocks
  380. for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
  381. PHINode *PN = cast<PHINode>(I);
  382. // If the incoming value from BB is again a PHINode in
  383. // BB which has the same incoming value for *PI as PN does, we can
  384. // merge the phi nodes and then the blocks can still be merged
  385. PHINode *BBPN = dyn_cast<PHINode>(PN->getIncomingValueForBlock(BB));
  386. if (BBPN && BBPN->getParent() == BB) {
  387. for (BlockSet::iterator PI = CommonPreds.begin(), PE = CommonPreds.end();
  388. PI != PE; PI++) {
  389. if (BBPN->getIncomingValueForBlock(*PI)
  390. != PN->getIncomingValueForBlock(*PI)) {
  391. DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in "
  392. << Succ->getName() << " is conflicting with "
  393. << BBPN->getName() << " with regard to common predecessor "
  394. << (*PI)->getName() << "\n");
  395. return false;
  396. }
  397. }
  398. } else {
  399. Value* Val = PN->getIncomingValueForBlock(BB);
  400. for (BlockSet::iterator PI = CommonPreds.begin(), PE = CommonPreds.end();
  401. PI != PE; PI++) {
  402. // See if the incoming value for the common predecessor is equal to the
  403. // one for BB, in which case this phi node will not prevent the merging
  404. // of the block.
  405. if (Val != PN->getIncomingValueForBlock(*PI)) {
  406. DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in "
  407. << Succ->getName() << " is conflicting with regard to common "
  408. << "predecessor " << (*PI)->getName() << "\n");
  409. return false;
  410. }
  411. }
  412. }
  413. }
  414. return true;
  415. }
  416. /// TryToSimplifyUncondBranchFromEmptyBlock - BB is known to contain an
  417. /// unconditional branch, and contains no instructions other than PHI nodes,
  418. /// potential debug intrinsics and the branch. If possible, eliminate BB by
  419. /// rewriting all the predecessors to branch to the successor block and return
  420. /// true. If we can't transform, return false.
  421. bool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB) {
  422. // We can't eliminate infinite loops.
  423. BasicBlock *Succ = cast<BranchInst>(BB->getTerminator())->getSuccessor(0);
  424. if (BB == Succ) return false;
  425. // Check to see if merging these blocks would cause conflicts for any of the
  426. // phi nodes in BB or Succ. If not, we can safely merge.
  427. if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false;
  428. // Check for cases where Succ has multiple predecessors and a PHI node in BB
  429. // has uses which will not disappear when the PHI nodes are merged. It is
  430. // possible to handle such cases, but difficult: it requires checking whether
  431. // BB dominates Succ, which is non-trivial to calculate in the case where
  432. // Succ has multiple predecessors. Also, it requires checking whether
  433. // constructing the necessary self-referential PHI node doesn't intoduce any
  434. // conflicts; this isn't too difficult, but the previous code for doing this
  435. // was incorrect.
  436. //
  437. // Note that if this check finds a live use, BB dominates Succ, so BB is
  438. // something like a loop pre-header (or rarely, a part of an irreducible CFG);
  439. // folding the branch isn't profitable in that case anyway.
  440. if (!Succ->getSinglePredecessor()) {
  441. BasicBlock::iterator BBI = BB->begin();
  442. while (isa<PHINode>(*BBI)) {
  443. for (Value::use_iterator UI = BBI->use_begin(), E = BBI->use_end();
  444. UI != E; ++UI) {
  445. if (PHINode* PN = dyn_cast<PHINode>(*UI)) {
  446. if (PN->getIncomingBlock(UI) != BB)
  447. return false;
  448. } else {
  449. return false;
  450. }
  451. }
  452. ++BBI;
  453. }
  454. }
  455. DEBUG(dbgs() << "Killing Trivial BB: \n" << *BB);
  456. if (isa<PHINode>(Succ->begin())) {
  457. // If there is more than one pred of succ, and there are PHI nodes in
  458. // the successor, then we need to add incoming edges for the PHI nodes
  459. //
  460. const SmallVector<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB));
  461. // Loop over all of the PHI nodes in the successor of BB.
  462. for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
  463. PHINode *PN = cast<PHINode>(I);
  464. Value *OldVal = PN->removeIncomingValue(BB, false);
  465. assert(OldVal && "No entry in PHI for Pred BB!");
  466. // If this incoming value is one of the PHI nodes in BB, the new entries
  467. // in the PHI node are the entries from the old PHI.
  468. if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
  469. PHINode *OldValPN = cast<PHINode>(OldVal);
  470. for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i)
  471. // Note that, since we are merging phi nodes and BB and Succ might
  472. // have common predecessors, we could end up with a phi node with
  473. // identical incoming branches. This will be cleaned up later (and
  474. // will trigger asserts if we try to clean it up now, without also
  475. // simplifying the corresponding conditional branch).
  476. PN->addIncoming(OldValPN->getIncomingValue(i),
  477. OldValPN->getIncomingBlock(i));
  478. } else {
  479. // Add an incoming value for each of the new incoming values.
  480. for (unsigned i = 0, e = BBPreds.size(); i != e; ++i)
  481. PN->addIncoming(OldVal, BBPreds[i]);
  482. }
  483. }
  484. }
  485. while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
  486. if (Succ->getSinglePredecessor()) {
  487. // BB is the only predecessor of Succ, so Succ will end up with exactly
  488. // the same predecessors BB had.
  489. Succ->getInstList().splice(Succ->begin(),
  490. BB->getInstList(), BB->begin());
  491. } else {
  492. // We explicitly check for such uses in CanPropagatePredecessorsForPHIs.
  493. assert(PN->use_empty() && "There shouldn't be any uses here!");
  494. PN->eraseFromParent();
  495. }
  496. }
  497. // Everything that jumped to BB now goes to Succ.
  498. BB->replaceAllUsesWith(Succ);
  499. if (!Succ->hasName()) Succ->takeName(BB);
  500. BB->eraseFromParent(); // Delete the old basic block.
  501. return true;
  502. }
  503. /// EliminateDuplicatePHINodes - Check for and eliminate duplicate PHI
  504. /// nodes in this block. This doesn't try to be clever about PHI nodes
  505. /// which differ only in the order of the incoming values, but instcombine
  506. /// orders them so it usually won't matter.
  507. ///
  508. bool llvm::EliminateDuplicatePHINodes(BasicBlock *BB) {
  509. bool Changed = false;
  510. // This implementation doesn't currently consider undef operands
  511. // specially. Theroetically, two phis which are identical except for
  512. // one having an undef where the other doesn't could be collapsed.
  513. // Map from PHI hash values to PHI nodes. If multiple PHIs have
  514. // the same hash value, the element is the first PHI in the
  515. // linked list in CollisionMap.
  516. DenseMap<uintptr_t, PHINode *> HashMap;
  517. // Maintain linked lists of PHI nodes with common hash values.
  518. DenseMap<PHINode *, PHINode *> CollisionMap;
  519. // Examine each PHI.
  520. for (BasicBlock::iterator I = BB->begin();
  521. PHINode *PN = dyn_cast<PHINode>(I++); ) {
  522. // Compute a hash value on the operands. Instcombine will likely have sorted
  523. // them, which helps expose duplicates, but we have to check all the
  524. // operands to be safe in case instcombine hasn't run.
  525. uintptr_t Hash = 0;
  526. for (User::op_iterator I = PN->op_begin(), E = PN->op_end(); I != E; ++I) {
  527. // This hash algorithm is quite weak as hash functions go, but it seems
  528. // to do a good enough job for this particular purpose, and is very quick.
  529. Hash ^= reinterpret_cast<uintptr_t>(static_cast<Value *>(*I));
  530. Hash = (Hash << 7) | (Hash >> (sizeof(uintptr_t) * CHAR_BIT - 7));
  531. }
  532. // If we've never seen this hash value before, it's a unique PHI.
  533. std::pair<DenseMap<uintptr_t, PHINode *>::iterator, bool> Pair =
  534. HashMap.insert(std::make_pair(Hash, PN));
  535. if (Pair.second) continue;
  536. // Otherwise it's either a duplicate or a hash collision.
  537. for (PHINode *OtherPN = Pair.first->second; ; ) {
  538. if (OtherPN->isIdenticalTo(PN)) {
  539. // A duplicate. Replace this PHI with its duplicate.
  540. PN->replaceAllUsesWith(OtherPN);
  541. PN->eraseFromParent();
  542. Changed = true;
  543. break;
  544. }
  545. // A non-duplicate hash collision.
  546. DenseMap<PHINode *, PHINode *>::iterator I = CollisionMap.find(OtherPN);
  547. if (I == CollisionMap.end()) {
  548. // Set this PHI to be the head of the linked list of colliding PHIs.
  549. PHINode *Old = Pair.first->second;
  550. Pair.first->second = PN;
  551. CollisionMap[PN] = Old;
  552. break;
  553. }
  554. // Procede to the next PHI in the list.
  555. OtherPN = I->second;
  556. }
  557. }
  558. return Changed;
  559. }