1 //===-- lib/Codegen/MachineRegisterInfo.cpp -------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Implementation of the MachineRegisterInfo class.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/CodeGen/MachineRegisterInfo.h"
15 #include "llvm/CodeGen/MachineInstrBuilder.h"
16 #include "llvm/IR/Function.h"
17 #include "llvm/Support/raw_os_ostream.h"
18 #include "llvm/Target/TargetInstrInfo.h"
19 #include "llvm/Target/TargetMachine.h"
20 #include "llvm/Target/TargetSubtargetInfo.h"
24 // Pin the vtable to this file.
25 void MachineRegisterInfo::Delegate::anchor() {}
27 MachineRegisterInfo::MachineRegisterInfo(const MachineFunction *MF)
28 : MF(MF), TheDelegate(nullptr), IsSSA(true), TracksLiveness(true),
29 TracksSubRegLiveness(false) {
30 VRegInfo.reserve(256);
31 RegAllocHints.reserve(256);
32 UsedRegUnits.resize(getTargetRegisterInfo()->getNumRegUnits());
33 UsedPhysRegMask.resize(getTargetRegisterInfo()->getNumRegs());
35 // Create the physreg use/def lists.
36 PhysRegUseDefLists.resize(getTargetRegisterInfo()->getNumRegs(), nullptr);
39 /// setRegClass - Set the register class of the specified virtual register.
42 MachineRegisterInfo::setRegClass(unsigned Reg, const TargetRegisterClass *RC) {
43 assert(RC && RC->isAllocatable() && "Invalid RC for virtual register");
44 VRegInfo[Reg].first = RC;
47 const TargetRegisterClass *
48 MachineRegisterInfo::constrainRegClass(unsigned Reg,
49 const TargetRegisterClass *RC,
50 unsigned MinNumRegs) {
51 const TargetRegisterClass *OldRC = getRegClass(Reg);
54 const TargetRegisterClass *NewRC =
55 getTargetRegisterInfo()->getCommonSubClass(OldRC, RC);
56 if (!NewRC || NewRC == OldRC)
58 if (NewRC->getNumRegs() < MinNumRegs)
60 setRegClass(Reg, NewRC);
65 MachineRegisterInfo::recomputeRegClass(unsigned Reg) {
66 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
67 const TargetRegisterClass *OldRC = getRegClass(Reg);
68 const TargetRegisterClass *NewRC =
69 getTargetRegisterInfo()->getLargestLegalSuperClass(OldRC, *MF);
71 // Stop early if there is no room to grow.
75 // Accumulate constraints from all uses.
76 for (MachineOperand &MO : reg_nodbg_operands(Reg)) {
77 // Apply the effect of the given operand to NewRC.
78 MachineInstr *MI = MO.getParent();
79 unsigned OpNo = &MO - &MI->getOperand(0);
80 NewRC = MI->getRegClassConstraintEffect(OpNo, NewRC, TII,
81 getTargetRegisterInfo());
82 if (!NewRC || NewRC == OldRC)
85 setRegClass(Reg, NewRC);
89 /// createVirtualRegister - Create and return a new virtual register in the
90 /// function with the specified register class.
93 MachineRegisterInfo::createVirtualRegister(const TargetRegisterClass *RegClass){
94 assert(RegClass && "Cannot create register without RegClass!");
95 assert(RegClass->isAllocatable() &&
96 "Virtual register RegClass must be allocatable.");
98 // New virtual register number.
99 unsigned Reg = TargetRegisterInfo::index2VirtReg(getNumVirtRegs());
101 VRegInfo[Reg].first = RegClass;
102 RegAllocHints.grow(Reg);
104 TheDelegate->MRI_NoteNewVirtualRegister(Reg);
108 /// clearVirtRegs - Remove all virtual registers (after physreg assignment).
109 void MachineRegisterInfo::clearVirtRegs() {
111 for (unsigned i = 0, e = getNumVirtRegs(); i != e; ++i) {
112 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
113 if (!VRegInfo[Reg].second)
116 llvm_unreachable("Remaining virtual register operands");
122 void MachineRegisterInfo::verifyUseList(unsigned Reg) const {
125 for (MachineOperand &M : reg_operands(Reg)) {
126 MachineOperand *MO = &M;
127 MachineInstr *MI = MO->getParent();
129 errs() << PrintReg(Reg, getTargetRegisterInfo())
130 << " use list MachineOperand " << MO
131 << " has no parent instruction.\n";
135 MachineOperand *MO0 = &MI->getOperand(0);
136 unsigned NumOps = MI->getNumOperands();
137 if (!(MO >= MO0 && MO < MO0+NumOps)) {
138 errs() << PrintReg(Reg, getTargetRegisterInfo())
139 << " use list MachineOperand " << MO
140 << " doesn't belong to parent MI: " << *MI;
144 errs() << PrintReg(Reg, getTargetRegisterInfo())
145 << " MachineOperand " << MO << ": " << *MO
146 << " is not a register\n";
149 if (MO->getReg() != Reg) {
150 errs() << PrintReg(Reg, getTargetRegisterInfo())
151 << " use-list MachineOperand " << MO << ": "
152 << *MO << " is the wrong register\n";
156 assert(Valid && "Invalid use list");
160 void MachineRegisterInfo::verifyUseLists() const {
162 for (unsigned i = 0, e = getNumVirtRegs(); i != e; ++i)
163 verifyUseList(TargetRegisterInfo::index2VirtReg(i));
164 for (unsigned i = 1, e = getTargetRegisterInfo()->getNumRegs(); i != e; ++i)
169 /// Add MO to the linked list of operands for its register.
170 void MachineRegisterInfo::addRegOperandToUseList(MachineOperand *MO) {
171 assert(!MO->isOnRegUseList() && "Already on list");
172 MachineOperand *&HeadRef = getRegUseDefListHead(MO->getReg());
173 MachineOperand *const Head = HeadRef;
175 // Head points to the first list element.
176 // Next is NULL on the last list element.
177 // Prev pointers are circular, so Head->Prev == Last.
179 // Head is NULL for an empty list.
181 MO->Contents.Reg.Prev = MO;
182 MO->Contents.Reg.Next = nullptr;
186 assert(MO->getReg() == Head->getReg() && "Different regs on the same list!");
188 // Insert MO between Last and Head in the circular Prev chain.
189 MachineOperand *Last = Head->Contents.Reg.Prev;
190 assert(Last && "Inconsistent use list");
191 assert(MO->getReg() == Last->getReg() && "Different regs on the same list!");
192 Head->Contents.Reg.Prev = MO;
193 MO->Contents.Reg.Prev = Last;
195 // Def operands always precede uses. This allows def_iterator to stop early.
196 // Insert def operands at the front, and use operands at the back.
198 // Insert def at the front.
199 MO->Contents.Reg.Next = Head;
202 // Insert use at the end.
203 MO->Contents.Reg.Next = nullptr;
204 Last->Contents.Reg.Next = MO;
208 /// Remove MO from its use-def list.
209 void MachineRegisterInfo::removeRegOperandFromUseList(MachineOperand *MO) {
210 assert(MO->isOnRegUseList() && "Operand not on use list");
211 MachineOperand *&HeadRef = getRegUseDefListHead(MO->getReg());
212 MachineOperand *const Head = HeadRef;
213 assert(Head && "List already empty");
215 // Unlink this from the doubly linked list of operands.
216 MachineOperand *Next = MO->Contents.Reg.Next;
217 MachineOperand *Prev = MO->Contents.Reg.Prev;
219 // Prev links are circular, next link is NULL instead of looping back to Head.
223 Prev->Contents.Reg.Next = Next;
225 (Next ? Next : Head)->Contents.Reg.Prev = Prev;
227 MO->Contents.Reg.Prev = nullptr;
228 MO->Contents.Reg.Next = nullptr;
231 /// Move NumOps operands from Src to Dst, updating use-def lists as needed.
233 /// The Dst range is assumed to be uninitialized memory. (Or it may contain
234 /// operands that won't be destroyed, which is OK because the MO destructor is
237 /// The Src and Dst ranges may overlap.
238 void MachineRegisterInfo::moveOperands(MachineOperand *Dst,
241 assert(Src != Dst && NumOps && "Noop moveOperands");
243 // Copy backwards if Dst is within the Src range.
245 if (Dst >= Src && Dst < Src + NumOps) {
251 // Copy one operand at a time.
253 new (Dst) MachineOperand(*Src);
255 // Dst takes Src's place in the use-def chain.
257 MachineOperand *&Head = getRegUseDefListHead(Src->getReg());
258 MachineOperand *Prev = Src->Contents.Reg.Prev;
259 MachineOperand *Next = Src->Contents.Reg.Next;
260 assert(Head && "List empty, but operand is chained");
261 assert(Prev && "Operand was not on use-def list");
263 // Prev links are circular, next link is NULL instead of looping back to
268 Prev->Contents.Reg.Next = Dst;
270 // Update Prev pointer. This also works when Src was pointing to itself
271 // in a 1-element list. In that case Head == Dst.
272 (Next ? Next : Head)->Contents.Reg.Prev = Dst;
280 /// replaceRegWith - Replace all instances of FromReg with ToReg in the
281 /// machine function. This is like llvm-level X->replaceAllUsesWith(Y),
282 /// except that it also changes any definitions of the register as well.
283 /// If ToReg is a physical register we apply the sub register to obtain the
284 /// final/proper physical register.
285 void MachineRegisterInfo::replaceRegWith(unsigned FromReg, unsigned ToReg) {
286 assert(FromReg != ToReg && "Cannot replace a reg with itself");
288 const TargetRegisterInfo *TRI = getTargetRegisterInfo();
290 // TODO: This could be more efficient by bulk changing the operands.
291 for (reg_iterator I = reg_begin(FromReg), E = reg_end(); I != E; ) {
292 MachineOperand &O = *I;
294 if (TargetRegisterInfo::isPhysicalRegister(ToReg)) {
295 O.substPhysReg(ToReg, *TRI);
302 /// getVRegDef - Return the machine instr that defines the specified virtual
303 /// register or null if none is found. This assumes that the code is in SSA
304 /// form, so there should only be one definition.
305 MachineInstr *MachineRegisterInfo::getVRegDef(unsigned Reg) const {
306 // Since we are in SSA form, we can use the first definition.
307 def_instr_iterator I = def_instr_begin(Reg);
308 assert((I.atEnd() || std::next(I) == def_instr_end()) &&
309 "getVRegDef assumes a single definition or no definition");
310 return !I.atEnd() ? &*I : nullptr;
313 /// getUniqueVRegDef - Return the unique machine instr that defines the
314 /// specified virtual register or null if none is found. If there are
315 /// multiple definitions or no definition, return null.
316 MachineInstr *MachineRegisterInfo::getUniqueVRegDef(unsigned Reg) const {
317 if (def_empty(Reg)) return nullptr;
318 def_instr_iterator I = def_instr_begin(Reg);
319 if (std::next(I) != def_instr_end())
324 bool MachineRegisterInfo::hasOneNonDBGUse(unsigned RegNo) const {
325 use_nodbg_iterator UI = use_nodbg_begin(RegNo);
326 if (UI == use_nodbg_end())
328 return ++UI == use_nodbg_end();
331 /// clearKillFlags - Iterate over all the uses of the given register and
332 /// clear the kill flag from the MachineOperand. This function is used by
333 /// optimization passes which extend register lifetimes and need only
334 /// preserve conservative kill flag information.
335 void MachineRegisterInfo::clearKillFlags(unsigned Reg) const {
336 for (MachineOperand &MO : use_operands(Reg))
340 bool MachineRegisterInfo::isLiveIn(unsigned Reg) const {
341 for (livein_iterator I = livein_begin(), E = livein_end(); I != E; ++I)
342 if (I->first == Reg || I->second == Reg)
347 /// getLiveInPhysReg - If VReg is a live-in virtual register, return the
348 /// corresponding live-in physical register.
349 unsigned MachineRegisterInfo::getLiveInPhysReg(unsigned VReg) const {
350 for (livein_iterator I = livein_begin(), E = livein_end(); I != E; ++I)
351 if (I->second == VReg)
356 /// getLiveInVirtReg - If PReg is a live-in physical register, return the
357 /// corresponding live-in physical register.
358 unsigned MachineRegisterInfo::getLiveInVirtReg(unsigned PReg) const {
359 for (livein_iterator I = livein_begin(), E = livein_end(); I != E; ++I)
360 if (I->first == PReg)
365 /// EmitLiveInCopies - Emit copies to initialize livein virtual registers
366 /// into the given entry block.
368 MachineRegisterInfo::EmitLiveInCopies(MachineBasicBlock *EntryMBB,
369 const TargetRegisterInfo &TRI,
370 const TargetInstrInfo &TII) {
371 // Emit the copies into the top of the block.
372 for (unsigned i = 0, e = LiveIns.size(); i != e; ++i)
373 if (LiveIns[i].second) {
374 if (use_empty(LiveIns[i].second)) {
375 // The livein has no uses. Drop it.
377 // It would be preferable to have isel avoid creating live-in
378 // records for unused arguments in the first place, but it's
379 // complicated by the debug info code for arguments.
380 LiveIns.erase(LiveIns.begin() + i);
384 BuildMI(*EntryMBB, EntryMBB->begin(), DebugLoc(),
385 TII.get(TargetOpcode::COPY), LiveIns[i].second)
386 .addReg(LiveIns[i].first);
388 // Add the register to the entry block live-in set.
389 EntryMBB->addLiveIn(LiveIns[i].first);
392 // Add the register to the entry block live-in set.
393 EntryMBB->addLiveIn(LiveIns[i].first);
397 unsigned MachineRegisterInfo::getMaxLaneMaskForVReg(unsigned Reg) const
399 // Lane masks are only defined for vregs.
400 assert(TargetRegisterInfo::isVirtualRegister(Reg));
401 const TargetRegisterClass &TRC = *getRegClass(Reg);
402 return TRC.getLaneMask();
406 void MachineRegisterInfo::dumpUses(unsigned Reg) const {
407 for (MachineInstr &I : use_instructions(Reg))
412 void MachineRegisterInfo::freezeReservedRegs(const MachineFunction &MF) {
413 ReservedRegs = getTargetRegisterInfo()->getReservedRegs(MF);
414 assert(ReservedRegs.size() == getTargetRegisterInfo()->getNumRegs() &&
415 "Invalid ReservedRegs vector from target");
418 bool MachineRegisterInfo::isConstantPhysReg(unsigned PhysReg,
419 const MachineFunction &MF) const {
420 assert(TargetRegisterInfo::isPhysicalRegister(PhysReg));
422 // Check if any overlapping register is modified, or allocatable so it may be
424 for (MCRegAliasIterator AI(PhysReg, getTargetRegisterInfo(), true);
426 if (!def_empty(*AI) || isAllocatable(*AI))
431 /// markUsesInDebugValueAsUndef - Mark every DBG_VALUE referencing the
432 /// specified register as undefined which causes the DBG_VALUE to be
433 /// deleted during LiveDebugVariables analysis.
434 void MachineRegisterInfo::markUsesInDebugValueAsUndef(unsigned Reg) const {
435 // Mark any DBG_VALUE that uses Reg as undef (but don't delete it.)
436 MachineRegisterInfo::use_instr_iterator nextI;
437 for (use_instr_iterator I = use_instr_begin(Reg), E = use_instr_end();
439 nextI = std::next(I); // I is invalidated by the setReg
440 MachineInstr *UseMI = &*I;
441 if (UseMI->isDebugValue())
442 UseMI->getOperand(0).setReg(0U);
446 static const Function *getCalledFunction(const MachineInstr &MI) {
447 for (const MachineOperand &MO : MI.operands()) {
450 const Function *Func = dyn_cast<Function>(MO.getGlobal());
457 static bool isNoReturnDef(const MachineOperand &MO) {
458 // Anything which is not a noreturn function is a real def.
459 const MachineInstr &MI = *MO.getParent();
462 const MachineBasicBlock &MBB = *MI.getParent();
463 if (!MBB.succ_empty())
465 const MachineFunction &MF = *MBB.getParent();
466 // We need to keep correct unwind information even if the function will
467 // not return, since the runtime may need it.
468 if (MF.getFunction()->hasFnAttribute(Attribute::UWTable))
470 const Function *Called = getCalledFunction(MI);
471 if (Called == nullptr || !Called->hasFnAttribute(Attribute::NoReturn)
472 || !Called->hasFnAttribute(Attribute::NoUnwind))
478 bool MachineRegisterInfo::isPhysRegModified(unsigned PhysReg) const {
479 if (UsedPhysRegMask.test(PhysReg))
481 const TargetRegisterInfo *TRI = getTargetRegisterInfo();
482 for (MCRegAliasIterator AI(PhysReg, TRI, true); AI.isValid(); ++AI) {
483 for (const MachineOperand &MO : make_range(def_begin(*AI), def_end())) {
484 if (isNoReturnDef(MO))