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 "PHIElimination.h"
18 #include "llvm/BasicBlock.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/CodeGen/LiveVariables.h"
21 #include "llvm/CodeGen/Passes.h"
22 #include "llvm/CodeGen/MachineFunctionPass.h"
23 #include "llvm/CodeGen/MachineInstr.h"
24 #include "llvm/CodeGen/MachineInstrBuilder.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/ADT/SmallPtrSet.h"
28 #include "llvm/ADT/STLExtras.h"
29 #include "llvm/ADT/Statistic.h"
30 #include "llvm/Support/Compiler.h"
35 STATISTIC(NumAtomic, "Number of atomic phis lowered");
37 char PHIElimination::ID = 0;
38 static RegisterPass<PHIElimination>
39 X("phi-node-elimination", "Eliminate PHI nodes for register allocation");
41 const PassInfo *const llvm::PHIEliminationID = &X;
43 void llvm::PHIElimination::getAnalysisUsage(AnalysisUsage &AU) const {
44 AU.addPreserved<LiveVariables>();
45 AU.addPreservedID(MachineLoopInfoID);
46 AU.addPreservedID(MachineDominatorsID);
47 MachineFunctionPass::getAnalysisUsage(AU);
50 bool llvm::PHIElimination::runOnMachineFunction(MachineFunction &Fn) {
51 MRI = &Fn.getRegInfo();
59 // Eliminate PHI instructions by inserting copies into predecessor blocks.
60 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
61 Changed |= EliminatePHINodes(Fn, *I);
63 // Remove dead IMPLICIT_DEF instructions.
64 for (SmallPtrSet<MachineInstr*,4>::iterator I = ImpDefs.begin(),
65 E = ImpDefs.end(); I != E; ++I) {
66 MachineInstr *DefMI = *I;
67 unsigned DefReg = DefMI->getOperand(0).getReg();
68 if (MRI->use_empty(DefReg))
69 DefMI->eraseFromParent();
73 VRegPHIUseCount.clear();
78 /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions in
79 /// predecessor basic blocks.
81 bool llvm::PHIElimination::EliminatePHINodes(MachineFunction &MF,
82 MachineBasicBlock &MBB) {
83 if (MBB.empty() || MBB.front().getOpcode() != TargetInstrInfo::PHI)
84 return false; // Quick exit for basic blocks without PHIs.
86 // Get an iterator to the first instruction after the last PHI node (this may
87 // also be the end of the basic block).
88 MachineBasicBlock::iterator AfterPHIsIt = SkipPHIsAndLabels(MBB, MBB.begin());
90 while (MBB.front().getOpcode() == TargetInstrInfo::PHI)
91 LowerAtomicPHINode(MBB, AfterPHIsIt);
96 /// isSourceDefinedByImplicitDef - Return true if all sources of the phi node
97 /// are implicit_def's.
98 static bool isSourceDefinedByImplicitDef(const MachineInstr *MPhi,
99 const MachineRegisterInfo *MRI) {
100 for (unsigned i = 1; i != MPhi->getNumOperands(); i += 2) {
101 unsigned SrcReg = MPhi->getOperand(i).getReg();
102 const MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
103 if (!DefMI || DefMI->getOpcode() != TargetInstrInfo::IMPLICIT_DEF)
109 // FindCopyInsertPoint - Find a safe place in MBB to insert a copy from SrcReg.
110 // This needs to be after any def or uses of SrcReg, but before any subsequent
111 // point where control flow might jump out of the basic block.
112 MachineBasicBlock::iterator
113 llvm::PHIElimination::FindCopyInsertPoint(MachineBasicBlock &MBB,
115 // Handle the trivial case trivially.
119 // If this basic block does not contain an invoke, then control flow always
120 // reaches the end of it, so place the copy there. The logic below works in
121 // this case too, but is more expensive.
122 if (!isa<InvokeInst>(MBB.getBasicBlock()->getTerminator()))
123 return MBB.getFirstTerminator();
125 // Discover any definition/uses in this basic block.
126 SmallPtrSet<MachineInstr*, 8> DefUsesInMBB;
127 for (MachineRegisterInfo::reg_iterator RI = MRI->reg_begin(SrcReg),
128 RE = MRI->reg_end(); RI != RE; ++RI) {
129 MachineInstr *DefUseMI = &*RI;
130 if (DefUseMI->getParent() == &MBB)
131 DefUsesInMBB.insert(DefUseMI);
134 MachineBasicBlock::iterator InsertPoint;
135 if (DefUsesInMBB.empty()) {
136 // No def/uses. Insert the copy at the start of the basic block.
137 InsertPoint = MBB.begin();
138 } else if (DefUsesInMBB.size() == 1) {
139 // Insert the copy immediately after the definition/use.
140 InsertPoint = *DefUsesInMBB.begin();
143 // Insert the copy immediately after the last definition/use.
144 InsertPoint = MBB.end();
145 while (!DefUsesInMBB.count(&*--InsertPoint)) {}
149 // Make sure the copy goes after any phi nodes however.
150 return SkipPHIsAndLabels(MBB, InsertPoint);
153 /// LowerAtomicPHINode - Lower the PHI node at the top of the specified block,
154 /// under the assuption that it needs to be lowered in a way that supports
155 /// atomic execution of PHIs. This lowering method is always correct all of the
158 void llvm::PHIElimination::LowerAtomicPHINode(
159 MachineBasicBlock &MBB,
160 MachineBasicBlock::iterator AfterPHIsIt) {
161 // Unlink the PHI node from the basic block, but don't delete the PHI yet.
162 MachineInstr *MPhi = MBB.remove(MBB.begin());
164 unsigned NumSrcs = (MPhi->getNumOperands() - 1) / 2;
165 unsigned DestReg = MPhi->getOperand(0).getReg();
166 bool isDead = MPhi->getOperand(0).isDead();
168 // Create a new register for the incoming PHI arguments.
169 MachineFunction &MF = *MBB.getParent();
170 const TargetRegisterClass *RC = MF.getRegInfo().getRegClass(DestReg);
171 unsigned IncomingReg = 0;
173 // Insert a register to register copy at the top of the current block (but
174 // after any remaining phi nodes) which copies the new incoming register
175 // into the phi node destination.
176 const TargetInstrInfo *TII = MF.getTarget().getInstrInfo();
177 if (isSourceDefinedByImplicitDef(MPhi, MRI))
178 // If all sources of a PHI node are implicit_def, just emit an
179 // implicit_def instead of a copy.
180 BuildMI(MBB, AfterPHIsIt, MPhi->getDebugLoc(),
181 TII->get(TargetInstrInfo::IMPLICIT_DEF), DestReg);
183 IncomingReg = MF.getRegInfo().createVirtualRegister(RC);
184 TII->copyRegToReg(MBB, AfterPHIsIt, DestReg, IncomingReg, RC, RC);
188 assert(!hasPHIDef(DestReg) && "Vreg has multiple phi-defs?");
189 PHIDefs[DestReg] = &MBB;
191 // Update live variable information if there is any.
192 LiveVariables *LV = getAnalysisIfAvailable<LiveVariables>();
194 MachineInstr *PHICopy = prior(AfterPHIsIt);
197 // Increment use count of the newly created virtual register.
198 LV->getVarInfo(IncomingReg).NumUses++;
200 // Add information to LiveVariables to know that the incoming value is
201 // killed. Note that because the value is defined in several places (once
202 // each for each incoming block), the "def" block and instruction fields
203 // for the VarInfo is not filled in.
204 LV->addVirtualRegisterKilled(IncomingReg, PHICopy);
207 // Since we are going to be deleting the PHI node, if it is the last use of
208 // any registers, or if the value itself is dead, we need to move this
209 // information over to the new copy we just inserted.
210 LV->removeVirtualRegistersKilled(MPhi);
212 // If the result is dead, update LV.
214 LV->addVirtualRegisterDead(DestReg, PHICopy);
215 LV->removeVirtualRegisterDead(DestReg, MPhi);
219 // Adjust the VRegPHIUseCount map to account for the removal of this PHI node.
220 for (unsigned i = 1; i != MPhi->getNumOperands(); i += 2)
221 --VRegPHIUseCount[BBVRegPair(MPhi->getOperand(i + 1).getMBB(),
222 MPhi->getOperand(i).getReg())];
224 // Now loop over all of the incoming arguments, changing them to copy into the
225 // IncomingReg register in the corresponding predecessor basic block.
226 SmallPtrSet<MachineBasicBlock*, 8> MBBsInsertedInto;
227 for (int i = NumSrcs - 1; i >= 0; --i) {
228 unsigned SrcReg = MPhi->getOperand(i*2+1).getReg();
229 assert(TargetRegisterInfo::isVirtualRegister(SrcReg) &&
230 "Machine PHI Operands must all be virtual registers!");
232 // Get the MachineBasicBlock equivalent of the BasicBlock that is the source
234 MachineBasicBlock &opBlock = *MPhi->getOperand(i*2+2).getMBB();
237 PHIKills[SrcReg].insert(&opBlock);
239 // If source is defined by an implicit def, there is no need to insert a
241 MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
242 if (DefMI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
243 ImpDefs.insert(DefMI);
247 // Check to make sure we haven't already emitted the copy for this block.
248 // This can happen because PHI nodes may have multiple entries for the same
250 if (!MBBsInsertedInto.insert(&opBlock))
251 continue; // If the copy has already been emitted, we're done.
253 // Find a safe location to insert the copy, this may be the first terminator
254 // in the block (or end()).
255 MachineBasicBlock::iterator InsertPos = FindCopyInsertPoint(opBlock, SrcReg);
258 TII->copyRegToReg(opBlock, InsertPos, IncomingReg, SrcReg, RC, RC);
260 // Now update live variable information if we have it. Otherwise we're done
263 // We want to be able to insert a kill of the register if this PHI (aka, the
264 // copy we just inserted) is the last use of the source value. Live
265 // variable analysis conservatively handles this by saying that the value is
266 // live until the end of the block the PHI entry lives in. If the value
267 // really is dead at the PHI copy, there will be no successor blocks which
268 // have the value live-in.
270 // Check to see if the copy is the last use, and if so, update the live
271 // variables information so that it knows the copy source instruction kills
272 // the incoming value.
273 LiveVariables::VarInfo &InRegVI = LV->getVarInfo(SrcReg);
275 // Loop over all of the successors of the basic block, checking to see if
276 // the value is either live in the block, or if it is killed in the block.
277 // Also check to see if this register is in use by another PHI node which
278 // has not yet been eliminated. If so, it will be killed at an appropriate
281 // Is it used by any PHI instructions in this block?
282 bool ValueIsLive = VRegPHIUseCount[BBVRegPair(&opBlock, SrcReg)] != 0;
284 std::vector<MachineBasicBlock*> OpSuccBlocks;
286 // Otherwise, scan successors, including the BB the PHI node lives in.
287 for (MachineBasicBlock::succ_iterator SI = opBlock.succ_begin(),
288 E = opBlock.succ_end(); SI != E && !ValueIsLive; ++SI) {
289 MachineBasicBlock *SuccMBB = *SI;
291 // Is it alive in this successor?
292 unsigned SuccIdx = SuccMBB->getNumber();
293 if (InRegVI.AliveBlocks.test(SuccIdx)) {
298 OpSuccBlocks.push_back(SuccMBB);
301 // Check to see if this value is live because there is a use in a successor
304 switch (OpSuccBlocks.size()) {
306 MachineBasicBlock *MBB = OpSuccBlocks[0];
307 for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i)
308 if (InRegVI.Kills[i]->getParent() == MBB) {
315 MachineBasicBlock *MBB1 = OpSuccBlocks[0], *MBB2 = OpSuccBlocks[1];
316 for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i)
317 if (InRegVI.Kills[i]->getParent() == MBB1 ||
318 InRegVI.Kills[i]->getParent() == MBB2) {
325 std::sort(OpSuccBlocks.begin(), OpSuccBlocks.end());
326 for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i)
327 if (std::binary_search(OpSuccBlocks.begin(), OpSuccBlocks.end(),
328 InRegVI.Kills[i]->getParent())) {
335 // Okay, if we now know that the value is not live out of the block, we can
336 // add a kill marker in this block saying that it kills the incoming value!
338 // In our final twist, we have to decide which instruction kills the
339 // register. In most cases this is the copy, however, the first
340 // terminator instruction at the end of the block may also use the value.
341 // In this case, we should mark *it* as being the killing block, not the
343 MachineBasicBlock::iterator KillInst = prior(InsertPos);
344 MachineBasicBlock::iterator Term = opBlock.getFirstTerminator();
345 if (Term != opBlock.end()) {
346 if (Term->readsRegister(SrcReg))
349 // Check that no other terminators use values.
351 for (MachineBasicBlock::iterator TI = next(Term); TI != opBlock.end();
353 assert(!TI->readsRegister(SrcReg) &&
354 "Terminator instructions cannot use virtual registers unless"
355 "they are the first terminator in a block!");
360 // Finally, mark it killed.
361 LV->addVirtualRegisterKilled(SrcReg, KillInst);
363 // This vreg no longer lives all of the way through opBlock.
364 unsigned opBlockNum = opBlock.getNumber();
365 InRegVI.AliveBlocks.reset(opBlockNum);
369 // Really delete the PHI instruction now!
370 MF.DeleteMachineInstr(MPhi);
374 /// analyzePHINodes - Gather information about the PHI nodes in here. In
375 /// particular, we want to map the number of uses of a virtual register which is
376 /// used in a PHI node. We map that to the BB the vreg is coming from. This is
377 /// used later to determine when the vreg is killed in the BB.
379 void llvm::PHIElimination::analyzePHINodes(const MachineFunction& Fn) {
380 for (MachineFunction::const_iterator I = Fn.begin(), E = Fn.end();
382 for (MachineBasicBlock::const_iterator BBI = I->begin(), BBE = I->end();
383 BBI != BBE && BBI->getOpcode() == TargetInstrInfo::PHI; ++BBI)
384 for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
385 ++VRegPHIUseCount[BBVRegPair(BBI->getOperand(i + 1).getMBB(),
386 BBI->getOperand(i).getReg())];