1 //===- PhiElimination.cpp - Eliminate PHI nodes by inserting copies -------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass eliminates machine instruction PHI nodes by inserting copy
10 // instructions.  This destroys SSA information, but is the desired input for
11 // some register allocators.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "PHIEliminationUtils.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/SmallPtrSet.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/Analysis/LoopInfo.h"
20 #include "llvm/CodeGen/LiveInterval.h"
21 #include "llvm/CodeGen/LiveIntervals.h"
22 #include "llvm/CodeGen/LiveVariables.h"
23 #include "llvm/CodeGen/MachineBasicBlock.h"
24 #include "llvm/CodeGen/MachineDominators.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineFunctionPass.h"
27 #include "llvm/CodeGen/MachineInstr.h"
28 #include "llvm/CodeGen/MachineInstrBuilder.h"
29 #include "llvm/CodeGen/MachineLoopInfo.h"
30 #include "llvm/CodeGen/MachineOperand.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/CodeGen/SlotIndexes.h"
33 #include "llvm/CodeGen/TargetInstrInfo.h"
34 #include "llvm/CodeGen/TargetLowering.h"
35 #include "llvm/CodeGen/TargetOpcodes.h"
36 #include "llvm/CodeGen/TargetPassConfig.h"
37 #include "llvm/CodeGen/TargetRegisterInfo.h"
38 #include "llvm/CodeGen/TargetSubtargetInfo.h"
39 #include "llvm/Pass.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include <cassert>
44 #include <iterator>
45 #include <utility>
46 
47 using namespace llvm;
48 
49 #define DEBUG_TYPE "phi-node-elimination"
50 
51 static cl::opt<bool>
52 DisableEdgeSplitting("disable-phi-elim-edge-splitting", cl::init(false),
53                      cl::Hidden, cl::desc("Disable critical edge splitting "
54                                           "during PHI elimination"));
55 
56 static cl::opt<bool>
57 SplitAllCriticalEdges("phi-elim-split-all-critical-edges", cl::init(false),
58                       cl::Hidden, cl::desc("Split all critical edges during "
59                                            "PHI elimination"));
60 
61 static cl::opt<bool> NoPhiElimLiveOutEarlyExit(
62     "no-phi-elim-live-out-early-exit", cl::init(false), cl::Hidden,
63     cl::desc("Do not use an early exit if isLiveOutPastPHIs returns true."));
64 
65 namespace {
66 
67   class PHIElimination : public MachineFunctionPass {
68     MachineRegisterInfo *MRI; // Machine register information
69     LiveVariables *LV;
70     LiveIntervals *LIS;
71 
72   public:
73     static char ID; // Pass identification, replacement for typeid
74 
75     PHIElimination() : MachineFunctionPass(ID) {
76       initializePHIEliminationPass(*PassRegistry::getPassRegistry());
77     }
78 
79     bool runOnMachineFunction(MachineFunction &MF) override;
80     void getAnalysisUsage(AnalysisUsage &AU) const override;
81 
82   private:
83     /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions
84     /// in predecessor basic blocks.
85     bool EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB);
86 
87     void LowerPHINode(MachineBasicBlock &MBB,
88                       MachineBasicBlock::iterator LastPHIIt);
89 
90     /// analyzePHINodes - Gather information about the PHI nodes in
91     /// here. In particular, we want to map the number of uses of a virtual
92     /// register which is used in a PHI node. We map that to the BB the
93     /// vreg is coming from. This is used later to determine when the vreg
94     /// is killed in the BB.
95     void analyzePHINodes(const MachineFunction& MF);
96 
97     /// Split critical edges where necessary for good coalescer performance.
98     bool SplitPHIEdges(MachineFunction &MF, MachineBasicBlock &MBB,
99                        MachineLoopInfo *MLI);
100 
101     // These functions are temporary abstractions around LiveVariables and
102     // LiveIntervals, so they can go away when LiveVariables does.
103     bool isLiveIn(unsigned Reg, const MachineBasicBlock *MBB);
104     bool isLiveOutPastPHIs(unsigned Reg, const MachineBasicBlock *MBB);
105 
106     using BBVRegPair = std::pair<unsigned, unsigned>;
107     using VRegPHIUse = DenseMap<BBVRegPair, unsigned>;
108 
109     VRegPHIUse VRegPHIUseCount;
110 
111     // Defs of PHI sources which are implicit_def.
112     SmallPtrSet<MachineInstr*, 4> ImpDefs;
113 
114     // Map reusable lowered PHI node -> incoming join register.
115     using LoweredPHIMap =
116         DenseMap<MachineInstr*, unsigned, MachineInstrExpressionTrait>;
117     LoweredPHIMap LoweredPHIs;
118   };
119 
120 } // end anonymous namespace
121 
122 STATISTIC(NumLowered, "Number of phis lowered");
123 STATISTIC(NumCriticalEdgesSplit, "Number of critical edges split");
124 STATISTIC(NumReused, "Number of reused lowered phis");
125 
126 char PHIElimination::ID = 0;
127 
128 char& llvm::PHIEliminationID = PHIElimination::ID;
129 
130 INITIALIZE_PASS_BEGIN(PHIElimination, DEBUG_TYPE,
131                       "Eliminate PHI nodes for register allocation",
132                       false, false)
133 INITIALIZE_PASS_DEPENDENCY(LiveVariables)
134 INITIALIZE_PASS_END(PHIElimination, DEBUG_TYPE,
135                     "Eliminate PHI nodes for register allocation", false, false)
136 
137 void PHIElimination::getAnalysisUsage(AnalysisUsage &AU) const {
138   AU.addUsedIfAvailable<LiveVariables>();
139   AU.addPreserved<LiveVariables>();
140   AU.addPreserved<SlotIndexes>();
141   AU.addPreserved<LiveIntervals>();
142   AU.addPreserved<MachineDominatorTree>();
143   AU.addPreserved<MachineLoopInfo>();
144   MachineFunctionPass::getAnalysisUsage(AU);
145 }
146 
147 bool PHIElimination::runOnMachineFunction(MachineFunction &MF) {
148   MRI = &MF.getRegInfo();
149   LV = getAnalysisIfAvailable<LiveVariables>();
150   LIS = getAnalysisIfAvailable<LiveIntervals>();
151 
152   bool Changed = false;
153 
154   // This pass takes the function out of SSA form.
155   MRI->leaveSSA();
156 
157   // Split critical edges to help the coalescer.
158   if (!DisableEdgeSplitting && (LV || LIS)) {
159     MachineLoopInfo *MLI = getAnalysisIfAvailable<MachineLoopInfo>();
160     for (auto &MBB : MF)
161       Changed |= SplitPHIEdges(MF, MBB, MLI);
162   }
163 
164   // Populate VRegPHIUseCount
165   analyzePHINodes(MF);
166 
167   // Eliminate PHI instructions by inserting copies into predecessor blocks.
168   for (auto &MBB : MF)
169     Changed |= EliminatePHINodes(MF, MBB);
170 
171   // Remove dead IMPLICIT_DEF instructions.
172   for (MachineInstr *DefMI : ImpDefs) {
173     Register DefReg = DefMI->getOperand(0).getReg();
174     if (MRI->use_nodbg_empty(DefReg)) {
175       if (LIS)
176         LIS->RemoveMachineInstrFromMaps(*DefMI);
177       DefMI->eraseFromParent();
178     }
179   }
180 
181   // Clean up the lowered PHI instructions.
182   for (auto &I : LoweredPHIs) {
183     if (LIS)
184       LIS->RemoveMachineInstrFromMaps(*I.first);
185     MF.DeleteMachineInstr(I.first);
186   }
187 
188   // TODO: we should use the incremental DomTree updater here.
189   if (Changed)
190     if (auto *MDT = getAnalysisIfAvailable<MachineDominatorTree>())
191       MDT->getBase().recalculate(MF);
192 
193   LoweredPHIs.clear();
194   ImpDefs.clear();
195   VRegPHIUseCount.clear();
196 
197   MF.getProperties().set(MachineFunctionProperties::Property::NoPHIs);
198 
199   return Changed;
200 }
201 
202 /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions in
203 /// predecessor basic blocks.
204 bool PHIElimination::EliminatePHINodes(MachineFunction &MF,
205                                        MachineBasicBlock &MBB) {
206   if (MBB.empty() || !MBB.front().isPHI())
207     return false;   // Quick exit for basic blocks without PHIs.
208 
209   // Get an iterator to the last PHI node.
210   MachineBasicBlock::iterator LastPHIIt =
211     std::prev(MBB.SkipPHIsAndLabels(MBB.begin()));
212 
213   assert((LastPHIIt == skipDebugInstructionsBackward(
214             std::prev(MBB.SkipPHIsLabelsAndDebug(MBB.begin())),
215             MBB.begin())) &&
216          "There must be no DBG_VALUEs between PHI and LABEL");
217 
218   while (MBB.front().isPHI())
219     LowerPHINode(MBB, LastPHIIt);
220 
221   return true;
222 }
223 
224 /// Return true if all defs of VirtReg are implicit-defs.
225 /// This includes registers with no defs.
226 static bool isImplicitlyDefined(unsigned VirtReg,
227                                 const MachineRegisterInfo &MRI) {
228   for (MachineInstr &DI : MRI.def_instructions(VirtReg))
229     if (!DI.isImplicitDef())
230       return false;
231   return true;
232 }
233 
234 /// Return true if all sources of the phi node are implicit_def's, or undef's.
235 static bool allPhiOperandsUndefined(const MachineInstr &MPhi,
236                                     const MachineRegisterInfo &MRI) {
237   for (unsigned I = 1, E = MPhi.getNumOperands(); I != E; I += 2) {
238     const MachineOperand &MO = MPhi.getOperand(I);
239     if (!isImplicitlyDefined(MO.getReg(), MRI) && !MO.isUndef())
240       return false;
241   }
242   return true;
243 }
244 /// LowerPHINode - Lower the PHI node at the top of the specified block.
245 void PHIElimination::LowerPHINode(MachineBasicBlock &MBB,
246                                   MachineBasicBlock::iterator LastPHIIt) {
247   ++NumLowered;
248 
249   MachineBasicBlock::iterator AfterPHIsIt = std::next(LastPHIIt);
250 
251   // Unlink the PHI node from the basic block, but don't delete the PHI yet.
252   MachineInstr *MPhi = MBB.remove(&*MBB.begin());
253 
254   unsigned NumSrcs = (MPhi->getNumOperands() - 1) / 2;
255   Register DestReg = MPhi->getOperand(0).getReg();
256   assert(MPhi->getOperand(0).getSubReg() == 0 && "Can't handle sub-reg PHIs");
257   bool isDead = MPhi->getOperand(0).isDead();
258 
259   // Create a new register for the incoming PHI arguments.
260   MachineFunction &MF = *MBB.getParent();
261   unsigned IncomingReg = 0;
262   bool reusedIncoming = false;  // Is IncomingReg reused from an earlier PHI?
263 
264   // Insert a register to register copy at the top of the current block (but
265   // after any remaining phi nodes) which copies the new incoming register
266   // into the phi node destination.
267   MachineInstr *PHICopy = nullptr;
268   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
269   if (allPhiOperandsUndefined(*MPhi, *MRI))
270     // If all sources of a PHI node are implicit_def or undef uses, just emit an
271     // implicit_def instead of a copy.
272     PHICopy = BuildMI(MBB, AfterPHIsIt, MPhi->getDebugLoc(),
273             TII->get(TargetOpcode::IMPLICIT_DEF), DestReg);
274   else {
275     // Can we reuse an earlier PHI node? This only happens for critical edges,
276     // typically those created by tail duplication.
277     unsigned &entry = LoweredPHIs[MPhi];
278     if (entry) {
279       // An identical PHI node was already lowered. Reuse the incoming register.
280       IncomingReg = entry;
281       reusedIncoming = true;
282       ++NumReused;
283       LLVM_DEBUG(dbgs() << "Reusing " << printReg(IncomingReg) << " for "
284                         << *MPhi);
285     } else {
286       const TargetRegisterClass *RC = MF.getRegInfo().getRegClass(DestReg);
287       entry = IncomingReg = MF.getRegInfo().createVirtualRegister(RC);
288     }
289     // Give the target possiblity to handle special cases fallthrough otherwise
290     PHICopy = TII->createPHIDestinationCopy(MBB, AfterPHIsIt, MPhi->getDebugLoc(),
291                                   IncomingReg, DestReg);
292   }
293 
294   // Update live variable information if there is any.
295   if (LV) {
296     if (IncomingReg) {
297       LiveVariables::VarInfo &VI = LV->getVarInfo(IncomingReg);
298 
299       // Increment use count of the newly created virtual register.
300       LV->setPHIJoin(IncomingReg);
301 
302       // When we are reusing the incoming register, it may already have been
303       // killed in this block. The old kill will also have been inserted at
304       // AfterPHIsIt, so it appears before the current PHICopy.
305       if (reusedIncoming)
306         if (MachineInstr *OldKill = VI.findKill(&MBB)) {
307           LLVM_DEBUG(dbgs() << "Remove old kill from " << *OldKill);
308           LV->removeVirtualRegisterKilled(IncomingReg, *OldKill);
309           LLVM_DEBUG(MBB.dump());
310         }
311 
312       // Add information to LiveVariables to know that the incoming value is
313       // killed.  Note that because the value is defined in several places (once
314       // each for each incoming block), the "def" block and instruction fields
315       // for the VarInfo is not filled in.
316       LV->addVirtualRegisterKilled(IncomingReg, *PHICopy);
317     }
318 
319     // Since we are going to be deleting the PHI node, if it is the last use of
320     // any registers, or if the value itself is dead, we need to move this
321     // information over to the new copy we just inserted.
322     LV->removeVirtualRegistersKilled(*MPhi);
323 
324     // If the result is dead, update LV.
325     if (isDead) {
326       LV->addVirtualRegisterDead(DestReg, *PHICopy);
327       LV->removeVirtualRegisterDead(DestReg, *MPhi);
328     }
329   }
330 
331   // Update LiveIntervals for the new copy or implicit def.
332   if (LIS) {
333     SlotIndex DestCopyIndex = LIS->InsertMachineInstrInMaps(*PHICopy);
334 
335     SlotIndex MBBStartIndex = LIS->getMBBStartIdx(&MBB);
336     if (IncomingReg) {
337       // Add the region from the beginning of MBB to the copy instruction to
338       // IncomingReg's live interval.
339       LiveInterval &IncomingLI = LIS->createEmptyInterval(IncomingReg);
340       VNInfo *IncomingVNI = IncomingLI.getVNInfoAt(MBBStartIndex);
341       if (!IncomingVNI)
342         IncomingVNI = IncomingLI.getNextValue(MBBStartIndex,
343                                               LIS->getVNInfoAllocator());
344       IncomingLI.addSegment(LiveInterval::Segment(MBBStartIndex,
345                                                   DestCopyIndex.getRegSlot(),
346                                                   IncomingVNI));
347     }
348 
349     LiveInterval &DestLI = LIS->getInterval(DestReg);
350     assert(DestLI.begin() != DestLI.end() &&
351            "PHIs should have nonempty LiveIntervals.");
352     if (DestLI.endIndex().isDead()) {
353       // A dead PHI's live range begins and ends at the start of the MBB, but
354       // the lowered copy, which will still be dead, needs to begin and end at
355       // the copy instruction.
356       VNInfo *OrigDestVNI = DestLI.getVNInfoAt(MBBStartIndex);
357       assert(OrigDestVNI && "PHI destination should be live at block entry.");
358       DestLI.removeSegment(MBBStartIndex, MBBStartIndex.getDeadSlot());
359       DestLI.createDeadDef(DestCopyIndex.getRegSlot(),
360                            LIS->getVNInfoAllocator());
361       DestLI.removeValNo(OrigDestVNI);
362     } else {
363       // Otherwise, remove the region from the beginning of MBB to the copy
364       // instruction from DestReg's live interval.
365       DestLI.removeSegment(MBBStartIndex, DestCopyIndex.getRegSlot());
366       VNInfo *DestVNI = DestLI.getVNInfoAt(DestCopyIndex.getRegSlot());
367       assert(DestVNI && "PHI destination should be live at its definition.");
368       DestVNI->def = DestCopyIndex.getRegSlot();
369     }
370   }
371 
372   // Adjust the VRegPHIUseCount map to account for the removal of this PHI node.
373   for (unsigned i = 1; i != MPhi->getNumOperands(); i += 2)
374     --VRegPHIUseCount[BBVRegPair(MPhi->getOperand(i+1).getMBB()->getNumber(),
375                                  MPhi->getOperand(i).getReg())];
376 
377   // Now loop over all of the incoming arguments, changing them to copy into the
378   // IncomingReg register in the corresponding predecessor basic block.
379   SmallPtrSet<MachineBasicBlock*, 8> MBBsInsertedInto;
380   for (int i = NumSrcs - 1; i >= 0; --i) {
381     Register SrcReg = MPhi->getOperand(i * 2 + 1).getReg();
382     unsigned SrcSubReg = MPhi->getOperand(i*2+1).getSubReg();
383     bool SrcUndef = MPhi->getOperand(i*2+1).isUndef() ||
384       isImplicitlyDefined(SrcReg, *MRI);
385     assert(Register::isVirtualRegister(SrcReg) &&
386            "Machine PHI Operands must all be virtual registers!");
387 
388     // Get the MachineBasicBlock equivalent of the BasicBlock that is the source
389     // path the PHI.
390     MachineBasicBlock &opBlock = *MPhi->getOperand(i*2+2).getMBB();
391 
392     // Check to make sure we haven't already emitted the copy for this block.
393     // This can happen because PHI nodes may have multiple entries for the same
394     // basic block.
395     if (!MBBsInsertedInto.insert(&opBlock).second)
396       continue;  // If the copy has already been emitted, we're done.
397 
398     // Find a safe location to insert the copy, this may be the first terminator
399     // in the block (or end()).
400     MachineBasicBlock::iterator InsertPos =
401       findPHICopyInsertPoint(&opBlock, &MBB, SrcReg);
402 
403     // Insert the copy.
404     MachineInstr *NewSrcInstr = nullptr;
405     if (!reusedIncoming && IncomingReg) {
406       if (SrcUndef) {
407         // The source register is undefined, so there is no need for a real
408         // COPY, but we still need to ensure joint dominance by defs.
409         // Insert an IMPLICIT_DEF instruction.
410         NewSrcInstr = BuildMI(opBlock, InsertPos, MPhi->getDebugLoc(),
411                               TII->get(TargetOpcode::IMPLICIT_DEF),
412                               IncomingReg);
413 
414         // Clean up the old implicit-def, if there even was one.
415         if (MachineInstr *DefMI = MRI->getVRegDef(SrcReg))
416           if (DefMI->isImplicitDef())
417             ImpDefs.insert(DefMI);
418       } else {
419         NewSrcInstr =
420             TII->createPHISourceCopy(opBlock, InsertPos, MPhi->getDebugLoc(),
421                                      SrcReg, SrcSubReg, IncomingReg);
422       }
423     }
424 
425     // We only need to update the LiveVariables kill of SrcReg if this was the
426     // last PHI use of SrcReg to be lowered on this CFG edge and it is not live
427     // out of the predecessor. We can also ignore undef sources.
428     if (LV && !SrcUndef &&
429         !VRegPHIUseCount[BBVRegPair(opBlock.getNumber(), SrcReg)] &&
430         !LV->isLiveOut(SrcReg, opBlock)) {
431       // We want to be able to insert a kill of the register if this PHI (aka,
432       // the copy we just inserted) is the last use of the source value. Live
433       // variable analysis conservatively handles this by saying that the value
434       // is live until the end of the block the PHI entry lives in. If the value
435       // really is dead at the PHI copy, there will be no successor blocks which
436       // have the value live-in.
437 
438       // Okay, if we now know that the value is not live out of the block, we
439       // can add a kill marker in this block saying that it kills the incoming
440       // value!
441 
442       // In our final twist, we have to decide which instruction kills the
443       // register.  In most cases this is the copy, however, terminator
444       // instructions at the end of the block may also use the value. In this
445       // case, we should mark the last such terminator as being the killing
446       // block, not the copy.
447       MachineBasicBlock::iterator KillInst = opBlock.end();
448       MachineBasicBlock::iterator FirstTerm = opBlock.getFirstTerminator();
449       for (MachineBasicBlock::iterator Term = FirstTerm;
450           Term != opBlock.end(); ++Term) {
451         if (Term->readsRegister(SrcReg))
452           KillInst = Term;
453       }
454 
455       if (KillInst == opBlock.end()) {
456         // No terminator uses the register.
457 
458         if (reusedIncoming || !IncomingReg) {
459           // We may have to rewind a bit if we didn't insert a copy this time.
460           KillInst = FirstTerm;
461           while (KillInst != opBlock.begin()) {
462             --KillInst;
463             if (KillInst->isDebugInstr())
464               continue;
465             if (KillInst->readsRegister(SrcReg))
466               break;
467           }
468         } else {
469           // We just inserted this copy.
470           KillInst = NewSrcInstr;
471         }
472       }
473       assert(KillInst->readsRegister(SrcReg) && "Cannot find kill instruction");
474 
475       // Finally, mark it killed.
476       LV->addVirtualRegisterKilled(SrcReg, *KillInst);
477 
478       // This vreg no longer lives all of the way through opBlock.
479       unsigned opBlockNum = opBlock.getNumber();
480       LV->getVarInfo(SrcReg).AliveBlocks.reset(opBlockNum);
481     }
482 
483     if (LIS) {
484       if (NewSrcInstr) {
485         LIS->InsertMachineInstrInMaps(*NewSrcInstr);
486         LIS->addSegmentToEndOfBlock(IncomingReg, *NewSrcInstr);
487       }
488 
489       if (!SrcUndef &&
490           !VRegPHIUseCount[BBVRegPair(opBlock.getNumber(), SrcReg)]) {
491         LiveInterval &SrcLI = LIS->getInterval(SrcReg);
492 
493         bool isLiveOut = false;
494         for (MachineBasicBlock::succ_iterator SI = opBlock.succ_begin(),
495              SE = opBlock.succ_end(); SI != SE; ++SI) {
496           SlotIndex startIdx = LIS->getMBBStartIdx(*SI);
497           VNInfo *VNI = SrcLI.getVNInfoAt(startIdx);
498 
499           // Definitions by other PHIs are not truly live-in for our purposes.
500           if (VNI && VNI->def != startIdx) {
501             isLiveOut = true;
502             break;
503           }
504         }
505 
506         if (!isLiveOut) {
507           MachineBasicBlock::iterator KillInst = opBlock.end();
508           MachineBasicBlock::iterator FirstTerm = opBlock.getFirstTerminator();
509           for (MachineBasicBlock::iterator Term = FirstTerm;
510               Term != opBlock.end(); ++Term) {
511             if (Term->readsRegister(SrcReg))
512               KillInst = Term;
513           }
514 
515           if (KillInst == opBlock.end()) {
516             // No terminator uses the register.
517 
518             if (reusedIncoming || !IncomingReg) {
519               // We may have to rewind a bit if we didn't just insert a copy.
520               KillInst = FirstTerm;
521               while (KillInst != opBlock.begin()) {
522                 --KillInst;
523                 if (KillInst->isDebugInstr())
524                   continue;
525                 if (KillInst->readsRegister(SrcReg))
526                   break;
527               }
528             } else {
529               // We just inserted this copy.
530               KillInst = std::prev(InsertPos);
531             }
532           }
533           assert(KillInst->readsRegister(SrcReg) &&
534                  "Cannot find kill instruction");
535 
536           SlotIndex LastUseIndex = LIS->getInstructionIndex(*KillInst);
537           SrcLI.removeSegment(LastUseIndex.getRegSlot(),
538                               LIS->getMBBEndIdx(&opBlock));
539         }
540       }
541     }
542   }
543 
544   // Really delete the PHI instruction now, if it is not in the LoweredPHIs map.
545   if (reusedIncoming || !IncomingReg) {
546     if (LIS)
547       LIS->RemoveMachineInstrFromMaps(*MPhi);
548     MF.DeleteMachineInstr(MPhi);
549   }
550 }
551 
552 /// analyzePHINodes - Gather information about the PHI nodes in here. In
553 /// particular, we want to map the number of uses of a virtual register which is
554 /// used in a PHI node. We map that to the BB the vreg is coming from. This is
555 /// used later to determine when the vreg is killed in the BB.
556 void PHIElimination::analyzePHINodes(const MachineFunction& MF) {
557   for (const auto &MBB : MF)
558     for (const auto &BBI : MBB) {
559       if (!BBI.isPHI())
560         break;
561       for (unsigned i = 1, e = BBI.getNumOperands(); i != e; i += 2)
562         ++VRegPHIUseCount[BBVRegPair(BBI.getOperand(i+1).getMBB()->getNumber(),
563                                      BBI.getOperand(i).getReg())];
564     }
565 }
566 
567 bool PHIElimination::SplitPHIEdges(MachineFunction &MF,
568                                    MachineBasicBlock &MBB,
569                                    MachineLoopInfo *MLI) {
570   if (MBB.empty() || !MBB.front().isPHI() || MBB.isEHPad())
571     return false;   // Quick exit for basic blocks without PHIs.
572 
573   const MachineLoop *CurLoop = MLI ? MLI->getLoopFor(&MBB) : nullptr;
574   bool IsLoopHeader = CurLoop && &MBB == CurLoop->getHeader();
575 
576   bool Changed = false;
577   for (MachineBasicBlock::iterator BBI = MBB.begin(), BBE = MBB.end();
578        BBI != BBE && BBI->isPHI(); ++BBI) {
579     for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2) {
580       Register Reg = BBI->getOperand(i).getReg();
581       MachineBasicBlock *PreMBB = BBI->getOperand(i+1).getMBB();
582       // Is there a critical edge from PreMBB to MBB?
583       if (PreMBB->succ_size() == 1)
584         continue;
585 
586       // Avoid splitting backedges of loops. It would introduce small
587       // out-of-line blocks into the loop which is very bad for code placement.
588       if (PreMBB == &MBB && !SplitAllCriticalEdges)
589         continue;
590       const MachineLoop *PreLoop = MLI ? MLI->getLoopFor(PreMBB) : nullptr;
591       if (IsLoopHeader && PreLoop == CurLoop && !SplitAllCriticalEdges)
592         continue;
593 
594       // LV doesn't consider a phi use live-out, so isLiveOut only returns true
595       // when the source register is live-out for some other reason than a phi
596       // use. That means the copy we will insert in PreMBB won't be a kill, and
597       // there is a risk it may not be coalesced away.
598       //
599       // If the copy would be a kill, there is no need to split the edge.
600       bool ShouldSplit = isLiveOutPastPHIs(Reg, PreMBB);
601       if (!ShouldSplit && !NoPhiElimLiveOutEarlyExit)
602         continue;
603       if (ShouldSplit) {
604         LLVM_DEBUG(dbgs() << printReg(Reg) << " live-out before critical edge "
605                           << printMBBReference(*PreMBB) << " -> "
606                           << printMBBReference(MBB) << ": " << *BBI);
607       }
608 
609       // If Reg is not live-in to MBB, it means it must be live-in to some
610       // other PreMBB successor, and we can avoid the interference by splitting
611       // the edge.
612       //
613       // If Reg *is* live-in to MBB, the interference is inevitable and a copy
614       // is likely to be left after coalescing. If we are looking at a loop
615       // exiting edge, split it so we won't insert code in the loop, otherwise
616       // don't bother.
617       ShouldSplit = ShouldSplit && !isLiveIn(Reg, &MBB);
618 
619       // Check for a loop exiting edge.
620       if (!ShouldSplit && CurLoop != PreLoop) {
621         LLVM_DEBUG({
622           dbgs() << "Split wouldn't help, maybe avoid loop copies?\n";
623           if (PreLoop)
624             dbgs() << "PreLoop: " << *PreLoop;
625           if (CurLoop)
626             dbgs() << "CurLoop: " << *CurLoop;
627         });
628         // This edge could be entering a loop, exiting a loop, or it could be
629         // both: Jumping directly form one loop to the header of a sibling
630         // loop.
631         // Split unless this edge is entering CurLoop from an outer loop.
632         ShouldSplit = PreLoop && !PreLoop->contains(CurLoop);
633       }
634       if (!ShouldSplit && !SplitAllCriticalEdges)
635         continue;
636       if (!PreMBB->SplitCriticalEdge(&MBB, *this)) {
637         LLVM_DEBUG(dbgs() << "Failed to split critical edge.\n");
638         continue;
639       }
640       Changed = true;
641       ++NumCriticalEdgesSplit;
642     }
643   }
644   return Changed;
645 }
646 
647 bool PHIElimination::isLiveIn(unsigned Reg, const MachineBasicBlock *MBB) {
648   assert((LV || LIS) &&
649          "isLiveIn() requires either LiveVariables or LiveIntervals");
650   if (LIS)
651     return LIS->isLiveInToMBB(LIS->getInterval(Reg), MBB);
652   else
653     return LV->isLiveIn(Reg, *MBB);
654 }
655 
656 bool PHIElimination::isLiveOutPastPHIs(unsigned Reg,
657                                        const MachineBasicBlock *MBB) {
658   assert((LV || LIS) &&
659          "isLiveOutPastPHIs() requires either LiveVariables or LiveIntervals");
660   // LiveVariables considers uses in PHIs to be in the predecessor basic block,
661   // so that a register used only in a PHI is not live out of the block. In
662   // contrast, LiveIntervals considers uses in PHIs to be on the edge rather than
663   // in the predecessor basic block, so that a register used only in a PHI is live
664   // out of the block.
665   if (LIS) {
666     const LiveInterval &LI = LIS->getInterval(Reg);
667     for (const MachineBasicBlock *SI : MBB->successors())
668       if (LI.liveAt(LIS->getMBBStartIdx(SI)))
669         return true;
670     return false;
671   } else {
672     return LV->isLiveOut(Reg, *MBB);
673   }
674 }
675