1 //===-- lib/Codegen/MachineRegisterInfo.cpp -------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Implementation of the MachineRegisterInfo class.
11 //
12 //===----------------------------------------------------------------------===//
13 
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"
21 
22 using namespace llvm;
23 
24 // Pin the vtable to this file.
25 void MachineRegisterInfo::Delegate::anchor() {}
26 
27 MachineRegisterInfo::MachineRegisterInfo(const MachineFunction *MF)
28   : MF(MF), TheDelegate(nullptr), IsSSA(true), TracksLiveness(true),
29     TracksSubRegLiveness(false) {
30   unsigned NumRegs = getTargetRegisterInfo()->getNumRegs();
31   VRegInfo.reserve(256);
32   RegAllocHints.reserve(256);
33   UsedPhysRegMask.resize(NumRegs);
34   PhysRegUseDefLists.reset(new MachineOperand*[NumRegs]());
35 }
36 
37 /// setRegClass - Set the register class of the specified virtual register.
38 ///
39 void
40 MachineRegisterInfo::setRegClass(unsigned Reg, const TargetRegisterClass *RC) {
41   assert(RC && RC->isAllocatable() && "Invalid RC for virtual register");
42   VRegInfo[Reg].first = RC;
43 }
44 
45 const TargetRegisterClass *
46 MachineRegisterInfo::constrainRegClass(unsigned Reg,
47                                        const TargetRegisterClass *RC,
48                                        unsigned MinNumRegs) {
49   const TargetRegisterClass *OldRC = getRegClass(Reg);
50   if (OldRC == RC)
51     return RC;
52   const TargetRegisterClass *NewRC =
53     getTargetRegisterInfo()->getCommonSubClass(OldRC, RC);
54   if (!NewRC || NewRC == OldRC)
55     return NewRC;
56   if (NewRC->getNumRegs() < MinNumRegs)
57     return nullptr;
58   setRegClass(Reg, NewRC);
59   return NewRC;
60 }
61 
62 bool
63 MachineRegisterInfo::recomputeRegClass(unsigned Reg) {
64   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
65   const TargetRegisterClass *OldRC = getRegClass(Reg);
66   const TargetRegisterClass *NewRC =
67       getTargetRegisterInfo()->getLargestLegalSuperClass(OldRC, *MF);
68 
69   // Stop early if there is no room to grow.
70   if (NewRC == OldRC)
71     return false;
72 
73   // Accumulate constraints from all uses.
74   for (MachineOperand &MO : reg_nodbg_operands(Reg)) {
75     // Apply the effect of the given operand to NewRC.
76     MachineInstr *MI = MO.getParent();
77     unsigned OpNo = &MO - &MI->getOperand(0);
78     NewRC = MI->getRegClassConstraintEffect(OpNo, NewRC, TII,
79                                             getTargetRegisterInfo());
80     if (!NewRC || NewRC == OldRC)
81       return false;
82   }
83   setRegClass(Reg, NewRC);
84   return true;
85 }
86 
87 /// createVirtualRegister - Create and return a new virtual register in the
88 /// function with the specified register class.
89 ///
90 unsigned
91 MachineRegisterInfo::createVirtualRegister(const TargetRegisterClass *RegClass){
92   assert(RegClass && "Cannot create register without RegClass!");
93   assert(RegClass->isAllocatable() &&
94          "Virtual register RegClass must be allocatable.");
95 
96   // New virtual register number.
97   unsigned Reg = TargetRegisterInfo::index2VirtReg(getNumVirtRegs());
98   VRegInfo.grow(Reg);
99   VRegInfo[Reg].first = RegClass;
100   RegAllocHints.grow(Reg);
101   if (TheDelegate)
102     TheDelegate->MRI_NoteNewVirtualRegister(Reg);
103   return Reg;
104 }
105 
106 unsigned
107 MachineRegisterInfo::getSize(unsigned VReg) const {
108   VRegToSizeMap::const_iterator SizeIt = getVRegToSize().find(VReg);
109   return SizeIt != getVRegToSize().end() ? SizeIt->second : 0;
110 }
111 
112 void MachineRegisterInfo::setSize(unsigned VReg, unsigned Size) {
113   getVRegToSize()[VReg] = Size;
114 }
115 
116 unsigned
117 MachineRegisterInfo::createGenericVirtualRegister(unsigned Size) {
118   assert(Size && "Cannot create empty virtual register");
119 
120   // New virtual register number.
121   unsigned Reg = TargetRegisterInfo::index2VirtReg(getNumVirtRegs());
122   VRegInfo.grow(Reg);
123   // FIXME: Should we use a dummy register class?
124   VRegInfo[Reg].first = nullptr;
125   getVRegToSize()[Reg] = Size;
126   RegAllocHints.grow(Reg);
127   if (TheDelegate)
128     TheDelegate->MRI_NoteNewVirtualRegister(Reg);
129   return Reg;
130 }
131 
132 /// clearVirtRegs - Remove all virtual registers (after physreg assignment).
133 void MachineRegisterInfo::clearVirtRegs() {
134 #ifndef NDEBUG
135   for (unsigned i = 0, e = getNumVirtRegs(); i != e; ++i) {
136     unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
137     if (!VRegInfo[Reg].second)
138       continue;
139     verifyUseList(Reg);
140     llvm_unreachable("Remaining virtual register operands");
141   }
142 #endif
143   VRegInfo.clear();
144   for (auto &I : LiveIns)
145     I.second = 0;
146 }
147 
148 void MachineRegisterInfo::verifyUseList(unsigned Reg) const {
149 #ifndef NDEBUG
150   bool Valid = true;
151   for (MachineOperand &M : reg_operands(Reg)) {
152     MachineOperand *MO = &M;
153     MachineInstr *MI = MO->getParent();
154     if (!MI) {
155       errs() << PrintReg(Reg, getTargetRegisterInfo())
156              << " use list MachineOperand " << MO
157              << " has no parent instruction.\n";
158       Valid = false;
159       continue;
160     }
161     MachineOperand *MO0 = &MI->getOperand(0);
162     unsigned NumOps = MI->getNumOperands();
163     if (!(MO >= MO0 && MO < MO0+NumOps)) {
164       errs() << PrintReg(Reg, getTargetRegisterInfo())
165              << " use list MachineOperand " << MO
166              << " doesn't belong to parent MI: " << *MI;
167       Valid = false;
168     }
169     if (!MO->isReg()) {
170       errs() << PrintReg(Reg, getTargetRegisterInfo())
171              << " MachineOperand " << MO << ": " << *MO
172              << " is not a register\n";
173       Valid = false;
174     }
175     if (MO->getReg() != Reg) {
176       errs() << PrintReg(Reg, getTargetRegisterInfo())
177              << " use-list MachineOperand " << MO << ": "
178              << *MO << " is the wrong register\n";
179       Valid = false;
180     }
181   }
182   assert(Valid && "Invalid use list");
183 #endif
184 }
185 
186 void MachineRegisterInfo::verifyUseLists() const {
187 #ifndef NDEBUG
188   for (unsigned i = 0, e = getNumVirtRegs(); i != e; ++i)
189     verifyUseList(TargetRegisterInfo::index2VirtReg(i));
190   for (unsigned i = 1, e = getTargetRegisterInfo()->getNumRegs(); i != e; ++i)
191     verifyUseList(i);
192 #endif
193 }
194 
195 /// Add MO to the linked list of operands for its register.
196 void MachineRegisterInfo::addRegOperandToUseList(MachineOperand *MO) {
197   assert(!MO->isOnRegUseList() && "Already on list");
198   MachineOperand *&HeadRef = getRegUseDefListHead(MO->getReg());
199   MachineOperand *const Head = HeadRef;
200 
201   // Head points to the first list element.
202   // Next is NULL on the last list element.
203   // Prev pointers are circular, so Head->Prev == Last.
204 
205   // Head is NULL for an empty list.
206   if (!Head) {
207     MO->Contents.Reg.Prev = MO;
208     MO->Contents.Reg.Next = nullptr;
209     HeadRef = MO;
210     return;
211   }
212   assert(MO->getReg() == Head->getReg() && "Different regs on the same list!");
213 
214   // Insert MO between Last and Head in the circular Prev chain.
215   MachineOperand *Last = Head->Contents.Reg.Prev;
216   assert(Last && "Inconsistent use list");
217   assert(MO->getReg() == Last->getReg() && "Different regs on the same list!");
218   Head->Contents.Reg.Prev = MO;
219   MO->Contents.Reg.Prev = Last;
220 
221   // Def operands always precede uses. This allows def_iterator to stop early.
222   // Insert def operands at the front, and use operands at the back.
223   if (MO->isDef()) {
224     // Insert def at the front.
225     MO->Contents.Reg.Next = Head;
226     HeadRef = MO;
227   } else {
228     // Insert use at the end.
229     MO->Contents.Reg.Next = nullptr;
230     Last->Contents.Reg.Next = MO;
231   }
232 }
233 
234 /// Remove MO from its use-def list.
235 void MachineRegisterInfo::removeRegOperandFromUseList(MachineOperand *MO) {
236   assert(MO->isOnRegUseList() && "Operand not on use list");
237   MachineOperand *&HeadRef = getRegUseDefListHead(MO->getReg());
238   MachineOperand *const Head = HeadRef;
239   assert(Head && "List already empty");
240 
241   // Unlink this from the doubly linked list of operands.
242   MachineOperand *Next = MO->Contents.Reg.Next;
243   MachineOperand *Prev = MO->Contents.Reg.Prev;
244 
245   // Prev links are circular, next link is NULL instead of looping back to Head.
246   if (MO == Head)
247     HeadRef = Next;
248   else
249     Prev->Contents.Reg.Next = Next;
250 
251   (Next ? Next : Head)->Contents.Reg.Prev = Prev;
252 
253   MO->Contents.Reg.Prev = nullptr;
254   MO->Contents.Reg.Next = nullptr;
255 }
256 
257 /// Move NumOps operands from Src to Dst, updating use-def lists as needed.
258 ///
259 /// The Dst range is assumed to be uninitialized memory. (Or it may contain
260 /// operands that won't be destroyed, which is OK because the MO destructor is
261 /// trivial anyway).
262 ///
263 /// The Src and Dst ranges may overlap.
264 void MachineRegisterInfo::moveOperands(MachineOperand *Dst,
265                                        MachineOperand *Src,
266                                        unsigned NumOps) {
267   assert(Src != Dst && NumOps && "Noop moveOperands");
268 
269   // Copy backwards if Dst is within the Src range.
270   int Stride = 1;
271   if (Dst >= Src && Dst < Src + NumOps) {
272     Stride = -1;
273     Dst += NumOps - 1;
274     Src += NumOps - 1;
275   }
276 
277   // Copy one operand at a time.
278   do {
279     new (Dst) MachineOperand(*Src);
280 
281     // Dst takes Src's place in the use-def chain.
282     if (Src->isReg()) {
283       MachineOperand *&Head = getRegUseDefListHead(Src->getReg());
284       MachineOperand *Prev = Src->Contents.Reg.Prev;
285       MachineOperand *Next = Src->Contents.Reg.Next;
286       assert(Head && "List empty, but operand is chained");
287       assert(Prev && "Operand was not on use-def list");
288 
289       // Prev links are circular, next link is NULL instead of looping back to
290       // Head.
291       if (Src == Head)
292         Head = Dst;
293       else
294         Prev->Contents.Reg.Next = Dst;
295 
296       // Update Prev pointer. This also works when Src was pointing to itself
297       // in a 1-element list. In that case Head == Dst.
298       (Next ? Next : Head)->Contents.Reg.Prev = Dst;
299     }
300 
301     Dst += Stride;
302     Src += Stride;
303   } while (--NumOps);
304 }
305 
306 /// replaceRegWith - Replace all instances of FromReg with ToReg in the
307 /// machine function.  This is like llvm-level X->replaceAllUsesWith(Y),
308 /// except that it also changes any definitions of the register as well.
309 /// If ToReg is a physical register we apply the sub register to obtain the
310 /// final/proper physical register.
311 void MachineRegisterInfo::replaceRegWith(unsigned FromReg, unsigned ToReg) {
312   assert(FromReg != ToReg && "Cannot replace a reg with itself");
313 
314   const TargetRegisterInfo *TRI = getTargetRegisterInfo();
315 
316   // TODO: This could be more efficient by bulk changing the operands.
317   for (reg_iterator I = reg_begin(FromReg), E = reg_end(); I != E; ) {
318     MachineOperand &O = *I;
319     ++I;
320     if (TargetRegisterInfo::isPhysicalRegister(ToReg)) {
321       O.substPhysReg(ToReg, *TRI);
322     } else {
323       O.setReg(ToReg);
324     }
325   }
326 }
327 
328 /// getVRegDef - Return the machine instr that defines the specified virtual
329 /// register or null if none is found.  This assumes that the code is in SSA
330 /// form, so there should only be one definition.
331 MachineInstr *MachineRegisterInfo::getVRegDef(unsigned Reg) const {
332   // Since we are in SSA form, we can use the first definition.
333   def_instr_iterator I = def_instr_begin(Reg);
334   assert((I.atEnd() || std::next(I) == def_instr_end()) &&
335          "getVRegDef assumes a single definition or no definition");
336   return !I.atEnd() ? &*I : nullptr;
337 }
338 
339 /// getUniqueVRegDef - Return the unique machine instr that defines the
340 /// specified virtual register or null if none is found.  If there are
341 /// multiple definitions or no definition, return null.
342 MachineInstr *MachineRegisterInfo::getUniqueVRegDef(unsigned Reg) const {
343   if (def_empty(Reg)) return nullptr;
344   def_instr_iterator I = def_instr_begin(Reg);
345   if (std::next(I) != def_instr_end())
346     return nullptr;
347   return &*I;
348 }
349 
350 bool MachineRegisterInfo::hasOneNonDBGUse(unsigned RegNo) const {
351   use_nodbg_iterator UI = use_nodbg_begin(RegNo);
352   if (UI == use_nodbg_end())
353     return false;
354   return ++UI == use_nodbg_end();
355 }
356 
357 /// clearKillFlags - Iterate over all the uses of the given register and
358 /// clear the kill flag from the MachineOperand. This function is used by
359 /// optimization passes which extend register lifetimes and need only
360 /// preserve conservative kill flag information.
361 void MachineRegisterInfo::clearKillFlags(unsigned Reg) const {
362   for (MachineOperand &MO : use_operands(Reg))
363     MO.setIsKill(false);
364 }
365 
366 bool MachineRegisterInfo::isLiveIn(unsigned Reg) const {
367   for (livein_iterator I = livein_begin(), E = livein_end(); I != E; ++I)
368     if (I->first == Reg || I->second == Reg)
369       return true;
370   return false;
371 }
372 
373 /// getLiveInPhysReg - If VReg is a live-in virtual register, return the
374 /// corresponding live-in physical register.
375 unsigned MachineRegisterInfo::getLiveInPhysReg(unsigned VReg) const {
376   for (livein_iterator I = livein_begin(), E = livein_end(); I != E; ++I)
377     if (I->second == VReg)
378       return I->first;
379   return 0;
380 }
381 
382 /// getLiveInVirtReg - If PReg is a live-in physical register, return the
383 /// corresponding live-in physical register.
384 unsigned MachineRegisterInfo::getLiveInVirtReg(unsigned PReg) const {
385   for (livein_iterator I = livein_begin(), E = livein_end(); I != E; ++I)
386     if (I->first == PReg)
387       return I->second;
388   return 0;
389 }
390 
391 /// EmitLiveInCopies - Emit copies to initialize livein virtual registers
392 /// into the given entry block.
393 void
394 MachineRegisterInfo::EmitLiveInCopies(MachineBasicBlock *EntryMBB,
395                                       const TargetRegisterInfo &TRI,
396                                       const TargetInstrInfo &TII) {
397   // Emit the copies into the top of the block.
398   for (unsigned i = 0, e = LiveIns.size(); i != e; ++i)
399     if (LiveIns[i].second) {
400       if (use_empty(LiveIns[i].second)) {
401         // The livein has no uses. Drop it.
402         //
403         // It would be preferable to have isel avoid creating live-in
404         // records for unused arguments in the first place, but it's
405         // complicated by the debug info code for arguments.
406         LiveIns.erase(LiveIns.begin() + i);
407         --i; --e;
408       } else {
409         // Emit a copy.
410         BuildMI(*EntryMBB, EntryMBB->begin(), DebugLoc(),
411                 TII.get(TargetOpcode::COPY), LiveIns[i].second)
412           .addReg(LiveIns[i].first);
413 
414         // Add the register to the entry block live-in set.
415         EntryMBB->addLiveIn(LiveIns[i].first);
416       }
417     } else {
418       // Add the register to the entry block live-in set.
419       EntryMBB->addLiveIn(LiveIns[i].first);
420     }
421 }
422 
423 LaneBitmask MachineRegisterInfo::getMaxLaneMaskForVReg(unsigned Reg) const {
424   // Lane masks are only defined for vregs.
425   assert(TargetRegisterInfo::isVirtualRegister(Reg));
426   const TargetRegisterClass &TRC = *getRegClass(Reg);
427   return TRC.getLaneMask();
428 }
429 
430 #ifndef NDEBUG
431 void MachineRegisterInfo::dumpUses(unsigned Reg) const {
432   for (MachineInstr &I : use_instructions(Reg))
433     I.dump();
434 }
435 #endif
436 
437 void MachineRegisterInfo::freezeReservedRegs(const MachineFunction &MF) {
438   ReservedRegs = getTargetRegisterInfo()->getReservedRegs(MF);
439   assert(ReservedRegs.size() == getTargetRegisterInfo()->getNumRegs() &&
440          "Invalid ReservedRegs vector from target");
441 }
442 
443 bool MachineRegisterInfo::isConstantPhysReg(unsigned PhysReg,
444                                             const MachineFunction &MF) const {
445   assert(TargetRegisterInfo::isPhysicalRegister(PhysReg));
446 
447   // Check if any overlapping register is modified, or allocatable so it may be
448   // used later.
449   for (MCRegAliasIterator AI(PhysReg, getTargetRegisterInfo(), true);
450        AI.isValid(); ++AI)
451     if (!def_empty(*AI) || isAllocatable(*AI))
452       return false;
453   return true;
454 }
455 
456 /// markUsesInDebugValueAsUndef - Mark every DBG_VALUE referencing the
457 /// specified register as undefined which causes the DBG_VALUE to be
458 /// deleted during LiveDebugVariables analysis.
459 void MachineRegisterInfo::markUsesInDebugValueAsUndef(unsigned Reg) const {
460   // Mark any DBG_VALUE that uses Reg as undef (but don't delete it.)
461   MachineRegisterInfo::use_instr_iterator nextI;
462   for (use_instr_iterator I = use_instr_begin(Reg), E = use_instr_end();
463        I != E; I = nextI) {
464     nextI = std::next(I);  // I is invalidated by the setReg
465     MachineInstr *UseMI = &*I;
466     if (UseMI->isDebugValue())
467       UseMI->getOperand(0).setReg(0U);
468   }
469 }
470 
471 static const Function *getCalledFunction(const MachineInstr &MI) {
472   for (const MachineOperand &MO : MI.operands()) {
473     if (!MO.isGlobal())
474       continue;
475     const Function *Func = dyn_cast<Function>(MO.getGlobal());
476     if (Func != nullptr)
477       return Func;
478   }
479   return nullptr;
480 }
481 
482 static bool isNoReturnDef(const MachineOperand &MO) {
483   // Anything which is not a noreturn function is a real def.
484   const MachineInstr &MI = *MO.getParent();
485   if (!MI.isCall())
486     return false;
487   const MachineBasicBlock &MBB = *MI.getParent();
488   if (!MBB.succ_empty())
489     return false;
490   const MachineFunction &MF = *MBB.getParent();
491   // We need to keep correct unwind information even if the function will
492   // not return, since the runtime may need it.
493   if (MF.getFunction()->hasFnAttribute(Attribute::UWTable))
494     return false;
495   const Function *Called = getCalledFunction(MI);
496   return !(Called == nullptr || !Called->hasFnAttribute(Attribute::NoReturn) ||
497            !Called->hasFnAttribute(Attribute::NoUnwind));
498 }
499 
500 bool MachineRegisterInfo::isPhysRegModified(unsigned PhysReg) const {
501   if (UsedPhysRegMask.test(PhysReg))
502     return true;
503   const TargetRegisterInfo *TRI = getTargetRegisterInfo();
504   for (MCRegAliasIterator AI(PhysReg, TRI, true); AI.isValid(); ++AI) {
505     for (const MachineOperand &MO : make_range(def_begin(*AI), def_end())) {
506       if (isNoReturnDef(MO))
507         continue;
508       return true;
509     }
510   }
511   return false;
512 }
513 
514 bool MachineRegisterInfo::isPhysRegUsed(unsigned PhysReg) const {
515   if (UsedPhysRegMask.test(PhysReg))
516     return true;
517   const TargetRegisterInfo *TRI = getTargetRegisterInfo();
518   for (MCRegAliasIterator AliasReg(PhysReg, TRI, true); AliasReg.isValid();
519        ++AliasReg) {
520     if (!reg_nodbg_empty(*AliasReg))
521       return true;
522   }
523   return false;
524 }
525