38 #include "llvm/Config/llvm-config.h" 50 #define DEBUG_TYPE "regalloc" 52 STATISTIC(NumSpillSlots,
"Number of spill slots allocated");
53 STATISTIC(NumIdCopies,
"Number of identity moves eliminated after rewriting");
64 MRI = &mf.getRegInfo();
65 TII = mf.getSubtarget().getInstrInfo();
66 TRI = mf.getSubtarget().getRegisterInfo();
70 Virt2StackSlotMap.clear();
71 Virt2SplitMap.clear();
79 Virt2PhysMap.resize(NumRegs);
80 Virt2StackSlotMap.resize(NumRegs);
81 Virt2SplitMap.resize(NumRegs);
88 "attempt to assign physical register to already mapped " 91 "Attempt to map virtReg to a reserved physReg");
92 Virt2PhysMap[virtReg] = physReg;
109 return getPhys(VirtReg) == Hint;
124 "attempt to assign stack slot to already spilled register");
126 return Virt2StackSlotMap[virtReg] = createSpillSlot(RC);
132 "attempt to assign stack slot to already spilled register");
135 "illegal fixed frame index");
136 Virt2StackSlotMap[virtReg] = SS;
140 OS <<
"********** REGISTER MAP **********\n";
144 OS <<
'[' <<
printReg(Reg, TRI) <<
" -> " 145 <<
printReg(Virt2PhysMap[Reg], TRI) <<
"] " 153 OS <<
'[' <<
printReg(Reg, TRI) <<
" -> fi#" << Virt2StackSlotMap[
Reg]
160 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 187 void addMBBLiveIns();
189 void addLiveInsForSubRanges(
const LiveInterval &LI,
unsigned PhysReg)
const;
192 bool subRegLiveThrough(
const MachineInstr &MI,
unsigned SuperPhysReg)
const;
216 "Virtual Register Rewriter",
false,
false)
226 AU.setPreservesCFG();
239 TRI = MF->getSubtarget().getRegisterInfo();
240 TII = MF->getSubtarget().getInstrInfo();
241 MRI = &MF->getRegInfo();
242 Indexes = &getAnalysis<SlotIndexes>();
243 LIS = &getAnalysis<LiveIntervals>();
244 VRM = &getAnalysis<VirtRegMap>();
245 LLVM_DEBUG(
dbgs() <<
"********** REWRITE VIRTUAL REGISTERS **********\n" 246 <<
"********** Function: " << MF->getName() <<
'\n');
250 LIS->addKillFlags(VRM);
259 getAnalysis<LiveDebugVariables>().emitDebugValues(VRM);
264 MRI->clearVirtRegs();
268 void VirtRegRewriter::addLiveInsForSubRanges(
const LiveInterval &LI,
269 unsigned PhysReg)
const {
273 using SubRangeIteratorPair =
274 std::pair<const LiveInterval::SubRange *, LiveInterval::const_iterator>;
280 SubRanges.
push_back(std::make_pair(&SR, SR.begin()));
281 if (!First.
isValid() || SR.segments.front().start < First)
282 First = SR.segments.front().start;
283 if (!Last.
isValid() || SR.segments.back().end > Last)
284 Last = SR.segments.back().end;
290 MBBI != Indexes->MBBIndexEnd() && MBBI->first <= Last; ++MBBI) {
295 for (
auto &RangeIterPair : SubRanges) {
298 while (SRI != SR->
end() && SRI->end <= MBBBegin)
300 if (SRI == SR->
end())
302 if (SRI->start <= MBBBegin)
314 void VirtRegRewriter::addMBBLiveIns() {
315 for (
unsigned Idx = 0, IdxE =
MRI->getNumVirtRegs(); Idx != IdxE; ++Idx) {
317 if (
MRI->reg_nodbg_empty(VirtReg))
320 if (LI.
empty() || LIS->intervalIsInOneMBB(LI))
324 unsigned PhysReg = VRM->getPhys(VirtReg);
328 addLiveInsForSubRanges(LI, PhysReg);
334 for (
const auto &Seg : LI) {
335 I = Indexes->advanceMBBIndex(I, Seg.start);
336 for (; I != Indexes->MBBIndexEnd() && I->first < Seg.end; ++
I) {
347 MBB.sortUniqueLiveIns();
352 bool VirtRegRewriter::readsUndefSubreg(
const MachineOperand &MO)
const {
360 SlotIndex BaseIndex = LIS->getInstructionIndex(MI);
364 "Reads of completely dead register should be marked undef already");
370 if ((SR.LaneMask & UseMask).any() && SR.liveAt(BaseIndex))
376 void VirtRegRewriter::handleIdentityCopy(
MachineInstr &
MI)
const {
395 Indexes->removeSingleMachineInstrFromMaps(MI);
404 void VirtRegRewriter::expandCopyBundle(
MachineInstr &MI)
const {
415 I !=
E &&
I->isBundledWithSucc(); ++
I) {
428 Src->getOperand(1).getReg()))
436 for (
int E = MIs.size(), PrevE =
E;
E > 1; PrevE =
E) {
437 for (
int I =
E;
I--; )
444 MF->getFunction().getContext().emitError(
445 "register rewriting failed: cycle in copy bundle");
455 if (BundledMI != BundleStart) {
457 MBB.
insert(FirstMI, BundledMI);
458 }
else if (BundledMI->isBundledWithSucc()) {
459 BundledMI->unbundleFromSucc();
460 BundleStart = &*std::next(BundledMI->getIterator());
463 if (Indexes && BundledMI != FirstMI)
464 Indexes->insertMachineInstrInMaps(*BundledMI);
472 bool VirtRegRewriter::subRegLiveThrough(
const MachineInstr &MI,
473 unsigned SuperPhysReg)
const {
474 SlotIndex MIIndex = LIS->getInstructionIndex(MI);
489 if (UnitRange.
liveAt(AfterMIDefs) && UnitRange.
liveAt(BeforeMIUses))
495 void VirtRegRewriter::rewrite() {
496 bool NoSubRegLiveness = !
MRI->subRegLivenessEnabled();
502 MBBI != MBBE; ++MBBI) {
505 MII = MBBI->instr_begin(), MIE = MBBI->instr_end(); MII != MIE;) {
519 unsigned VirtReg = MO.
getReg();
520 unsigned PhysReg = VRM->getPhys(VirtReg);
522 "Instruction uses unmapped VirtReg");
523 assert(!
MRI->isReserved(PhysReg) &&
"Reserved register assignment");
528 if (NoSubRegLiveness || !
MRI->shouldTrackSubRegLiveness(VirtReg)) {
533 (MO.
isDef() && subRegLiveThrough(*MI, PhysReg)))
545 if (readsUndefSubreg(MO))
550 }
else if (!MO.
isDead()) {
565 PhysReg =
TRI->getSubReg(PhysReg, SubReg);
566 assert(PhysReg &&
"Invalid SubReg for physical register");
577 while (!SuperKills.
empty())
580 while (!SuperDeads.
empty())
583 while (!SuperDefs.
empty())
588 expandCopyBundle(*MI);
591 handleIdentityCopy(*MI);
bool isRegMask() const
isRegMask - Tests if this is a MO_RegisterMask operand.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
mop_iterator operands_end()
A common definition of LaneBitmask for use in TableGen and CodeGen.
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
const TargetRegisterClass * getRegClass(unsigned Reg) const
Return the register class of the specified virtual register.
SlotIndex getBaseIndex() const
Returns the base index for associated with this index.
This class represents lattice values for constants.
static unsigned index2VirtReg(unsigned Index)
Convert a 0-based index to a virtual register number.
A Module instance is used to store all the information related to an LLVM module. ...
bool addRegisterDead(unsigned Reg, const TargetRegisterInfo *RegInfo, bool AddIfNotFound=false)
We have determined MI defined a register without a use.
bool isBundledWithPred() const
Return true if this instruction is part of a bundle, and it is not the first instruction in the bundl...
void push_back(const T &Elt)
LiveInterval - This class represents the liveness of a register, or stack slot.
unsigned getReg() const
getReg - Returns the register number.
void setIsUndef(bool Val=true)
static bool isVirtualRegister(unsigned Reg)
Return true if the specified register number is in the virtual register namespace.
unsigned getSubReg() const
void print(raw_ostream &OS, const Module *M=nullptr) const override
print - Print out the internal state of the pass.
A live range for subregisters.
bool isValid() const
Returns true if this is a valid index.
STATISTIC(NumFunctions, "Total number of functions")
unsigned const TargetRegisterInfo * TRI
void setIsRenamable(bool Val=true)
unsigned getSpillSize(const TargetRegisterClass &RC) const
Return the size in bytes of the stack slot allocated to hold a spilled copy of a register from class ...
This class represents the liveness of a register, stack slot, etc.
const char * getRegClassName(const TargetRegisterClass *Class) const
Returns the name of the register class.
unsigned getSpillAlignment(const TargetRegisterClass &RC) const
Return the minimum required alignment in bytes for a spill slot for a register of this class...
#define INITIALIZE_PASS_DEPENDENCY(depName)
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
const HexagonInstrInfo * TII
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
unsigned getNumOperands() const
Retuns the total number of operands.
Printable printReg(unsigned Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
bool isBundledWithSucc() const
Return true if this instruction is part of a bundle, and it is not the last instruction in the bundle...
iterator_range< subrange_iterator > subranges()
bool hasSubRanges() const
Returns true if subregister liveness information is available.
SmallVectorImpl< IdxMBBPair >::const_iterator MBBIndexIterator
Iterator over the idx2MBBMap (sorted pairs of slot index of basic block begin and basic block) ...
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
bool readsReg() const
readsReg - Returns true if this operand reads the previous value of its register. ...
bool isIdentityCopy() const
Return true is the instruction is an identity copy.
int getObjectIndexBegin() const
Return the minimum frame object index.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
TargetInstrInfo - Interface to description of machine instruction set.
void addLiveIn(MCPhysReg PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
unsigned const MachineRegisterInfo * MRI
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
bool liveAt(SlotIndex index) const
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MachineRegisterInfo & getRegInfo() const
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
bool hasPreferredPhys(unsigned VirtReg)
returns true if VirtReg is assigned to its preferred physreg.
bool runOnMachineFunction(MachineFunction &MF) override
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
Represent the analysis usage information of a pass.
constexpr bool none() const
void setIsInternalRead(bool Val=true)
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
unsigned getNumVirtRegs() const
getNumVirtRegs - Return the number of virtual registers created.
bool hasKnownPreference(unsigned VirtReg)
returns true if VirtReg has a known preferred register.
int CreateSpillStackObject(uint64_t Size, unsigned Alignment)
Create a new statically sized stack object that represents a spill slot, returning a nonnegative iden...
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
void eraseFromBundle()
Unlink 'this' form its basic block and delete it.
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
MachineInstr * removeFromBundle()
Unlink this instruction from its basic block and return it without deleting it.
Iterator for intrusive lists based on ilist_node.
void setDesc(const MCInstrDesc &tid)
Replace the instruction descriptor (thus opcode) of the current instruction with a new one...
void assignVirt2Phys(unsigned virtReg, MCPhysReg physReg)
creates a mapping for the specified virtual register to the specified physical register ...
Segments::const_iterator const_iterator
MachineOperand class - Representation of each machine instruction operand.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Promote Memory to Register
LLVM_NODISCARD T pop_back_val()
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
void addRegisterDefined(unsigned Reg, const TargetRegisterInfo *RegInfo=nullptr)
We have determined MI defines a register.
const uint32_t * getRegMask() const
getRegMask - Returns a bit mask of registers preserved by this RegMask operand.
iterator insert(iterator I, T &&Elt)
const MachineBasicBlock * getParent() const
MachineRegisterInfo - Keep track of information for virtual and physical registers, including vreg register classes, use/def chains for registers, etc.
MachineFunctionProperties & set(Property P)
Virtual Register Rewriter
Representation of each machine instruction.
static bool isPhysicalRegister(unsigned Reg)
Return true if the specified register number is in the physical register namespace.
std::pair< unsigned, unsigned > getRegAllocationHint(unsigned VReg) const
getRegAllocationHint - Return the register allocation hint for the specified virtual register...
reverse_self_iterator getReverseIterator()
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
LLVM_NODISCARD bool empty() const
void setReg(unsigned Reg)
Change the register this operand corresponds to.
void push_back(MachineInstr *MI)
void setSubReg(unsigned subReg)
bool hasPhys(unsigned virtReg) const
returns true if the specified virtual register is mapped to a physical register
virtual MachineFunctionProperties getSetProperties() const
unsigned getPhys(unsigned virtReg) const
returns the physical register mapped to the specified virtual register
bool isReg() const
isReg - Tests if this is a MO_Register operand.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
mop_iterator operands_begin()
char & VirtRegRewriterID
VirtRegRewriter pass.
MachineFunctionPass(char &ID)
This class implements an extremely fast bulk output stream that can only output to a stream...
int assignVirt2StackSlot(unsigned virtReg)
create a mapping for the specifed virtual register to the next available stack slot ...
bool addRegisterKilled(unsigned IncomingReg, const TargetRegisterInfo *RegInfo, bool AddIfNotFound=false)
We have determined MI kills a register.
unsigned getSimpleHint(unsigned VReg) const
getSimpleHint - same as getRegAllocationHint except it will only return a target independent hint...
const MachineOperand & getOperand(unsigned i) const
SlotIndex - An opaque wrapper around machine indexes.
SlotIndex getBoundaryIndex() const
Returns the boundary index for associated with this index.
Properties which a MachineFunction may have at a given point in time.
INITIALIZE_PASS_BEGIN(VirtRegRewriter, "virtregrewriter", "Virtual Register Rewriter", false, false) INITIALIZE_PASS_END(VirtRegRewriter