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