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/ADT/BitVector.h"
15 #include "llvm/CodeGen/MachineFrameInfo.h"
16 #include "llvm/CodeGen/MachineFunction.h"
17 #include "llvm/CodeGen/MachineRegisterInfo.h"
18 #include "llvm/CodeGen/VirtRegMap.h"
19 #include "llvm/IR/Function.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/Format.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include "llvm/Target/TargetFrameLowering.h"
24 #include "llvm/Target/TargetRegisterInfo.h"
25 
26 #define DEBUG_TYPE "target-reg-info"
27 
28 using namespace llvm;
29 
30 TargetRegisterInfo::TargetRegisterInfo(const TargetRegisterInfoDesc *ID,
31                              regclass_iterator RCB, regclass_iterator RCE,
32                              const char *const *SRINames,
33                              const LaneBitmask *SRILaneMasks,
34                              LaneBitmask SRICoveringLanes)
35   : InfoDesc(ID), SubRegIndexNames(SRINames),
36     SubRegIndexLaneMasks(SRILaneMasks),
37     RegClassBegin(RCB), RegClassEnd(RCE),
38     CoveringLanes(SRICoveringLanes) {
39 }
40 
41 TargetRegisterInfo::~TargetRegisterInfo() {}
42 
43 void TargetRegisterInfo::markSuperRegs(BitVector &RegisterSet, unsigned Reg)
44     const {
45   for (MCSuperRegIterator AI(Reg, this, true); AI.isValid(); ++AI)
46     RegisterSet.set(*AI);
47 }
48 
49 bool TargetRegisterInfo::checkAllSuperRegsMarked(const BitVector &RegisterSet,
50     ArrayRef<MCPhysReg> Exceptions) const {
51   // Check that all super registers of reserved regs are reserved as well.
52   BitVector Checked(getNumRegs());
53   for (int Reg = RegisterSet.find_first(); Reg>=0;
54        Reg = RegisterSet.find_next(Reg)) {
55     if (Checked[Reg])
56       continue;
57     for (MCSuperRegIterator SR(Reg, this); SR.isValid(); ++SR) {
58       if (!RegisterSet[*SR] && !is_contained(Exceptions, Reg)) {
59         dbgs() << "Error: Super register " << PrintReg(*SR, this)
60                << " of reserved register " << PrintReg(Reg, this)
61                << " is not reserved.\n";
62         return false;
63       }
64 
65       // We transitively check superregs. So we can remember this for later
66       // to avoid compiletime explosion in deep register hierarchies.
67       Checked.set(*SR);
68     }
69   }
70   return true;
71 }
72 
73 namespace llvm {
74 
75 Printable PrintReg(unsigned Reg, const TargetRegisterInfo *TRI,
76                    unsigned SubIdx) {
77   return Printable([Reg, TRI, SubIdx](raw_ostream &OS) {
78     if (!Reg)
79       OS << "%noreg";
80     else if (TargetRegisterInfo::isStackSlot(Reg))
81       OS << "SS#" << TargetRegisterInfo::stackSlot2Index(Reg);
82     else if (TargetRegisterInfo::isVirtualRegister(Reg))
83       OS << "%vreg" << TargetRegisterInfo::virtReg2Index(Reg);
84     else if (TRI && Reg < TRI->getNumRegs())
85       OS << '%' << TRI->getName(Reg);
86     else
87       OS << "%physreg" << Reg;
88     if (SubIdx) {
89       if (TRI)
90         OS << ':' << TRI->getSubRegIndexName(SubIdx);
91       else
92         OS << ":sub(" << SubIdx << ')';
93     }
94   });
95 }
96 
97 Printable PrintRegUnit(unsigned Unit, const TargetRegisterInfo *TRI) {
98   return Printable([Unit, TRI](raw_ostream &OS) {
99     // Generic printout when TRI is missing.
100     if (!TRI) {
101       OS << "Unit~" << Unit;
102       return;
103     }
104 
105     // Check for invalid register units.
106     if (Unit >= TRI->getNumRegUnits()) {
107       OS << "BadUnit~" << Unit;
108       return;
109     }
110 
111     // Normal units have at least one root.
112     MCRegUnitRootIterator Roots(Unit, TRI);
113     assert(Roots.isValid() && "Unit has no roots.");
114     OS << TRI->getName(*Roots);
115     for (++Roots; Roots.isValid(); ++Roots)
116       OS << '~' << TRI->getName(*Roots);
117   });
118 }
119 
120 Printable PrintVRegOrUnit(unsigned Unit, const TargetRegisterInfo *TRI) {
121   return Printable([Unit, TRI](raw_ostream &OS) {
122     if (TRI && TRI->isVirtualRegister(Unit)) {
123       OS << "%vreg" << TargetRegisterInfo::virtReg2Index(Unit);
124     } else {
125       OS << PrintRegUnit(Unit, TRI);
126     }
127   });
128 }
129 
130 } // End of llvm namespace
131 
132 /// getAllocatableClass - Return the maximal subclass of the given register
133 /// class that is alloctable, or NULL.
134 const TargetRegisterClass *
135 TargetRegisterInfo::getAllocatableClass(const TargetRegisterClass *RC) const {
136   if (!RC || RC->isAllocatable())
137     return RC;
138 
139   for (BitMaskClassIterator It(RC->getSubClassMask(), *this); It.isValid();
140        ++It) {
141     const TargetRegisterClass *SubRC = getRegClass(It.getID());
142     if (SubRC->isAllocatable())
143       return SubRC;
144   }
145   return nullptr;
146 }
147 
148 /// getMinimalPhysRegClass - Returns the Register Class of a physical
149 /// register of the given type, picking the most sub register class of
150 /// the right type that contains this physreg.
151 const TargetRegisterClass *
152 TargetRegisterInfo::getMinimalPhysRegClass(unsigned reg, MVT VT) const {
153   assert(isPhysicalRegister(reg) && "reg must be a physical register");
154 
155   // Pick the most sub register class of the right type that contains
156   // this physreg.
157   const TargetRegisterClass* BestRC = nullptr;
158   for (const TargetRegisterClass* RC : regclasses()) {
159     if ((VT == MVT::Other || RC->hasType(VT)) && RC->contains(reg) &&
160         (!BestRC || BestRC->hasSubClass(RC)))
161       BestRC = RC;
162   }
163 
164   assert(BestRC && "Couldn't find the register class");
165   return BestRC;
166 }
167 
168 /// getAllocatableSetForRC - Toggle the bits that represent allocatable
169 /// registers for the specific register class.
170 static void getAllocatableSetForRC(const MachineFunction &MF,
171                                    const TargetRegisterClass *RC, BitVector &R){
172   assert(RC->isAllocatable() && "invalid for nonallocatable sets");
173   ArrayRef<MCPhysReg> Order = RC->getRawAllocationOrder(MF);
174   for (unsigned i = 0; i != Order.size(); ++i)
175     R.set(Order[i]);
176 }
177 
178 BitVector TargetRegisterInfo::getAllocatableSet(const MachineFunction &MF,
179                                           const TargetRegisterClass *RC) const {
180   BitVector Allocatable(getNumRegs());
181   if (RC) {
182     // A register class with no allocatable subclass returns an empty set.
183     const TargetRegisterClass *SubClass = getAllocatableClass(RC);
184     if (SubClass)
185       getAllocatableSetForRC(MF, SubClass, Allocatable);
186   } else {
187     for (const TargetRegisterClass *C : regclasses())
188       if (C->isAllocatable())
189         getAllocatableSetForRC(MF, C, Allocatable);
190   }
191 
192   // Mask out the reserved registers
193   BitVector Reserved = getReservedRegs(MF);
194   Allocatable &= Reserved.flip();
195 
196   return Allocatable;
197 }
198 
199 static inline
200 const TargetRegisterClass *firstCommonClass(const uint32_t *A,
201                                             const uint32_t *B,
202                                             const TargetRegisterInfo *TRI,
203                                             const MVT::SimpleValueType SVT =
204                                             MVT::SimpleValueType::Any) {
205   const MVT VT(SVT);
206   for (unsigned I = 0, E = TRI->getNumRegClasses(); I < E; I += 32)
207     if (unsigned Common = *A++ & *B++) {
208       const TargetRegisterClass *RC =
209           TRI->getRegClass(I + countTrailingZeros(Common));
210       if (SVT == MVT::SimpleValueType::Any || RC->hasType(VT))
211         return RC;
212     }
213   return nullptr;
214 }
215 
216 const TargetRegisterClass *
217 TargetRegisterInfo::getCommonSubClass(const TargetRegisterClass *A,
218                                       const TargetRegisterClass *B,
219                                       const MVT::SimpleValueType SVT) const {
220   // First take care of the trivial cases.
221   if (A == B)
222     return A;
223   if (!A || !B)
224     return nullptr;
225 
226   // Register classes are ordered topologically, so the largest common
227   // sub-class it the common sub-class with the smallest ID.
228   return firstCommonClass(A->getSubClassMask(), B->getSubClassMask(), this, SVT);
229 }
230 
231 const TargetRegisterClass *
232 TargetRegisterInfo::getMatchingSuperRegClass(const TargetRegisterClass *A,
233                                              const TargetRegisterClass *B,
234                                              unsigned Idx) const {
235   assert(A && B && "Missing register class");
236   assert(Idx && "Bad sub-register index");
237 
238   // Find Idx in the list of super-register indices.
239   for (SuperRegClassIterator RCI(B, this); RCI.isValid(); ++RCI)
240     if (RCI.getSubReg() == Idx)
241       // The bit mask contains all register classes that are projected into B
242       // by Idx. Find a class that is also a sub-class of A.
243       return firstCommonClass(RCI.getMask(), A->getSubClassMask(), this);
244   return nullptr;
245 }
246 
247 const TargetRegisterClass *TargetRegisterInfo::
248 getCommonSuperRegClass(const TargetRegisterClass *RCA, unsigned SubA,
249                        const TargetRegisterClass *RCB, unsigned SubB,
250                        unsigned &PreA, unsigned &PreB) const {
251   assert(RCA && SubA && RCB && SubB && "Invalid arguments");
252 
253   // Search all pairs of sub-register indices that project into RCA and RCB
254   // respectively. This is quadratic, but usually the sets are very small. On
255   // most targets like X86, there will only be a single sub-register index
256   // (e.g., sub_16bit projecting into GR16).
257   //
258   // The worst case is a register class like DPR on ARM.
259   // We have indices dsub_0..dsub_7 projecting into that class.
260   //
261   // It is very common that one register class is a sub-register of the other.
262   // Arrange for RCA to be the larger register so the answer will be found in
263   // the first iteration. This makes the search linear for the most common
264   // case.
265   const TargetRegisterClass *BestRC = nullptr;
266   unsigned *BestPreA = &PreA;
267   unsigned *BestPreB = &PreB;
268   if (RCA->getSize() < RCB->getSize()) {
269     std::swap(RCA, RCB);
270     std::swap(SubA, SubB);
271     std::swap(BestPreA, BestPreB);
272   }
273 
274   // Also terminate the search one we have found a register class as small as
275   // RCA.
276   unsigned MinSize = RCA->getSize();
277 
278   for (SuperRegClassIterator IA(RCA, this, true); IA.isValid(); ++IA) {
279     unsigned FinalA = composeSubRegIndices(IA.getSubReg(), SubA);
280     for (SuperRegClassIterator IB(RCB, this, true); IB.isValid(); ++IB) {
281       // Check if a common super-register class exists for this index pair.
282       const TargetRegisterClass *RC =
283         firstCommonClass(IA.getMask(), IB.getMask(), this);
284       if (!RC || RC->getSize() < MinSize)
285         continue;
286 
287       // The indexes must compose identically: PreA+SubA == PreB+SubB.
288       unsigned FinalB = composeSubRegIndices(IB.getSubReg(), SubB);
289       if (FinalA != FinalB)
290         continue;
291 
292       // Is RC a better candidate than BestRC?
293       if (BestRC && RC->getSize() >= BestRC->getSize())
294         continue;
295 
296       // Yes, RC is the smallest super-register seen so far.
297       BestRC = RC;
298       *BestPreA = IA.getSubReg();
299       *BestPreB = IB.getSubReg();
300 
301       // Bail early if we reached MinSize. We won't find a better candidate.
302       if (BestRC->getSize() == MinSize)
303         return BestRC;
304     }
305   }
306   return BestRC;
307 }
308 
309 /// \brief Check if the registers defined by the pair (RegisterClass, SubReg)
310 /// share the same register file.
311 static bool shareSameRegisterFile(const TargetRegisterInfo &TRI,
312                                   const TargetRegisterClass *DefRC,
313                                   unsigned DefSubReg,
314                                   const TargetRegisterClass *SrcRC,
315                                   unsigned SrcSubReg) {
316   // Same register class.
317   if (DefRC == SrcRC)
318     return true;
319 
320   // Both operands are sub registers. Check if they share a register class.
321   unsigned SrcIdx, DefIdx;
322   if (SrcSubReg && DefSubReg) {
323     return TRI.getCommonSuperRegClass(SrcRC, SrcSubReg, DefRC, DefSubReg,
324                                       SrcIdx, DefIdx) != nullptr;
325   }
326 
327   // At most one of the register is a sub register, make it Src to avoid
328   // duplicating the test.
329   if (!SrcSubReg) {
330     std::swap(DefSubReg, SrcSubReg);
331     std::swap(DefRC, SrcRC);
332   }
333 
334   // One of the register is a sub register, check if we can get a superclass.
335   if (SrcSubReg)
336     return TRI.getMatchingSuperRegClass(SrcRC, DefRC, SrcSubReg) != nullptr;
337 
338   // Plain copy.
339   return TRI.getCommonSubClass(DefRC, SrcRC) != nullptr;
340 }
341 
342 bool TargetRegisterInfo::shouldRewriteCopySrc(const TargetRegisterClass *DefRC,
343                                               unsigned DefSubReg,
344                                               const TargetRegisterClass *SrcRC,
345                                               unsigned SrcSubReg) const {
346   // If this source does not incur a cross register bank copy, use it.
347   return shareSameRegisterFile(*this, DefRC, DefSubReg, SrcRC, SrcSubReg);
348 }
349 
350 // Compute target-independent register allocator hints to help eliminate copies.
351 void
352 TargetRegisterInfo::getRegAllocationHints(unsigned VirtReg,
353                                           ArrayRef<MCPhysReg> Order,
354                                           SmallVectorImpl<MCPhysReg> &Hints,
355                                           const MachineFunction &MF,
356                                           const VirtRegMap *VRM,
357                                           const LiveRegMatrix *Matrix) const {
358   const MachineRegisterInfo &MRI = MF.getRegInfo();
359   std::pair<unsigned, unsigned> Hint = MRI.getRegAllocationHint(VirtReg);
360 
361   // Hints with HintType != 0 were set by target-dependent code.
362   // Such targets must provide their own implementation of
363   // TRI::getRegAllocationHints to interpret those hint types.
364   assert(Hint.first == 0 && "Target must implement TRI::getRegAllocationHints");
365 
366   // Target-independent hints are either a physical or a virtual register.
367   unsigned Phys = Hint.second;
368   if (VRM && isVirtualRegister(Phys))
369     Phys = VRM->getPhys(Phys);
370 
371   // Check that Phys is a valid hint in VirtReg's register class.
372   if (!isPhysicalRegister(Phys))
373     return;
374   if (MRI.isReserved(Phys))
375     return;
376   // Check that Phys is in the allocation order. We shouldn't heed hints
377   // from VirtReg's register class if they aren't in the allocation order. The
378   // target probably has a reason for removing the register.
379   if (!is_contained(Order, Phys))
380     return;
381 
382   // All clear, tell the register allocator to prefer this register.
383   Hints.push_back(Phys);
384 }
385 
386 bool TargetRegisterInfo::canRealignStack(const MachineFunction &MF) const {
387   return !MF.getFunction()->hasFnAttribute("no-realign-stack");
388 }
389 
390 bool TargetRegisterInfo::needsStackRealignment(
391     const MachineFunction &MF) const {
392   const MachineFrameInfo &MFI = MF.getFrameInfo();
393   const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
394   const Function *F = MF.getFunction();
395   unsigned StackAlign = TFI->getStackAlignment();
396   bool requiresRealignment = ((MFI.getMaxAlignment() > StackAlign) ||
397                               F->hasFnAttribute(Attribute::StackAlignment));
398   if (MF.getFunction()->hasFnAttribute("stackrealign") || requiresRealignment) {
399     if (canRealignStack(MF))
400       return true;
401     DEBUG(dbgs() << "Can't realign function's stack: " << F->getName() << "\n");
402   }
403   return false;
404 }
405 
406 bool TargetRegisterInfo::regmaskSubsetEqual(const uint32_t *mask0,
407                                             const uint32_t *mask1) const {
408   unsigned N = (getNumRegs()+31) / 32;
409   for (unsigned I = 0; I < N; ++I)
410     if ((mask0[I] & mask1[I]) != mask0[I])
411       return false;
412   return true;
413 }
414 
415 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
416 LLVM_DUMP_METHOD
417 void TargetRegisterInfo::dumpReg(unsigned Reg, unsigned SubRegIndex,
418                                  const TargetRegisterInfo *TRI) {
419   dbgs() << PrintReg(Reg, TRI, SubRegIndex) << "\n";
420 }
421 #endif
422