1 //===-- PhiElimination.cpp - Eliminate PHI nodes by inserting copies ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
14 //===----------------------------------------------------------------------===//
16 #define DEBUG_TYPE "phielim"
17 #include "llvm/CodeGen/LiveVariables.h"
18 #include "llvm/CodeGen/Passes.h"
19 #include "llvm/CodeGen/MachineFunctionPass.h"
20 #include "llvm/CodeGen/MachineInstr.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/CodeGen/MachineRegisterInfo.h"
23 #include "llvm/Target/TargetInstrInfo.h"
24 #include "llvm/Target/TargetMachine.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 #include "llvm/ADT/STLExtras.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/Support/Compiler.h"
33 STATISTIC(NumAtomic, "Number of atomic phis lowered");
34 STATISTIC(NumEH, "Number of EH try blocks skipped");
37 class VISIBILITY_HIDDEN PNE : public MachineFunctionPass {
38 MachineRegisterInfo *MRI; // Machine register information
41 static char ID; // Pass identification, replacement for typeid
42 PNE() : MachineFunctionPass(&ID) {}
44 virtual bool runOnMachineFunction(MachineFunction &Fn);
46 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
47 AU.addPreserved<LiveVariables>();
48 AU.addPreservedID(MachineLoopInfoID);
49 AU.addPreservedID(MachineDominatorsID);
50 MachineFunctionPass::getAnalysisUsage(AU);
54 /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions
55 /// in predecessor basic blocks.
57 bool EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB);
58 void LowerAtomicPHINode(MachineBasicBlock &MBB,
59 MachineBasicBlock::iterator AfterPHIsIt);
61 /// analyzePHINodes - Gather information about the PHI nodes in
62 /// here. In particular, we want to map the number of uses of a virtual
63 /// register which is used in a PHI node. We map that to the BB the
64 /// vreg is coming from. This is used later to determine when the vreg
65 /// is killed in the BB.
67 void analyzePHINodes(const MachineFunction& Fn);
69 void WalkPassEHTryRange(MachineBasicBlock &MBB,
70 MachineBasicBlock::iterator &I, unsigned SrcReg);
72 typedef std::pair<const MachineBasicBlock*, unsigned> BBVRegPair;
73 typedef std::map<BBVRegPair, unsigned> VRegPHIUse;
75 VRegPHIUse VRegPHIUseCount;
77 // Defs of PHI sources which are implicit_def.
78 SmallPtrSet<MachineInstr*, 4> ImpDefs;
83 static RegisterPass<PNE>
84 X("phi-node-elimination", "Eliminate PHI nodes for register allocation");
86 const PassInfo *const llvm::PHIEliminationID = &X;
88 bool PNE::runOnMachineFunction(MachineFunction &Fn) {
89 MRI = &Fn.getRegInfo();
95 // Eliminate PHI instructions by inserting copies into predecessor blocks.
96 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
97 Changed |= EliminatePHINodes(Fn, *I);
99 // Remove dead IMPLICIT_DEF instructions.
100 for (SmallPtrSet<MachineInstr*,4>::iterator I = ImpDefs.begin(),
101 E = ImpDefs.end(); I != E; ++I) {
102 MachineInstr *DefMI = *I;
103 unsigned DefReg = DefMI->getOperand(0).getReg();
104 if (MRI->use_empty(DefReg))
105 DefMI->eraseFromParent();
109 VRegPHIUseCount.clear();
114 /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions in
115 /// predecessor basic blocks.
117 bool PNE::EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB) {
118 if (MBB.empty() || MBB.front().getOpcode() != TargetInstrInfo::PHI)
119 return false; // Quick exit for basic blocks without PHIs.
121 // Get an iterator to the first instruction after the last PHI node (this may
122 // also be the end of the basic block).
123 MachineBasicBlock::iterator AfterPHIsIt = MBB.begin();
124 while (AfterPHIsIt != MBB.end() &&
125 AfterPHIsIt->getOpcode() == TargetInstrInfo::PHI)
126 ++AfterPHIsIt; // Skip over all of the PHI nodes...
128 while (MBB.front().getOpcode() == TargetInstrInfo::PHI)
129 LowerAtomicPHINode(MBB, AfterPHIsIt);
134 /// isSourceDefinedByImplicitDef - Return true if all sources of the phi node
135 /// are implicit_def's.
136 static bool isSourceDefinedByImplicitDef(const MachineInstr *MPhi,
137 const MachineRegisterInfo *MRI) {
138 for (unsigned i = 1; i != MPhi->getNumOperands(); i += 2) {
139 unsigned SrcReg = MPhi->getOperand(i).getReg();
140 const MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
141 if (!DefMI || DefMI->getOpcode() != TargetInstrInfo::IMPLICIT_DEF)
147 void PNE::WalkPassEHTryRange(MachineBasicBlock &MBB,
148 MachineBasicBlock::iterator &I, unsigned SrcReg) {
149 if (I == MBB.begin())
151 MachineBasicBlock::iterator PI = prior(I);
152 if (PI->getOpcode() != TargetInstrInfo::EH_LABEL)
155 // Trying to walk pass the EH try range. If we run into a use instruction,
156 // we want to insert the copy there.
157 SmallPtrSet<MachineInstr*, 4> UsesInMBB;
158 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(SrcReg),
159 UE = MRI->use_end(); UI != UE; ++UI) {
160 MachineInstr *UseMI = &*UI;
161 if (UseMI->getParent() == &MBB)
162 UsesInMBB.insert(UseMI);
165 while (PI != MBB.begin()) {
167 if (PI->getOpcode() == TargetInstrInfo::EH_LABEL) {
171 } else if (UsesInMBB.count(&*PI)) {
180 /// LowerAtomicPHINode - Lower the PHI node at the top of the specified block,
181 /// under the assuption that it needs to be lowered in a way that supports
182 /// atomic execution of PHIs. This lowering method is always correct all of the
185 void PNE::LowerAtomicPHINode(MachineBasicBlock &MBB,
186 MachineBasicBlock::iterator AfterPHIsIt) {
187 // Unlink the PHI node from the basic block, but don't delete the PHI yet.
188 MachineInstr *MPhi = MBB.remove(MBB.begin());
190 unsigned NumSrcs = (MPhi->getNumOperands() - 1) / 2;
191 unsigned DestReg = MPhi->getOperand(0).getReg();
192 bool isDead = MPhi->getOperand(0).isDead();
194 // Create a new register for the incoming PHI arguments.
195 MachineFunction &MF = *MBB.getParent();
196 const TargetRegisterClass *RC = MF.getRegInfo().getRegClass(DestReg);
197 unsigned IncomingReg = 0;
199 // Insert a register to register copy at the top of the current block (but
200 // after any remaining phi nodes) which copies the new incoming register
201 // into the phi node destination.
202 const TargetInstrInfo *TII = MF.getTarget().getInstrInfo();
203 if (isSourceDefinedByImplicitDef(MPhi, MRI))
204 // If all sources of a PHI node are implicit_def, just emit an
205 // implicit_def instead of a copy.
206 BuildMI(MBB, AfterPHIsIt, MPhi->getDebugLoc(),
207 TII->get(TargetInstrInfo::IMPLICIT_DEF), DestReg);
209 IncomingReg = MF.getRegInfo().createVirtualRegister(RC);
210 TII->copyRegToReg(MBB, AfterPHIsIt, DestReg, IncomingReg, RC, RC);
213 // Update live variable information if there is any.
214 LiveVariables *LV = getAnalysisIfAvailable<LiveVariables>();
216 MachineInstr *PHICopy = prior(AfterPHIsIt);
219 // Increment use count of the newly created virtual register.
220 LV->getVarInfo(IncomingReg).NumUses++;
222 // Add information to LiveVariables to know that the incoming value is
223 // killed. Note that because the value is defined in several places (once
224 // each for each incoming block), the "def" block and instruction fields
225 // for the VarInfo is not filled in.
226 LV->addVirtualRegisterKilled(IncomingReg, PHICopy);
228 LV->getVarInfo(IncomingReg).UsedBlocks[MBB.getNumber()] = true;
231 // Since we are going to be deleting the PHI node, if it is the last use of
232 // any registers, or if the value itself is dead, we need to move this
233 // information over to the new copy we just inserted.
234 LV->removeVirtualRegistersKilled(MPhi);
236 // If the result is dead, update LV.
238 LV->addVirtualRegisterDead(DestReg, PHICopy);
239 LV->removeVirtualRegisterDead(DestReg, MPhi);
243 // Adjust the VRegPHIUseCount map to account for the removal of this PHI node.
244 for (unsigned i = 1; i != MPhi->getNumOperands(); i += 2)
245 --VRegPHIUseCount[BBVRegPair(MPhi->getOperand(i + 1).getMBB(),
246 MPhi->getOperand(i).getReg())];
248 // Now loop over all of the incoming arguments, changing them to copy into the
249 // IncomingReg register in the corresponding predecessor basic block.
250 SmallPtrSet<MachineBasicBlock*, 8> MBBsInsertedInto;
251 for (int i = NumSrcs - 1; i >= 0; --i) {
252 unsigned SrcReg = MPhi->getOperand(i*2+1).getReg();
253 assert(TargetRegisterInfo::isVirtualRegister(SrcReg) &&
254 "Machine PHI Operands must all be virtual registers!");
256 // If source is defined by an implicit def, there is no need to insert a
258 MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
259 if (DefMI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
260 ImpDefs.insert(DefMI);
264 // Get the MachineBasicBlock equivalent of the BasicBlock that is the source
266 MachineBasicBlock &opBlock = *MPhi->getOperand(i*2+2).getMBB();
268 // Check to make sure we haven't already emitted the copy for this block.
269 // This can happen because PHI nodes may have multiple entries for the same
271 if (!MBBsInsertedInto.insert(&opBlock))
272 continue; // If the copy has already been emitted, we're done.
274 // Find a safe location to insert the copy, this may be the first terminator
275 // in the block (or end()).
276 MachineBasicBlock::iterator InsertPos = opBlock.getFirstTerminator();
278 // Walk pass EH try range if needed.
279 WalkPassEHTryRange(opBlock, InsertPos, SrcReg);
282 TII->copyRegToReg(opBlock, InsertPos, IncomingReg, SrcReg, RC, RC);
284 // Now update live variable information if we have it. Otherwise we're done
287 // We want to be able to insert a kill of the register if this PHI (aka, the
288 // copy we just inserted) is the last use of the source value. Live
289 // variable analysis conservatively handles this by saying that the value is
290 // live until the end of the block the PHI entry lives in. If the value
291 // really is dead at the PHI copy, there will be no successor blocks which
292 // have the value live-in.
294 // Check to see if the copy is the last use, and if so, update the live
295 // variables information so that it knows the copy source instruction kills
296 // the incoming value.
297 LiveVariables::VarInfo &InRegVI = LV->getVarInfo(SrcReg);
298 InRegVI.UsedBlocks[opBlock.getNumber()] = true;
300 // Loop over all of the successors of the basic block, checking to see if
301 // the value is either live in the block, or if it is killed in the block.
302 // Also check to see if this register is in use by another PHI node which
303 // has not yet been eliminated. If so, it will be killed at an appropriate
306 // Is it used by any PHI instructions in this block?
307 bool ValueIsLive = VRegPHIUseCount[BBVRegPair(&opBlock, SrcReg)] != 0;
309 std::vector<MachineBasicBlock*> OpSuccBlocks;
311 // Otherwise, scan successors, including the BB the PHI node lives in.
312 for (MachineBasicBlock::succ_iterator SI = opBlock.succ_begin(),
313 E = opBlock.succ_end(); SI != E && !ValueIsLive; ++SI) {
314 MachineBasicBlock *SuccMBB = *SI;
316 // Is it alive in this successor?
317 unsigned SuccIdx = SuccMBB->getNumber();
318 if (SuccIdx < InRegVI.AliveBlocks.size() &&
319 InRegVI.AliveBlocks[SuccIdx]) {
324 OpSuccBlocks.push_back(SuccMBB);
327 // Check to see if this value is live because there is a use in a successor
330 switch (OpSuccBlocks.size()) {
332 MachineBasicBlock *MBB = OpSuccBlocks[0];
333 for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i)
334 if (InRegVI.Kills[i]->getParent() == MBB) {
341 MachineBasicBlock *MBB1 = OpSuccBlocks[0], *MBB2 = OpSuccBlocks[1];
342 for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i)
343 if (InRegVI.Kills[i]->getParent() == MBB1 ||
344 InRegVI.Kills[i]->getParent() == MBB2) {
351 std::sort(OpSuccBlocks.begin(), OpSuccBlocks.end());
352 for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i)
353 if (std::binary_search(OpSuccBlocks.begin(), OpSuccBlocks.end(),
354 InRegVI.Kills[i]->getParent())) {
361 // Okay, if we now know that the value is not live out of the block, we can
362 // add a kill marker in this block saying that it kills the incoming value!
364 // In our final twist, we have to decide which instruction kills the
365 // register. In most cases this is the copy, however, the first
366 // terminator instruction at the end of the block may also use the value.
367 // In this case, we should mark *it* as being the killing block, not the
369 MachineBasicBlock::iterator KillInst = prior(InsertPos);
370 MachineBasicBlock::iterator Term = opBlock.getFirstTerminator();
371 if (Term != opBlock.end()) {
372 if (Term->readsRegister(SrcReg))
375 // Check that no other terminators use values.
377 for (MachineBasicBlock::iterator TI = next(Term); TI != opBlock.end();
379 assert(!TI->readsRegister(SrcReg) &&
380 "Terminator instructions cannot use virtual registers unless"
381 "they are the first terminator in a block!");
386 // Finally, mark it killed.
387 LV->addVirtualRegisterKilled(SrcReg, KillInst);
389 // This vreg no longer lives all of the way through opBlock.
390 unsigned opBlockNum = opBlock.getNumber();
391 if (opBlockNum < InRegVI.AliveBlocks.size())
392 InRegVI.AliveBlocks[opBlockNum] = false;
396 // Really delete the PHI instruction now!
397 MF.DeleteMachineInstr(MPhi);
401 /// analyzePHINodes - Gather information about the PHI nodes in here. In
402 /// particular, we want to map the number of uses of a virtual register which is
403 /// used in a PHI node. We map that to the BB the vreg is coming from. This is
404 /// used later to determine when the vreg is killed in the BB.
406 void PNE::analyzePHINodes(const MachineFunction& Fn) {
407 for (MachineFunction::const_iterator I = Fn.begin(), E = Fn.end();
409 for (MachineBasicBlock::const_iterator BBI = I->begin(), BBE = I->end();
410 BBI != BBE && BBI->getOpcode() == TargetInstrInfo::PHI; ++BBI)
411 for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
412 ++VRegPHIUseCount[BBVRegPair(BBI->getOperand(i + 1).getMBB(),
413 BBI->getOperand(i).getReg())];