12cab237bSDimitry Andric //===- llvm/CodeGen/VirtRegMap.cpp - Virtual Register Map -----------------===//
2f22ef01cSRoman Divacky //
3f22ef01cSRoman Divacky // The LLVM Compiler Infrastructure
4f22ef01cSRoman Divacky //
5f22ef01cSRoman Divacky // This file is distributed under the University of Illinois Open Source
6f22ef01cSRoman Divacky // License. See LICENSE.TXT for details.
7f22ef01cSRoman Divacky //
8f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
9f22ef01cSRoman Divacky //
10f22ef01cSRoman Divacky // This file implements the VirtRegMap class.
11f22ef01cSRoman Divacky //
12f22ef01cSRoman Divacky // It also contains implementations of the Spiller interface, which, given a
13f22ef01cSRoman Divacky // virtual register map and a machine function, eliminates all virtual
14f22ef01cSRoman Divacky // references by replacing them with physical register references - adding spill
15f22ef01cSRoman Divacky // code as necessary.
16f22ef01cSRoman Divacky //
17f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
18f22ef01cSRoman Divacky
19139f7f9bSDimitry Andric #include "llvm/CodeGen/VirtRegMap.h"
207ae0e2c9SDimitry Andric #include "LiveDebugVariables.h"
212cab237bSDimitry Andric #include "llvm/ADT/SmallVector.h"
22139f7f9bSDimitry Andric #include "llvm/ADT/Statistic.h"
232cab237bSDimitry Andric #include "llvm/CodeGen/LiveInterval.h"
242cab237bSDimitry Andric #include "llvm/CodeGen/LiveIntervals.h"
25da09e106SDimitry Andric #include "llvm/CodeGen/LiveStacks.h"
262cab237bSDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
27f22ef01cSRoman Divacky #include "llvm/CodeGen/MachineFrameInfo.h"
28f22ef01cSRoman Divacky #include "llvm/CodeGen/MachineFunction.h"
292cab237bSDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h"
302cab237bSDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
312cab237bSDimitry Andric #include "llvm/CodeGen/MachineOperand.h"
32f22ef01cSRoman Divacky #include "llvm/CodeGen/MachineRegisterInfo.h"
332cab237bSDimitry Andric #include "llvm/CodeGen/SlotIndexes.h"
342cab237bSDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
352cab237bSDimitry Andric #include "llvm/CodeGen/TargetOpcodes.h"
362cab237bSDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
372cab237bSDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
384ba319b5SDimitry Andric #include "llvm/Config/llvm-config.h"
392cab237bSDimitry Andric #include "llvm/MC/LaneBitmask.h"
402cab237bSDimitry Andric #include "llvm/Pass.h"
41f22ef01cSRoman Divacky #include "llvm/Support/Compiler.h"
42f22ef01cSRoman Divacky #include "llvm/Support/Debug.h"
43f22ef01cSRoman Divacky #include "llvm/Support/raw_ostream.h"
442cab237bSDimitry Andric #include <cassert>
452cab237bSDimitry Andric #include <iterator>
462cab237bSDimitry Andric #include <utility>
472cab237bSDimitry Andric
48f22ef01cSRoman Divacky using namespace llvm;
49f22ef01cSRoman Divacky
5091bc56edSDimitry Andric #define DEBUG_TYPE "regalloc"
5191bc56edSDimitry Andric
526122f3e6SDimitry Andric STATISTIC(NumSpillSlots, "Number of spill slots allocated");
53bd5abe19SDimitry Andric STATISTIC(NumIdCopies, "Number of identity moves eliminated after rewriting");
54f22ef01cSRoman Divacky
55f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
56f22ef01cSRoman Divacky // VirtRegMap implementation
57f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
58f22ef01cSRoman Divacky
59f22ef01cSRoman Divacky char VirtRegMap::ID = 0;
60f22ef01cSRoman Divacky
612754fe60SDimitry Andric INITIALIZE_PASS(VirtRegMap, "virtregmap", "Virtual Register Map", false, false)
62f22ef01cSRoman Divacky
runOnMachineFunction(MachineFunction & mf)63f22ef01cSRoman Divacky bool VirtRegMap::runOnMachineFunction(MachineFunction &mf) {
64f22ef01cSRoman Divacky MRI = &mf.getRegInfo();
6539d628a0SDimitry Andric TII = mf.getSubtarget().getInstrInfo();
6639d628a0SDimitry Andric TRI = mf.getSubtarget().getRegisterInfo();
67f22ef01cSRoman Divacky MF = &mf;
68f22ef01cSRoman Divacky
69f22ef01cSRoman Divacky Virt2PhysMap.clear();
70f22ef01cSRoman Divacky Virt2StackSlotMap.clear();
71f22ef01cSRoman Divacky Virt2SplitMap.clear();
72f22ef01cSRoman Divacky
73f22ef01cSRoman Divacky grow();
74f22ef01cSRoman Divacky return false;
75f22ef01cSRoman Divacky }
76f22ef01cSRoman Divacky
grow()77f22ef01cSRoman Divacky void VirtRegMap::grow() {
782754fe60SDimitry Andric unsigned NumRegs = MF->getRegInfo().getNumVirtRegs();
792754fe60SDimitry Andric Virt2PhysMap.resize(NumRegs);
802754fe60SDimitry Andric Virt2StackSlotMap.resize(NumRegs);
812754fe60SDimitry Andric Virt2SplitMap.resize(NumRegs);
822754fe60SDimitry Andric }
832754fe60SDimitry Andric
assignVirt2Phys(unsigned virtReg,MCPhysReg physReg)84db17bf38SDimitry Andric void VirtRegMap::assignVirt2Phys(unsigned virtReg, MCPhysReg physReg) {
85db17bf38SDimitry Andric assert(TargetRegisterInfo::isVirtualRegister(virtReg) &&
86db17bf38SDimitry Andric TargetRegisterInfo::isPhysicalRegister(physReg));
87db17bf38SDimitry Andric assert(Virt2PhysMap[virtReg] == NO_PHYS_REG &&
88db17bf38SDimitry Andric "attempt to assign physical register to already mapped "
89db17bf38SDimitry Andric "virtual register");
90db17bf38SDimitry Andric assert(!getRegInfo().isReserved(physReg) &&
91db17bf38SDimitry Andric "Attempt to map virtReg to a reserved physReg");
92db17bf38SDimitry Andric Virt2PhysMap[virtReg] = physReg;
93db17bf38SDimitry Andric }
94db17bf38SDimitry Andric
createSpillSlot(const TargetRegisterClass * RC)952754fe60SDimitry Andric unsigned VirtRegMap::createSpillSlot(const TargetRegisterClass *RC) {
9651690af2SDimitry Andric unsigned Size = TRI->getSpillSize(*RC);
9751690af2SDimitry Andric unsigned Align = TRI->getSpillAlignment(*RC);
9851690af2SDimitry Andric int SS = MF->getFrameInfo().CreateSpillStackObject(Size, Align);
996122f3e6SDimitry Andric ++NumSpillSlots;
1002754fe60SDimitry Andric return SS;
101f22ef01cSRoman Divacky }
102f22ef01cSRoman Divacky
hasPreferredPhys(unsigned VirtReg)103139f7f9bSDimitry Andric bool VirtRegMap::hasPreferredPhys(unsigned VirtReg) {
104139f7f9bSDimitry Andric unsigned Hint = MRI->getSimpleHint(VirtReg);
105139f7f9bSDimitry Andric if (!Hint)
1063ca95b02SDimitry Andric return false;
107139f7f9bSDimitry Andric if (TargetRegisterInfo::isVirtualRegister(Hint))
108139f7f9bSDimitry Andric Hint = getPhys(Hint);
109139f7f9bSDimitry Andric return getPhys(VirtReg) == Hint;
110139f7f9bSDimitry Andric }
111139f7f9bSDimitry Andric
hasKnownPreference(unsigned VirtReg)112139f7f9bSDimitry Andric bool VirtRegMap::hasKnownPreference(unsigned VirtReg) {
113139f7f9bSDimitry Andric std::pair<unsigned, unsigned> Hint = MRI->getRegAllocationHint(VirtReg);
114139f7f9bSDimitry Andric if (TargetRegisterInfo::isPhysicalRegister(Hint.second))
115139f7f9bSDimitry Andric return true;
116139f7f9bSDimitry Andric if (TargetRegisterInfo::isVirtualRegister(Hint.second))
117139f7f9bSDimitry Andric return hasPhys(Hint.second);
118139f7f9bSDimitry Andric return false;
119f22ef01cSRoman Divacky }
120f22ef01cSRoman Divacky
assignVirt2StackSlot(unsigned virtReg)121f22ef01cSRoman Divacky int VirtRegMap::assignVirt2StackSlot(unsigned virtReg) {
122f22ef01cSRoman Divacky assert(TargetRegisterInfo::isVirtualRegister(virtReg));
123f22ef01cSRoman Divacky assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
124f22ef01cSRoman Divacky "attempt to assign stack slot to already spilled register");
125f22ef01cSRoman Divacky const TargetRegisterClass* RC = MF->getRegInfo().getRegClass(virtReg);
1262754fe60SDimitry Andric return Virt2StackSlotMap[virtReg] = createSpillSlot(RC);
127f22ef01cSRoman Divacky }
128f22ef01cSRoman Divacky
assignVirt2StackSlot(unsigned virtReg,int SS)129f22ef01cSRoman Divacky void VirtRegMap::assignVirt2StackSlot(unsigned virtReg, int SS) {
130f22ef01cSRoman Divacky assert(TargetRegisterInfo::isVirtualRegister(virtReg));
131f22ef01cSRoman Divacky assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
132f22ef01cSRoman Divacky "attempt to assign stack slot to already spilled register");
133f22ef01cSRoman Divacky assert((SS >= 0 ||
134d88c1a5aSDimitry Andric (SS >= MF->getFrameInfo().getObjectIndexBegin())) &&
135f22ef01cSRoman Divacky "illegal fixed frame index");
136f22ef01cSRoman Divacky Virt2StackSlotMap[virtReg] = SS;
137f22ef01cSRoman Divacky }
138f22ef01cSRoman Divacky
print(raw_ostream & OS,const Module *) const1397ae0e2c9SDimitry Andric void VirtRegMap::print(raw_ostream &OS, const Module*) const {
1407ae0e2c9SDimitry Andric OS << "********** REGISTER MAP **********\n";
1417ae0e2c9SDimitry Andric for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
1427ae0e2c9SDimitry Andric unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
1437ae0e2c9SDimitry Andric if (Virt2PhysMap[Reg] != (unsigned)VirtRegMap::NO_PHYS_REG) {
1442cab237bSDimitry Andric OS << '[' << printReg(Reg, TRI) << " -> "
1452cab237bSDimitry Andric << printReg(Virt2PhysMap[Reg], TRI) << "] "
14639d628a0SDimitry Andric << TRI->getRegClassName(MRI->getRegClass(Reg)) << "\n";
1477ae0e2c9SDimitry Andric }
1487ae0e2c9SDimitry Andric }
1497ae0e2c9SDimitry Andric
1507ae0e2c9SDimitry Andric for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
1517ae0e2c9SDimitry Andric unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
1527ae0e2c9SDimitry Andric if (Virt2StackSlotMap[Reg] != VirtRegMap::NO_STACK_SLOT) {
1532cab237bSDimitry Andric OS << '[' << printReg(Reg, TRI) << " -> fi#" << Virt2StackSlotMap[Reg]
15439d628a0SDimitry Andric << "] " << TRI->getRegClassName(MRI->getRegClass(Reg)) << "\n";
1557ae0e2c9SDimitry Andric }
1567ae0e2c9SDimitry Andric }
1577ae0e2c9SDimitry Andric OS << '\n';
1587ae0e2c9SDimitry Andric }
1597ae0e2c9SDimitry Andric
1603861d79fSDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dump() const1613ca95b02SDimitry Andric LLVM_DUMP_METHOD void VirtRegMap::dump() const {
1627ae0e2c9SDimitry Andric print(dbgs());
1637ae0e2c9SDimitry Andric }
1643861d79fSDimitry Andric #endif
1657ae0e2c9SDimitry Andric
1667ae0e2c9SDimitry Andric //===----------------------------------------------------------------------===//
1677ae0e2c9SDimitry Andric // VirtRegRewriter
1687ae0e2c9SDimitry Andric //===----------------------------------------------------------------------===//
1697ae0e2c9SDimitry Andric //
1707ae0e2c9SDimitry Andric // The VirtRegRewriter is the last of the register allocator passes.
1717ae0e2c9SDimitry Andric // It rewrites virtual registers to physical registers as specified in the
1727ae0e2c9SDimitry Andric // VirtRegMap analysis. It also updates live-in information on basic blocks
1737ae0e2c9SDimitry Andric // according to LiveIntervals.
1747ae0e2c9SDimitry Andric //
1757ae0e2c9SDimitry Andric namespace {
1762cab237bSDimitry Andric
1777ae0e2c9SDimitry Andric class VirtRegRewriter : public MachineFunctionPass {
1787ae0e2c9SDimitry Andric MachineFunction *MF;
1797ae0e2c9SDimitry Andric const TargetRegisterInfo *TRI;
1807ae0e2c9SDimitry Andric const TargetInstrInfo *TII;
1817ae0e2c9SDimitry Andric MachineRegisterInfo *MRI;
1827ae0e2c9SDimitry Andric SlotIndexes *Indexes;
1837ae0e2c9SDimitry Andric LiveIntervals *LIS;
1847ae0e2c9SDimitry Andric VirtRegMap *VRM;
1857ae0e2c9SDimitry Andric
1867ae0e2c9SDimitry Andric void rewrite();
1877ae0e2c9SDimitry Andric void addMBBLiveIns();
1888f0fd8f6SDimitry Andric bool readsUndefSubreg(const MachineOperand &MO) const;
1897d523365SDimitry Andric void addLiveInsForSubRanges(const LiveInterval &LI, unsigned PhysReg) const;
1903ca95b02SDimitry Andric void handleIdentityCopy(MachineInstr &MI) const;
1917a7e6055SDimitry Andric void expandCopyBundle(MachineInstr &MI) const;
1920554abf0SDimitry Andric bool subRegLiveThrough(const MachineInstr &MI, unsigned SuperPhysReg) const;
1937d523365SDimitry Andric
1947ae0e2c9SDimitry Andric public:
1957ae0e2c9SDimitry Andric static char ID;
1962cab237bSDimitry Andric
VirtRegRewriter()1977ae0e2c9SDimitry Andric VirtRegRewriter() : MachineFunctionPass(ID) {}
1987ae0e2c9SDimitry Andric
19991bc56edSDimitry Andric void getAnalysisUsage(AnalysisUsage &AU) const override;
2007ae0e2c9SDimitry Andric
20191bc56edSDimitry Andric bool runOnMachineFunction(MachineFunction&) override;
2022cab237bSDimitry Andric
getSetProperties() const2033ca95b02SDimitry Andric MachineFunctionProperties getSetProperties() const override {
2043ca95b02SDimitry Andric return MachineFunctionProperties().set(
205d88c1a5aSDimitry Andric MachineFunctionProperties::Property::NoVRegs);
2063ca95b02SDimitry Andric }
2077ae0e2c9SDimitry Andric };
2082cab237bSDimitry Andric
2097ae0e2c9SDimitry Andric } // end anonymous namespace
2107ae0e2c9SDimitry Andric
2112cab237bSDimitry Andric char VirtRegRewriter::ID = 0;
2122cab237bSDimitry Andric
2137ae0e2c9SDimitry Andric char &llvm::VirtRegRewriterID = VirtRegRewriter::ID;
2147ae0e2c9SDimitry Andric
2157ae0e2c9SDimitry Andric INITIALIZE_PASS_BEGIN(VirtRegRewriter, "virtregrewriter",
2167ae0e2c9SDimitry Andric "Virtual Register Rewriter", false, false)
INITIALIZE_PASS_DEPENDENCY(SlotIndexes)2177ae0e2c9SDimitry Andric INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
2187ae0e2c9SDimitry Andric INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
2197ae0e2c9SDimitry Andric INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables)
2203861d79fSDimitry Andric INITIALIZE_PASS_DEPENDENCY(LiveStacks)
2217ae0e2c9SDimitry Andric INITIALIZE_PASS_DEPENDENCY(VirtRegMap)
2227ae0e2c9SDimitry Andric INITIALIZE_PASS_END(VirtRegRewriter, "virtregrewriter",
2237ae0e2c9SDimitry Andric "Virtual Register Rewriter", false, false)
2247ae0e2c9SDimitry Andric
2257ae0e2c9SDimitry Andric void VirtRegRewriter::getAnalysisUsage(AnalysisUsage &AU) const {
2267ae0e2c9SDimitry Andric AU.setPreservesCFG();
2277ae0e2c9SDimitry Andric AU.addRequired<LiveIntervals>();
2287ae0e2c9SDimitry Andric AU.addRequired<SlotIndexes>();
2297ae0e2c9SDimitry Andric AU.addPreserved<SlotIndexes>();
2307ae0e2c9SDimitry Andric AU.addRequired<LiveDebugVariables>();
2313861d79fSDimitry Andric AU.addRequired<LiveStacks>();
2323861d79fSDimitry Andric AU.addPreserved<LiveStacks>();
2337ae0e2c9SDimitry Andric AU.addRequired<VirtRegMap>();
2347ae0e2c9SDimitry Andric MachineFunctionPass::getAnalysisUsage(AU);
2357ae0e2c9SDimitry Andric }
2367ae0e2c9SDimitry Andric
runOnMachineFunction(MachineFunction & fn)2377ae0e2c9SDimitry Andric bool VirtRegRewriter::runOnMachineFunction(MachineFunction &fn) {
2387ae0e2c9SDimitry Andric MF = &fn;
23939d628a0SDimitry Andric TRI = MF->getSubtarget().getRegisterInfo();
24039d628a0SDimitry Andric TII = MF->getSubtarget().getInstrInfo();
2417ae0e2c9SDimitry Andric MRI = &MF->getRegInfo();
2427ae0e2c9SDimitry Andric Indexes = &getAnalysis<SlotIndexes>();
2437ae0e2c9SDimitry Andric LIS = &getAnalysis<LiveIntervals>();
2447ae0e2c9SDimitry Andric VRM = &getAnalysis<VirtRegMap>();
2454ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "********** REWRITE VIRTUAL REGISTERS **********\n"
2464ba319b5SDimitry Andric << "********** Function: " << MF->getName() << '\n');
2474ba319b5SDimitry Andric LLVM_DEBUG(VRM->dump());
2487ae0e2c9SDimitry Andric
2497ae0e2c9SDimitry Andric // Add kill flags while we still have virtual registers.
2503861d79fSDimitry Andric LIS->addKillFlags(VRM);
2517ae0e2c9SDimitry Andric
2527ae0e2c9SDimitry Andric // Live-in lists on basic blocks are required for physregs.
2537ae0e2c9SDimitry Andric addMBBLiveIns();
2547ae0e2c9SDimitry Andric
2557ae0e2c9SDimitry Andric // Rewrite virtual registers.
2567ae0e2c9SDimitry Andric rewrite();
2577ae0e2c9SDimitry Andric
2587ae0e2c9SDimitry Andric // Write out new DBG_VALUE instructions.
2597ae0e2c9SDimitry Andric getAnalysis<LiveDebugVariables>().emitDebugValues(VRM);
2607ae0e2c9SDimitry Andric
2617ae0e2c9SDimitry Andric // All machine operands and other references to virtual registers have been
2627ae0e2c9SDimitry Andric // replaced. Remove the virtual registers and release all the transient data.
2637ae0e2c9SDimitry Andric VRM->clearAllVirt();
2647ae0e2c9SDimitry Andric MRI->clearVirtRegs();
2657ae0e2c9SDimitry Andric return true;
2667ae0e2c9SDimitry Andric }
2677ae0e2c9SDimitry Andric
addLiveInsForSubRanges(const LiveInterval & LI,unsigned PhysReg) const2687d523365SDimitry Andric void VirtRegRewriter::addLiveInsForSubRanges(const LiveInterval &LI,
2697d523365SDimitry Andric unsigned PhysReg) const {
2707d523365SDimitry Andric assert(!LI.empty());
2717d523365SDimitry Andric assert(LI.hasSubRanges());
2727d523365SDimitry Andric
2732cab237bSDimitry Andric using SubRangeIteratorPair =
2742cab237bSDimitry Andric std::pair<const LiveInterval::SubRange *, LiveInterval::const_iterator>;
2752cab237bSDimitry Andric
2767d523365SDimitry Andric SmallVector<SubRangeIteratorPair, 4> SubRanges;
2777d523365SDimitry Andric SlotIndex First;
2787d523365SDimitry Andric SlotIndex Last;
2797d523365SDimitry Andric for (const LiveInterval::SubRange &SR : LI.subranges()) {
2807d523365SDimitry Andric SubRanges.push_back(std::make_pair(&SR, SR.begin()));
2817d523365SDimitry Andric if (!First.isValid() || SR.segments.front().start < First)
2827d523365SDimitry Andric First = SR.segments.front().start;
2837d523365SDimitry Andric if (!Last.isValid() || SR.segments.back().end > Last)
2847d523365SDimitry Andric Last = SR.segments.back().end;
2857d523365SDimitry Andric }
2867d523365SDimitry Andric
2877d523365SDimitry Andric // Check all mbb start positions between First and Last while
2887d523365SDimitry Andric // simulatenously advancing an iterator for each subrange.
2897d523365SDimitry Andric for (SlotIndexes::MBBIndexIterator MBBI = Indexes->findMBBIndex(First);
2907d523365SDimitry Andric MBBI != Indexes->MBBIndexEnd() && MBBI->first <= Last; ++MBBI) {
2917d523365SDimitry Andric SlotIndex MBBBegin = MBBI->first;
2927d523365SDimitry Andric // Advance all subrange iterators so that their end position is just
2937d523365SDimitry Andric // behind MBBBegin (or the iterator is at the end).
294d88c1a5aSDimitry Andric LaneBitmask LaneMask;
2957d523365SDimitry Andric for (auto &RangeIterPair : SubRanges) {
2967d523365SDimitry Andric const LiveInterval::SubRange *SR = RangeIterPair.first;
2977d523365SDimitry Andric LiveInterval::const_iterator &SRI = RangeIterPair.second;
2987d523365SDimitry Andric while (SRI != SR->end() && SRI->end <= MBBBegin)
2997d523365SDimitry Andric ++SRI;
3007d523365SDimitry Andric if (SRI == SR->end())
3017d523365SDimitry Andric continue;
3027d523365SDimitry Andric if (SRI->start <= MBBBegin)
3037d523365SDimitry Andric LaneMask |= SR->LaneMask;
3047d523365SDimitry Andric }
305d88c1a5aSDimitry Andric if (LaneMask.none())
3067d523365SDimitry Andric continue;
3077d523365SDimitry Andric MachineBasicBlock *MBB = MBBI->second;
3087d523365SDimitry Andric MBB->addLiveIn(PhysReg, LaneMask);
3097d523365SDimitry Andric }
3107d523365SDimitry Andric }
3117d523365SDimitry Andric
3127ae0e2c9SDimitry Andric // Compute MBB live-in lists from virtual register live ranges and their
3137ae0e2c9SDimitry Andric // assignments.
addMBBLiveIns()3147ae0e2c9SDimitry Andric void VirtRegRewriter::addMBBLiveIns() {
3157ae0e2c9SDimitry Andric for (unsigned Idx = 0, IdxE = MRI->getNumVirtRegs(); Idx != IdxE; ++Idx) {
3167ae0e2c9SDimitry Andric unsigned VirtReg = TargetRegisterInfo::index2VirtReg(Idx);
3177ae0e2c9SDimitry Andric if (MRI->reg_nodbg_empty(VirtReg))
3187ae0e2c9SDimitry Andric continue;
3197ae0e2c9SDimitry Andric LiveInterval &LI = LIS->getInterval(VirtReg);
3207ae0e2c9SDimitry Andric if (LI.empty() || LIS->intervalIsInOneMBB(LI))
3217ae0e2c9SDimitry Andric continue;
3227ae0e2c9SDimitry Andric // This is a virtual register that is live across basic blocks. Its
3237ae0e2c9SDimitry Andric // assigned PhysReg must be marked as live-in to those blocks.
3247ae0e2c9SDimitry Andric unsigned PhysReg = VRM->getPhys(VirtReg);
3257ae0e2c9SDimitry Andric assert(PhysReg != VirtRegMap::NO_PHYS_REG && "Unmapped virtual register.");
3267ae0e2c9SDimitry Andric
32739d628a0SDimitry Andric if (LI.hasSubRanges()) {
3287d523365SDimitry Andric addLiveInsForSubRanges(LI, PhysReg);
32939d628a0SDimitry Andric } else {
3307d523365SDimitry Andric // Go over MBB begin positions and see if we have segments covering them.
3317d523365SDimitry Andric // The following works because segments and the MBBIndex list are both
3327d523365SDimitry Andric // sorted by slot indexes.
3337d523365SDimitry Andric SlotIndexes::MBBIndexIterator I = Indexes->MBBIndexBegin();
3347d523365SDimitry Andric for (const auto &Seg : LI) {
3357d523365SDimitry Andric I = Indexes->advanceMBBIndex(I, Seg.start);
3367d523365SDimitry Andric for (; I != Indexes->MBBIndexEnd() && I->first < Seg.end; ++I) {
3377d523365SDimitry Andric MachineBasicBlock *MBB = I->second;
3387d523365SDimitry Andric MBB->addLiveIn(PhysReg);
3397d523365SDimitry Andric }
3407ae0e2c9SDimitry Andric }
3417ae0e2c9SDimitry Andric }
3427ae0e2c9SDimitry Andric }
343ff0cc061SDimitry Andric
344ff0cc061SDimitry Andric // Sort and unique MBB LiveIns as we've not checked if SubReg/PhysReg were in
345ff0cc061SDimitry Andric // each MBB's LiveIns set before calling addLiveIn on them.
346ff0cc061SDimitry Andric for (MachineBasicBlock &MBB : *MF)
347ff0cc061SDimitry Andric MBB.sortUniqueLiveIns();
34839d628a0SDimitry Andric }
3497ae0e2c9SDimitry Andric
3508f0fd8f6SDimitry Andric /// Returns true if the given machine operand \p MO only reads undefined lanes.
3518f0fd8f6SDimitry Andric /// The function only works for use operands with a subregister set.
readsUndefSubreg(const MachineOperand & MO) const3528f0fd8f6SDimitry Andric bool VirtRegRewriter::readsUndefSubreg(const MachineOperand &MO) const {
3538f0fd8f6SDimitry Andric // Shortcut if the operand is already marked undef.
3548f0fd8f6SDimitry Andric if (MO.isUndef())
3558f0fd8f6SDimitry Andric return true;
3568f0fd8f6SDimitry Andric
3578f0fd8f6SDimitry Andric unsigned Reg = MO.getReg();
3588f0fd8f6SDimitry Andric const LiveInterval &LI = LIS->getInterval(Reg);
3598f0fd8f6SDimitry Andric const MachineInstr &MI = *MO.getParent();
3603ca95b02SDimitry Andric SlotIndex BaseIndex = LIS->getInstructionIndex(MI);
3618f0fd8f6SDimitry Andric // This code is only meant to handle reading undefined subregisters which
3628f0fd8f6SDimitry Andric // we couldn't properly detect before.
3638f0fd8f6SDimitry Andric assert(LI.liveAt(BaseIndex) &&
3648f0fd8f6SDimitry Andric "Reads of completely dead register should be marked undef already");
3658f0fd8f6SDimitry Andric unsigned SubRegIdx = MO.getSubReg();
366d88c1a5aSDimitry Andric assert(SubRegIdx != 0 && LI.hasSubRanges());
3677d523365SDimitry Andric LaneBitmask UseMask = TRI->getSubRegIndexLaneMask(SubRegIdx);
3688f0fd8f6SDimitry Andric // See if any of the relevant subregister liveranges is defined at this point.
3698f0fd8f6SDimitry Andric for (const LiveInterval::SubRange &SR : LI.subranges()) {
370d88c1a5aSDimitry Andric if ((SR.LaneMask & UseMask).any() && SR.liveAt(BaseIndex))
3718f0fd8f6SDimitry Andric return false;
3728f0fd8f6SDimitry Andric }
3738f0fd8f6SDimitry Andric return true;
3748f0fd8f6SDimitry Andric }
3758f0fd8f6SDimitry Andric
handleIdentityCopy(MachineInstr & MI) const3763ca95b02SDimitry Andric void VirtRegRewriter::handleIdentityCopy(MachineInstr &MI) const {
3773ca95b02SDimitry Andric if (!MI.isIdentityCopy())
3783ca95b02SDimitry Andric return;
3794ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "Identity copy: " << MI);
3803ca95b02SDimitry Andric ++NumIdCopies;
3813ca95b02SDimitry Andric
3823ca95b02SDimitry Andric // Copies like:
3832cab237bSDimitry Andric // %r0 = COPY undef %r0
3842cab237bSDimitry Andric // %al = COPY %al, implicit-def %eax
3853ca95b02SDimitry Andric // give us additional liveness information: The target (super-)register
3863ca95b02SDimitry Andric // must not be valid before this point. Replace the COPY with a KILL
3873ca95b02SDimitry Andric // instruction to maintain this information.
3883ca95b02SDimitry Andric if (MI.getOperand(0).isUndef() || MI.getNumOperands() > 2) {
3893ca95b02SDimitry Andric MI.setDesc(TII->get(TargetOpcode::KILL));
3904ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << " replace by: " << MI);
3913ca95b02SDimitry Andric return;
3923ca95b02SDimitry Andric }
3933ca95b02SDimitry Andric
3943ca95b02SDimitry Andric if (Indexes)
3957a7e6055SDimitry Andric Indexes->removeSingleMachineInstrFromMaps(MI);
3967a7e6055SDimitry Andric MI.eraseFromBundle();
3974ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << " deleted.\n");
3983ca95b02SDimitry Andric }
3993ca95b02SDimitry Andric
4007a7e6055SDimitry Andric /// The liverange splitting logic sometimes produces bundles of copies when
4017a7e6055SDimitry Andric /// subregisters are involved. Expand these into a sequence of copy instructions
4027a7e6055SDimitry Andric /// after processing the last in the bundle. Does not update LiveIntervals
4037a7e6055SDimitry Andric /// which we shouldn't need for this instruction anymore.
expandCopyBundle(MachineInstr & MI) const4047a7e6055SDimitry Andric void VirtRegRewriter::expandCopyBundle(MachineInstr &MI) const {
4057a7e6055SDimitry Andric if (!MI.isCopy())
4067a7e6055SDimitry Andric return;
4077a7e6055SDimitry Andric
4087a7e6055SDimitry Andric if (MI.isBundledWithPred() && !MI.isBundledWithSucc()) {
4094ba319b5SDimitry Andric SmallVector<MachineInstr *, 2> MIs({&MI});
4104ba319b5SDimitry Andric
4117a7e6055SDimitry Andric // Only do this when the complete bundle is made out of COPYs.
4127a7e6055SDimitry Andric MachineBasicBlock &MBB = *MI.getParent();
4137a7e6055SDimitry Andric for (MachineBasicBlock::reverse_instr_iterator I =
4147a7e6055SDimitry Andric std::next(MI.getReverseIterator()), E = MBB.instr_rend();
4157a7e6055SDimitry Andric I != E && I->isBundledWithSucc(); ++I) {
4167a7e6055SDimitry Andric if (!I->isCopy())
4177a7e6055SDimitry Andric return;
4184ba319b5SDimitry Andric MIs.push_back(&*I);
4194ba319b5SDimitry Andric }
4204ba319b5SDimitry Andric MachineInstr *FirstMI = MIs.back();
4214ba319b5SDimitry Andric
4224ba319b5SDimitry Andric auto anyRegsAlias = [](const MachineInstr *Dst,
4234ba319b5SDimitry Andric ArrayRef<MachineInstr *> Srcs,
4244ba319b5SDimitry Andric const TargetRegisterInfo *TRI) {
4254ba319b5SDimitry Andric for (const MachineInstr *Src : Srcs)
4264ba319b5SDimitry Andric if (Src != Dst)
4274ba319b5SDimitry Andric if (TRI->regsOverlap(Dst->getOperand(0).getReg(),
4284ba319b5SDimitry Andric Src->getOperand(1).getReg()))
4294ba319b5SDimitry Andric return true;
4304ba319b5SDimitry Andric return false;
4314ba319b5SDimitry Andric };
4324ba319b5SDimitry Andric
4334ba319b5SDimitry Andric // If any of the destination registers in the bundle of copies alias any of
4344ba319b5SDimitry Andric // the source registers, try to schedule the instructions to avoid any
4354ba319b5SDimitry Andric // clobbering.
4364ba319b5SDimitry Andric for (int E = MIs.size(), PrevE = E; E > 1; PrevE = E) {
4374ba319b5SDimitry Andric for (int I = E; I--; )
4384ba319b5SDimitry Andric if (!anyRegsAlias(MIs[I], makeArrayRef(MIs).take_front(E), TRI)) {
4394ba319b5SDimitry Andric if (I + 1 != E)
4404ba319b5SDimitry Andric std::swap(MIs[I], MIs[E - 1]);
4414ba319b5SDimitry Andric --E;
4424ba319b5SDimitry Andric }
4434ba319b5SDimitry Andric if (PrevE == E) {
4444ba319b5SDimitry Andric MF->getFunction().getContext().emitError(
4454ba319b5SDimitry Andric "register rewriting failed: cycle in copy bundle");
4464ba319b5SDimitry Andric break;
4474ba319b5SDimitry Andric }
4487a7e6055SDimitry Andric }
4497a7e6055SDimitry Andric
4504ba319b5SDimitry Andric MachineInstr *BundleStart = FirstMI;
4514ba319b5SDimitry Andric for (MachineInstr *BundledMI : llvm::reverse(MIs)) {
4524ba319b5SDimitry Andric // If instruction is in the middle of the bundle, move it before the
4534ba319b5SDimitry Andric // bundle starts, otherwise, just unbundle it. When we get to the last
4544ba319b5SDimitry Andric // instruction, the bundle will have been completely undone.
4554ba319b5SDimitry Andric if (BundledMI != BundleStart) {
4564ba319b5SDimitry Andric BundledMI->removeFromBundle();
4574ba319b5SDimitry Andric MBB.insert(FirstMI, BundledMI);
4584ba319b5SDimitry Andric } else if (BundledMI->isBundledWithSucc()) {
4594ba319b5SDimitry Andric BundledMI->unbundleFromSucc();
4604ba319b5SDimitry Andric BundleStart = &*std::next(BundledMI->getIterator());
4614ba319b5SDimitry Andric }
4627a7e6055SDimitry Andric
4634ba319b5SDimitry Andric if (Indexes && BundledMI != FirstMI)
4644ba319b5SDimitry Andric Indexes->insertMachineInstrInMaps(*BundledMI);
4657a7e6055SDimitry Andric }
4667a7e6055SDimitry Andric }
4677a7e6055SDimitry Andric }
4687a7e6055SDimitry Andric
4690554abf0SDimitry Andric /// Check whether (part of) \p SuperPhysReg is live through \p MI.
4700554abf0SDimitry Andric /// \pre \p MI defines a subregister of a virtual register that
4710554abf0SDimitry Andric /// has been assigned to \p SuperPhysReg.
subRegLiveThrough(const MachineInstr & MI,unsigned SuperPhysReg) const4720554abf0SDimitry Andric bool VirtRegRewriter::subRegLiveThrough(const MachineInstr &MI,
4730554abf0SDimitry Andric unsigned SuperPhysReg) const {
4740554abf0SDimitry Andric SlotIndex MIIndex = LIS->getInstructionIndex(MI);
4750554abf0SDimitry Andric SlotIndex BeforeMIUses = MIIndex.getBaseIndex();
4760554abf0SDimitry Andric SlotIndex AfterMIDefs = MIIndex.getBoundaryIndex();
4770554abf0SDimitry Andric for (MCRegUnitIterator Unit(SuperPhysReg, TRI); Unit.isValid(); ++Unit) {
4780554abf0SDimitry Andric const LiveRange &UnitRange = LIS->getRegUnit(*Unit);
4790554abf0SDimitry Andric // If the regunit is live both before and after MI,
4800554abf0SDimitry Andric // we assume it is live through.
4810554abf0SDimitry Andric // Generally speaking, this is not true, because something like
4820554abf0SDimitry Andric // "RU = op RU" would match that description.
4830554abf0SDimitry Andric // However, we know that we are trying to assess whether
4840554abf0SDimitry Andric // a def of a virtual reg, vreg, is live at the same time of RU.
4850554abf0SDimitry Andric // If we are in the "RU = op RU" situation, that means that vreg
4860554abf0SDimitry Andric // is defined at the same time as RU (i.e., "vreg, RU = op RU").
4870554abf0SDimitry Andric // Thus, vreg and RU interferes and vreg cannot be assigned to
4880554abf0SDimitry Andric // SuperPhysReg. Therefore, this situation cannot happen.
4890554abf0SDimitry Andric if (UnitRange.liveAt(AfterMIDefs) && UnitRange.liveAt(BeforeMIUses))
4900554abf0SDimitry Andric return true;
4910554abf0SDimitry Andric }
4920554abf0SDimitry Andric return false;
4930554abf0SDimitry Andric }
4940554abf0SDimitry Andric
rewrite()4957ae0e2c9SDimitry Andric void VirtRegRewriter::rewrite() {
496ff0cc061SDimitry Andric bool NoSubRegLiveness = !MRI->subRegLivenessEnabled();
4973b0f4066SDimitry Andric SmallVector<unsigned, 8> SuperDeads;
4983b0f4066SDimitry Andric SmallVector<unsigned, 8> SuperDefs;
4992754fe60SDimitry Andric SmallVector<unsigned, 8> SuperKills;
50091bc56edSDimitry Andric
5012754fe60SDimitry Andric for (MachineFunction::iterator MBBI = MF->begin(), MBBE = MF->end();
5022754fe60SDimitry Andric MBBI != MBBE; ++MBBI) {
5034ba319b5SDimitry Andric LLVM_DEBUG(MBBI->print(dbgs(), Indexes));
504dff0c46cSDimitry Andric for (MachineBasicBlock::instr_iterator
505dff0c46cSDimitry Andric MII = MBBI->instr_begin(), MIE = MBBI->instr_end(); MII != MIE;) {
5067d523365SDimitry Andric MachineInstr *MI = &*MII;
5072754fe60SDimitry Andric ++MII;
5082754fe60SDimitry Andric
5092754fe60SDimitry Andric for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
5102754fe60SDimitry Andric MOE = MI->operands_end(); MOI != MOE; ++MOI) {
5112754fe60SDimitry Andric MachineOperand &MO = *MOI;
512dff0c46cSDimitry Andric
513dff0c46cSDimitry Andric // Make sure MRI knows about registers clobbered by regmasks.
514dff0c46cSDimitry Andric if (MO.isRegMask())
515dff0c46cSDimitry Andric MRI->addPhysRegsUsedFromRegMask(MO.getRegMask());
516dff0c46cSDimitry Andric
5172754fe60SDimitry Andric if (!MO.isReg() || !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
5182754fe60SDimitry Andric continue;
5192754fe60SDimitry Andric unsigned VirtReg = MO.getReg();
5207ae0e2c9SDimitry Andric unsigned PhysReg = VRM->getPhys(VirtReg);
5217ae0e2c9SDimitry Andric assert(PhysReg != VirtRegMap::NO_PHYS_REG &&
5227ae0e2c9SDimitry Andric "Instruction uses unmapped VirtReg");
5233861d79fSDimitry Andric assert(!MRI->isReserved(PhysReg) && "Reserved register assignment");
5242754fe60SDimitry Andric
5252754fe60SDimitry Andric // Preserve semantics of sub-register operands.
5268f0fd8f6SDimitry Andric unsigned SubReg = MO.getSubReg();
5278f0fd8f6SDimitry Andric if (SubReg != 0) {
528*b5893f02SDimitry Andric if (NoSubRegLiveness || !MRI->shouldTrackSubRegLiveness(VirtReg)) {
5292754fe60SDimitry Andric // A virtual register kill refers to the whole register, so we may
5302cab237bSDimitry Andric // have to add implicit killed operands for the super-register. A
5316122f3e6SDimitry Andric // partial redef always kills and redefines the super-register.
5320554abf0SDimitry Andric if ((MO.readsReg() && (MO.isDef() || MO.isKill())) ||
5330554abf0SDimitry Andric (MO.isDef() && subRegLiveThrough(*MI, PhysReg)))
5342754fe60SDimitry Andric SuperKills.push_back(PhysReg);
5356122f3e6SDimitry Andric
5366122f3e6SDimitry Andric if (MO.isDef()) {
5376122f3e6SDimitry Andric // Also add implicit defs for the super-register.
5386122f3e6SDimitry Andric if (MO.isDead())
5393b0f4066SDimitry Andric SuperDeads.push_back(PhysReg);
5403b0f4066SDimitry Andric else
5413b0f4066SDimitry Andric SuperDefs.push_back(PhysReg);
5426122f3e6SDimitry Andric }
5438f0fd8f6SDimitry Andric } else {
5448f0fd8f6SDimitry Andric if (MO.isUse()) {
5458f0fd8f6SDimitry Andric if (readsUndefSubreg(MO))
5468f0fd8f6SDimitry Andric // We need to add an <undef> flag if the subregister is
5478f0fd8f6SDimitry Andric // completely undefined (and we are not adding super-register
5488f0fd8f6SDimitry Andric // defs).
5498f0fd8f6SDimitry Andric MO.setIsUndef(true);
5508f0fd8f6SDimitry Andric } else if (!MO.isDead()) {
5518f0fd8f6SDimitry Andric assert(MO.isDef());
5528f0fd8f6SDimitry Andric }
55339d628a0SDimitry Andric }
5542754fe60SDimitry Andric
5552cab237bSDimitry Andric // The def undef and def internal flags only make sense for
5567a7e6055SDimitry Andric // sub-register defs, and we are substituting a full physreg. An
5572cab237bSDimitry Andric // implicit killed operand from the SuperKills list will represent the
5587a7e6055SDimitry Andric // partial read of the super-register.
5597a7e6055SDimitry Andric if (MO.isDef()) {
5608f0fd8f6SDimitry Andric MO.setIsUndef(false);
5617a7e6055SDimitry Andric MO.setIsInternalRead(false);
5627a7e6055SDimitry Andric }
5638f0fd8f6SDimitry Andric
5642754fe60SDimitry Andric // PhysReg operands cannot have subregister indexes.
5658f0fd8f6SDimitry Andric PhysReg = TRI->getSubReg(PhysReg, SubReg);
5662754fe60SDimitry Andric assert(PhysReg && "Invalid SubReg for physical register");
5672754fe60SDimitry Andric MO.setSubReg(0);
5682754fe60SDimitry Andric }
5692754fe60SDimitry Andric // Rewrite. Note we could have used MachineOperand::substPhysReg(), but
5702754fe60SDimitry Andric // we need the inlining here.
5712754fe60SDimitry Andric MO.setReg(PhysReg);
5724ba319b5SDimitry Andric MO.setIsRenamable(true);
5732754fe60SDimitry Andric }
5742754fe60SDimitry Andric
5752754fe60SDimitry Andric // Add any missing super-register kills after rewriting the whole
5762754fe60SDimitry Andric // instruction.
5772754fe60SDimitry Andric while (!SuperKills.empty())
5782754fe60SDimitry Andric MI->addRegisterKilled(SuperKills.pop_back_val(), TRI, true);
5792754fe60SDimitry Andric
5803b0f4066SDimitry Andric while (!SuperDeads.empty())
5813b0f4066SDimitry Andric MI->addRegisterDead(SuperDeads.pop_back_val(), TRI, true);
5823b0f4066SDimitry Andric
5833b0f4066SDimitry Andric while (!SuperDefs.empty())
5843b0f4066SDimitry Andric MI->addRegisterDefined(SuperDefs.pop_back_val(), TRI);
5853b0f4066SDimitry Andric
5864ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "> " << *MI);
5872754fe60SDimitry Andric
5887a7e6055SDimitry Andric expandCopyBundle(*MI);
5897a7e6055SDimitry Andric
5903ca95b02SDimitry Andric // We can remove identity copies right now.
5913ca95b02SDimitry Andric handleIdentityCopy(*MI);
5922754fe60SDimitry Andric }
5932754fe60SDimitry Andric }
5942754fe60SDimitry Andric }
595