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