PHIElimination.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. //===-- PhiElimination.cpp - Eliminate PHI nodes by inserting copies ------===//
  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 pass eliminates machine instruction PHI nodes by inserting copy
  11. // instructions. This destroys SSA information, but is the desired input for
  12. // some register allocators.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #define DEBUG_TYPE "phielim"
  16. #include "llvm/CodeGen/LiveVariables.h"
  17. #include "llvm/CodeGen/Passes.h"
  18. #include "llvm/CodeGen/MachineFunctionPass.h"
  19. #include "llvm/CodeGen/MachineInstr.h"
  20. #include "llvm/CodeGen/MachineInstrBuilder.h"
  21. #include "llvm/CodeGen/MachineRegisterInfo.h"
  22. #include "llvm/Target/TargetInstrInfo.h"
  23. #include "llvm/Target/TargetMachine.h"
  24. #include "llvm/ADT/SmallPtrSet.h"
  25. #include "llvm/ADT/STLExtras.h"
  26. #include "llvm/ADT/Statistic.h"
  27. #include "llvm/Support/Compiler.h"
  28. #include <algorithm>
  29. #include <map>
  30. using namespace llvm;
  31. STATISTIC(NumAtomic, "Number of atomic phis lowered");
  32. namespace {
  33. class VISIBILITY_HIDDEN PNE : public MachineFunctionPass {
  34. MachineRegisterInfo *MRI; // Machine register information
  35. public:
  36. static char ID; // Pass identification, replacement for typeid
  37. PNE() : MachineFunctionPass(&ID) {}
  38. virtual bool runOnMachineFunction(MachineFunction &Fn);
  39. virtual void getAnalysisUsage(AnalysisUsage &AU) const {
  40. AU.addPreserved<LiveVariables>();
  41. AU.addPreservedID(MachineLoopInfoID);
  42. AU.addPreservedID(MachineDominatorsID);
  43. MachineFunctionPass::getAnalysisUsage(AU);
  44. }
  45. private:
  46. /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions
  47. /// in predecessor basic blocks.
  48. ///
  49. bool EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB);
  50. void LowerAtomicPHINode(MachineBasicBlock &MBB,
  51. MachineBasicBlock::iterator AfterPHIsIt);
  52. /// analyzePHINodes - Gather information about the PHI nodes in
  53. /// here. In particular, we want to map the number of uses of a virtual
  54. /// register which is used in a PHI node. We map that to the BB the
  55. /// vreg is coming from. This is used later to determine when the vreg
  56. /// is killed in the BB.
  57. ///
  58. void analyzePHINodes(const MachineFunction& Fn);
  59. typedef std::pair<const MachineBasicBlock*, unsigned> BBVRegPair;
  60. typedef std::map<BBVRegPair, unsigned> VRegPHIUse;
  61. VRegPHIUse VRegPHIUseCount;
  62. // Defs of PHI sources which are implicit_def.
  63. SmallPtrSet<MachineInstr*, 4> ImpDefs;
  64. };
  65. }
  66. char PNE::ID = 0;
  67. static RegisterPass<PNE>
  68. X("phi-node-elimination", "Eliminate PHI nodes for register allocation");
  69. const PassInfo *const llvm::PHIEliminationID = &X;
  70. bool PNE::runOnMachineFunction(MachineFunction &Fn) {
  71. MRI = &Fn.getRegInfo();
  72. analyzePHINodes(Fn);
  73. bool Changed = false;
  74. // Eliminate PHI instructions by inserting copies into predecessor blocks.
  75. for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
  76. Changed |= EliminatePHINodes(Fn, *I);
  77. // Remove dead IMPLICIT_DEF instructions.
  78. for (SmallPtrSet<MachineInstr*,4>::iterator I = ImpDefs.begin(),
  79. E = ImpDefs.end(); I != E; ++I) {
  80. MachineInstr *DefMI = *I;
  81. unsigned DefReg = DefMI->getOperand(0).getReg();
  82. if (MRI->use_empty(DefReg))
  83. DefMI->eraseFromParent();
  84. }
  85. ImpDefs.clear();
  86. VRegPHIUseCount.clear();
  87. return Changed;
  88. }
  89. /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions in
  90. /// predecessor basic blocks.
  91. ///
  92. bool PNE::EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB) {
  93. if (MBB.empty() || MBB.front().getOpcode() != TargetInstrInfo::PHI)
  94. return false; // Quick exit for basic blocks without PHIs.
  95. // Get an iterator to the first instruction after the last PHI node (this may
  96. // also be the end of the basic block).
  97. MachineBasicBlock::iterator AfterPHIsIt = MBB.begin();
  98. while (AfterPHIsIt != MBB.end() &&
  99. AfterPHIsIt->getOpcode() == TargetInstrInfo::PHI)
  100. ++AfterPHIsIt; // Skip over all of the PHI nodes...
  101. while (MBB.front().getOpcode() == TargetInstrInfo::PHI)
  102. LowerAtomicPHINode(MBB, AfterPHIsIt);
  103. return true;
  104. }
  105. /// isSourceDefinedByImplicitDef - Return true if all sources of the phi node
  106. /// are implicit_def's.
  107. static bool isSourceDefinedByImplicitDef(const MachineInstr *MPhi,
  108. const MachineRegisterInfo *MRI) {
  109. for (unsigned i = 1; i != MPhi->getNumOperands(); i += 2) {
  110. unsigned SrcReg = MPhi->getOperand(i).getReg();
  111. const MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
  112. if (!DefMI || DefMI->getOpcode() != TargetInstrInfo::IMPLICIT_DEF)
  113. return false;
  114. }
  115. return true;
  116. }
  117. /// LowerAtomicPHINode - Lower the PHI node at the top of the specified block,
  118. /// under the assuption that it needs to be lowered in a way that supports
  119. /// atomic execution of PHIs. This lowering method is always correct all of the
  120. /// time.
  121. ///
  122. void PNE::LowerAtomicPHINode(MachineBasicBlock &MBB,
  123. MachineBasicBlock::iterator AfterPHIsIt) {
  124. // Unlink the PHI node from the basic block, but don't delete the PHI yet.
  125. MachineInstr *MPhi = MBB.remove(MBB.begin());
  126. unsigned NumSrcs = (MPhi->getNumOperands() - 1) / 2;
  127. unsigned DestReg = MPhi->getOperand(0).getReg();
  128. bool isDead = MPhi->getOperand(0).isDead();
  129. // Create a new register for the incoming PHI arguments.
  130. MachineFunction &MF = *MBB.getParent();
  131. const TargetRegisterClass *RC = MF.getRegInfo().getRegClass(DestReg);
  132. unsigned IncomingReg = 0;
  133. // Insert a register to register copy at the top of the current block (but
  134. // after any remaining phi nodes) which copies the new incoming register
  135. // into the phi node destination.
  136. const TargetInstrInfo *TII = MF.getTarget().getInstrInfo();
  137. if (isSourceDefinedByImplicitDef(MPhi, MRI))
  138. // If all sources of a PHI node are implicit_def, just emit an
  139. // implicit_def instead of a copy.
  140. BuildMI(MBB, AfterPHIsIt,
  141. TII->get(TargetInstrInfo::IMPLICIT_DEF), DestReg);
  142. else {
  143. IncomingReg = MF.getRegInfo().createVirtualRegister(RC);
  144. TII->copyRegToReg(MBB, AfterPHIsIt, DestReg, IncomingReg, RC, RC);
  145. }
  146. // Update live variable information if there is any.
  147. LiveVariables *LV = getAnalysisToUpdate<LiveVariables>();
  148. if (LV) {
  149. MachineInstr *PHICopy = prior(AfterPHIsIt);
  150. if (IncomingReg) {
  151. // Increment use count of the newly created virtual register.
  152. LV->getVarInfo(IncomingReg).NumUses++;
  153. // Add information to LiveVariables to know that the incoming value is
  154. // killed. Note that because the value is defined in several places (once
  155. // each for each incoming block), the "def" block and instruction fields
  156. // for the VarInfo is not filled in.
  157. LV->addVirtualRegisterKilled(IncomingReg, PHICopy);
  158. LV->getVarInfo(IncomingReg).UsedBlocks[MBB.getNumber()] = true;
  159. }
  160. // Since we are going to be deleting the PHI node, if it is the last use of
  161. // any registers, or if the value itself is dead, we need to move this
  162. // information over to the new copy we just inserted.
  163. LV->removeVirtualRegistersKilled(MPhi);
  164. // If the result is dead, update LV.
  165. if (isDead) {
  166. LV->addVirtualRegisterDead(DestReg, PHICopy);
  167. LV->removeVirtualRegisterDead(DestReg, MPhi);
  168. }
  169. }
  170. // Adjust the VRegPHIUseCount map to account for the removal of this PHI node.
  171. for (unsigned i = 1; i != MPhi->getNumOperands(); i += 2)
  172. --VRegPHIUseCount[BBVRegPair(MPhi->getOperand(i + 1).getMBB(),
  173. MPhi->getOperand(i).getReg())];
  174. // Now loop over all of the incoming arguments, changing them to copy into the
  175. // IncomingReg register in the corresponding predecessor basic block.
  176. SmallPtrSet<MachineBasicBlock*, 8> MBBsInsertedInto;
  177. for (int i = NumSrcs - 1; i >= 0; --i) {
  178. unsigned SrcReg = MPhi->getOperand(i*2+1).getReg();
  179. assert(TargetRegisterInfo::isVirtualRegister(SrcReg) &&
  180. "Machine PHI Operands must all be virtual registers!");
  181. // If source is defined by an implicit def, there is no need to insert a
  182. // copy.
  183. MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
  184. if (DefMI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
  185. ImpDefs.insert(DefMI);
  186. continue;
  187. }
  188. // Get the MachineBasicBlock equivalent of the BasicBlock that is the source
  189. // path the PHI.
  190. MachineBasicBlock &opBlock = *MPhi->getOperand(i*2+2).getMBB();
  191. // Check to make sure we haven't already emitted the copy for this block.
  192. // This can happen because PHI nodes may have multiple entries for the same
  193. // basic block.
  194. if (!MBBsInsertedInto.insert(&opBlock))
  195. continue; // If the copy has already been emitted, we're done.
  196. // Find a safe location to insert the copy, this may be the first terminator
  197. // in the block (or end()).
  198. MachineBasicBlock::iterator InsertPos = opBlock.getFirstTerminator();
  199. // Insert the copy.
  200. TII->copyRegToReg(opBlock, InsertPos, IncomingReg, SrcReg, RC, RC);
  201. // Now update live variable information if we have it. Otherwise we're done
  202. if (!LV) continue;
  203. // We want to be able to insert a kill of the register if this PHI (aka, the
  204. // copy we just inserted) is the last use of the source value. Live
  205. // variable analysis conservatively handles this by saying that the value is
  206. // live until the end of the block the PHI entry lives in. If the value
  207. // really is dead at the PHI copy, there will be no successor blocks which
  208. // have the value live-in.
  209. //
  210. // Check to see if the copy is the last use, and if so, update the live
  211. // variables information so that it knows the copy source instruction kills
  212. // the incoming value.
  213. LiveVariables::VarInfo &InRegVI = LV->getVarInfo(SrcReg);
  214. InRegVI.UsedBlocks[opBlock.getNumber()] = true;
  215. // Loop over all of the successors of the basic block, checking to see if
  216. // the value is either live in the block, or if it is killed in the block.
  217. // Also check to see if this register is in use by another PHI node which
  218. // has not yet been eliminated. If so, it will be killed at an appropriate
  219. // point later.
  220. // Is it used by any PHI instructions in this block?
  221. bool ValueIsLive = VRegPHIUseCount[BBVRegPair(&opBlock, SrcReg)] != 0;
  222. std::vector<MachineBasicBlock*> OpSuccBlocks;
  223. // Otherwise, scan successors, including the BB the PHI node lives in.
  224. for (MachineBasicBlock::succ_iterator SI = opBlock.succ_begin(),
  225. E = opBlock.succ_end(); SI != E && !ValueIsLive; ++SI) {
  226. MachineBasicBlock *SuccMBB = *SI;
  227. // Is it alive in this successor?
  228. unsigned SuccIdx = SuccMBB->getNumber();
  229. if (SuccIdx < InRegVI.AliveBlocks.size() &&
  230. InRegVI.AliveBlocks[SuccIdx]) {
  231. ValueIsLive = true;
  232. break;
  233. }
  234. OpSuccBlocks.push_back(SuccMBB);
  235. }
  236. // Check to see if this value is live because there is a use in a successor
  237. // that kills it.
  238. if (!ValueIsLive) {
  239. switch (OpSuccBlocks.size()) {
  240. case 1: {
  241. MachineBasicBlock *MBB = OpSuccBlocks[0];
  242. for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i)
  243. if (InRegVI.Kills[i]->getParent() == MBB) {
  244. ValueIsLive = true;
  245. break;
  246. }
  247. break;
  248. }
  249. case 2: {
  250. MachineBasicBlock *MBB1 = OpSuccBlocks[0], *MBB2 = OpSuccBlocks[1];
  251. for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i)
  252. if (InRegVI.Kills[i]->getParent() == MBB1 ||
  253. InRegVI.Kills[i]->getParent() == MBB2) {
  254. ValueIsLive = true;
  255. break;
  256. }
  257. break;
  258. }
  259. default:
  260. std::sort(OpSuccBlocks.begin(), OpSuccBlocks.end());
  261. for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i)
  262. if (std::binary_search(OpSuccBlocks.begin(), OpSuccBlocks.end(),
  263. InRegVI.Kills[i]->getParent())) {
  264. ValueIsLive = true;
  265. break;
  266. }
  267. }
  268. }
  269. // Okay, if we now know that the value is not live out of the block, we can
  270. // add a kill marker in this block saying that it kills the incoming value!
  271. if (!ValueIsLive) {
  272. // In our final twist, we have to decide which instruction kills the
  273. // register. In most cases this is the copy, however, the first
  274. // terminator instruction at the end of the block may also use the value.
  275. // In this case, we should mark *it* as being the killing block, not the
  276. // copy.
  277. MachineBasicBlock::iterator KillInst = prior(InsertPos);
  278. MachineBasicBlock::iterator Term = opBlock.getFirstTerminator();
  279. if (Term != opBlock.end()) {
  280. if (Term->readsRegister(SrcReg))
  281. KillInst = Term;
  282. // Check that no other terminators use values.
  283. #ifndef NDEBUG
  284. for (MachineBasicBlock::iterator TI = next(Term); TI != opBlock.end();
  285. ++TI) {
  286. assert(!TI->readsRegister(SrcReg) &&
  287. "Terminator instructions cannot use virtual registers unless"
  288. "they are the first terminator in a block!");
  289. }
  290. #endif
  291. }
  292. // Finally, mark it killed.
  293. LV->addVirtualRegisterKilled(SrcReg, KillInst);
  294. // This vreg no longer lives all of the way through opBlock.
  295. unsigned opBlockNum = opBlock.getNumber();
  296. if (opBlockNum < InRegVI.AliveBlocks.size())
  297. InRegVI.AliveBlocks[opBlockNum] = false;
  298. }
  299. }
  300. // Really delete the PHI instruction now!
  301. MF.DeleteMachineInstr(MPhi);
  302. ++NumAtomic;
  303. }
  304. /// analyzePHINodes - Gather information about the PHI nodes in here. In
  305. /// particular, we want to map the number of uses of a virtual register which is
  306. /// used in a PHI node. We map that to the BB the vreg is coming from. This is
  307. /// used later to determine when the vreg is killed in the BB.
  308. ///
  309. void PNE::analyzePHINodes(const MachineFunction& Fn) {
  310. for (MachineFunction::const_iterator I = Fn.begin(), E = Fn.end();
  311. I != E; ++I)
  312. for (MachineBasicBlock::const_iterator BBI = I->begin(), BBE = I->end();
  313. BBI != BBE && BBI->getOpcode() == TargetInstrInfo::PHI; ++BBI)
  314. for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
  315. ++VRegPHIUseCount[BBVRegPair(BBI->getOperand(i + 1).getMBB(),
  316. BBI->getOperand(i).getReg())];
  317. }