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