LLVM API Documentation

PHIElimination.cpp
Go to the documentation of this file.
00001 //===-- PhiElimination.cpp - Eliminate PHI nodes by inserting copies ------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This pass eliminates machine instruction PHI nodes by inserting copy
00011 // instructions.  This destroys SSA information, but is the desired input for
00012 // some register allocators.
00013 //
00014 //===----------------------------------------------------------------------===//
00015 
00016 #include "llvm/CodeGen/Passes.h"
00017 #include "PHIEliminationUtils.h"
00018 #include "llvm/ADT/STLExtras.h"
00019 #include "llvm/ADT/SmallPtrSet.h"
00020 #include "llvm/ADT/Statistic.h"
00021 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
00022 #include "llvm/CodeGen/LiveVariables.h"
00023 #include "llvm/CodeGen/MachineDominators.h"
00024 #include "llvm/CodeGen/MachineInstr.h"
00025 #include "llvm/CodeGen/MachineInstrBuilder.h"
00026 #include "llvm/CodeGen/MachineLoopInfo.h"
00027 #include "llvm/CodeGen/MachineRegisterInfo.h"
00028 #include "llvm/IR/Function.h"
00029 #include "llvm/Support/CommandLine.h"
00030 #include "llvm/Support/Compiler.h"
00031 #include "llvm/Support/Debug.h"
00032 #include "llvm/Target/TargetInstrInfo.h"
00033 #include "llvm/Target/TargetMachine.h"
00034 #include "llvm/Target/TargetSubtargetInfo.h"
00035 #include <algorithm>
00036 using namespace llvm;
00037 
00038 #define DEBUG_TYPE "phielim"
00039 
00040 static cl::opt<bool>
00041 DisableEdgeSplitting("disable-phi-elim-edge-splitting", cl::init(false),
00042                      cl::Hidden, cl::desc("Disable critical edge splitting "
00043                                           "during PHI elimination"));
00044 
00045 static cl::opt<bool>
00046 SplitAllCriticalEdges("phi-elim-split-all-critical-edges", cl::init(false),
00047                       cl::Hidden, cl::desc("Split all critical edges during "
00048                                            "PHI elimination"));
00049 
00050 namespace {
00051   class PHIElimination : public MachineFunctionPass {
00052     MachineRegisterInfo *MRI; // Machine register information
00053     LiveVariables *LV;
00054     LiveIntervals *LIS;
00055 
00056   public:
00057     static char ID; // Pass identification, replacement for typeid
00058     PHIElimination() : MachineFunctionPass(ID) {
00059       initializePHIEliminationPass(*PassRegistry::getPassRegistry());
00060     }
00061 
00062     bool runOnMachineFunction(MachineFunction &Fn) override;
00063     void getAnalysisUsage(AnalysisUsage &AU) const override;
00064 
00065   private:
00066     /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions
00067     /// in predecessor basic blocks.
00068     ///
00069     bool EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB);
00070     void LowerPHINode(MachineBasicBlock &MBB,
00071                       MachineBasicBlock::iterator LastPHIIt);
00072 
00073     /// analyzePHINodes - Gather information about the PHI nodes in
00074     /// here. In particular, we want to map the number of uses of a virtual
00075     /// register which is used in a PHI node. We map that to the BB the
00076     /// vreg is coming from. This is used later to determine when the vreg
00077     /// is killed in the BB.
00078     ///
00079     void analyzePHINodes(const MachineFunction& Fn);
00080 
00081     /// Split critical edges where necessary for good coalescer performance.
00082     bool SplitPHIEdges(MachineFunction &MF, MachineBasicBlock &MBB,
00083                        MachineLoopInfo *MLI);
00084 
00085     // These functions are temporary abstractions around LiveVariables and
00086     // LiveIntervals, so they can go away when LiveVariables does.
00087     bool isLiveIn(unsigned Reg, MachineBasicBlock *MBB);
00088     bool isLiveOutPastPHIs(unsigned Reg, MachineBasicBlock *MBB);
00089 
00090     typedef std::pair<unsigned, unsigned> BBVRegPair;
00091     typedef DenseMap<BBVRegPair, unsigned> VRegPHIUse;
00092 
00093     VRegPHIUse VRegPHIUseCount;
00094 
00095     // Defs of PHI sources which are implicit_def.
00096     SmallPtrSet<MachineInstr*, 4> ImpDefs;
00097 
00098     // Map reusable lowered PHI node -> incoming join register.
00099     typedef DenseMap<MachineInstr*, unsigned,
00100                      MachineInstrExpressionTrait> LoweredPHIMap;
00101     LoweredPHIMap LoweredPHIs;
00102   };
00103 }
00104 
00105 STATISTIC(NumLowered, "Number of phis lowered");
00106 STATISTIC(NumCriticalEdgesSplit, "Number of critical edges split");
00107 STATISTIC(NumReused, "Number of reused lowered phis");
00108 
00109 char PHIElimination::ID = 0;
00110 char& llvm::PHIEliminationID = PHIElimination::ID;
00111 
00112 INITIALIZE_PASS_BEGIN(PHIElimination, "phi-node-elimination",
00113                       "Eliminate PHI nodes for register allocation",
00114                       false, false)
00115 INITIALIZE_PASS_DEPENDENCY(LiveVariables)
00116 INITIALIZE_PASS_END(PHIElimination, "phi-node-elimination",
00117                     "Eliminate PHI nodes for register allocation", false, false)
00118 
00119 void PHIElimination::getAnalysisUsage(AnalysisUsage &AU) const {
00120   AU.addPreserved<LiveVariables>();
00121   AU.addPreserved<SlotIndexes>();
00122   AU.addPreserved<LiveIntervals>();
00123   AU.addPreserved<MachineDominatorTree>();
00124   AU.addPreserved<MachineLoopInfo>();
00125   MachineFunctionPass::getAnalysisUsage(AU);
00126 }
00127 
00128 bool PHIElimination::runOnMachineFunction(MachineFunction &MF) {
00129   MRI = &MF.getRegInfo();
00130   LV = getAnalysisIfAvailable<LiveVariables>();
00131   LIS = getAnalysisIfAvailable<LiveIntervals>();
00132 
00133   bool Changed = false;
00134 
00135   // This pass takes the function out of SSA form.
00136   MRI->leaveSSA();
00137 
00138   // Split critical edges to help the coalescer. This does not yet support
00139   // updating LiveIntervals, so we disable it.
00140   if (!DisableEdgeSplitting && (LV || LIS)) {
00141     MachineLoopInfo *MLI = getAnalysisIfAvailable<MachineLoopInfo>();
00142     for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
00143       Changed |= SplitPHIEdges(MF, *I, MLI);
00144   }
00145 
00146   // Populate VRegPHIUseCount
00147   analyzePHINodes(MF);
00148 
00149   // Eliminate PHI instructions by inserting copies into predecessor blocks.
00150   for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
00151     Changed |= EliminatePHINodes(MF, *I);
00152 
00153   // Remove dead IMPLICIT_DEF instructions.
00154   for (MachineInstr *DefMI : ImpDefs) {
00155     unsigned DefReg = DefMI->getOperand(0).getReg();
00156     if (MRI->use_nodbg_empty(DefReg)) {
00157       if (LIS)
00158         LIS->RemoveMachineInstrFromMaps(DefMI);
00159       DefMI->eraseFromParent();
00160     }
00161   }
00162 
00163   // Clean up the lowered PHI instructions.
00164   for (LoweredPHIMap::iterator I = LoweredPHIs.begin(), E = LoweredPHIs.end();
00165        I != E; ++I) {
00166     if (LIS)
00167       LIS->RemoveMachineInstrFromMaps(I->first);
00168     MF.DeleteMachineInstr(I->first);
00169   }
00170 
00171   LoweredPHIs.clear();
00172   ImpDefs.clear();
00173   VRegPHIUseCount.clear();
00174 
00175   return Changed;
00176 }
00177 
00178 /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions in
00179 /// predecessor basic blocks.
00180 ///
00181 bool PHIElimination::EliminatePHINodes(MachineFunction &MF,
00182                                              MachineBasicBlock &MBB) {
00183   if (MBB.empty() || !MBB.front().isPHI())
00184     return false;   // Quick exit for basic blocks without PHIs.
00185 
00186   // Get an iterator to the first instruction after the last PHI node (this may
00187   // also be the end of the basic block).
00188   MachineBasicBlock::iterator LastPHIIt =
00189     std::prev(MBB.SkipPHIsAndLabels(MBB.begin()));
00190 
00191   while (MBB.front().isPHI())
00192     LowerPHINode(MBB, LastPHIIt);
00193 
00194   return true;
00195 }
00196 
00197 /// isImplicitlyDefined - Return true if all defs of VirtReg are implicit-defs.
00198 /// This includes registers with no defs.
00199 static bool isImplicitlyDefined(unsigned VirtReg,
00200                                 const MachineRegisterInfo *MRI) {
00201   for (MachineInstr &DI : MRI->def_instructions(VirtReg))
00202     if (!DI.isImplicitDef())
00203       return false;
00204   return true;
00205 }
00206 
00207 /// isSourceDefinedByImplicitDef - Return true if all sources of the phi node
00208 /// are implicit_def's.
00209 static bool isSourceDefinedByImplicitDef(const MachineInstr *MPhi,
00210                                          const MachineRegisterInfo *MRI) {
00211   for (unsigned i = 1; i != MPhi->getNumOperands(); i += 2)
00212     if (!isImplicitlyDefined(MPhi->getOperand(i).getReg(), MRI))
00213       return false;
00214   return true;
00215 }
00216 
00217 
00218 /// LowerPHINode - Lower the PHI node at the top of the specified block,
00219 ///
00220 void PHIElimination::LowerPHINode(MachineBasicBlock &MBB,
00221                                   MachineBasicBlock::iterator LastPHIIt) {
00222   ++NumLowered;
00223 
00224   MachineBasicBlock::iterator AfterPHIsIt = std::next(LastPHIIt);
00225 
00226   // Unlink the PHI node from the basic block, but don't delete the PHI yet.
00227   MachineInstr *MPhi = MBB.remove(MBB.begin());
00228 
00229   unsigned NumSrcs = (MPhi->getNumOperands() - 1) / 2;
00230   unsigned DestReg = MPhi->getOperand(0).getReg();
00231   assert(MPhi->getOperand(0).getSubReg() == 0 && "Can't handle sub-reg PHIs");
00232   bool isDead = MPhi->getOperand(0).isDead();
00233 
00234   // Create a new register for the incoming PHI arguments.
00235   MachineFunction &MF = *MBB.getParent();
00236   unsigned IncomingReg = 0;
00237   bool reusedIncoming = false;  // Is IncomingReg reused from an earlier PHI?
00238 
00239   // Insert a register to register copy at the top of the current block (but
00240   // after any remaining phi nodes) which copies the new incoming register
00241   // into the phi node destination.
00242   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
00243   if (isSourceDefinedByImplicitDef(MPhi, MRI))
00244     // If all sources of a PHI node are implicit_def, just emit an
00245     // implicit_def instead of a copy.
00246     BuildMI(MBB, AfterPHIsIt, MPhi->getDebugLoc(),
00247             TII->get(TargetOpcode::IMPLICIT_DEF), DestReg);
00248   else {
00249     // Can we reuse an earlier PHI node? This only happens for critical edges,
00250     // typically those created by tail duplication.
00251     unsigned &entry = LoweredPHIs[MPhi];
00252     if (entry) {
00253       // An identical PHI node was already lowered. Reuse the incoming register.
00254       IncomingReg = entry;
00255       reusedIncoming = true;
00256       ++NumReused;
00257       DEBUG(dbgs() << "Reusing " << PrintReg(IncomingReg) << " for " << *MPhi);
00258     } else {
00259       const TargetRegisterClass *RC = MF.getRegInfo().getRegClass(DestReg);
00260       entry = IncomingReg = MF.getRegInfo().createVirtualRegister(RC);
00261     }
00262     BuildMI(MBB, AfterPHIsIt, MPhi->getDebugLoc(),
00263             TII->get(TargetOpcode::COPY), DestReg)
00264       .addReg(IncomingReg);
00265   }
00266 
00267   // Update live variable information if there is any.
00268   if (LV) {
00269     MachineInstr *PHICopy = std::prev(AfterPHIsIt);
00270 
00271     if (IncomingReg) {
00272       LiveVariables::VarInfo &VI = LV->getVarInfo(IncomingReg);
00273 
00274       // Increment use count of the newly created virtual register.
00275       LV->setPHIJoin(IncomingReg);
00276 
00277       // When we are reusing the incoming register, it may already have been
00278       // killed in this block. The old kill will also have been inserted at
00279       // AfterPHIsIt, so it appears before the current PHICopy.
00280       if (reusedIncoming)
00281         if (MachineInstr *OldKill = VI.findKill(&MBB)) {
00282           DEBUG(dbgs() << "Remove old kill from " << *OldKill);
00283           LV->removeVirtualRegisterKilled(IncomingReg, OldKill);
00284           DEBUG(MBB.dump());
00285         }
00286 
00287       // Add information to LiveVariables to know that the incoming value is
00288       // killed.  Note that because the value is defined in several places (once
00289       // each for each incoming block), the "def" block and instruction fields
00290       // for the VarInfo is not filled in.
00291       LV->addVirtualRegisterKilled(IncomingReg, PHICopy);
00292     }
00293 
00294     // Since we are going to be deleting the PHI node, if it is the last use of
00295     // any registers, or if the value itself is dead, we need to move this
00296     // information over to the new copy we just inserted.
00297     LV->removeVirtualRegistersKilled(MPhi);
00298 
00299     // If the result is dead, update LV.
00300     if (isDead) {
00301       LV->addVirtualRegisterDead(DestReg, PHICopy);
00302       LV->removeVirtualRegisterDead(DestReg, MPhi);
00303     }
00304   }
00305 
00306   // Update LiveIntervals for the new copy or implicit def.
00307   if (LIS) {
00308     MachineInstr *NewInstr = std::prev(AfterPHIsIt);
00309     SlotIndex DestCopyIndex = LIS->InsertMachineInstrInMaps(NewInstr);
00310 
00311     SlotIndex MBBStartIndex = LIS->getMBBStartIdx(&MBB);
00312     if (IncomingReg) {
00313       // Add the region from the beginning of MBB to the copy instruction to
00314       // IncomingReg's live interval.
00315       LiveInterval &IncomingLI = LIS->createEmptyInterval(IncomingReg);
00316       VNInfo *IncomingVNI = IncomingLI.getVNInfoAt(MBBStartIndex);
00317       if (!IncomingVNI)
00318         IncomingVNI = IncomingLI.getNextValue(MBBStartIndex,
00319                                               LIS->getVNInfoAllocator());
00320       IncomingLI.addSegment(LiveInterval::Segment(MBBStartIndex,
00321                                                   DestCopyIndex.getRegSlot(),
00322                                                   IncomingVNI));
00323     }
00324 
00325     LiveInterval &DestLI = LIS->getInterval(DestReg);
00326     assert(DestLI.begin() != DestLI.end() &&
00327            "PHIs should have nonempty LiveIntervals.");
00328     if (DestLI.endIndex().isDead()) {
00329       // A dead PHI's live range begins and ends at the start of the MBB, but
00330       // the lowered copy, which will still be dead, needs to begin and end at
00331       // the copy instruction.
00332       VNInfo *OrigDestVNI = DestLI.getVNInfoAt(MBBStartIndex);
00333       assert(OrigDestVNI && "PHI destination should be live at block entry.");
00334       DestLI.removeSegment(MBBStartIndex, MBBStartIndex.getDeadSlot());
00335       DestLI.createDeadDef(DestCopyIndex.getRegSlot(),
00336                            LIS->getVNInfoAllocator());
00337       DestLI.removeValNo(OrigDestVNI);
00338     } else {
00339       // Otherwise, remove the region from the beginning of MBB to the copy
00340       // instruction from DestReg's live interval.
00341       DestLI.removeSegment(MBBStartIndex, DestCopyIndex.getRegSlot());
00342       VNInfo *DestVNI = DestLI.getVNInfoAt(DestCopyIndex.getRegSlot());
00343       assert(DestVNI && "PHI destination should be live at its definition.");
00344       DestVNI->def = DestCopyIndex.getRegSlot();
00345     }
00346   }
00347 
00348   // Adjust the VRegPHIUseCount map to account for the removal of this PHI node.
00349   for (unsigned i = 1; i != MPhi->getNumOperands(); i += 2)
00350     --VRegPHIUseCount[BBVRegPair(MPhi->getOperand(i+1).getMBB()->getNumber(),
00351                                  MPhi->getOperand(i).getReg())];
00352 
00353   // Now loop over all of the incoming arguments, changing them to copy into the
00354   // IncomingReg register in the corresponding predecessor basic block.
00355   SmallPtrSet<MachineBasicBlock*, 8> MBBsInsertedInto;
00356   for (int i = NumSrcs - 1; i >= 0; --i) {
00357     unsigned SrcReg = MPhi->getOperand(i*2+1).getReg();
00358     unsigned SrcSubReg = MPhi->getOperand(i*2+1).getSubReg();
00359     bool SrcUndef = MPhi->getOperand(i*2+1).isUndef() ||
00360       isImplicitlyDefined(SrcReg, MRI);
00361     assert(TargetRegisterInfo::isVirtualRegister(SrcReg) &&
00362            "Machine PHI Operands must all be virtual registers!");
00363 
00364     // Get the MachineBasicBlock equivalent of the BasicBlock that is the source
00365     // path the PHI.
00366     MachineBasicBlock &opBlock = *MPhi->getOperand(i*2+2).getMBB();
00367 
00368     // Check to make sure we haven't already emitted the copy for this block.
00369     // This can happen because PHI nodes may have multiple entries for the same
00370     // basic block.
00371     if (!MBBsInsertedInto.insert(&opBlock))
00372       continue;  // If the copy has already been emitted, we're done.
00373 
00374     // Find a safe location to insert the copy, this may be the first terminator
00375     // in the block (or end()).
00376     MachineBasicBlock::iterator InsertPos =
00377       findPHICopyInsertPoint(&opBlock, &MBB, SrcReg);
00378 
00379     // Insert the copy.
00380     MachineInstr *NewSrcInstr = nullptr;
00381     if (!reusedIncoming && IncomingReg) {
00382       if (SrcUndef) {
00383         // The source register is undefined, so there is no need for a real
00384         // COPY, but we still need to ensure joint dominance by defs.
00385         // Insert an IMPLICIT_DEF instruction.
00386         NewSrcInstr = BuildMI(opBlock, InsertPos, MPhi->getDebugLoc(),
00387                               TII->get(TargetOpcode::IMPLICIT_DEF),
00388                               IncomingReg);
00389 
00390         // Clean up the old implicit-def, if there even was one.
00391         if (MachineInstr *DefMI = MRI->getVRegDef(SrcReg))
00392           if (DefMI->isImplicitDef())
00393             ImpDefs.insert(DefMI);
00394       } else {
00395         NewSrcInstr = BuildMI(opBlock, InsertPos, MPhi->getDebugLoc(),
00396                             TII->get(TargetOpcode::COPY), IncomingReg)
00397                         .addReg(SrcReg, 0, SrcSubReg);
00398       }
00399     }
00400 
00401     // We only need to update the LiveVariables kill of SrcReg if this was the
00402     // last PHI use of SrcReg to be lowered on this CFG edge and it is not live
00403     // out of the predecessor. We can also ignore undef sources.
00404     if (LV && !SrcUndef &&
00405         !VRegPHIUseCount[BBVRegPair(opBlock.getNumber(), SrcReg)] &&
00406         !LV->isLiveOut(SrcReg, opBlock)) {
00407       // We want to be able to insert a kill of the register if this PHI (aka,
00408       // the copy we just inserted) is the last use of the source value. Live
00409       // variable analysis conservatively handles this by saying that the value
00410       // is live until the end of the block the PHI entry lives in. If the value
00411       // really is dead at the PHI copy, there will be no successor blocks which
00412       // have the value live-in.
00413 
00414       // Okay, if we now know that the value is not live out of the block, we
00415       // can add a kill marker in this block saying that it kills the incoming
00416       // value!
00417 
00418       // In our final twist, we have to decide which instruction kills the
00419       // register.  In most cases this is the copy, however, terminator
00420       // instructions at the end of the block may also use the value. In this
00421       // case, we should mark the last such terminator as being the killing
00422       // block, not the copy.
00423       MachineBasicBlock::iterator KillInst = opBlock.end();
00424       MachineBasicBlock::iterator FirstTerm = opBlock.getFirstTerminator();
00425       for (MachineBasicBlock::iterator Term = FirstTerm;
00426           Term != opBlock.end(); ++Term) {
00427         if (Term->readsRegister(SrcReg))
00428           KillInst = Term;
00429       }
00430 
00431       if (KillInst == opBlock.end()) {
00432         // No terminator uses the register.
00433 
00434         if (reusedIncoming || !IncomingReg) {
00435           // We may have to rewind a bit if we didn't insert a copy this time.
00436           KillInst = FirstTerm;
00437           while (KillInst != opBlock.begin()) {
00438             --KillInst;
00439             if (KillInst->isDebugValue())
00440               continue;
00441             if (KillInst->readsRegister(SrcReg))
00442               break;
00443           }
00444         } else {
00445           // We just inserted this copy.
00446           KillInst = std::prev(InsertPos);
00447         }
00448       }
00449       assert(KillInst->readsRegister(SrcReg) && "Cannot find kill instruction");
00450 
00451       // Finally, mark it killed.
00452       LV->addVirtualRegisterKilled(SrcReg, KillInst);
00453 
00454       // This vreg no longer lives all of the way through opBlock.
00455       unsigned opBlockNum = opBlock.getNumber();
00456       LV->getVarInfo(SrcReg).AliveBlocks.reset(opBlockNum);
00457     }
00458 
00459     if (LIS) {
00460       if (NewSrcInstr) {
00461         LIS->InsertMachineInstrInMaps(NewSrcInstr);
00462         LIS->addSegmentToEndOfBlock(IncomingReg, NewSrcInstr);
00463       }
00464 
00465       if (!SrcUndef &&
00466           !VRegPHIUseCount[BBVRegPair(opBlock.getNumber(), SrcReg)]) {
00467         LiveInterval &SrcLI = LIS->getInterval(SrcReg);
00468 
00469         bool isLiveOut = false;
00470         for (MachineBasicBlock::succ_iterator SI = opBlock.succ_begin(),
00471              SE = opBlock.succ_end(); SI != SE; ++SI) {
00472           SlotIndex startIdx = LIS->getMBBStartIdx(*SI);
00473           VNInfo *VNI = SrcLI.getVNInfoAt(startIdx);
00474 
00475           // Definitions by other PHIs are not truly live-in for our purposes.
00476           if (VNI && VNI->def != startIdx) {
00477             isLiveOut = true;
00478             break;
00479           }
00480         }
00481 
00482         if (!isLiveOut) {
00483           MachineBasicBlock::iterator KillInst = opBlock.end();
00484           MachineBasicBlock::iterator FirstTerm = opBlock.getFirstTerminator();
00485           for (MachineBasicBlock::iterator Term = FirstTerm;
00486               Term != opBlock.end(); ++Term) {
00487             if (Term->readsRegister(SrcReg))
00488               KillInst = Term;
00489           }
00490 
00491           if (KillInst == opBlock.end()) {
00492             // No terminator uses the register.
00493 
00494             if (reusedIncoming || !IncomingReg) {
00495               // We may have to rewind a bit if we didn't just insert a copy.
00496               KillInst = FirstTerm;
00497               while (KillInst != opBlock.begin()) {
00498                 --KillInst;
00499                 if (KillInst->isDebugValue())
00500                   continue;
00501                 if (KillInst->readsRegister(SrcReg))
00502                   break;
00503               }
00504             } else {
00505               // We just inserted this copy.
00506               KillInst = std::prev(InsertPos);
00507             }
00508           }
00509           assert(KillInst->readsRegister(SrcReg) &&
00510                  "Cannot find kill instruction");
00511 
00512           SlotIndex LastUseIndex = LIS->getInstructionIndex(KillInst);
00513           SrcLI.removeSegment(LastUseIndex.getRegSlot(),
00514                               LIS->getMBBEndIdx(&opBlock));
00515         }
00516       }
00517     }
00518   }
00519 
00520   // Really delete the PHI instruction now, if it is not in the LoweredPHIs map.
00521   if (reusedIncoming || !IncomingReg) {
00522     if (LIS)
00523       LIS->RemoveMachineInstrFromMaps(MPhi);
00524     MF.DeleteMachineInstr(MPhi);
00525   }
00526 }
00527 
00528 /// analyzePHINodes - Gather information about the PHI nodes in here. In
00529 /// particular, we want to map the number of uses of a virtual register which is
00530 /// used in a PHI node. We map that to the BB the vreg is coming from. This is
00531 /// used later to determine when the vreg is killed in the BB.
00532 ///
00533 void PHIElimination::analyzePHINodes(const MachineFunction& MF) {
00534   for (const auto &MBB : MF)
00535     for (const auto &BBI : MBB) {
00536       if (!BBI.isPHI())
00537         break;
00538       for (unsigned i = 1, e = BBI.getNumOperands(); i != e; i += 2)
00539         ++VRegPHIUseCount[BBVRegPair(BBI.getOperand(i+1).getMBB()->getNumber(),
00540                                      BBI.getOperand(i).getReg())];
00541     }
00542 }
00543 
00544 bool PHIElimination::SplitPHIEdges(MachineFunction &MF,
00545                                    MachineBasicBlock &MBB,
00546                                    MachineLoopInfo *MLI) {
00547   if (MBB.empty() || !MBB.front().isPHI() || MBB.isLandingPad())
00548     return false;   // Quick exit for basic blocks without PHIs.
00549 
00550   const MachineLoop *CurLoop = MLI ? MLI->getLoopFor(&MBB) : nullptr;
00551   bool IsLoopHeader = CurLoop && &MBB == CurLoop->getHeader();
00552 
00553   bool Changed = false;
00554   for (MachineBasicBlock::iterator BBI = MBB.begin(), BBE = MBB.end();
00555        BBI != BBE && BBI->isPHI(); ++BBI) {
00556     for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2) {
00557       unsigned Reg = BBI->getOperand(i).getReg();
00558       MachineBasicBlock *PreMBB = BBI->getOperand(i+1).getMBB();
00559       // Is there a critical edge from PreMBB to MBB?
00560       if (PreMBB->succ_size() == 1)
00561         continue;
00562 
00563       // Avoid splitting backedges of loops. It would introduce small
00564       // out-of-line blocks into the loop which is very bad for code placement.
00565       if (PreMBB == &MBB && !SplitAllCriticalEdges)
00566         continue;
00567       const MachineLoop *PreLoop = MLI ? MLI->getLoopFor(PreMBB) : nullptr;
00568       if (IsLoopHeader && PreLoop == CurLoop && !SplitAllCriticalEdges)
00569         continue;
00570 
00571       // LV doesn't consider a phi use live-out, so isLiveOut only returns true
00572       // when the source register is live-out for some other reason than a phi
00573       // use. That means the copy we will insert in PreMBB won't be a kill, and
00574       // there is a risk it may not be coalesced away.
00575       //
00576       // If the copy would be a kill, there is no need to split the edge.
00577       if (!isLiveOutPastPHIs(Reg, PreMBB) && !SplitAllCriticalEdges)
00578         continue;
00579 
00580       DEBUG(dbgs() << PrintReg(Reg) << " live-out before critical edge BB#"
00581                    << PreMBB->getNumber() << " -> BB#" << MBB.getNumber()
00582                    << ": " << *BBI);
00583 
00584       // If Reg is not live-in to MBB, it means it must be live-in to some
00585       // other PreMBB successor, and we can avoid the interference by splitting
00586       // the edge.
00587       //
00588       // If Reg *is* live-in to MBB, the interference is inevitable and a copy
00589       // is likely to be left after coalescing. If we are looking at a loop
00590       // exiting edge, split it so we won't insert code in the loop, otherwise
00591       // don't bother.
00592       bool ShouldSplit = !isLiveIn(Reg, &MBB) || SplitAllCriticalEdges;
00593 
00594       // Check for a loop exiting edge.
00595       if (!ShouldSplit && CurLoop != PreLoop) {
00596         DEBUG({
00597           dbgs() << "Split wouldn't help, maybe avoid loop copies?\n";
00598           if (PreLoop) dbgs() << "PreLoop: " << *PreLoop;
00599           if (CurLoop) dbgs() << "CurLoop: " << *CurLoop;
00600         });
00601         // This edge could be entering a loop, exiting a loop, or it could be
00602         // both: Jumping directly form one loop to the header of a sibling
00603         // loop.
00604         // Split unless this edge is entering CurLoop from an outer loop.
00605         ShouldSplit = PreLoop && !PreLoop->contains(CurLoop);
00606       }
00607       if (!ShouldSplit)
00608         continue;
00609       if (!PreMBB->SplitCriticalEdge(&MBB, this)) {
00610         DEBUG(dbgs() << "Failed to split critical edge.\n");
00611         continue;
00612       }
00613       Changed = true;
00614       ++NumCriticalEdgesSplit;
00615     }
00616   }
00617   return Changed;
00618 }
00619 
00620 bool PHIElimination::isLiveIn(unsigned Reg, MachineBasicBlock *MBB) {
00621   assert((LV || LIS) &&
00622          "isLiveIn() requires either LiveVariables or LiveIntervals");
00623   if (LIS)
00624     return LIS->isLiveInToMBB(LIS->getInterval(Reg), MBB);
00625   else
00626     return LV->isLiveIn(Reg, *MBB);
00627 }
00628 
00629 bool PHIElimination::isLiveOutPastPHIs(unsigned Reg, MachineBasicBlock *MBB) {
00630   assert((LV || LIS) &&
00631          "isLiveOutPastPHIs() requires either LiveVariables or LiveIntervals");
00632   // LiveVariables considers uses in PHIs to be in the predecessor basic block,
00633   // so that a register used only in a PHI is not live out of the block. In
00634   // contrast, LiveIntervals considers uses in PHIs to be on the edge rather than
00635   // in the predecessor basic block, so that a register used only in a PHI is live
00636   // out of the block.
00637   if (LIS) {
00638     const LiveInterval &LI = LIS->getInterval(Reg);
00639     for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
00640          SE = MBB->succ_end(); SI != SE; ++SI) {
00641       if (LI.liveAt(LIS->getMBBStartIdx(*SI)))
00642         return true;
00643     }
00644     return false;
00645   } else {
00646     return LV->isLiveOut(Reg, *MBB);
00647   }
00648 }