10b57cec5SDimitry Andric //===- PhiElimination.cpp - Eliminate PHI nodes by inserting copies -------===// 20b57cec5SDimitry Andric // 30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 60b57cec5SDimitry Andric // 70b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 80b57cec5SDimitry Andric // 90b57cec5SDimitry Andric // This pass eliminates machine instruction PHI nodes by inserting copy 100b57cec5SDimitry Andric // instructions. This destroys SSA information, but is the desired input for 110b57cec5SDimitry Andric // some register allocators. 120b57cec5SDimitry Andric // 130b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 140b57cec5SDimitry Andric 15*0fca6ea1SDimitry Andric #include "llvm/CodeGen/PHIElimination.h" 160b57cec5SDimitry Andric #include "PHIEliminationUtils.h" 170b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h" 180b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h" 190b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h" 200b57cec5SDimitry Andric #include "llvm/Analysis/LoopInfo.h" 210b57cec5SDimitry Andric #include "llvm/CodeGen/LiveInterval.h" 220b57cec5SDimitry Andric #include "llvm/CodeGen/LiveIntervals.h" 230b57cec5SDimitry Andric #include "llvm/CodeGen/LiveVariables.h" 240b57cec5SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h" 250b57cec5SDimitry Andric #include "llvm/CodeGen/MachineDominators.h" 260b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunction.h" 270b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h" 280b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstr.h" 290b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h" 300b57cec5SDimitry Andric #include "llvm/CodeGen/MachineLoopInfo.h" 310b57cec5SDimitry Andric #include "llvm/CodeGen/MachineOperand.h" 320b57cec5SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h" 330b57cec5SDimitry Andric #include "llvm/CodeGen/SlotIndexes.h" 340b57cec5SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h" 350b57cec5SDimitry Andric #include "llvm/CodeGen/TargetOpcodes.h" 360b57cec5SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h" 370b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h" 380b57cec5SDimitry Andric #include "llvm/Pass.h" 390b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h" 400b57cec5SDimitry Andric #include "llvm/Support/Debug.h" 410b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h" 420b57cec5SDimitry Andric #include <cassert> 430b57cec5SDimitry Andric #include <iterator> 440b57cec5SDimitry Andric #include <utility> 450b57cec5SDimitry Andric 460b57cec5SDimitry Andric using namespace llvm; 470b57cec5SDimitry Andric 480b57cec5SDimitry Andric #define DEBUG_TYPE "phi-node-elimination" 490b57cec5SDimitry Andric 500b57cec5SDimitry Andric static cl::opt<bool> 510b57cec5SDimitry Andric DisableEdgeSplitting("disable-phi-elim-edge-splitting", cl::init(false), 52*0fca6ea1SDimitry Andric cl::Hidden, 53*0fca6ea1SDimitry Andric cl::desc("Disable critical edge splitting " 540b57cec5SDimitry Andric "during PHI elimination")); 550b57cec5SDimitry Andric 560b57cec5SDimitry Andric static cl::opt<bool> 570b57cec5SDimitry Andric SplitAllCriticalEdges("phi-elim-split-all-critical-edges", cl::init(false), 58*0fca6ea1SDimitry Andric cl::Hidden, 59*0fca6ea1SDimitry Andric cl::desc("Split all critical edges during " 600b57cec5SDimitry Andric "PHI elimination")); 610b57cec5SDimitry Andric 620b57cec5SDimitry Andric static cl::opt<bool> NoPhiElimLiveOutEarlyExit( 630b57cec5SDimitry Andric "no-phi-elim-live-out-early-exit", cl::init(false), cl::Hidden, 640b57cec5SDimitry Andric cl::desc("Do not use an early exit if isLiveOutPastPHIs returns true.")); 650b57cec5SDimitry Andric 660b57cec5SDimitry Andric namespace { 670b57cec5SDimitry Andric 68*0fca6ea1SDimitry Andric class PHIEliminationImpl { 6906c3fb27SDimitry Andric MachineRegisterInfo *MRI = nullptr; // Machine register information 7006c3fb27SDimitry Andric LiveVariables *LV = nullptr; 7106c3fb27SDimitry Andric LiveIntervals *LIS = nullptr; 72*0fca6ea1SDimitry Andric MachineLoopInfo *MLI = nullptr; 73*0fca6ea1SDimitry Andric MachineDominatorTree *MDT = nullptr; 740b57cec5SDimitry Andric 750b57cec5SDimitry Andric /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions 760b57cec5SDimitry Andric /// in predecessor basic blocks. 770b57cec5SDimitry Andric bool EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB); 780b57cec5SDimitry Andric 790b57cec5SDimitry Andric void LowerPHINode(MachineBasicBlock &MBB, 80*0fca6ea1SDimitry Andric MachineBasicBlock::iterator LastPHIIt, 81*0fca6ea1SDimitry Andric bool AllEdgesCritical); 820b57cec5SDimitry Andric 830b57cec5SDimitry Andric /// analyzePHINodes - Gather information about the PHI nodes in 840b57cec5SDimitry Andric /// here. In particular, we want to map the number of uses of a virtual 850b57cec5SDimitry Andric /// register which is used in a PHI node. We map that to the BB the 860b57cec5SDimitry Andric /// vreg is coming from. This is used later to determine when the vreg 870b57cec5SDimitry Andric /// is killed in the BB. 880b57cec5SDimitry Andric void analyzePHINodes(const MachineFunction &MF); 890b57cec5SDimitry Andric 900b57cec5SDimitry Andric /// Split critical edges where necessary for good coalescer performance. 910b57cec5SDimitry Andric bool SplitPHIEdges(MachineFunction &MF, MachineBasicBlock &MBB, 925ffd83dbSDimitry Andric MachineLoopInfo *MLI, 935ffd83dbSDimitry Andric std::vector<SparseBitVector<>> *LiveInSets); 940b57cec5SDimitry Andric 950b57cec5SDimitry Andric // These functions are temporary abstractions around LiveVariables and 960b57cec5SDimitry Andric // LiveIntervals, so they can go away when LiveVariables does. 97e8d8bef9SDimitry Andric bool isLiveIn(Register Reg, const MachineBasicBlock *MBB); 98e8d8bef9SDimitry Andric bool isLiveOutPastPHIs(Register Reg, const MachineBasicBlock *MBB); 990b57cec5SDimitry Andric 100e8d8bef9SDimitry Andric using BBVRegPair = std::pair<unsigned, Register>; 1010b57cec5SDimitry Andric using VRegPHIUse = DenseMap<BBVRegPair, unsigned>; 1020b57cec5SDimitry Andric 103349cc55cSDimitry Andric // Count the number of non-undef PHI uses of each register in each BB. 1040b57cec5SDimitry Andric VRegPHIUse VRegPHIUseCount; 1050b57cec5SDimitry Andric 1060b57cec5SDimitry Andric // Defs of PHI sources which are implicit_def. 1070b57cec5SDimitry Andric SmallPtrSet<MachineInstr *, 4> ImpDefs; 1080b57cec5SDimitry Andric 1090b57cec5SDimitry Andric // Map reusable lowered PHI node -> incoming join register. 1100b57cec5SDimitry Andric using LoweredPHIMap = 1110b57cec5SDimitry Andric DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>; 1120b57cec5SDimitry Andric LoweredPHIMap LoweredPHIs; 113*0fca6ea1SDimitry Andric 114*0fca6ea1SDimitry Andric MachineFunctionPass *P = nullptr; 115*0fca6ea1SDimitry Andric MachineFunctionAnalysisManager *MFAM = nullptr; 116*0fca6ea1SDimitry Andric 117*0fca6ea1SDimitry Andric public: 118*0fca6ea1SDimitry Andric PHIEliminationImpl(MachineFunctionPass *P) : P(P) { 119*0fca6ea1SDimitry Andric auto *LVWrapper = P->getAnalysisIfAvailable<LiveVariablesWrapperPass>(); 120*0fca6ea1SDimitry Andric auto *LISWrapper = P->getAnalysisIfAvailable<LiveIntervalsWrapperPass>(); 121*0fca6ea1SDimitry Andric auto *MLIWrapper = P->getAnalysisIfAvailable<MachineLoopInfoWrapperPass>(); 122*0fca6ea1SDimitry Andric auto *MDTWrapper = 123*0fca6ea1SDimitry Andric P->getAnalysisIfAvailable<MachineDominatorTreeWrapperPass>(); 124*0fca6ea1SDimitry Andric LV = LVWrapper ? &LVWrapper->getLV() : nullptr; 125*0fca6ea1SDimitry Andric LIS = LISWrapper ? &LISWrapper->getLIS() : nullptr; 126*0fca6ea1SDimitry Andric MLI = MLIWrapper ? &MLIWrapper->getLI() : nullptr; 127*0fca6ea1SDimitry Andric MDT = MDTWrapper ? &MDTWrapper->getDomTree() : nullptr; 128*0fca6ea1SDimitry Andric } 129*0fca6ea1SDimitry Andric 130*0fca6ea1SDimitry Andric PHIEliminationImpl(MachineFunction &MF, MachineFunctionAnalysisManager &AM) 131*0fca6ea1SDimitry Andric : LV(AM.getCachedResult<LiveVariablesAnalysis>(MF)), 132*0fca6ea1SDimitry Andric LIS(AM.getCachedResult<LiveIntervalsAnalysis>(MF)), 133*0fca6ea1SDimitry Andric MLI(AM.getCachedResult<MachineLoopAnalysis>(MF)), 134*0fca6ea1SDimitry Andric MDT(AM.getCachedResult<MachineDominatorTreeAnalysis>(MF)), MFAM(&AM) {} 135*0fca6ea1SDimitry Andric 136*0fca6ea1SDimitry Andric bool run(MachineFunction &MF); 137*0fca6ea1SDimitry Andric }; 138*0fca6ea1SDimitry Andric 139*0fca6ea1SDimitry Andric class PHIElimination : public MachineFunctionPass { 140*0fca6ea1SDimitry Andric public: 141*0fca6ea1SDimitry Andric static char ID; // Pass identification, replacement for typeid 142*0fca6ea1SDimitry Andric 143*0fca6ea1SDimitry Andric PHIElimination() : MachineFunctionPass(ID) { 144*0fca6ea1SDimitry Andric initializePHIEliminationPass(*PassRegistry::getPassRegistry()); 145*0fca6ea1SDimitry Andric } 146*0fca6ea1SDimitry Andric 147*0fca6ea1SDimitry Andric bool runOnMachineFunction(MachineFunction &MF) override { 148*0fca6ea1SDimitry Andric PHIEliminationImpl Impl(this); 149*0fca6ea1SDimitry Andric return Impl.run(MF); 150*0fca6ea1SDimitry Andric } 151*0fca6ea1SDimitry Andric 152*0fca6ea1SDimitry Andric MachineFunctionProperties getSetProperties() const override { 153*0fca6ea1SDimitry Andric return MachineFunctionProperties().set( 154*0fca6ea1SDimitry Andric MachineFunctionProperties::Property::NoPHIs); 155*0fca6ea1SDimitry Andric } 156*0fca6ea1SDimitry Andric 157*0fca6ea1SDimitry Andric void getAnalysisUsage(AnalysisUsage &AU) const override; 1580b57cec5SDimitry Andric }; 1590b57cec5SDimitry Andric 1600b57cec5SDimitry Andric } // end anonymous namespace 1610b57cec5SDimitry Andric 162*0fca6ea1SDimitry Andric PreservedAnalyses 163*0fca6ea1SDimitry Andric PHIEliminationPass::run(MachineFunction &MF, 164*0fca6ea1SDimitry Andric MachineFunctionAnalysisManager &MFAM) { 165*0fca6ea1SDimitry Andric PHIEliminationImpl Impl(MF, MFAM); 166*0fca6ea1SDimitry Andric bool Changed = Impl.run(MF); 167*0fca6ea1SDimitry Andric if (!Changed) 168*0fca6ea1SDimitry Andric return PreservedAnalyses::all(); 169*0fca6ea1SDimitry Andric auto PA = getMachineFunctionPassPreservedAnalyses(); 170*0fca6ea1SDimitry Andric PA.preserve<LiveIntervalsAnalysis>(); 171*0fca6ea1SDimitry Andric PA.preserve<LiveVariablesAnalysis>(); 172*0fca6ea1SDimitry Andric PA.preserve<SlotIndexesAnalysis>(); 173*0fca6ea1SDimitry Andric PA.preserve<MachineDominatorTreeAnalysis>(); 174*0fca6ea1SDimitry Andric PA.preserve<MachineLoopAnalysis>(); 175*0fca6ea1SDimitry Andric return PA; 176*0fca6ea1SDimitry Andric } 177*0fca6ea1SDimitry Andric 1780b57cec5SDimitry Andric STATISTIC(NumLowered, "Number of phis lowered"); 1790b57cec5SDimitry Andric STATISTIC(NumCriticalEdgesSplit, "Number of critical edges split"); 1800b57cec5SDimitry Andric STATISTIC(NumReused, "Number of reused lowered phis"); 1810b57cec5SDimitry Andric 1820b57cec5SDimitry Andric char PHIElimination::ID = 0; 1830b57cec5SDimitry Andric 1840b57cec5SDimitry Andric char &llvm::PHIEliminationID = PHIElimination::ID; 1850b57cec5SDimitry Andric 1860b57cec5SDimitry Andric INITIALIZE_PASS_BEGIN(PHIElimination, DEBUG_TYPE, 187*0fca6ea1SDimitry Andric "Eliminate PHI nodes for register allocation", false, 188*0fca6ea1SDimitry Andric false) 189*0fca6ea1SDimitry Andric INITIALIZE_PASS_DEPENDENCY(LiveVariablesWrapperPass) 1900b57cec5SDimitry Andric INITIALIZE_PASS_END(PHIElimination, DEBUG_TYPE, 1910b57cec5SDimitry Andric "Eliminate PHI nodes for register allocation", false, false) 1920b57cec5SDimitry Andric 1930b57cec5SDimitry Andric void PHIElimination::getAnalysisUsage(AnalysisUsage &AU) const { 194*0fca6ea1SDimitry Andric AU.addUsedIfAvailable<LiveVariablesWrapperPass>(); 195*0fca6ea1SDimitry Andric AU.addPreserved<LiveVariablesWrapperPass>(); 196*0fca6ea1SDimitry Andric AU.addPreserved<SlotIndexesWrapperPass>(); 197*0fca6ea1SDimitry Andric AU.addPreserved<LiveIntervalsWrapperPass>(); 198*0fca6ea1SDimitry Andric AU.addPreserved<MachineDominatorTreeWrapperPass>(); 199*0fca6ea1SDimitry Andric AU.addPreserved<MachineLoopInfoWrapperPass>(); 2000b57cec5SDimitry Andric MachineFunctionPass::getAnalysisUsage(AU); 2010b57cec5SDimitry Andric } 2020b57cec5SDimitry Andric 203*0fca6ea1SDimitry Andric bool PHIEliminationImpl::run(MachineFunction &MF) { 2040b57cec5SDimitry Andric MRI = &MF.getRegInfo(); 2050b57cec5SDimitry Andric 2060b57cec5SDimitry Andric bool Changed = false; 2070b57cec5SDimitry Andric 2080b57cec5SDimitry Andric // Split critical edges to help the coalescer. 2090b57cec5SDimitry Andric if (!DisableEdgeSplitting && (LV || LIS)) { 2105ffd83dbSDimitry Andric // A set of live-in regs for each MBB which is used to update LV 2115ffd83dbSDimitry Andric // efficiently also with large functions. 2125ffd83dbSDimitry Andric std::vector<SparseBitVector<>> LiveInSets; 2135ffd83dbSDimitry Andric if (LV) { 2145ffd83dbSDimitry Andric LiveInSets.resize(MF.size()); 2155ffd83dbSDimitry Andric for (unsigned Index = 0, e = MRI->getNumVirtRegs(); Index != e; ++Index) { 2165ffd83dbSDimitry Andric // Set the bit for this register for each MBB where it is 2175ffd83dbSDimitry Andric // live-through or live-in (killed). 218bdd1243dSDimitry Andric Register VirtReg = Register::index2VirtReg(Index); 2195ffd83dbSDimitry Andric MachineInstr *DefMI = MRI->getVRegDef(VirtReg); 2205ffd83dbSDimitry Andric if (!DefMI) 2215ffd83dbSDimitry Andric continue; 2225ffd83dbSDimitry Andric LiveVariables::VarInfo &VI = LV->getVarInfo(VirtReg); 2235ffd83dbSDimitry Andric SparseBitVector<>::iterator AliveBlockItr = VI.AliveBlocks.begin(); 2245ffd83dbSDimitry Andric SparseBitVector<>::iterator EndItr = VI.AliveBlocks.end(); 2255ffd83dbSDimitry Andric while (AliveBlockItr != EndItr) { 2265ffd83dbSDimitry Andric unsigned BlockNum = *(AliveBlockItr++); 2275ffd83dbSDimitry Andric LiveInSets[BlockNum].set(Index); 2285ffd83dbSDimitry Andric } 2295ffd83dbSDimitry Andric // The register is live into an MBB in which it is killed but not 2305ffd83dbSDimitry Andric // defined. See comment for VarInfo in LiveVariables.h. 2315ffd83dbSDimitry Andric MachineBasicBlock *DefMBB = DefMI->getParent(); 2325ffd83dbSDimitry Andric if (VI.Kills.size() > 1 || 2335ffd83dbSDimitry Andric (!VI.Kills.empty() && VI.Kills.front()->getParent() != DefMBB)) 2345ffd83dbSDimitry Andric for (auto *MI : VI.Kills) 2355ffd83dbSDimitry Andric LiveInSets[MI->getParent()->getNumber()].set(Index); 2365ffd83dbSDimitry Andric } 2375ffd83dbSDimitry Andric } 2385ffd83dbSDimitry Andric 2390b57cec5SDimitry Andric for (auto &MBB : MF) 2405ffd83dbSDimitry Andric Changed |= SplitPHIEdges(MF, MBB, MLI, (LV ? &LiveInSets : nullptr)); 2410b57cec5SDimitry Andric } 2420b57cec5SDimitry Andric 2435ffd83dbSDimitry Andric // This pass takes the function out of SSA form. 2445ffd83dbSDimitry Andric MRI->leaveSSA(); 2455ffd83dbSDimitry Andric 2460b57cec5SDimitry Andric // Populate VRegPHIUseCount 247*0fca6ea1SDimitry Andric if (LV || LIS) 2480b57cec5SDimitry Andric analyzePHINodes(MF); 2490b57cec5SDimitry Andric 2500b57cec5SDimitry Andric // Eliminate PHI instructions by inserting copies into predecessor blocks. 2510b57cec5SDimitry Andric for (auto &MBB : MF) 2520b57cec5SDimitry Andric Changed |= EliminatePHINodes(MF, MBB); 2530b57cec5SDimitry Andric 2540b57cec5SDimitry Andric // Remove dead IMPLICIT_DEF instructions. 2550b57cec5SDimitry Andric for (MachineInstr *DefMI : ImpDefs) { 2568bcb0991SDimitry Andric Register DefReg = DefMI->getOperand(0).getReg(); 2570b57cec5SDimitry Andric if (MRI->use_nodbg_empty(DefReg)) { 2580b57cec5SDimitry Andric if (LIS) 2590b57cec5SDimitry Andric LIS->RemoveMachineInstrFromMaps(*DefMI); 2600b57cec5SDimitry Andric DefMI->eraseFromParent(); 2610b57cec5SDimitry Andric } 2620b57cec5SDimitry Andric } 2630b57cec5SDimitry Andric 2640b57cec5SDimitry Andric // Clean up the lowered PHI instructions. 2650b57cec5SDimitry Andric for (auto &I : LoweredPHIs) { 2660b57cec5SDimitry Andric if (LIS) 2670b57cec5SDimitry Andric LIS->RemoveMachineInstrFromMaps(*I.first); 2680eae32dcSDimitry Andric MF.deleteMachineInstr(I.first); 2690b57cec5SDimitry Andric } 2700b57cec5SDimitry Andric 2718bcb0991SDimitry Andric // TODO: we should use the incremental DomTree updater here. 272*0fca6ea1SDimitry Andric if (Changed && MDT) 2738bcb0991SDimitry Andric MDT->getBase().recalculate(MF); 2748bcb0991SDimitry Andric 2750b57cec5SDimitry Andric LoweredPHIs.clear(); 2760b57cec5SDimitry Andric ImpDefs.clear(); 2770b57cec5SDimitry Andric VRegPHIUseCount.clear(); 2780b57cec5SDimitry Andric 2790b57cec5SDimitry Andric MF.getProperties().set(MachineFunctionProperties::Property::NoPHIs); 2800b57cec5SDimitry Andric 2810b57cec5SDimitry Andric return Changed; 2820b57cec5SDimitry Andric } 2830b57cec5SDimitry Andric 2840b57cec5SDimitry Andric /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions in 2850b57cec5SDimitry Andric /// predecessor basic blocks. 286*0fca6ea1SDimitry Andric bool PHIEliminationImpl::EliminatePHINodes(MachineFunction &MF, 2870b57cec5SDimitry Andric MachineBasicBlock &MBB) { 2880b57cec5SDimitry Andric if (MBB.empty() || !MBB.front().isPHI()) 2890b57cec5SDimitry Andric return false; // Quick exit for basic blocks without PHIs. 2900b57cec5SDimitry Andric 2910b57cec5SDimitry Andric // Get an iterator to the last PHI node. 2920b57cec5SDimitry Andric MachineBasicBlock::iterator LastPHIIt = 2930b57cec5SDimitry Andric std::prev(MBB.SkipPHIsAndLabels(MBB.begin())); 2940b57cec5SDimitry Andric 295*0fca6ea1SDimitry Andric // If all incoming edges are critical, we try to deduplicate identical PHIs so 296*0fca6ea1SDimitry Andric // that we generate fewer copies. If at any edge is non-critical, we either 297*0fca6ea1SDimitry Andric // have less than two predecessors (=> no PHIs) or a predecessor has only us 298*0fca6ea1SDimitry Andric // as a successor (=> identical PHI node can't occur in different block). 299*0fca6ea1SDimitry Andric bool AllEdgesCritical = MBB.pred_size() >= 2; 300*0fca6ea1SDimitry Andric for (MachineBasicBlock *Pred : MBB.predecessors()) { 301*0fca6ea1SDimitry Andric if (Pred->succ_size() < 2) { 302*0fca6ea1SDimitry Andric AllEdgesCritical = false; 303*0fca6ea1SDimitry Andric break; 304*0fca6ea1SDimitry Andric } 305*0fca6ea1SDimitry Andric } 306*0fca6ea1SDimitry Andric 3070b57cec5SDimitry Andric while (MBB.front().isPHI()) 308*0fca6ea1SDimitry Andric LowerPHINode(MBB, LastPHIIt, AllEdgesCritical); 3090b57cec5SDimitry Andric 3100b57cec5SDimitry Andric return true; 3110b57cec5SDimitry Andric } 3120b57cec5SDimitry Andric 3130b57cec5SDimitry Andric /// Return true if all defs of VirtReg are implicit-defs. 3140b57cec5SDimitry Andric /// This includes registers with no defs. 3150b57cec5SDimitry Andric static bool isImplicitlyDefined(unsigned VirtReg, 3160b57cec5SDimitry Andric const MachineRegisterInfo &MRI) { 3170b57cec5SDimitry Andric for (MachineInstr &DI : MRI.def_instructions(VirtReg)) 3180b57cec5SDimitry Andric if (!DI.isImplicitDef()) 3190b57cec5SDimitry Andric return false; 3200b57cec5SDimitry Andric return true; 3210b57cec5SDimitry Andric } 3220b57cec5SDimitry Andric 3230b57cec5SDimitry Andric /// Return true if all sources of the phi node are implicit_def's, or undef's. 3240b57cec5SDimitry Andric static bool allPhiOperandsUndefined(const MachineInstr &MPhi, 3250b57cec5SDimitry Andric const MachineRegisterInfo &MRI) { 3260b57cec5SDimitry Andric for (unsigned I = 1, E = MPhi.getNumOperands(); I != E; I += 2) { 3270b57cec5SDimitry Andric const MachineOperand &MO = MPhi.getOperand(I); 3280b57cec5SDimitry Andric if (!isImplicitlyDefined(MO.getReg(), MRI) && !MO.isUndef()) 3290b57cec5SDimitry Andric return false; 3300b57cec5SDimitry Andric } 3310b57cec5SDimitry Andric return true; 3320b57cec5SDimitry Andric } 3330b57cec5SDimitry Andric /// LowerPHINode - Lower the PHI node at the top of the specified block. 334*0fca6ea1SDimitry Andric void PHIEliminationImpl::LowerPHINode(MachineBasicBlock &MBB, 335*0fca6ea1SDimitry Andric MachineBasicBlock::iterator LastPHIIt, 336*0fca6ea1SDimitry Andric bool AllEdgesCritical) { 3370b57cec5SDimitry Andric ++NumLowered; 3380b57cec5SDimitry Andric 3390b57cec5SDimitry Andric MachineBasicBlock::iterator AfterPHIsIt = std::next(LastPHIIt); 3400b57cec5SDimitry Andric 3410b57cec5SDimitry Andric // Unlink the PHI node from the basic block, but don't delete the PHI yet. 3420b57cec5SDimitry Andric MachineInstr *MPhi = MBB.remove(&*MBB.begin()); 3430b57cec5SDimitry Andric 3440b57cec5SDimitry Andric unsigned NumSrcs = (MPhi->getNumOperands() - 1) / 2; 3458bcb0991SDimitry Andric Register DestReg = MPhi->getOperand(0).getReg(); 3460b57cec5SDimitry Andric assert(MPhi->getOperand(0).getSubReg() == 0 && "Can't handle sub-reg PHIs"); 3470b57cec5SDimitry Andric bool isDead = MPhi->getOperand(0).isDead(); 3480b57cec5SDimitry Andric 3490b57cec5SDimitry Andric // Create a new register for the incoming PHI arguments. 3500b57cec5SDimitry Andric MachineFunction &MF = *MBB.getParent(); 3510b57cec5SDimitry Andric unsigned IncomingReg = 0; 352*0fca6ea1SDimitry Andric bool EliminateNow = true; // delay elimination of nodes in LoweredPHIs 3530b57cec5SDimitry Andric bool reusedIncoming = false; // Is IncomingReg reused from an earlier PHI? 3540b57cec5SDimitry Andric 3550b57cec5SDimitry Andric // Insert a register to register copy at the top of the current block (but 3560b57cec5SDimitry Andric // after any remaining phi nodes) which copies the new incoming register 3570b57cec5SDimitry Andric // into the phi node destination. 3588bcb0991SDimitry Andric MachineInstr *PHICopy = nullptr; 3590b57cec5SDimitry Andric const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 3600b57cec5SDimitry Andric if (allPhiOperandsUndefined(*MPhi, *MRI)) 3610b57cec5SDimitry Andric // If all sources of a PHI node are implicit_def or undef uses, just emit an 3620b57cec5SDimitry Andric // implicit_def instead of a copy. 3638bcb0991SDimitry Andric PHICopy = BuildMI(MBB, AfterPHIsIt, MPhi->getDebugLoc(), 3640b57cec5SDimitry Andric TII->get(TargetOpcode::IMPLICIT_DEF), DestReg); 3650b57cec5SDimitry Andric else { 3660b57cec5SDimitry Andric // Can we reuse an earlier PHI node? This only happens for critical edges, 367*0fca6ea1SDimitry Andric // typically those created by tail duplication. Typically, an identical PHI 368*0fca6ea1SDimitry Andric // node can't occur, so avoid hashing/storing such PHIs, which is somewhat 369*0fca6ea1SDimitry Andric // expensive. 370*0fca6ea1SDimitry Andric unsigned *Entry = nullptr; 371*0fca6ea1SDimitry Andric if (AllEdgesCritical) 372*0fca6ea1SDimitry Andric Entry = &LoweredPHIs[MPhi]; 373*0fca6ea1SDimitry Andric if (Entry && *Entry) { 3740b57cec5SDimitry Andric // An identical PHI node was already lowered. Reuse the incoming register. 375*0fca6ea1SDimitry Andric IncomingReg = *Entry; 3760b57cec5SDimitry Andric reusedIncoming = true; 3770b57cec5SDimitry Andric ++NumReused; 3780b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Reusing " << printReg(IncomingReg) << " for " 3790b57cec5SDimitry Andric << *MPhi); 3800b57cec5SDimitry Andric } else { 3810b57cec5SDimitry Andric const TargetRegisterClass *RC = MF.getRegInfo().getRegClass(DestReg); 382*0fca6ea1SDimitry Andric IncomingReg = MF.getRegInfo().createVirtualRegister(RC); 383*0fca6ea1SDimitry Andric if (Entry) { 384*0fca6ea1SDimitry Andric EliminateNow = false; 385*0fca6ea1SDimitry Andric *Entry = IncomingReg; 3860b57cec5SDimitry Andric } 387*0fca6ea1SDimitry Andric } 388*0fca6ea1SDimitry Andric 3898bcb0991SDimitry Andric // Give the target possiblity to handle special cases fallthrough otherwise 390*0fca6ea1SDimitry Andric PHICopy = TII->createPHIDestinationCopy( 391*0fca6ea1SDimitry Andric MBB, AfterPHIsIt, MPhi->getDebugLoc(), IncomingReg, DestReg); 3920b57cec5SDimitry Andric } 3930b57cec5SDimitry Andric 394fe6060f1SDimitry Andric if (MPhi->peekDebugInstrNum()) { 395fe6060f1SDimitry Andric // If referred to by debug-info, store where this PHI was. 396fe6060f1SDimitry Andric MachineFunction *MF = MBB.getParent(); 397fe6060f1SDimitry Andric unsigned ID = MPhi->peekDebugInstrNum(); 398fe6060f1SDimitry Andric auto P = MachineFunction::DebugPHIRegallocPos(&MBB, IncomingReg, 0); 399fe6060f1SDimitry Andric auto Res = MF->DebugPHIPositions.insert({ID, P}); 400fe6060f1SDimitry Andric assert(Res.second); 401fe6060f1SDimitry Andric (void)Res; 402fe6060f1SDimitry Andric } 403fe6060f1SDimitry Andric 4040b57cec5SDimitry Andric // Update live variable information if there is any. 4050b57cec5SDimitry Andric if (LV) { 4060b57cec5SDimitry Andric if (IncomingReg) { 4070b57cec5SDimitry Andric LiveVariables::VarInfo &VI = LV->getVarInfo(IncomingReg); 4080b57cec5SDimitry Andric 409e8d8bef9SDimitry Andric MachineInstr *OldKill = nullptr; 410e8d8bef9SDimitry Andric bool IsPHICopyAfterOldKill = false; 411e8d8bef9SDimitry Andric 412e8d8bef9SDimitry Andric if (reusedIncoming && (OldKill = VI.findKill(&MBB))) { 413e8d8bef9SDimitry Andric // Calculate whether the PHICopy is after the OldKill. 414e8d8bef9SDimitry Andric // In general, the PHICopy is inserted as the first non-phi instruction 415e8d8bef9SDimitry Andric // by default, so it's before the OldKill. But some Target hooks for 416e8d8bef9SDimitry Andric // createPHIDestinationCopy() may modify the default insert position of 417e8d8bef9SDimitry Andric // PHICopy. 418*0fca6ea1SDimitry Andric for (auto I = MBB.SkipPHIsAndLabels(MBB.begin()), E = MBB.end(); I != E; 419*0fca6ea1SDimitry Andric ++I) { 420e8d8bef9SDimitry Andric if (I == PHICopy) 421e8d8bef9SDimitry Andric break; 422e8d8bef9SDimitry Andric 423e8d8bef9SDimitry Andric if (I == OldKill) { 424e8d8bef9SDimitry Andric IsPHICopyAfterOldKill = true; 425e8d8bef9SDimitry Andric break; 426e8d8bef9SDimitry Andric } 427e8d8bef9SDimitry Andric } 428e8d8bef9SDimitry Andric } 429e8d8bef9SDimitry Andric 430e8d8bef9SDimitry Andric // When we are reusing the incoming register and it has been marked killed 431e8d8bef9SDimitry Andric // by OldKill, if the PHICopy is after the OldKill, we should remove the 432e8d8bef9SDimitry Andric // killed flag from OldKill. 433e8d8bef9SDimitry Andric if (IsPHICopyAfterOldKill) { 4340b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Remove old kill from " << *OldKill); 4350b57cec5SDimitry Andric LV->removeVirtualRegisterKilled(IncomingReg, *OldKill); 4360b57cec5SDimitry Andric LLVM_DEBUG(MBB.dump()); 4370b57cec5SDimitry Andric } 4380b57cec5SDimitry Andric 439e8d8bef9SDimitry Andric // Add information to LiveVariables to know that the first used incoming 440e8d8bef9SDimitry Andric // value or the resued incoming value whose PHICopy is after the OldKIll 441e8d8bef9SDimitry Andric // is killed. Note that because the value is defined in several places 442e8d8bef9SDimitry Andric // (once each for each incoming block), the "def" block and instruction 443e8d8bef9SDimitry Andric // fields for the VarInfo is not filled in. 444e8d8bef9SDimitry Andric if (!OldKill || IsPHICopyAfterOldKill) 4458bcb0991SDimitry Andric LV->addVirtualRegisterKilled(IncomingReg, *PHICopy); 4460b57cec5SDimitry Andric } 4470b57cec5SDimitry Andric 4480b57cec5SDimitry Andric // Since we are going to be deleting the PHI node, if it is the last use of 4490b57cec5SDimitry Andric // any registers, or if the value itself is dead, we need to move this 4500b57cec5SDimitry Andric // information over to the new copy we just inserted. 4510b57cec5SDimitry Andric LV->removeVirtualRegistersKilled(*MPhi); 4520b57cec5SDimitry Andric 4530b57cec5SDimitry Andric // If the result is dead, update LV. 4540b57cec5SDimitry Andric if (isDead) { 4558bcb0991SDimitry Andric LV->addVirtualRegisterDead(DestReg, *PHICopy); 4560b57cec5SDimitry Andric LV->removeVirtualRegisterDead(DestReg, *MPhi); 4570b57cec5SDimitry Andric } 4580b57cec5SDimitry Andric } 4590b57cec5SDimitry Andric 4600b57cec5SDimitry Andric // Update LiveIntervals for the new copy or implicit def. 4610b57cec5SDimitry Andric if (LIS) { 4628bcb0991SDimitry Andric SlotIndex DestCopyIndex = LIS->InsertMachineInstrInMaps(*PHICopy); 4630b57cec5SDimitry Andric 4640b57cec5SDimitry Andric SlotIndex MBBStartIndex = LIS->getMBBStartIdx(&MBB); 4650b57cec5SDimitry Andric if (IncomingReg) { 4660b57cec5SDimitry Andric // Add the region from the beginning of MBB to the copy instruction to 4670b57cec5SDimitry Andric // IncomingReg's live interval. 4685f757f3fSDimitry Andric LiveInterval &IncomingLI = LIS->getOrCreateEmptyInterval(IncomingReg); 4690b57cec5SDimitry Andric VNInfo *IncomingVNI = IncomingLI.getVNInfoAt(MBBStartIndex); 4700b57cec5SDimitry Andric if (!IncomingVNI) 471*0fca6ea1SDimitry Andric IncomingVNI = 472*0fca6ea1SDimitry Andric IncomingLI.getNextValue(MBBStartIndex, LIS->getVNInfoAllocator()); 473*0fca6ea1SDimitry Andric IncomingLI.addSegment(LiveInterval::Segment( 474*0fca6ea1SDimitry Andric MBBStartIndex, DestCopyIndex.getRegSlot(), IncomingVNI)); 4750b57cec5SDimitry Andric } 4760b57cec5SDimitry Andric 4770b57cec5SDimitry Andric LiveInterval &DestLI = LIS->getInterval(DestReg); 4785f757f3fSDimitry Andric assert(!DestLI.empty() && "PHIs should have non-empty LiveIntervals."); 4795f757f3fSDimitry Andric 4805f757f3fSDimitry Andric SlotIndex NewStart = DestCopyIndex.getRegSlot(); 4815f757f3fSDimitry Andric 4825f757f3fSDimitry Andric SmallVector<LiveRange *> ToUpdate({&DestLI}); 4835f757f3fSDimitry Andric for (auto &SR : DestLI.subranges()) 4845f757f3fSDimitry Andric ToUpdate.push_back(&SR); 4855f757f3fSDimitry Andric 4865f757f3fSDimitry Andric for (auto LR : ToUpdate) { 4875f757f3fSDimitry Andric auto DestSegment = LR->find(MBBStartIndex); 4885f757f3fSDimitry Andric assert(DestSegment != LR->end() && 4895f757f3fSDimitry Andric "PHI destination must be live in block"); 4905f757f3fSDimitry Andric 4915f757f3fSDimitry Andric if (LR->endIndex().isDead()) { 4920b57cec5SDimitry Andric // A dead PHI's live range begins and ends at the start of the MBB, but 4930b57cec5SDimitry Andric // the lowered copy, which will still be dead, needs to begin and end at 4940b57cec5SDimitry Andric // the copy instruction. 4955f757f3fSDimitry Andric VNInfo *OrigDestVNI = LR->getVNInfoAt(DestSegment->start); 4960b57cec5SDimitry Andric assert(OrigDestVNI && "PHI destination should be live at block entry."); 4975f757f3fSDimitry Andric LR->removeSegment(DestSegment->start, DestSegment->start.getDeadSlot()); 4985f757f3fSDimitry Andric LR->createDeadDef(NewStart, LIS->getVNInfoAllocator()); 4995f757f3fSDimitry Andric LR->removeValNo(OrigDestVNI); 5005f757f3fSDimitry Andric continue; 5015f757f3fSDimitry Andric } 5025f757f3fSDimitry Andric 5035f757f3fSDimitry Andric // Destination copies are not inserted in the same order as the PHI nodes 5045f757f3fSDimitry Andric // they replace. Hence the start of the live range may need to be adjusted 5055f757f3fSDimitry Andric // to match the actual slot index of the copy. 5065f757f3fSDimitry Andric if (DestSegment->start > NewStart) { 5075f757f3fSDimitry Andric VNInfo *VNI = LR->getVNInfoAt(DestSegment->start); 5085f757f3fSDimitry Andric assert(VNI && "value should be defined for known segment"); 5095f757f3fSDimitry Andric LR->addSegment( 5105f757f3fSDimitry Andric LiveInterval::Segment(NewStart, DestSegment->start, VNI)); 5115f757f3fSDimitry Andric } else if (DestSegment->start < NewStart) { 5125f757f3fSDimitry Andric assert(DestSegment->start >= MBBStartIndex); 5135f757f3fSDimitry Andric assert(DestSegment->end >= DestCopyIndex.getRegSlot()); 5145f757f3fSDimitry Andric LR->removeSegment(DestSegment->start, NewStart); 5155f757f3fSDimitry Andric } 5165f757f3fSDimitry Andric VNInfo *DestVNI = LR->getVNInfoAt(NewStart); 5170b57cec5SDimitry Andric assert(DestVNI && "PHI destination should be live at its definition."); 5185f757f3fSDimitry Andric DestVNI->def = NewStart; 5190b57cec5SDimitry Andric } 5200b57cec5SDimitry Andric } 5210b57cec5SDimitry Andric 5220b57cec5SDimitry Andric // Adjust the VRegPHIUseCount map to account for the removal of this PHI node. 523*0fca6ea1SDimitry Andric if (LV || LIS) { 524349cc55cSDimitry Andric for (unsigned i = 1; i != MPhi->getNumOperands(); i += 2) { 525349cc55cSDimitry Andric if (!MPhi->getOperand(i).isUndef()) { 526349cc55cSDimitry Andric --VRegPHIUseCount[BBVRegPair( 527349cc55cSDimitry Andric MPhi->getOperand(i + 1).getMBB()->getNumber(), 5280b57cec5SDimitry Andric MPhi->getOperand(i).getReg())]; 529349cc55cSDimitry Andric } 530349cc55cSDimitry Andric } 531*0fca6ea1SDimitry Andric } 5320b57cec5SDimitry Andric 5330b57cec5SDimitry Andric // Now loop over all of the incoming arguments, changing them to copy into the 5340b57cec5SDimitry Andric // IncomingReg register in the corresponding predecessor basic block. 5350b57cec5SDimitry Andric SmallPtrSet<MachineBasicBlock *, 8> MBBsInsertedInto; 5360b57cec5SDimitry Andric for (int i = NumSrcs - 1; i >= 0; --i) { 5378bcb0991SDimitry Andric Register SrcReg = MPhi->getOperand(i * 2 + 1).getReg(); 5380b57cec5SDimitry Andric unsigned SrcSubReg = MPhi->getOperand(i * 2 + 1).getSubReg(); 5390b57cec5SDimitry Andric bool SrcUndef = MPhi->getOperand(i * 2 + 1).isUndef() || 5400b57cec5SDimitry Andric isImplicitlyDefined(SrcReg, *MRI); 541bdd1243dSDimitry Andric assert(SrcReg.isVirtual() && 5420b57cec5SDimitry Andric "Machine PHI Operands must all be virtual registers!"); 5430b57cec5SDimitry Andric 5440b57cec5SDimitry Andric // Get the MachineBasicBlock equivalent of the BasicBlock that is the source 5450b57cec5SDimitry Andric // path the PHI. 5460b57cec5SDimitry Andric MachineBasicBlock &opBlock = *MPhi->getOperand(i * 2 + 2).getMBB(); 5470b57cec5SDimitry Andric 5480b57cec5SDimitry Andric // Check to make sure we haven't already emitted the copy for this block. 5490b57cec5SDimitry Andric // This can happen because PHI nodes may have multiple entries for the same 5500b57cec5SDimitry Andric // basic block. 5510b57cec5SDimitry Andric if (!MBBsInsertedInto.insert(&opBlock).second) 5520b57cec5SDimitry Andric continue; // If the copy has already been emitted, we're done. 5530b57cec5SDimitry Andric 554e8d8bef9SDimitry Andric MachineInstr *SrcRegDef = MRI->getVRegDef(SrcReg); 555e8d8bef9SDimitry Andric if (SrcRegDef && TII->isUnspillableTerminator(SrcRegDef)) { 556e8d8bef9SDimitry Andric assert(SrcRegDef->getOperand(0).isReg() && 557e8d8bef9SDimitry Andric SrcRegDef->getOperand(0).isDef() && 558e8d8bef9SDimitry Andric "Expected operand 0 to be a reg def!"); 559e8d8bef9SDimitry Andric // Now that the PHI's use has been removed (as the instruction was 560e8d8bef9SDimitry Andric // removed) there should be no other uses of the SrcReg. 561e8d8bef9SDimitry Andric assert(MRI->use_empty(SrcReg) && 562e8d8bef9SDimitry Andric "Expected a single use from UnspillableTerminator"); 563e8d8bef9SDimitry Andric SrcRegDef->getOperand(0).setReg(IncomingReg); 564349cc55cSDimitry Andric 565349cc55cSDimitry Andric // Update LiveVariables. 566349cc55cSDimitry Andric if (LV) { 567349cc55cSDimitry Andric LiveVariables::VarInfo &SrcVI = LV->getVarInfo(SrcReg); 568349cc55cSDimitry Andric LiveVariables::VarInfo &IncomingVI = LV->getVarInfo(IncomingReg); 569349cc55cSDimitry Andric IncomingVI.AliveBlocks = std::move(SrcVI.AliveBlocks); 570349cc55cSDimitry Andric SrcVI.AliveBlocks.clear(); 571349cc55cSDimitry Andric } 572349cc55cSDimitry Andric 573e8d8bef9SDimitry Andric continue; 574e8d8bef9SDimitry Andric } 575e8d8bef9SDimitry Andric 5760b57cec5SDimitry Andric // Find a safe location to insert the copy, this may be the first terminator 5770b57cec5SDimitry Andric // in the block (or end()). 5780b57cec5SDimitry Andric MachineBasicBlock::iterator InsertPos = 5790b57cec5SDimitry Andric findPHICopyInsertPoint(&opBlock, &MBB, SrcReg); 5800b57cec5SDimitry Andric 5810b57cec5SDimitry Andric // Insert the copy. 5820b57cec5SDimitry Andric MachineInstr *NewSrcInstr = nullptr; 5830b57cec5SDimitry Andric if (!reusedIncoming && IncomingReg) { 5840b57cec5SDimitry Andric if (SrcUndef) { 5850b57cec5SDimitry Andric // The source register is undefined, so there is no need for a real 5860b57cec5SDimitry Andric // COPY, but we still need to ensure joint dominance by defs. 5870b57cec5SDimitry Andric // Insert an IMPLICIT_DEF instruction. 588*0fca6ea1SDimitry Andric NewSrcInstr = 589*0fca6ea1SDimitry Andric BuildMI(opBlock, InsertPos, MPhi->getDebugLoc(), 590*0fca6ea1SDimitry Andric TII->get(TargetOpcode::IMPLICIT_DEF), IncomingReg); 5910b57cec5SDimitry Andric 5920b57cec5SDimitry Andric // Clean up the old implicit-def, if there even was one. 5930b57cec5SDimitry Andric if (MachineInstr *DefMI = MRI->getVRegDef(SrcReg)) 5940b57cec5SDimitry Andric if (DefMI->isImplicitDef()) 5950b57cec5SDimitry Andric ImpDefs.insert(DefMI); 5960b57cec5SDimitry Andric } else { 597fe6060f1SDimitry Andric // Delete the debug location, since the copy is inserted into a 598fe6060f1SDimitry Andric // different basic block. 599fe6060f1SDimitry Andric NewSrcInstr = TII->createPHISourceCopy(opBlock, InsertPos, nullptr, 6008bcb0991SDimitry Andric SrcReg, SrcSubReg, IncomingReg); 6010b57cec5SDimitry Andric } 6020b57cec5SDimitry Andric } 6030b57cec5SDimitry Andric 6040b57cec5SDimitry Andric // We only need to update the LiveVariables kill of SrcReg if this was the 6050b57cec5SDimitry Andric // last PHI use of SrcReg to be lowered on this CFG edge and it is not live 6060b57cec5SDimitry Andric // out of the predecessor. We can also ignore undef sources. 6070b57cec5SDimitry Andric if (LV && !SrcUndef && 6080b57cec5SDimitry Andric !VRegPHIUseCount[BBVRegPair(opBlock.getNumber(), SrcReg)] && 6090b57cec5SDimitry Andric !LV->isLiveOut(SrcReg, opBlock)) { 6100b57cec5SDimitry Andric // We want to be able to insert a kill of the register if this PHI (aka, 6110b57cec5SDimitry Andric // the copy we just inserted) is the last use of the source value. Live 6120b57cec5SDimitry Andric // variable analysis conservatively handles this by saying that the value 6130b57cec5SDimitry Andric // is live until the end of the block the PHI entry lives in. If the value 6140b57cec5SDimitry Andric // really is dead at the PHI copy, there will be no successor blocks which 6150b57cec5SDimitry Andric // have the value live-in. 6160b57cec5SDimitry Andric 6170b57cec5SDimitry Andric // Okay, if we now know that the value is not live out of the block, we 6180b57cec5SDimitry Andric // can add a kill marker in this block saying that it kills the incoming 6190b57cec5SDimitry Andric // value! 6200b57cec5SDimitry Andric 6210b57cec5SDimitry Andric // In our final twist, we have to decide which instruction kills the 6220b57cec5SDimitry Andric // register. In most cases this is the copy, however, terminator 6230b57cec5SDimitry Andric // instructions at the end of the block may also use the value. In this 6240b57cec5SDimitry Andric // case, we should mark the last such terminator as being the killing 6250b57cec5SDimitry Andric // block, not the copy. 6260b57cec5SDimitry Andric MachineBasicBlock::iterator KillInst = opBlock.end(); 627349cc55cSDimitry Andric for (MachineBasicBlock::iterator Term = InsertPos; Term != opBlock.end(); 628349cc55cSDimitry Andric ++Term) { 629*0fca6ea1SDimitry Andric if (Term->readsRegister(SrcReg, /*TRI=*/nullptr)) 6300b57cec5SDimitry Andric KillInst = Term; 6310b57cec5SDimitry Andric } 6320b57cec5SDimitry Andric 6330b57cec5SDimitry Andric if (KillInst == opBlock.end()) { 6340b57cec5SDimitry Andric // No terminator uses the register. 6350b57cec5SDimitry Andric 6360b57cec5SDimitry Andric if (reusedIncoming || !IncomingReg) { 6370b57cec5SDimitry Andric // We may have to rewind a bit if we didn't insert a copy this time. 638349cc55cSDimitry Andric KillInst = InsertPos; 6390b57cec5SDimitry Andric while (KillInst != opBlock.begin()) { 6400b57cec5SDimitry Andric --KillInst; 6410b57cec5SDimitry Andric if (KillInst->isDebugInstr()) 6420b57cec5SDimitry Andric continue; 643*0fca6ea1SDimitry Andric if (KillInst->readsRegister(SrcReg, /*TRI=*/nullptr)) 6440b57cec5SDimitry Andric break; 6450b57cec5SDimitry Andric } 6460b57cec5SDimitry Andric } else { 6470b57cec5SDimitry Andric // We just inserted this copy. 6488bcb0991SDimitry Andric KillInst = NewSrcInstr; 6490b57cec5SDimitry Andric } 6500b57cec5SDimitry Andric } 651*0fca6ea1SDimitry Andric assert(KillInst->readsRegister(SrcReg, /*TRI=*/nullptr) && 652*0fca6ea1SDimitry Andric "Cannot find kill instruction"); 6530b57cec5SDimitry Andric 6540b57cec5SDimitry Andric // Finally, mark it killed. 6550b57cec5SDimitry Andric LV->addVirtualRegisterKilled(SrcReg, *KillInst); 6560b57cec5SDimitry Andric 6570b57cec5SDimitry Andric // This vreg no longer lives all of the way through opBlock. 6580b57cec5SDimitry Andric unsigned opBlockNum = opBlock.getNumber(); 6590b57cec5SDimitry Andric LV->getVarInfo(SrcReg).AliveBlocks.reset(opBlockNum); 6600b57cec5SDimitry Andric } 6610b57cec5SDimitry Andric 6620b57cec5SDimitry Andric if (LIS) { 6630b57cec5SDimitry Andric if (NewSrcInstr) { 6640b57cec5SDimitry Andric LIS->InsertMachineInstrInMaps(*NewSrcInstr); 6650b57cec5SDimitry Andric LIS->addSegmentToEndOfBlock(IncomingReg, *NewSrcInstr); 6660b57cec5SDimitry Andric } 6670b57cec5SDimitry Andric 6680b57cec5SDimitry Andric if (!SrcUndef && 6690b57cec5SDimitry Andric !VRegPHIUseCount[BBVRegPair(opBlock.getNumber(), SrcReg)]) { 6700b57cec5SDimitry Andric LiveInterval &SrcLI = LIS->getInterval(SrcReg); 6710b57cec5SDimitry Andric 6720b57cec5SDimitry Andric bool isLiveOut = false; 673fe6060f1SDimitry Andric for (MachineBasicBlock *Succ : opBlock.successors()) { 674fe6060f1SDimitry Andric SlotIndex startIdx = LIS->getMBBStartIdx(Succ); 6750b57cec5SDimitry Andric VNInfo *VNI = SrcLI.getVNInfoAt(startIdx); 6760b57cec5SDimitry Andric 6770b57cec5SDimitry Andric // Definitions by other PHIs are not truly live-in for our purposes. 6780b57cec5SDimitry Andric if (VNI && VNI->def != startIdx) { 6790b57cec5SDimitry Andric isLiveOut = true; 6800b57cec5SDimitry Andric break; 6810b57cec5SDimitry Andric } 6820b57cec5SDimitry Andric } 6830b57cec5SDimitry Andric 6840b57cec5SDimitry Andric if (!isLiveOut) { 6850b57cec5SDimitry Andric MachineBasicBlock::iterator KillInst = opBlock.end(); 686349cc55cSDimitry Andric for (MachineBasicBlock::iterator Term = InsertPos; 6870b57cec5SDimitry Andric Term != opBlock.end(); ++Term) { 688*0fca6ea1SDimitry Andric if (Term->readsRegister(SrcReg, /*TRI=*/nullptr)) 6890b57cec5SDimitry Andric KillInst = Term; 6900b57cec5SDimitry Andric } 6910b57cec5SDimitry Andric 6920b57cec5SDimitry Andric if (KillInst == opBlock.end()) { 6930b57cec5SDimitry Andric // No terminator uses the register. 6940b57cec5SDimitry Andric 6950b57cec5SDimitry Andric if (reusedIncoming || !IncomingReg) { 6960b57cec5SDimitry Andric // We may have to rewind a bit if we didn't just insert a copy. 697349cc55cSDimitry Andric KillInst = InsertPos; 6980b57cec5SDimitry Andric while (KillInst != opBlock.begin()) { 6990b57cec5SDimitry Andric --KillInst; 7000b57cec5SDimitry Andric if (KillInst->isDebugInstr()) 7010b57cec5SDimitry Andric continue; 702*0fca6ea1SDimitry Andric if (KillInst->readsRegister(SrcReg, /*TRI=*/nullptr)) 7030b57cec5SDimitry Andric break; 7040b57cec5SDimitry Andric } 7050b57cec5SDimitry Andric } else { 7060b57cec5SDimitry Andric // We just inserted this copy. 7070b57cec5SDimitry Andric KillInst = std::prev(InsertPos); 7080b57cec5SDimitry Andric } 7090b57cec5SDimitry Andric } 710*0fca6ea1SDimitry Andric assert(KillInst->readsRegister(SrcReg, /*TRI=*/nullptr) && 7110b57cec5SDimitry Andric "Cannot find kill instruction"); 7120b57cec5SDimitry Andric 7130b57cec5SDimitry Andric SlotIndex LastUseIndex = LIS->getInstructionIndex(*KillInst); 7140b57cec5SDimitry Andric SrcLI.removeSegment(LastUseIndex.getRegSlot(), 7150b57cec5SDimitry Andric LIS->getMBBEndIdx(&opBlock)); 7165f757f3fSDimitry Andric for (auto &SR : SrcLI.subranges()) { 7175f757f3fSDimitry Andric SR.removeSegment(LastUseIndex.getRegSlot(), 7185f757f3fSDimitry Andric LIS->getMBBEndIdx(&opBlock)); 7195f757f3fSDimitry Andric } 7200b57cec5SDimitry Andric } 7210b57cec5SDimitry Andric } 7220b57cec5SDimitry Andric } 7230b57cec5SDimitry Andric } 7240b57cec5SDimitry Andric 7250b57cec5SDimitry Andric // Really delete the PHI instruction now, if it is not in the LoweredPHIs map. 726*0fca6ea1SDimitry Andric if (EliminateNow) { 7270b57cec5SDimitry Andric if (LIS) 7280b57cec5SDimitry Andric LIS->RemoveMachineInstrFromMaps(*MPhi); 7290eae32dcSDimitry Andric MF.deleteMachineInstr(MPhi); 7300b57cec5SDimitry Andric } 7310b57cec5SDimitry Andric } 7320b57cec5SDimitry Andric 7330b57cec5SDimitry Andric /// analyzePHINodes - Gather information about the PHI nodes in here. In 7340b57cec5SDimitry Andric /// particular, we want to map the number of uses of a virtual register which is 7350b57cec5SDimitry Andric /// used in a PHI node. We map that to the BB the vreg is coming from. This is 7360b57cec5SDimitry Andric /// used later to determine when the vreg is killed in the BB. 737*0fca6ea1SDimitry Andric void PHIEliminationImpl::analyzePHINodes(const MachineFunction &MF) { 738349cc55cSDimitry Andric for (const auto &MBB : MF) { 7390b57cec5SDimitry Andric for (const auto &BBI : MBB) { 7400b57cec5SDimitry Andric if (!BBI.isPHI()) 7410b57cec5SDimitry Andric break; 742349cc55cSDimitry Andric for (unsigned i = 1, e = BBI.getNumOperands(); i != e; i += 2) { 743349cc55cSDimitry Andric if (!BBI.getOperand(i).isUndef()) { 744349cc55cSDimitry Andric ++VRegPHIUseCount[BBVRegPair( 745349cc55cSDimitry Andric BBI.getOperand(i + 1).getMBB()->getNumber(), 7460b57cec5SDimitry Andric BBI.getOperand(i).getReg())]; 7470b57cec5SDimitry Andric } 7480b57cec5SDimitry Andric } 749349cc55cSDimitry Andric } 750349cc55cSDimitry Andric } 751349cc55cSDimitry Andric } 7520b57cec5SDimitry Andric 753*0fca6ea1SDimitry Andric bool PHIEliminationImpl::SplitPHIEdges( 754*0fca6ea1SDimitry Andric MachineFunction &MF, MachineBasicBlock &MBB, MachineLoopInfo *MLI, 7555ffd83dbSDimitry Andric std::vector<SparseBitVector<>> *LiveInSets) { 7560b57cec5SDimitry Andric if (MBB.empty() || !MBB.front().isPHI() || MBB.isEHPad()) 7570b57cec5SDimitry Andric return false; // Quick exit for basic blocks without PHIs. 7580b57cec5SDimitry Andric 7590b57cec5SDimitry Andric const MachineLoop *CurLoop = MLI ? MLI->getLoopFor(&MBB) : nullptr; 7600b57cec5SDimitry Andric bool IsLoopHeader = CurLoop && &MBB == CurLoop->getHeader(); 7610b57cec5SDimitry Andric 7620b57cec5SDimitry Andric bool Changed = false; 7630b57cec5SDimitry Andric for (MachineBasicBlock::iterator BBI = MBB.begin(), BBE = MBB.end(); 7640b57cec5SDimitry Andric BBI != BBE && BBI->isPHI(); ++BBI) { 7650b57cec5SDimitry Andric for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2) { 7668bcb0991SDimitry Andric Register Reg = BBI->getOperand(i).getReg(); 7670b57cec5SDimitry Andric MachineBasicBlock *PreMBB = BBI->getOperand(i + 1).getMBB(); 7680b57cec5SDimitry Andric // Is there a critical edge from PreMBB to MBB? 7690b57cec5SDimitry Andric if (PreMBB->succ_size() == 1) 7700b57cec5SDimitry Andric continue; 7710b57cec5SDimitry Andric 7720b57cec5SDimitry Andric // Avoid splitting backedges of loops. It would introduce small 7730b57cec5SDimitry Andric // out-of-line blocks into the loop which is very bad for code placement. 7740b57cec5SDimitry Andric if (PreMBB == &MBB && !SplitAllCriticalEdges) 7750b57cec5SDimitry Andric continue; 7760b57cec5SDimitry Andric const MachineLoop *PreLoop = MLI ? MLI->getLoopFor(PreMBB) : nullptr; 7770b57cec5SDimitry Andric if (IsLoopHeader && PreLoop == CurLoop && !SplitAllCriticalEdges) 7780b57cec5SDimitry Andric continue; 7790b57cec5SDimitry Andric 7800b57cec5SDimitry Andric // LV doesn't consider a phi use live-out, so isLiveOut only returns true 7810b57cec5SDimitry Andric // when the source register is live-out for some other reason than a phi 7820b57cec5SDimitry Andric // use. That means the copy we will insert in PreMBB won't be a kill, and 7830b57cec5SDimitry Andric // there is a risk it may not be coalesced away. 7840b57cec5SDimitry Andric // 7850b57cec5SDimitry Andric // If the copy would be a kill, there is no need to split the edge. 7860b57cec5SDimitry Andric bool ShouldSplit = isLiveOutPastPHIs(Reg, PreMBB); 7870b57cec5SDimitry Andric if (!ShouldSplit && !NoPhiElimLiveOutEarlyExit) 7880b57cec5SDimitry Andric continue; 7890b57cec5SDimitry Andric if (ShouldSplit) { 7900b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << printReg(Reg) << " live-out before critical edge " 7910b57cec5SDimitry Andric << printMBBReference(*PreMBB) << " -> " 7920b57cec5SDimitry Andric << printMBBReference(MBB) << ": " << *BBI); 7930b57cec5SDimitry Andric } 7940b57cec5SDimitry Andric 7950b57cec5SDimitry Andric // If Reg is not live-in to MBB, it means it must be live-in to some 7960b57cec5SDimitry Andric // other PreMBB successor, and we can avoid the interference by splitting 7970b57cec5SDimitry Andric // the edge. 7980b57cec5SDimitry Andric // 7990b57cec5SDimitry Andric // If Reg *is* live-in to MBB, the interference is inevitable and a copy 8000b57cec5SDimitry Andric // is likely to be left after coalescing. If we are looking at a loop 8010b57cec5SDimitry Andric // exiting edge, split it so we won't insert code in the loop, otherwise 8020b57cec5SDimitry Andric // don't bother. 8030b57cec5SDimitry Andric ShouldSplit = ShouldSplit && !isLiveIn(Reg, &MBB); 8040b57cec5SDimitry Andric 8050b57cec5SDimitry Andric // Check for a loop exiting edge. 8060b57cec5SDimitry Andric if (!ShouldSplit && CurLoop != PreLoop) { 8070b57cec5SDimitry Andric LLVM_DEBUG({ 8080b57cec5SDimitry Andric dbgs() << "Split wouldn't help, maybe avoid loop copies?\n"; 8090b57cec5SDimitry Andric if (PreLoop) 8100b57cec5SDimitry Andric dbgs() << "PreLoop: " << *PreLoop; 8110b57cec5SDimitry Andric if (CurLoop) 8120b57cec5SDimitry Andric dbgs() << "CurLoop: " << *CurLoop; 8130b57cec5SDimitry Andric }); 8140b57cec5SDimitry Andric // This edge could be entering a loop, exiting a loop, or it could be 8150b57cec5SDimitry Andric // both: Jumping directly form one loop to the header of a sibling 8160b57cec5SDimitry Andric // loop. 8170b57cec5SDimitry Andric // Split unless this edge is entering CurLoop from an outer loop. 8180b57cec5SDimitry Andric ShouldSplit = PreLoop && !PreLoop->contains(CurLoop); 8190b57cec5SDimitry Andric } 8200b57cec5SDimitry Andric if (!ShouldSplit && !SplitAllCriticalEdges) 8210b57cec5SDimitry Andric continue; 822*0fca6ea1SDimitry Andric if (!(P ? PreMBB->SplitCriticalEdge(&MBB, *P, LiveInSets) 823*0fca6ea1SDimitry Andric : PreMBB->SplitCriticalEdge(&MBB, *MFAM, LiveInSets))) { 8240b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Failed to split critical edge.\n"); 8250b57cec5SDimitry Andric continue; 8260b57cec5SDimitry Andric } 8270b57cec5SDimitry Andric Changed = true; 8280b57cec5SDimitry Andric ++NumCriticalEdgesSplit; 8290b57cec5SDimitry Andric } 8300b57cec5SDimitry Andric } 8310b57cec5SDimitry Andric return Changed; 8320b57cec5SDimitry Andric } 8330b57cec5SDimitry Andric 834*0fca6ea1SDimitry Andric bool PHIEliminationImpl::isLiveIn(Register Reg, const MachineBasicBlock *MBB) { 8350b57cec5SDimitry Andric assert((LV || LIS) && 8360b57cec5SDimitry Andric "isLiveIn() requires either LiveVariables or LiveIntervals"); 8370b57cec5SDimitry Andric if (LIS) 8380b57cec5SDimitry Andric return LIS->isLiveInToMBB(LIS->getInterval(Reg), MBB); 8390b57cec5SDimitry Andric else 8400b57cec5SDimitry Andric return LV->isLiveIn(Reg, *MBB); 8410b57cec5SDimitry Andric } 8420b57cec5SDimitry Andric 843*0fca6ea1SDimitry Andric bool PHIEliminationImpl::isLiveOutPastPHIs(Register Reg, 8440b57cec5SDimitry Andric const MachineBasicBlock *MBB) { 8450b57cec5SDimitry Andric assert((LV || LIS) && 8460b57cec5SDimitry Andric "isLiveOutPastPHIs() requires either LiveVariables or LiveIntervals"); 8470b57cec5SDimitry Andric // LiveVariables considers uses in PHIs to be in the predecessor basic block, 8480b57cec5SDimitry Andric // so that a register used only in a PHI is not live out of the block. In 849*0fca6ea1SDimitry Andric // contrast, LiveIntervals considers uses in PHIs to be on the edge rather 850*0fca6ea1SDimitry Andric // than in the predecessor basic block, so that a register used only in a PHI 851*0fca6ea1SDimitry Andric // is live out of the block. 8520b57cec5SDimitry Andric if (LIS) { 8530b57cec5SDimitry Andric const LiveInterval &LI = LIS->getInterval(Reg); 8540b57cec5SDimitry Andric for (const MachineBasicBlock *SI : MBB->successors()) 8550b57cec5SDimitry Andric if (LI.liveAt(LIS->getMBBStartIdx(SI))) 8560b57cec5SDimitry Andric return true; 8570b57cec5SDimitry Andric return false; 8580b57cec5SDimitry Andric } else { 8590b57cec5SDimitry Andric return LV->isLiveOut(Reg, *MBB); 8600b57cec5SDimitry Andric } 8610b57cec5SDimitry Andric } 862