[FunctionAttrs] Move the malloc-like test to a static helper function
[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 // Compute target-independent register allocator hints to help eliminate copies.
269 void
270 TargetRegisterInfo::getRegAllocationHints(unsigned VirtReg,
271                                           ArrayRef<MCPhysReg> Order,
272                                           SmallVectorImpl<MCPhysReg> &Hints,
273                                           const MachineFunction &MF,
274                                           const VirtRegMap *VRM,
275                                           const LiveRegMatrix *Matrix) const {
276   const MachineRegisterInfo &MRI = MF.getRegInfo();
277   std::pair<unsigned, unsigned> Hint = MRI.getRegAllocationHint(VirtReg);
278
279   // Hints with HintType != 0 were set by target-dependent code.
280   // Such targets must provide their own implementation of
281   // TRI::getRegAllocationHints to interpret those hint types.
282   assert(Hint.first == 0 && "Target must implement TRI::getRegAllocationHints");
283
284   // Target-independent hints are either a physical or a virtual register.
285   unsigned Phys = Hint.second;
286   if (VRM && isVirtualRegister(Phys))
287     Phys = VRM->getPhys(Phys);
288
289   // Check that Phys is a valid hint in VirtReg's register class.
290   if (!isPhysicalRegister(Phys))
291     return;
292   if (MRI.isReserved(Phys))
293     return;
294   // Check that Phys is in the allocation order. We shouldn't heed hints
295   // from VirtReg's register class if they aren't in the allocation order. The
296   // target probably has a reason for removing the register.
297   if (std::find(Order.begin(), Order.end(), Phys) == Order.end())
298     return;
299
300   // All clear, tell the register allocator to prefer this register.
301   Hints.push_back(Phys);
302 }
303
304 bool TargetRegisterInfo::canRealignStack(const MachineFunction &MF) const {
305   return !MF.getFunction()->hasFnAttribute("no-realign-stack");
306 }
307
308 bool TargetRegisterInfo::needsStackRealignment(
309     const MachineFunction &MF) const {
310   const MachineFrameInfo *MFI = MF.getFrameInfo();
311   const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
312   const Function *F = MF.getFunction();
313   unsigned StackAlign = TFI->getStackAlignment();
314   bool requiresRealignment = ((MFI->getMaxAlignment() > StackAlign) ||
315                               F->hasFnAttribute(Attribute::StackAlignment));
316   if (MF.getFunction()->hasFnAttribute("stackrealign") || requiresRealignment) {
317     if (canRealignStack(MF))
318       return true;
319     DEBUG(dbgs() << "Can't realign function's stack: " << F->getName() << "\n");
320   }
321   return false;
322 }
323
324 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
325 void
326 TargetRegisterInfo::dumpReg(unsigned Reg, unsigned SubRegIndex,
327                             const TargetRegisterInfo *TRI) {
328   dbgs() << PrintReg(Reg, TRI, SubRegIndex) << "\n";
329 }
330 #endif