1 //===- TargetRegisterInfo.cpp - Target Register Information Implementation ===//
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 // This file implements the TargetRegisterInfo interface.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Target/TargetRegisterInfo.h"
15 #include "llvm/ADT/BitVector.h"
16 #include "llvm/CodeGen/MachineFunction.h"
17 #include "llvm/CodeGen/MachineRegisterInfo.h"
18 #include "llvm/CodeGen/VirtRegMap.h"
19 #include "llvm/Support/Debug.h"
20 #include "llvm/Support/raw_ostream.h"
21 
22 using namespace llvm;
23 
TargetRegisterInfo(const TargetRegisterInfoDesc * ID,regclass_iterator RCB,regclass_iterator RCE,const char * const * SRINames,const unsigned * SRILaneMasks,unsigned SRICoveringLanes)24 TargetRegisterInfo::TargetRegisterInfo(const TargetRegisterInfoDesc *ID,
25                              regclass_iterator RCB, regclass_iterator RCE,
26                              const char *const *SRINames,
27                              const unsigned *SRILaneMasks,
28                              unsigned SRICoveringLanes)
29   : InfoDesc(ID), SubRegIndexNames(SRINames),
30     SubRegIndexLaneMasks(SRILaneMasks),
31     RegClassBegin(RCB), RegClassEnd(RCE),
32     CoveringLanes(SRICoveringLanes) {
33 }
34 
~TargetRegisterInfo()35 TargetRegisterInfo::~TargetRegisterInfo() {}
36 
print(raw_ostream & OS) const37 void PrintReg::print(raw_ostream &OS) const {
38   if (!Reg)
39     OS << "%noreg";
40   else if (TargetRegisterInfo::isStackSlot(Reg))
41     OS << "SS#" << TargetRegisterInfo::stackSlot2Index(Reg);
42   else if (TargetRegisterInfo::isVirtualRegister(Reg))
43     OS << "%vreg" << TargetRegisterInfo::virtReg2Index(Reg);
44   else if (TRI && Reg < TRI->getNumRegs())
45     OS << '%' << TRI->getName(Reg);
46   else
47     OS << "%physreg" << Reg;
48   if (SubIdx) {
49     if (TRI)
50       OS << ':' << TRI->getSubRegIndexName(SubIdx);
51     else
52       OS << ":sub(" << SubIdx << ')';
53   }
54 }
55 
print(raw_ostream & OS) const56 void PrintRegUnit::print(raw_ostream &OS) const {
57   // Generic printout when TRI is missing.
58   if (!TRI) {
59     OS << "Unit~" << Unit;
60     return;
61   }
62 
63   // Check for invalid register units.
64   if (Unit >= TRI->getNumRegUnits()) {
65     OS << "BadUnit~" << Unit;
66     return;
67   }
68 
69   // Normal units have at least one root.
70   MCRegUnitRootIterator Roots(Unit, TRI);
71   assert(Roots.isValid() && "Unit has no roots.");
72   OS << TRI->getName(*Roots);
73   for (++Roots; Roots.isValid(); ++Roots)
74     OS << '~' << TRI->getName(*Roots);
75 }
76 
print(raw_ostream & OS) const77 void PrintVRegOrUnit::print(raw_ostream &OS) const {
78   if (TRI && TRI->isVirtualRegister(Unit)) {
79     OS << "%vreg" << TargetRegisterInfo::virtReg2Index(Unit);
80     return;
81   }
82   PrintRegUnit::print(OS);
83 }
84 
85 /// getAllocatableClass - Return the maximal subclass of the given register
86 /// class that is alloctable, or NULL.
87 const TargetRegisterClass *
getAllocatableClass(const TargetRegisterClass * RC) const88 TargetRegisterInfo::getAllocatableClass(const TargetRegisterClass *RC) const {
89   if (!RC || RC->isAllocatable())
90     return RC;
91 
92   const unsigned *SubClass = RC->getSubClassMask();
93   for (unsigned Base = 0, BaseE = getNumRegClasses();
94        Base < BaseE; Base += 32) {
95     unsigned Idx = Base;
96     for (unsigned Mask = *SubClass++; Mask; Mask >>= 1) {
97       unsigned Offset = countTrailingZeros(Mask);
98       const TargetRegisterClass *SubRC = getRegClass(Idx + Offset);
99       if (SubRC->isAllocatable())
100         return SubRC;
101       Mask >>= Offset;
102       Idx += Offset + 1;
103     }
104   }
105   return nullptr;
106 }
107 
108 /// getMinimalPhysRegClass - Returns the Register Class of a physical
109 /// register of the given type, picking the most sub register class of
110 /// the right type that contains this physreg.
111 const TargetRegisterClass *
getMinimalPhysRegClass(unsigned reg,MVT VT) const112 TargetRegisterInfo::getMinimalPhysRegClass(unsigned reg, MVT VT) const {
113   assert(isPhysicalRegister(reg) && "reg must be a physical register");
114 
115   // Pick the most sub register class of the right type that contains
116   // this physreg.
117   const TargetRegisterClass* BestRC = nullptr;
118   for (regclass_iterator I = regclass_begin(), E = regclass_end(); I != E; ++I){
119     const TargetRegisterClass* RC = *I;
120     if ((VT == MVT::Other || RC->hasType(VT)) && RC->contains(reg) &&
121         (!BestRC || BestRC->hasSubClass(RC)))
122       BestRC = RC;
123   }
124 
125   assert(BestRC && "Couldn't find the register class");
126   return BestRC;
127 }
128 
129 /// getAllocatableSetForRC - Toggle the bits that represent allocatable
130 /// registers for the specific register class.
getAllocatableSetForRC(const MachineFunction & MF,const TargetRegisterClass * RC,BitVector & R)131 static void getAllocatableSetForRC(const MachineFunction &MF,
132                                    const TargetRegisterClass *RC, BitVector &R){
133   assert(RC->isAllocatable() && "invalid for nonallocatable sets");
134   ArrayRef<MCPhysReg> Order = RC->getRawAllocationOrder(MF);
135   for (unsigned i = 0; i != Order.size(); ++i)
136     R.set(Order[i]);
137 }
138 
getAllocatableSet(const MachineFunction & MF,const TargetRegisterClass * RC) const139 BitVector TargetRegisterInfo::getAllocatableSet(const MachineFunction &MF,
140                                           const TargetRegisterClass *RC) const {
141   BitVector Allocatable(getNumRegs());
142   if (RC) {
143     // A register class with no allocatable subclass returns an empty set.
144     const TargetRegisterClass *SubClass = getAllocatableClass(RC);
145     if (SubClass)
146       getAllocatableSetForRC(MF, SubClass, Allocatable);
147   } else {
148     for (TargetRegisterInfo::regclass_iterator I = regclass_begin(),
149          E = regclass_end(); I != E; ++I)
150       if ((*I)->isAllocatable())
151         getAllocatableSetForRC(MF, *I, Allocatable);
152   }
153 
154   // Mask out the reserved registers
155   BitVector Reserved = getReservedRegs(MF);
156   Allocatable &= Reserved.flip();
157 
158   return Allocatable;
159 }
160 
161 static inline
firstCommonClass(const uint32_t * A,const uint32_t * B,const TargetRegisterInfo * TRI)162 const TargetRegisterClass *firstCommonClass(const uint32_t *A,
163                                             const uint32_t *B,
164                                             const TargetRegisterInfo *TRI) {
165   for (unsigned I = 0, E = TRI->getNumRegClasses(); I < E; I += 32)
166     if (unsigned Common = *A++ & *B++)
167       return TRI->getRegClass(I + countTrailingZeros(Common));
168   return nullptr;
169 }
170 
171 const TargetRegisterClass *
getCommonSubClass(const TargetRegisterClass * A,const TargetRegisterClass * B) const172 TargetRegisterInfo::getCommonSubClass(const TargetRegisterClass *A,
173                                       const TargetRegisterClass *B) const {
174   // First take care of the trivial cases.
175   if (A == B)
176     return A;
177   if (!A || !B)
178     return nullptr;
179 
180   // Register classes are ordered topologically, so the largest common
181   // sub-class it the common sub-class with the smallest ID.
182   return firstCommonClass(A->getSubClassMask(), B->getSubClassMask(), this);
183 }
184 
185 const TargetRegisterClass *
getMatchingSuperRegClass(const TargetRegisterClass * A,const TargetRegisterClass * B,unsigned Idx) const186 TargetRegisterInfo::getMatchingSuperRegClass(const TargetRegisterClass *A,
187                                              const TargetRegisterClass *B,
188                                              unsigned Idx) const {
189   assert(A && B && "Missing register class");
190   assert(Idx && "Bad sub-register index");
191 
192   // Find Idx in the list of super-register indices.
193   for (SuperRegClassIterator RCI(B, this); RCI.isValid(); ++RCI)
194     if (RCI.getSubReg() == Idx)
195       // The bit mask contains all register classes that are projected into B
196       // by Idx. Find a class that is also a sub-class of A.
197       return firstCommonClass(RCI.getMask(), A->getSubClassMask(), this);
198   return nullptr;
199 }
200 
201 const TargetRegisterClass *TargetRegisterInfo::
getCommonSuperRegClass(const TargetRegisterClass * RCA,unsigned SubA,const TargetRegisterClass * RCB,unsigned SubB,unsigned & PreA,unsigned & PreB) const202 getCommonSuperRegClass(const TargetRegisterClass *RCA, unsigned SubA,
203                        const TargetRegisterClass *RCB, unsigned SubB,
204                        unsigned &PreA, unsigned &PreB) const {
205   assert(RCA && SubA && RCB && SubB && "Invalid arguments");
206 
207   // Search all pairs of sub-register indices that project into RCA and RCB
208   // respectively. This is quadratic, but usually the sets are very small. On
209   // most targets like X86, there will only be a single sub-register index
210   // (e.g., sub_16bit projecting into GR16).
211   //
212   // The worst case is a register class like DPR on ARM.
213   // We have indices dsub_0..dsub_7 projecting into that class.
214   //
215   // It is very common that one register class is a sub-register of the other.
216   // Arrange for RCA to be the larger register so the answer will be found in
217   // the first iteration. This makes the search linear for the most common
218   // case.
219   const TargetRegisterClass *BestRC = nullptr;
220   unsigned *BestPreA = &PreA;
221   unsigned *BestPreB = &PreB;
222   if (RCA->getSize() < RCB->getSize()) {
223     std::swap(RCA, RCB);
224     std::swap(SubA, SubB);
225     std::swap(BestPreA, BestPreB);
226   }
227 
228   // Also terminate the search one we have found a register class as small as
229   // RCA.
230   unsigned MinSize = RCA->getSize();
231 
232   for (SuperRegClassIterator IA(RCA, this, true); IA.isValid(); ++IA) {
233     unsigned FinalA = composeSubRegIndices(IA.getSubReg(), SubA);
234     for (SuperRegClassIterator IB(RCB, this, true); IB.isValid(); ++IB) {
235       // Check if a common super-register class exists for this index pair.
236       const TargetRegisterClass *RC =
237         firstCommonClass(IA.getMask(), IB.getMask(), this);
238       if (!RC || RC->getSize() < MinSize)
239         continue;
240 
241       // The indexes must compose identically: PreA+SubA == PreB+SubB.
242       unsigned FinalB = composeSubRegIndices(IB.getSubReg(), SubB);
243       if (FinalA != FinalB)
244         continue;
245 
246       // Is RC a better candidate than BestRC?
247       if (BestRC && RC->getSize() >= BestRC->getSize())
248         continue;
249 
250       // Yes, RC is the smallest super-register seen so far.
251       BestRC = RC;
252       *BestPreA = IA.getSubReg();
253       *BestPreB = IB.getSubReg();
254 
255       // Bail early if we reached MinSize. We won't find a better candidate.
256       if (BestRC->getSize() == MinSize)
257         return BestRC;
258     }
259   }
260   return BestRC;
261 }
262 
263 // Compute target-independent register allocator hints to help eliminate copies.
264 void
getRegAllocationHints(unsigned VirtReg,ArrayRef<MCPhysReg> Order,SmallVectorImpl<MCPhysReg> & Hints,const MachineFunction & MF,const VirtRegMap * VRM) const265 TargetRegisterInfo::getRegAllocationHints(unsigned VirtReg,
266                                           ArrayRef<MCPhysReg> Order,
267                                           SmallVectorImpl<MCPhysReg> &Hints,
268                                           const MachineFunction &MF,
269                                           const VirtRegMap *VRM) const {
270   const MachineRegisterInfo &MRI = MF.getRegInfo();
271   std::pair<unsigned, unsigned> Hint = MRI.getRegAllocationHint(VirtReg);
272 
273   // Hints with HintType != 0 were set by target-dependent code.
274   // Such targets must provide their own implementation of
275   // TRI::getRegAllocationHints to interpret those hint types.
276   assert(Hint.first == 0 && "Target must implement TRI::getRegAllocationHints");
277 
278   // Target-independent hints are either a physical or a virtual register.
279   unsigned Phys = Hint.second;
280   if (VRM && isVirtualRegister(Phys))
281     Phys = VRM->getPhys(Phys);
282 
283   // Check that Phys is a valid hint in VirtReg's register class.
284   if (!isPhysicalRegister(Phys))
285     return;
286   if (MRI.isReserved(Phys))
287     return;
288   // Check that Phys is in the allocation order. We shouldn't heed hints
289   // from VirtReg's register class if they aren't in the allocation order. The
290   // target probably has a reason for removing the register.
291   if (std::find(Order.begin(), Order.end(), Phys) == Order.end())
292     return;
293 
294   // All clear, tell the register allocator to prefer this register.
295   Hints.push_back(Phys);
296 }
297 
298 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
299 void
dumpReg(unsigned Reg,unsigned SubRegIndex,const TargetRegisterInfo * TRI)300 TargetRegisterInfo::dumpReg(unsigned Reg, unsigned SubRegIndex,
301                             const TargetRegisterInfo *TRI) {
302   dbgs() << PrintReg(Reg, TRI, SubRegIndex) << "\n";
303 }
304 #endif
305