Place new basic blocks immediately after their predecessor when splitting
[oota-llvm.git] / lib / CodeGen / PHIElimination.cpp
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
16 #define DEBUG_TYPE "phielim"
17 #include "PHIElimination.h"
18 #include "llvm/CodeGen/LiveVariables.h"
19 #include "llvm/CodeGen/Passes.h"
20 #include "llvm/CodeGen/MachineDominators.h"
21 #include "llvm/CodeGen/MachineInstr.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/Function.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/ADT/SmallPtrSet.h"
27 #include "llvm/ADT/STLExtras.h"
28 #include "llvm/ADT/Statistic.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Compiler.h"
31 #include "llvm/Support/Debug.h"
32 #include <algorithm>
33 #include <map>
34 using namespace llvm;
35
36 STATISTIC(NumAtomic, "Number of atomic phis lowered");
37 STATISTIC(NumSplits, "Number of critical edges split on demand");
38
39 char PHIElimination::ID = 0;
40 static RegisterPass<PHIElimination>
41 X("phi-node-elimination", "Eliminate PHI nodes for register allocation");
42
43 const PassInfo *const llvm::PHIEliminationID = &X;
44
45 void llvm::PHIElimination::getAnalysisUsage(AnalysisUsage &AU) const {
46   AU.addPreserved<LiveVariables>();
47   AU.addPreserved<MachineDominatorTree>();
48   // rdar://7401784 This would be nice:
49   // AU.addPreservedID(MachineLoopInfoID);
50   MachineFunctionPass::getAnalysisUsage(AU);
51 }
52
53 bool llvm::PHIElimination::runOnMachineFunction(MachineFunction &Fn) {
54   MRI = &Fn.getRegInfo();
55
56   PHIDefs.clear();
57   PHIKills.clear();
58   bool Changed = false;
59
60   // Split critical edges to help the coalescer
61   if (LiveVariables *LV = getAnalysisIfAvailable<LiveVariables>())
62     for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
63       Changed |= SplitPHIEdges(Fn, *I, *LV);
64
65   // Populate VRegPHIUseCount
66   analyzePHINodes(Fn);
67
68   // Eliminate PHI instructions by inserting copies into predecessor blocks.
69   for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
70     Changed |= EliminatePHINodes(Fn, *I);
71
72   // Remove dead IMPLICIT_DEF instructions.
73   for (SmallPtrSet<MachineInstr*,4>::iterator I = ImpDefs.begin(),
74          E = ImpDefs.end(); I != E; ++I) {
75     MachineInstr *DefMI = *I;
76     unsigned DefReg = DefMI->getOperand(0).getReg();
77     if (MRI->use_empty(DefReg))
78       DefMI->eraseFromParent();
79   }
80
81   ImpDefs.clear();
82   VRegPHIUseCount.clear();
83   return Changed;
84 }
85
86 /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions in
87 /// predecessor basic blocks.
88 ///
89 bool llvm::PHIElimination::EliminatePHINodes(MachineFunction &MF,
90                                              MachineBasicBlock &MBB) {
91   if (MBB.empty() || MBB.front().getOpcode() != TargetInstrInfo::PHI)
92     return false;   // Quick exit for basic blocks without PHIs.
93
94   // Get an iterator to the first instruction after the last PHI node (this may
95   // also be the end of the basic block).
96   MachineBasicBlock::iterator AfterPHIsIt = SkipPHIsAndLabels(MBB, MBB.begin());
97
98   while (MBB.front().getOpcode() == TargetInstrInfo::PHI)
99     LowerAtomicPHINode(MBB, AfterPHIsIt);
100
101   return true;
102 }
103
104 /// isSourceDefinedByImplicitDef - Return true if all sources of the phi node
105 /// are implicit_def's.
106 static bool isSourceDefinedByImplicitDef(const MachineInstr *MPhi,
107                                          const MachineRegisterInfo *MRI) {
108   for (unsigned i = 1; i != MPhi->getNumOperands(); i += 2) {
109     unsigned SrcReg = MPhi->getOperand(i).getReg();
110     const MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
111     if (!DefMI || DefMI->getOpcode() != TargetInstrInfo::IMPLICIT_DEF)
112       return false;
113   }
114   return true;
115 }
116
117 // FindCopyInsertPoint - Find a safe place in MBB to insert a copy from SrcReg
118 // when following the CFG edge to SuccMBB. This needs to be after any def of
119 // SrcReg, but before any subsequent point where control flow might jump out of
120 // the basic block.
121 MachineBasicBlock::iterator
122 llvm::PHIElimination::FindCopyInsertPoint(MachineBasicBlock &MBB,
123                                           MachineBasicBlock &SuccMBB,
124                                           unsigned SrcReg) {
125   // Handle the trivial case trivially.
126   if (MBB.empty())
127     return MBB.begin();
128
129   // Usually, we just want to insert the copy before the first terminator
130   // instruction. However, for the edge going to a landing pad, we must insert
131   // the copy before the call/invoke instruction.
132   if (!SuccMBB.isLandingPad())
133     return MBB.getFirstTerminator();
134
135   // Discover any defs/uses in this basic block.
136   SmallPtrSet<MachineInstr*, 8> DefUsesInMBB;
137   for (MachineRegisterInfo::reg_iterator RI = MRI->reg_begin(SrcReg),
138          RE = MRI->reg_end(); RI != RE; ++RI) {
139     MachineInstr *DefUseMI = &*RI;
140     if (DefUseMI->getParent() == &MBB)
141       DefUsesInMBB.insert(DefUseMI);
142   }
143
144   MachineBasicBlock::iterator InsertPoint;
145   if (DefUsesInMBB.empty()) {
146     // No defs.  Insert the copy at the start of the basic block.
147     InsertPoint = MBB.begin();
148   } else if (DefUsesInMBB.size() == 1) {
149     // Insert the copy immediately after the def/use.
150     InsertPoint = *DefUsesInMBB.begin();
151     ++InsertPoint;
152   } else {
153     // Insert the copy immediately after the last def/use.
154     InsertPoint = MBB.end();
155     while (!DefUsesInMBB.count(&*--InsertPoint)) {}
156     ++InsertPoint;
157   }
158
159   // Make sure the copy goes after any phi nodes however.
160   return SkipPHIsAndLabels(MBB, InsertPoint);
161 }
162
163 /// LowerAtomicPHINode - Lower the PHI node at the top of the specified block,
164 /// under the assuption that it needs to be lowered in a way that supports
165 /// atomic execution of PHIs.  This lowering method is always correct all of the
166 /// time.
167 ///
168 void llvm::PHIElimination::LowerAtomicPHINode(
169                                       MachineBasicBlock &MBB,
170                                       MachineBasicBlock::iterator AfterPHIsIt) {
171   // Unlink the PHI node from the basic block, but don't delete the PHI yet.
172   MachineInstr *MPhi = MBB.remove(MBB.begin());
173
174   unsigned NumSrcs = (MPhi->getNumOperands() - 1) / 2;
175   unsigned DestReg = MPhi->getOperand(0).getReg();
176   bool isDead = MPhi->getOperand(0).isDead();
177
178   // Create a new register for the incoming PHI arguments.
179   MachineFunction &MF = *MBB.getParent();
180   const TargetRegisterClass *RC = MF.getRegInfo().getRegClass(DestReg);
181   unsigned IncomingReg = 0;
182
183   // Insert a register to register copy at the top of the current block (but
184   // after any remaining phi nodes) which copies the new incoming register
185   // into the phi node destination.
186   const TargetInstrInfo *TII = MF.getTarget().getInstrInfo();
187   if (isSourceDefinedByImplicitDef(MPhi, MRI))
188     // If all sources of a PHI node are implicit_def, just emit an
189     // implicit_def instead of a copy.
190     BuildMI(MBB, AfterPHIsIt, MPhi->getDebugLoc(),
191             TII->get(TargetInstrInfo::IMPLICIT_DEF), DestReg);
192   else {
193     IncomingReg = MF.getRegInfo().createVirtualRegister(RC);
194     TII->copyRegToReg(MBB, AfterPHIsIt, DestReg, IncomingReg, RC, RC);
195   }
196
197   // Record PHI def.
198   assert(!hasPHIDef(DestReg) && "Vreg has multiple phi-defs?");
199   PHIDefs[DestReg] = &MBB;
200
201   // Update live variable information if there is any.
202   LiveVariables *LV = getAnalysisIfAvailable<LiveVariables>();
203   if (LV) {
204     MachineInstr *PHICopy = prior(AfterPHIsIt);
205
206     if (IncomingReg) {
207       // Increment use count of the newly created virtual register.
208       LV->getVarInfo(IncomingReg).NumUses++;
209
210       // Add information to LiveVariables to know that the incoming value is
211       // killed.  Note that because the value is defined in several places (once
212       // each for each incoming block), the "def" block and instruction fields
213       // for the VarInfo is not filled in.
214       LV->addVirtualRegisterKilled(IncomingReg, PHICopy);
215     }
216
217     // Since we are going to be deleting the PHI node, if it is the last use of
218     // any registers, or if the value itself is dead, we need to move this
219     // information over to the new copy we just inserted.
220     LV->removeVirtualRegistersKilled(MPhi);
221
222     // If the result is dead, update LV.
223     if (isDead) {
224       LV->addVirtualRegisterDead(DestReg, PHICopy);
225       LV->removeVirtualRegisterDead(DestReg, MPhi);
226     }
227   }
228
229   // Adjust the VRegPHIUseCount map to account for the removal of this PHI node.
230   for (unsigned i = 1; i != MPhi->getNumOperands(); i += 2)
231     --VRegPHIUseCount[BBVRegPair(MPhi->getOperand(i + 1).getMBB(),
232                                  MPhi->getOperand(i).getReg())];
233
234   // Now loop over all of the incoming arguments, changing them to copy into the
235   // IncomingReg register in the corresponding predecessor basic block.
236   SmallPtrSet<MachineBasicBlock*, 8> MBBsInsertedInto;
237   for (int i = NumSrcs - 1; i >= 0; --i) {
238     unsigned SrcReg = MPhi->getOperand(i*2+1).getReg();
239     assert(TargetRegisterInfo::isVirtualRegister(SrcReg) &&
240            "Machine PHI Operands must all be virtual registers!");
241
242     // Get the MachineBasicBlock equivalent of the BasicBlock that is the source
243     // path the PHI.
244     MachineBasicBlock &opBlock = *MPhi->getOperand(i*2+2).getMBB();
245
246     // Record the kill.
247     PHIKills[SrcReg].insert(&opBlock);
248
249     // If source is defined by an implicit def, there is no need to insert a
250     // copy.
251     MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
252     if (DefMI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
253       ImpDefs.insert(DefMI);
254       continue;
255     }
256
257     // Check to make sure we haven't already emitted the copy for this block.
258     // This can happen because PHI nodes may have multiple entries for the same
259     // basic block.
260     if (!MBBsInsertedInto.insert(&opBlock))
261       continue;  // If the copy has already been emitted, we're done.
262
263     // Find a safe location to insert the copy, this may be the first terminator
264     // in the block (or end()).
265     MachineBasicBlock::iterator InsertPos =
266       FindCopyInsertPoint(opBlock, MBB, SrcReg);
267
268     // Insert the copy.
269     TII->copyRegToReg(opBlock, InsertPos, IncomingReg, SrcReg, RC, RC);
270
271     // Now update live variable information if we have it.  Otherwise we're done
272     if (!LV) continue;
273
274     // We want to be able to insert a kill of the register if this PHI (aka, the
275     // copy we just inserted) is the last use of the source value.  Live
276     // variable analysis conservatively handles this by saying that the value is
277     // live until the end of the block the PHI entry lives in.  If the value
278     // really is dead at the PHI copy, there will be no successor blocks which
279     // have the value live-in.
280
281     // Also check to see if this register is in use by another PHI node which
282     // has not yet been eliminated.  If so, it will be killed at an appropriate
283     // point later.
284
285     // Is it used by any PHI instructions in this block?
286     bool ValueIsUsed = VRegPHIUseCount[BBVRegPair(&opBlock, SrcReg)] != 0;
287
288     // Okay, if we now know that the value is not live out of the block, we can
289     // add a kill marker in this block saying that it kills the incoming value!
290     if (!ValueIsUsed && !isLiveOut(SrcReg, opBlock, *LV)) {
291       // In our final twist, we have to decide which instruction kills the
292       // register.  In most cases this is the copy, however, the first
293       // terminator instruction at the end of the block may also use the value.
294       // In this case, we should mark *it* as being the killing block, not the
295       // copy.
296       MachineBasicBlock::iterator KillInst = prior(InsertPos);
297       MachineBasicBlock::iterator Term = opBlock.getFirstTerminator();
298       if (Term != opBlock.end()) {
299         if (Term->readsRegister(SrcReg))
300           KillInst = Term;
301
302         // Check that no other terminators use values.
303 #ifndef NDEBUG
304         for (MachineBasicBlock::iterator TI = next(Term); TI != opBlock.end();
305              ++TI) {
306           assert(!TI->readsRegister(SrcReg) &&
307                  "Terminator instructions cannot use virtual registers unless"
308                  "they are the first terminator in a block!");
309         }
310 #endif
311       }
312
313       // Finally, mark it killed.
314       LV->addVirtualRegisterKilled(SrcReg, KillInst);
315
316       // This vreg no longer lives all of the way through opBlock.
317       unsigned opBlockNum = opBlock.getNumber();
318       LV->getVarInfo(SrcReg).AliveBlocks.reset(opBlockNum);
319     }
320   }
321
322   // Really delete the PHI instruction now!
323   MF.DeleteMachineInstr(MPhi);
324   ++NumAtomic;
325 }
326
327 /// analyzePHINodes - Gather information about the PHI nodes in here. In
328 /// particular, we want to map the number of uses of a virtual register which is
329 /// used in a PHI node. We map that to the BB the vreg is coming from. This is
330 /// used later to determine when the vreg is killed in the BB.
331 ///
332 void llvm::PHIElimination::analyzePHINodes(const MachineFunction& Fn) {
333   for (MachineFunction::const_iterator I = Fn.begin(), E = Fn.end();
334        I != E; ++I)
335     for (MachineBasicBlock::const_iterator BBI = I->begin(), BBE = I->end();
336          BBI != BBE && BBI->getOpcode() == TargetInstrInfo::PHI; ++BBI)
337       for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
338         ++VRegPHIUseCount[BBVRegPair(BBI->getOperand(i + 1).getMBB(),
339                                      BBI->getOperand(i).getReg())];
340 }
341
342 bool llvm::PHIElimination::SplitPHIEdges(MachineFunction &MF,
343                                          MachineBasicBlock &MBB,
344                                          LiveVariables &LV) {
345   if (MBB.empty() || MBB.front().getOpcode() != TargetInstrInfo::PHI)
346     return false;   // Quick exit for basic blocks without PHIs.
347
348   for (MachineBasicBlock::const_iterator BBI = MBB.begin(), BBE = MBB.end();
349        BBI != BBE && BBI->getOpcode() == TargetInstrInfo::PHI; ++BBI) {
350     for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2) {
351       unsigned Reg = BBI->getOperand(i).getReg();
352       MachineBasicBlock *PreMBB = BBI->getOperand(i+1).getMBB();
353       // We break edges when registers are live out from the predecessor block
354       // (not considering PHI nodes). If the register is live in to this block
355       // anyway, we would gain nothing from splitting.
356       if (isLiveOut(Reg, *PreMBB, LV) && !isLiveIn(Reg, MBB, LV))
357         SplitCriticalEdge(PreMBB, &MBB);
358     }
359   }
360   return true;
361 }
362
363 bool llvm::PHIElimination::isLiveOut(unsigned Reg, const MachineBasicBlock &MBB,
364                                      LiveVariables &LV) {
365   LiveVariables::VarInfo &VI = LV.getVarInfo(Reg);
366
367   // Loop over all of the successors of the basic block, checking to see if
368   // the value is either live in the block, or if it is killed in the block.
369   std::vector<MachineBasicBlock*> OpSuccBlocks;
370   for (MachineBasicBlock::const_succ_iterator SI = MBB.succ_begin(),
371          E = MBB.succ_end(); SI != E; ++SI) {
372     MachineBasicBlock *SuccMBB = *SI;
373
374     // Is it alive in this successor?
375     unsigned SuccIdx = SuccMBB->getNumber();
376     if (VI.AliveBlocks.test(SuccIdx))
377       return true;
378     OpSuccBlocks.push_back(SuccMBB);
379   }
380
381   // Check to see if this value is live because there is a use in a successor
382   // that kills it.
383   switch (OpSuccBlocks.size()) {
384   case 1: {
385     MachineBasicBlock *SuccMBB = OpSuccBlocks[0];
386     for (unsigned i = 0, e = VI.Kills.size(); i != e; ++i)
387       if (VI.Kills[i]->getParent() == SuccMBB)
388         return true;
389     break;
390   }
391   case 2: {
392     MachineBasicBlock *SuccMBB1 = OpSuccBlocks[0], *SuccMBB2 = OpSuccBlocks[1];
393     for (unsigned i = 0, e = VI.Kills.size(); i != e; ++i)
394       if (VI.Kills[i]->getParent() == SuccMBB1 ||
395           VI.Kills[i]->getParent() == SuccMBB2)
396         return true;
397     break;
398   }
399   default:
400     std::sort(OpSuccBlocks.begin(), OpSuccBlocks.end());
401     for (unsigned i = 0, e = VI.Kills.size(); i != e; ++i)
402       if (std::binary_search(OpSuccBlocks.begin(), OpSuccBlocks.end(),
403                              VI.Kills[i]->getParent()))
404         return true;
405   }
406   return false;
407 }
408
409 bool llvm::PHIElimination::isLiveIn(unsigned Reg, const MachineBasicBlock &MBB,
410                                     LiveVariables &LV) {
411   LiveVariables::VarInfo &VI = LV.getVarInfo(Reg);
412
413   if (VI.AliveBlocks.test(MBB.getNumber()))
414     return true;
415
416   // defined in MBB?
417   const MachineInstr *Def = MRI->getVRegDef(Reg);
418   if (Def && Def->getParent() == &MBB)
419     return false;
420
421   // killed in MBB?
422   return VI.findKill(&MBB);
423 }
424
425 MachineBasicBlock *PHIElimination::SplitCriticalEdge(MachineBasicBlock *A,
426                                                      MachineBasicBlock *B) {
427   assert(A && B && "Missing MBB end point");
428
429   MachineFunction *MF = A->getParent();
430
431   // We may need to update A's terminator, but we can't do that if AnalyzeBranch
432   // fails. If A uses a jump table, we won't touch it.
433   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
434   MachineBasicBlock *TBB = 0, *FBB = 0;
435   SmallVector<MachineOperand, 4> Cond;
436   if (TII->AnalyzeBranch(*A, TBB, FBB, Cond))
437     return NULL;
438
439   ++NumSplits;
440
441   MachineBasicBlock *NMBB = MF->CreateMachineBasicBlock();
442   MF->insert(next(MachineFunction::iterator(A)), NMBB);
443   DEBUG(errs() << "PHIElimination splitting critical edge:"
444         " BB#" << A->getNumber()
445         << " -- BB#" << NMBB->getNumber()
446         << " -- BB#" << B->getNumber() << '\n');
447
448   A->ReplaceUsesOfBlockWith(B, NMBB);
449   A->updateTerminator();
450
451   // Insert unconditional "jump B" instruction in NMBB if necessary.
452   NMBB->addSuccessor(B);
453   if (!NMBB->isLayoutSuccessor(B)) {
454     Cond.clear();
455     MF->getTarget().getInstrInfo()->InsertBranch(*NMBB, B, NULL, Cond);
456   }
457
458   // Fix PHI nodes in B so they refer to NMBB instead of A
459   for (MachineBasicBlock::iterator i = B->begin(), e = B->end();
460        i != e && i->getOpcode() == TargetInstrInfo::PHI; ++i)
461     for (unsigned ni = 1, ne = i->getNumOperands(); ni != ne; ni += 2)
462       if (i->getOperand(ni+1).getMBB() == A)
463         i->getOperand(ni+1).setMBB(NMBB);
464
465   if (LiveVariables *LV=getAnalysisIfAvailable<LiveVariables>())
466     LV->addNewBlock(NMBB, A);
467
468   if (MachineDominatorTree *MDT=getAnalysisIfAvailable<MachineDominatorTree>())
469     MDT->addNewBlock(NMBB, A);
470
471   return NMBB;
472 }