blob: 0314ae569cecd7d3511ecda0ad0468ee48ded2eb [file] [log] [blame]
Chris Lattnerbc40e892003-01-13 20:01:16 +00001//===-- PhiElimination.cpp - Eliminate PHI nodes by inserting copies ------===//
Misha Brukmanedf128a2005-04-21 22:36:52 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanedf128a2005-04-21 22:36:52 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerbc40e892003-01-13 20:01:16 +00009//
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
Misha Brukmand7a10c82005-05-05 23:45:17 +000016#include "llvm/CodeGen/LiveVariables.h"
Chris Lattner0742b592004-02-23 18:38:20 +000017#include "llvm/CodeGen/Passes.h"
Chris Lattnerbc40e892003-01-13 20:01:16 +000018#include "llvm/CodeGen/MachineFunctionPass.h"
19#include "llvm/CodeGen/MachineInstr.h"
20#include "llvm/CodeGen/SSARegMap.h"
Chris Lattner3501fea2003-01-14 22:00:31 +000021#include "llvm/Target/TargetInstrInfo.h"
Chris Lattnerbc40e892003-01-13 20:01:16 +000022#include "llvm/Target/TargetMachine.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000023#include "llvm/ADT/DenseMap.h"
24#include "llvm/ADT/STLExtras.h"
Chris Lattner6db07562005-10-03 07:22:07 +000025#include "llvm/ADT/Statistic.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000026#include "llvm/Support/Compiler.h"
Chris Lattner53a79aa2005-10-03 04:47:08 +000027#include <set>
Chris Lattner6db07562005-10-03 07:22:07 +000028#include <algorithm>
Chris Lattner0742b592004-02-23 18:38:20 +000029using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000030
Chris Lattnerbc40e892003-01-13 20:01:16 +000031namespace {
Andrew Lenharthed41f1b2006-07-20 17:28:38 +000032 static Statistic<> NumAtomic("phielim", "Number of atomic phis lowered");
33 static Statistic<> NumSimple("phielim", "Number of simple phis lowered");
Chris Lattner6db07562005-10-03 07:22:07 +000034
Chris Lattner95255282006-06-28 23:17:24 +000035 struct VISIBILITY_HIDDEN PNE : public MachineFunctionPass {
Chris Lattnerbc40e892003-01-13 20:01:16 +000036 bool runOnMachineFunction(MachineFunction &Fn) {
Bill Wendling4da1abb2006-09-27 22:37:35 +000037 analyzePHINodes(Fn);
38
Chris Lattnerbc40e892003-01-13 20:01:16 +000039 bool Changed = false;
40
41 // Eliminate PHI instructions by inserting copies into predecessor blocks.
Chris Lattnerbc40e892003-01-13 20:01:16 +000042 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
Misha Brukmandedf2bd2005-04-22 04:01:18 +000043 Changed |= EliminatePHINodes(Fn, *I);
Chris Lattnerbc40e892003-01-13 20:01:16 +000044
Bill Wendling4da1abb2006-09-27 22:37:35 +000045 VRegPHIUseCount.clear();
Chris Lattnerbc40e892003-01-13 20:01:16 +000046 return Changed;
47 }
48
49 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
50 AU.addPreserved<LiveVariables>();
51 MachineFunctionPass::getAnalysisUsage(AU);
52 }
53
54 private:
55 /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions
56 /// in predecessor basic blocks.
57 ///
58 bool EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB);
Chris Lattner53a79aa2005-10-03 04:47:08 +000059 void LowerAtomicPHINode(MachineBasicBlock &MBB,
Bill Wendling4da1abb2006-09-27 22:37:35 +000060 MachineBasicBlock::iterator AfterPHIsIt);
61
62 /// analyzePHINodes - Gather information about the PHI nodes in
63 /// here. In particular, we want to map the number of uses of a virtual
64 /// register which is used in a PHI node. We map that to the BB the
65 /// vreg is coming from. This is used later to determine when the vreg
66 /// is killed in the BB.
67 ///
68 void analyzePHINodes(const MachineFunction& Fn);
69
70 typedef std::pair<const MachineBasicBlock*, unsigned> BBVRegPair;
71 typedef std::map<BBVRegPair, unsigned> VRegPHIUse;
72
73 VRegPHIUse VRegPHIUseCount;
Chris Lattnerbc40e892003-01-13 20:01:16 +000074 };
75
76 RegisterPass<PNE> X("phi-node-elimination",
Misha Brukmandedf2bd2005-04-22 04:01:18 +000077 "Eliminate PHI nodes for register allocation");
Chris Lattnerbc40e892003-01-13 20:01:16 +000078}
79
Chris Lattner0742b592004-02-23 18:38:20 +000080const PassInfo *llvm::PHIEliminationID = X.getPassInfo();
Chris Lattnerbc40e892003-01-13 20:01:16 +000081
82/// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions in
83/// predecessor basic blocks.
84///
85bool PNE::EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB) {
Alkis Evlogimenosc0b9dc52004-02-12 02:27:10 +000086 if (MBB.empty() || MBB.front().getOpcode() != TargetInstrInfo::PHI)
Chris Lattner53a79aa2005-10-03 04:47:08 +000087 return false; // Quick exit for basic blocks without PHIs.
Chris Lattnerbc40e892003-01-13 20:01:16 +000088
Chris Lattner791f8962004-05-10 18:47:18 +000089 // Get an iterator to the first instruction after the last PHI node (this may
Chris Lattner53a79aa2005-10-03 04:47:08 +000090 // also be the end of the basic block).
Chris Lattner791f8962004-05-10 18:47:18 +000091 MachineBasicBlock::iterator AfterPHIsIt = MBB.begin();
92 while (AfterPHIsIt != MBB.end() &&
Chris Lattnerbee88722004-05-12 21:47:57 +000093 AfterPHIsIt->getOpcode() == TargetInstrInfo::PHI)
Chris Lattner791f8962004-05-10 18:47:18 +000094 ++AfterPHIsIt; // Skip over all of the PHI nodes...
95
Bill Wendling4da1abb2006-09-27 22:37:35 +000096 while (MBB.front().getOpcode() == TargetInstrInfo::PHI)
97 LowerAtomicPHINode(MBB, AfterPHIsIt);
98
Chris Lattner53a79aa2005-10-03 04:47:08 +000099 return true;
100}
Misha Brukmanedf128a2005-04-21 22:36:52 +0000101
Chris Lattner2adfa7e2006-01-04 07:12:21 +0000102/// InstructionUsesRegister - Return true if the specified machine instr has a
103/// use of the specified register.
104static bool InstructionUsesRegister(MachineInstr *MI, unsigned SrcReg) {
105 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
Chris Lattner103de772006-08-12 05:41:39 +0000106 if (MI->getOperand(i).isRegister() &&
107 MI->getOperand(i).getReg() == SrcReg &&
108 MI->getOperand(i).isUse())
Chris Lattner2adfa7e2006-01-04 07:12:21 +0000109 return true;
110 return false;
111}
112
Chris Lattner53a79aa2005-10-03 04:47:08 +0000113/// LowerAtomicPHINode - Lower the PHI node at the top of the specified block,
114/// under the assuption that it needs to be lowered in a way that supports
115/// atomic execution of PHIs. This lowering method is always correct all of the
116/// time.
117void PNE::LowerAtomicPHINode(MachineBasicBlock &MBB,
Bill Wendling4da1abb2006-09-27 22:37:35 +0000118 MachineBasicBlock::iterator AfterPHIsIt) {
Chris Lattner53a79aa2005-10-03 04:47:08 +0000119 // Unlink the PHI node from the basic block, but don't delete the PHI yet.
120 MachineInstr *MPhi = MBB.remove(MBB.begin());
Chris Lattnerbc40e892003-01-13 20:01:16 +0000121
Chris Lattner53a79aa2005-10-03 04:47:08 +0000122 unsigned DestReg = MPhi->getOperand(0).getReg();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000123
Chris Lattner53a79aa2005-10-03 04:47:08 +0000124 // Create a new register for the incoming PHI arguments/
125 MachineFunction &MF = *MBB.getParent();
126 const TargetRegisterClass *RC = MF.getSSARegMap()->getRegClass(DestReg);
127 unsigned IncomingReg = MF.getSSARegMap()->createVirtualRegister(RC);
Chris Lattnerbc40e892003-01-13 20:01:16 +0000128
Chris Lattner53a79aa2005-10-03 04:47:08 +0000129 // Insert a register to register copy in the top of the current block (but
130 // after any remaining phi nodes) which copies the new incoming register
131 // into the phi node destination.
132 //
133 const MRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
134 RegInfo->copyRegToReg(MBB, AfterPHIsIt, DestReg, IncomingReg, RC);
135
136 // Update live variable information if there is any...
137 LiveVariables *LV = getAnalysisToUpdate<LiveVariables>();
138 if (LV) {
139 MachineInstr *PHICopy = prior(AfterPHIsIt);
140
141 // Add information to LiveVariables to know that the incoming value is
142 // killed. Note that because the value is defined in several places (once
143 // each for each incoming block), the "def" block and instruction fields
144 // for the VarInfo is not filled in.
Chris Lattnerbc40e892003-01-13 20:01:16 +0000145 //
Chris Lattner53a79aa2005-10-03 04:47:08 +0000146 LV->addVirtualRegisterKilled(IncomingReg, PHICopy);
Misha Brukmanedf128a2005-04-21 22:36:52 +0000147
Chris Lattner53a79aa2005-10-03 04:47:08 +0000148 // Since we are going to be deleting the PHI node, if it is the last use
149 // of any registers, or if the value itself is dead, we need to move this
150 // information over to the new copy we just inserted.
151 //
152 LV->removeVirtualRegistersKilled(MPhi);
Chris Lattnerbc40e892003-01-13 20:01:16 +0000153
Chris Lattner6db07562005-10-03 07:22:07 +0000154 // If the result is dead, update LV.
155 if (LV->RegisterDefIsDead(MPhi, DestReg)) {
156 LV->addVirtualRegisterDead(DestReg, PHICopy);
Chris Lattner53a79aa2005-10-03 04:47:08 +0000157 LV->removeVirtualRegistersDead(MPhi);
158 }
Chris Lattner172c3622006-01-04 06:47:48 +0000159
160 // Realize that the destination register is defined by the PHI copy now, not
161 // the PHI itself.
162 LV->getVarInfo(DestReg).DefInst = PHICopy;
Chris Lattner53a79aa2005-10-03 04:47:08 +0000163 }
Chris Lattnerbc40e892003-01-13 20:01:16 +0000164
Chris Lattner53a79aa2005-10-03 04:47:08 +0000165 // Adjust the VRegPHIUseCount map to account for the removal of this PHI
166 // node.
Chris Lattner6db07562005-10-03 07:22:07 +0000167 unsigned NumPreds = (MPhi->getNumOperands()-1)/2;
Chris Lattner53a79aa2005-10-03 04:47:08 +0000168 for (unsigned i = 1; i != MPhi->getNumOperands(); i += 2)
Bill Wendling4da1abb2006-09-27 22:37:35 +0000169 VRegPHIUseCount[BBVRegPair(
170 MPhi->getOperand(i + 1).getMachineBasicBlock(),
171 MPhi->getOperand(i).getReg())] -= NumPreds;
Chris Lattner572c7702003-05-12 14:28:28 +0000172
Chris Lattner53a79aa2005-10-03 04:47:08 +0000173 // Now loop over all of the incoming arguments, changing them to copy into
174 // the IncomingReg register in the corresponding predecessor basic block.
175 //
Chris Lattner6db07562005-10-03 07:22:07 +0000176 std::set<MachineBasicBlock*> MBBsInsertedInto;
Chris Lattner53a79aa2005-10-03 04:47:08 +0000177 for (int i = MPhi->getNumOperands() - 1; i >= 2; i-=2) {
Chris Lattner6db07562005-10-03 07:22:07 +0000178 unsigned SrcReg = MPhi->getOperand(i-1).getReg();
179 assert(MRegisterInfo::isVirtualRegister(SrcReg) &&
180 "Machine PHI Operands must all be virtual registers!");
Chris Lattner53a79aa2005-10-03 04:47:08 +0000181
182 // Get the MachineBasicBlock equivalent of the BasicBlock that is the
183 // source path the PHI.
184 MachineBasicBlock &opBlock = *MPhi->getOperand(i).getMachineBasicBlock();
185
Chris Lattner53a79aa2005-10-03 04:47:08 +0000186 // Check to make sure we haven't already emitted the copy for this block.
187 // This can happen because PHI nodes may have multiple entries for the
Chris Lattner6db07562005-10-03 07:22:07 +0000188 // same basic block.
189 if (!MBBsInsertedInto.insert(&opBlock).second)
190 continue; // If the copy has already been emitted, we're done.
191
192 // Get an iterator pointing to the first terminator in the block (or end()).
193 // This is the point where we can insert a copy if we'd like to.
194 MachineBasicBlock::iterator I = opBlock.getFirstTerminator();
195
196 // Insert the copy.
197 RegInfo->copyRegToReg(opBlock, I, IncomingReg, SrcReg, RC);
Chris Lattner53a79aa2005-10-03 04:47:08 +0000198
Chris Lattner6db07562005-10-03 07:22:07 +0000199 // Now update live variable information if we have it. Otherwise we're done
200 if (!LV) continue;
201
202 // We want to be able to insert a kill of the register if this PHI
203 // (aka, the copy we just inserted) is the last use of the source
204 // value. Live variable analysis conservatively handles this by
205 // saying that the value is live until the end of the block the PHI
206 // entry lives in. If the value really is dead at the PHI copy, there
207 // will be no successor blocks which have the value live-in.
208 //
209 // Check to see if the copy is the last use, and if so, update the
210 // live variables information so that it knows the copy source
211 // instruction kills the incoming value.
212 //
213 LiveVariables::VarInfo &InRegVI = LV->getVarInfo(SrcReg);
214
215 // Loop over all of the successors of the basic block, checking to see
216 // if the value is either live in the block, or if it is killed in the
217 // block. Also check to see if this register is in use by another PHI
218 // node which has not yet been eliminated. If so, it will be killed
219 // at an appropriate point later.
220 //
221
222 // Is it used by any PHI instructions in this block?
Bill Wendling4da1abb2006-09-27 22:37:35 +0000223 bool ValueIsLive =
224 VRegPHIUseCount[BBVRegPair(
225 MPhi->getOperand(i).getMachineBasicBlock(),
226 SrcReg)] != 0;
Chris Lattner6db07562005-10-03 07:22:07 +0000227
228 std::vector<MachineBasicBlock*> OpSuccBlocks;
229
230 // Otherwise, scan successors, including the BB the PHI node lives in.
231 for (MachineBasicBlock::succ_iterator SI = opBlock.succ_begin(),
232 E = opBlock.succ_end(); SI != E && !ValueIsLive; ++SI) {
233 MachineBasicBlock *SuccMBB = *SI;
234
235 // Is it alive in this successor?
236 unsigned SuccIdx = SuccMBB->getNumber();
237 if (SuccIdx < InRegVI.AliveBlocks.size() &&
238 InRegVI.AliveBlocks[SuccIdx]) {
239 ValueIsLive = true;
240 break;
Chris Lattner927ce5d2003-05-12 03:55:21 +0000241 }
Chris Lattner6db07562005-10-03 07:22:07 +0000242
243 OpSuccBlocks.push_back(SuccMBB);
Chris Lattner927ce5d2003-05-12 03:55:21 +0000244 }
245
Chris Lattner6db07562005-10-03 07:22:07 +0000246 // Check to see if this value is live because there is a use in a successor
247 // that kills it.
248 if (!ValueIsLive) {
249 switch (OpSuccBlocks.size()) {
250 case 1: {
251 MachineBasicBlock *MBB = OpSuccBlocks[0];
252 for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i)
253 if (InRegVI.Kills[i]->getParent() == MBB) {
Chris Lattner53a79aa2005-10-03 04:47:08 +0000254 ValueIsLive = true;
255 break;
256 }
Chris Lattner6db07562005-10-03 07:22:07 +0000257 break;
Chris Lattnerbc40e892003-01-13 20:01:16 +0000258 }
Chris Lattner6db07562005-10-03 07:22:07 +0000259 case 2: {
260 MachineBasicBlock *MBB1 = OpSuccBlocks[0], *MBB2 = OpSuccBlocks[1];
261 for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i)
262 if (InRegVI.Kills[i]->getParent() == MBB1 ||
263 InRegVI.Kills[i]->getParent() == MBB2) {
264 ValueIsLive = true;
265 break;
266 }
267 break;
268 }
269 default:
270 std::sort(OpSuccBlocks.begin(), OpSuccBlocks.end());
271 for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i)
272 if (std::binary_search(OpSuccBlocks.begin(), OpSuccBlocks.end(),
273 InRegVI.Kills[i]->getParent())) {
274 ValueIsLive = true;
275 break;
276 }
277 }
278 }
279
280 // Okay, if we now know that the value is not live out of the block,
Chris Lattner2adfa7e2006-01-04 07:12:21 +0000281 // we can add a kill marker in this block saying that it kills the incoming
282 // value!
Chris Lattner6db07562005-10-03 07:22:07 +0000283 if (!ValueIsLive) {
Chris Lattner2adfa7e2006-01-04 07:12:21 +0000284 // In our final twist, we have to decide which instruction kills the
285 // register. In most cases this is the copy, however, the first
286 // terminator instruction at the end of the block may also use the value.
287 // In this case, we should mark *it* as being the killing block, not the
288 // copy.
289 bool FirstTerminatorUsesValue = false;
290 if (I != opBlock.end()) {
291 FirstTerminatorUsesValue = InstructionUsesRegister(I, SrcReg);
292
293 // Check that no other terminators use values.
294#ifndef NDEBUG
295 for (MachineBasicBlock::iterator TI = next(I); TI != opBlock.end();
296 ++TI) {
297 assert(!InstructionUsesRegister(TI, SrcReg) &&
298 "Terminator instructions cannot use virtual registers unless"
299 "they are the first terminator in a block!");
300 }
301#endif
302 }
303
304 MachineBasicBlock::iterator KillInst;
305 if (!FirstTerminatorUsesValue)
306 KillInst = prior(I);
307 else
308 KillInst = I;
309
310 // Finally, mark it killed.
311 LV->addVirtualRegisterKilled(SrcReg, KillInst);
Chris Lattner6db07562005-10-03 07:22:07 +0000312
313 // This vreg no longer lives all of the way through opBlock.
314 unsigned opBlockNum = opBlock.getNumber();
315 if (opBlockNum < InRegVI.AliveBlocks.size())
316 InRegVI.AliveBlocks[opBlockNum] = false;
Chris Lattnerbc40e892003-01-13 20:01:16 +0000317 }
Chris Lattnerbc40e892003-01-13 20:01:16 +0000318 }
Chris Lattner53a79aa2005-10-03 04:47:08 +0000319
320 // Really delete the PHI instruction now!
321 delete MPhi;
Chris Lattner6db07562005-10-03 07:22:07 +0000322 ++NumAtomic;
Chris Lattnerbc40e892003-01-13 20:01:16 +0000323}
Bill Wendling4da1abb2006-09-27 22:37:35 +0000324
325/// analyzePHINodes - Gather information about the PHI nodes in here. In
326/// particular, we want to map the number of uses of a virtual register which is
327/// used in a PHI node. We map that to the BB the vreg is coming from. This is
328/// used later to determine when the vreg is killed in the BB.
329///
330void PNE::analyzePHINodes(const MachineFunction& Fn) {
331 for (MachineFunction::const_iterator I = Fn.begin(), E = Fn.end();
332 I != E; ++I)
333 for (MachineBasicBlock::const_iterator BBI = I->begin(), BBE = I->end();
334 BBI != BBE && BBI->getOpcode() == TargetInstrInfo::PHI; ++BBI)
335 for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
336 VRegPHIUseCount[BBVRegPair(
337 BBI->getOperand(i + 1).getMachineBasicBlock(),
338 BBI->getOperand(i).getReg())]++;
339}