Do not track subregister liveness when it brings no benefits
[oota-llvm.git] / include / llvm / Target / TargetRegisterInfo.h
1 //=== Target/TargetRegisterInfo.h - Target Register Information -*- C++ -*-===//
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 describes an abstract interface used to get information about a
11 // target machines register file.  This information is used for a variety of
12 // purposed, especially register allocation.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #ifndef LLVM_TARGET_TARGETREGISTERINFO_H
17 #define LLVM_TARGET_TARGETREGISTERINFO_H
18
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/CodeGen/MachineBasicBlock.h"
21 #include "llvm/CodeGen/MachineValueType.h"
22 #include "llvm/IR/CallingConv.h"
23 #include "llvm/MC/MCRegisterInfo.h"
24 #include <cassert>
25 #include <functional>
26
27 namespace llvm {
28
29 class BitVector;
30 class MachineFunction;
31 class RegScavenger;
32 template<class T> class SmallVectorImpl;
33 class VirtRegMap;
34 class raw_ostream;
35
36 class TargetRegisterClass {
37 public:
38   typedef const MCPhysReg* iterator;
39   typedef const MCPhysReg* const_iterator;
40   typedef const MVT::SimpleValueType* vt_iterator;
41   typedef const TargetRegisterClass* const * sc_iterator;
42
43   // Instance variables filled by tablegen, do not use!
44   const MCRegisterClass *MC;
45   const vt_iterator VTs;
46   const uint32_t *SubClassMask;
47   const uint16_t *SuperRegIndices;
48   const unsigned LaneMask;
49   /// Whether the class supports two (or more) disjunct subregister indices.
50   const bool HasDisjunctSubRegs;
51   const sc_iterator SuperClasses;
52   ArrayRef<MCPhysReg> (*OrderFunc)(const MachineFunction&);
53
54   /// getID() - Return the register class ID number.
55   ///
56   unsigned getID() const { return MC->getID(); }
57
58   /// begin/end - Return all of the registers in this class.
59   ///
60   iterator       begin() const { return MC->begin(); }
61   iterator         end() const { return MC->end(); }
62
63   /// getNumRegs - Return the number of registers in this class.
64   ///
65   unsigned getNumRegs() const { return MC->getNumRegs(); }
66
67   /// getRegister - Return the specified register in the class.
68   ///
69   unsigned getRegister(unsigned i) const {
70     return MC->getRegister(i);
71   }
72
73   /// contains - Return true if the specified register is included in this
74   /// register class.  This does not include virtual registers.
75   bool contains(unsigned Reg) const {
76     return MC->contains(Reg);
77   }
78
79   /// contains - Return true if both registers are in this class.
80   bool contains(unsigned Reg1, unsigned Reg2) const {
81     return MC->contains(Reg1, Reg2);
82   }
83
84   /// getSize - Return the size of the register in bytes, which is also the size
85   /// of a stack slot allocated to hold a spilled copy of this register.
86   unsigned getSize() const { return MC->getSize(); }
87
88   /// getAlignment - Return the minimum required alignment for a register of
89   /// this class.
90   unsigned getAlignment() const { return MC->getAlignment(); }
91
92   /// getCopyCost - Return the cost of copying a value between two registers in
93   /// this class. A negative number means the register class is very expensive
94   /// to copy e.g. status flag register classes.
95   int getCopyCost() const { return MC->getCopyCost(); }
96
97   /// isAllocatable - Return true if this register class may be used to create
98   /// virtual registers.
99   bool isAllocatable() const { return MC->isAllocatable(); }
100
101   /// hasType - return true if this TargetRegisterClass has the ValueType vt.
102   ///
103   bool hasType(MVT vt) const {
104     for(int i = 0; VTs[i] != MVT::Other; ++i)
105       if (MVT(VTs[i]) == vt)
106         return true;
107     return false;
108   }
109
110   /// vt_begin / vt_end - Loop over all of the value types that can be
111   /// represented by values in this register class.
112   vt_iterator vt_begin() const {
113     return VTs;
114   }
115
116   vt_iterator vt_end() const {
117     vt_iterator I = VTs;
118     while (*I != MVT::Other) ++I;
119     return I;
120   }
121
122   /// hasSubClass - return true if the specified TargetRegisterClass
123   /// is a proper sub-class of this TargetRegisterClass.
124   bool hasSubClass(const TargetRegisterClass *RC) const {
125     return RC != this && hasSubClassEq(RC);
126   }
127
128   /// hasSubClassEq - Returns true if RC is a sub-class of or equal to this
129   /// class.
130   bool hasSubClassEq(const TargetRegisterClass *RC) const {
131     unsigned ID = RC->getID();
132     return (SubClassMask[ID / 32] >> (ID % 32)) & 1;
133   }
134
135   /// hasSuperClass - return true if the specified TargetRegisterClass is a
136   /// proper super-class of this TargetRegisterClass.
137   bool hasSuperClass(const TargetRegisterClass *RC) const {
138     return RC->hasSubClass(this);
139   }
140
141   /// hasSuperClassEq - Returns true if RC is a super-class of or equal to this
142   /// class.
143   bool hasSuperClassEq(const TargetRegisterClass *RC) const {
144     return RC->hasSubClassEq(this);
145   }
146
147   /// getSubClassMask - Returns a bit vector of subclasses, including this one.
148   /// The vector is indexed by class IDs, see hasSubClassEq() above for how to
149   /// use it.
150   const uint32_t *getSubClassMask() const {
151     return SubClassMask;
152   }
153
154   /// getSuperRegIndices - Returns a 0-terminated list of sub-register indices
155   /// that project some super-register class into this register class. The list
156   /// has an entry for each Idx such that:
157   ///
158   ///   There exists SuperRC where:
159   ///     For all Reg in SuperRC:
160   ///       this->contains(Reg:Idx)
161   ///
162   const uint16_t *getSuperRegIndices() const {
163     return SuperRegIndices;
164   }
165
166   /// getSuperClasses - Returns a NULL terminated list of super-classes.  The
167   /// classes are ordered by ID which is also a topological ordering from large
168   /// to small classes.  The list does NOT include the current class.
169   sc_iterator getSuperClasses() const {
170     return SuperClasses;
171   }
172
173   /// isASubClass - return true if this TargetRegisterClass is a subset
174   /// class of at least one other TargetRegisterClass.
175   bool isASubClass() const {
176     return SuperClasses[0] != nullptr;
177   }
178
179   /// getRawAllocationOrder - Returns the preferred order for allocating
180   /// registers from this register class in MF. The raw order comes directly
181   /// from the .td file and may include reserved registers that are not
182   /// allocatable. Register allocators should also make sure to allocate
183   /// callee-saved registers only after all the volatiles are used. The
184   /// RegisterClassInfo class provides filtered allocation orders with
185   /// callee-saved registers moved to the end.
186   ///
187   /// The MachineFunction argument can be used to tune the allocatable
188   /// registers based on the characteristics of the function, subtarget, or
189   /// other criteria.
190   ///
191   /// By default, this method returns all registers in the class.
192   ///
193   ArrayRef<MCPhysReg> getRawAllocationOrder(const MachineFunction &MF) const {
194     return OrderFunc ? OrderFunc(MF) : makeArrayRef(begin(), getNumRegs());
195   }
196
197   /// Returns the combination of all lane masks of register in this class.
198   /// The lane masks of the registers are the combination of all lane masks
199   /// of their subregisters.
200   unsigned getLaneMask() const {
201     return LaneMask;
202   }
203 };
204
205 /// TargetRegisterInfoDesc - Extra information, not in MCRegisterDesc, about
206 /// registers. These are used by codegen, not by MC.
207 struct TargetRegisterInfoDesc {
208   unsigned CostPerUse;          // Extra cost of instructions using register.
209   bool inAllocatableClass;      // Register belongs to an allocatable regclass.
210 };
211
212 /// Each TargetRegisterClass has a per register weight, and weight
213 /// limit which must be less than the limits of its pressure sets.
214 struct RegClassWeight {
215   unsigned RegWeight;
216   unsigned WeightLimit;
217 };
218
219 /// TargetRegisterInfo base class - We assume that the target defines a static
220 /// array of TargetRegisterDesc objects that represent all of the machine
221 /// registers that the target has.  As such, we simply have to track a pointer
222 /// to this array so that we can turn register number into a register
223 /// descriptor.
224 ///
225 class TargetRegisterInfo : public MCRegisterInfo {
226 public:
227   typedef const TargetRegisterClass * const * regclass_iterator;
228 private:
229   const TargetRegisterInfoDesc *InfoDesc;     // Extra desc array for codegen
230   const char *const *SubRegIndexNames;        // Names of subreg indexes.
231   // Pointer to array of lane masks, one per sub-reg index.
232   const unsigned *SubRegIndexLaneMasks;
233
234   regclass_iterator RegClassBegin, RegClassEnd;   // List of regclasses
235   unsigned CoveringLanes;
236
237 protected:
238   TargetRegisterInfo(const TargetRegisterInfoDesc *ID,
239                      regclass_iterator RegClassBegin,
240                      regclass_iterator RegClassEnd,
241                      const char *const *SRINames,
242                      const unsigned *SRILaneMasks,
243                      unsigned CoveringLanes);
244   virtual ~TargetRegisterInfo();
245 public:
246
247   // Register numbers can represent physical registers, virtual registers, and
248   // sometimes stack slots. The unsigned values are divided into these ranges:
249   //
250   //   0           Not a register, can be used as a sentinel.
251   //   [1;2^30)    Physical registers assigned by TableGen.
252   //   [2^30;2^31) Stack slots. (Rarely used.)
253   //   [2^31;2^32) Virtual registers assigned by MachineRegisterInfo.
254   //
255   // Further sentinels can be allocated from the small negative integers.
256   // DenseMapInfo<unsigned> uses -1u and -2u.
257
258   /// isStackSlot - Sometimes it is useful the be able to store a non-negative
259   /// frame index in a variable that normally holds a register. isStackSlot()
260   /// returns true if Reg is in the range used for stack slots.
261   ///
262   /// Note that isVirtualRegister() and isPhysicalRegister() cannot handle stack
263   /// slots, so if a variable may contains a stack slot, always check
264   /// isStackSlot() first.
265   ///
266   static bool isStackSlot(unsigned Reg) {
267     return int(Reg) >= (1 << 30);
268   }
269
270   /// stackSlot2Index - Compute the frame index from a register value
271   /// representing a stack slot.
272   static int stackSlot2Index(unsigned Reg) {
273     assert(isStackSlot(Reg) && "Not a stack slot");
274     return int(Reg - (1u << 30));
275   }
276
277   /// index2StackSlot - Convert a non-negative frame index to a stack slot
278   /// register value.
279   static unsigned index2StackSlot(int FI) {
280     assert(FI >= 0 && "Cannot hold a negative frame index.");
281     return FI + (1u << 30);
282   }
283
284   /// isPhysicalRegister - Return true if the specified register number is in
285   /// the physical register namespace.
286   static bool isPhysicalRegister(unsigned Reg) {
287     assert(!isStackSlot(Reg) && "Not a register! Check isStackSlot() first.");
288     return int(Reg) > 0;
289   }
290
291   /// isVirtualRegister - Return true if the specified register number is in
292   /// the virtual register namespace.
293   static bool isVirtualRegister(unsigned Reg) {
294     assert(!isStackSlot(Reg) && "Not a register! Check isStackSlot() first.");
295     return int(Reg) < 0;
296   }
297
298   /// virtReg2Index - Convert a virtual register number to a 0-based index.
299   /// The first virtual register in a function will get the index 0.
300   static unsigned virtReg2Index(unsigned Reg) {
301     assert(isVirtualRegister(Reg) && "Not a virtual register");
302     return Reg & ~(1u << 31);
303   }
304
305   /// index2VirtReg - Convert a 0-based index to a virtual register number.
306   /// This is the inverse operation of VirtReg2IndexFunctor below.
307   static unsigned index2VirtReg(unsigned Index) {
308     return Index | (1u << 31);
309   }
310
311   /// getMinimalPhysRegClass - Returns the Register Class of a physical
312   /// register of the given type, picking the most sub register class of
313   /// the right type that contains this physreg.
314   const TargetRegisterClass *
315     getMinimalPhysRegClass(unsigned Reg, MVT VT = MVT::Other) const;
316
317   /// getAllocatableClass - Return the maximal subclass of the given register
318   /// class that is alloctable, or NULL.
319   const TargetRegisterClass *
320     getAllocatableClass(const TargetRegisterClass *RC) const;
321
322   /// getAllocatableSet - Returns a bitset indexed by register number
323   /// indicating if a register is allocatable or not. If a register class is
324   /// specified, returns the subset for the class.
325   BitVector getAllocatableSet(const MachineFunction &MF,
326                               const TargetRegisterClass *RC = nullptr) const;
327
328   /// getCostPerUse - Return the additional cost of using this register instead
329   /// of other registers in its class.
330   unsigned getCostPerUse(unsigned RegNo) const {
331     return InfoDesc[RegNo].CostPerUse;
332   }
333
334   /// isInAllocatableClass - Return true if the register is in the allocation
335   /// of any register class.
336   bool isInAllocatableClass(unsigned RegNo) const {
337     return InfoDesc[RegNo].inAllocatableClass;
338   }
339
340   /// getSubRegIndexName - Return the human-readable symbolic target-specific
341   /// name for the specified SubRegIndex.
342   const char *getSubRegIndexName(unsigned SubIdx) const {
343     assert(SubIdx && SubIdx < getNumSubRegIndices() &&
344            "This is not a subregister index");
345     return SubRegIndexNames[SubIdx-1];
346   }
347
348   /// getSubRegIndexLaneMask - Return a bitmask representing the parts of a
349   /// register that are covered by SubIdx.
350   ///
351   /// Lane masks for sub-register indices are similar to register units for
352   /// physical registers. The individual bits in a lane mask can't be assigned
353   /// any specific meaning. They can be used to check if two sub-register
354   /// indices overlap.
355   ///
356   /// If the target has a register such that:
357   ///
358   ///   getSubReg(Reg, A) overlaps getSubReg(Reg, B)
359   ///
360   /// then:
361   ///
362   ///   (getSubRegIndexLaneMask(A) & getSubRegIndexLaneMask(B)) != 0
363   ///
364   /// The converse is not necessarily true. If two lane masks have a common
365   /// bit, the corresponding sub-registers may not overlap, but it can be
366   /// assumed that they usually will.
367   /// SubIdx == 0 is allowed, it has the lane mask ~0u.
368   unsigned getSubRegIndexLaneMask(unsigned SubIdx) const {
369     assert(SubIdx < getNumSubRegIndices() && "This is not a subregister index");
370     return SubRegIndexLaneMasks[SubIdx];
371   }
372
373   /// The lane masks returned by getSubRegIndexLaneMask() above can only be
374   /// used to determine if sub-registers overlap - they can't be used to
375   /// determine if a set of sub-registers completely cover another
376   /// sub-register.
377   ///
378   /// The X86 general purpose registers have two lanes corresponding to the
379   /// sub_8bit and sub_8bit_hi sub-registers. Both sub_32bit and sub_16bit have
380   /// lane masks '3', but the sub_16bit sub-register doesn't fully cover the
381   /// sub_32bit sub-register.
382   ///
383   /// On the other hand, the ARM NEON lanes fully cover their registers: The
384   /// dsub_0 sub-register is completely covered by the ssub_0 and ssub_1 lanes.
385   /// This is related to the CoveredBySubRegs property on register definitions.
386   ///
387   /// This function returns a bit mask of lanes that completely cover their
388   /// sub-registers. More precisely, given:
389   ///
390   ///   Covering = getCoveringLanes();
391   ///   MaskA = getSubRegIndexLaneMask(SubA);
392   ///   MaskB = getSubRegIndexLaneMask(SubB);
393   ///
394   /// If (MaskA & ~(MaskB & Covering)) == 0, then SubA is completely covered by
395   /// SubB.
396   unsigned getCoveringLanes() const { return CoveringLanes; }
397
398   /// regsOverlap - Returns true if the two registers are equal or alias each
399   /// other. The registers may be virtual register.
400   bool regsOverlap(unsigned regA, unsigned regB) const {
401     if (regA == regB) return true;
402     if (isVirtualRegister(regA) || isVirtualRegister(regB))
403       return false;
404
405     // Regunits are numerically ordered. Find a common unit.
406     MCRegUnitIterator RUA(regA, this);
407     MCRegUnitIterator RUB(regB, this);
408     do {
409       if (*RUA == *RUB) return true;
410       if (*RUA < *RUB) ++RUA;
411       else             ++RUB;
412     } while (RUA.isValid() && RUB.isValid());
413     return false;
414   }
415
416   /// hasRegUnit - Returns true if Reg contains RegUnit.
417   bool hasRegUnit(unsigned Reg, unsigned RegUnit) const {
418     for (MCRegUnitIterator Units(Reg, this); Units.isValid(); ++Units)
419       if (*Units == RegUnit)
420         return true;
421     return false;
422   }
423
424   /// getCalleeSavedRegs - Return a null-terminated list of all of the
425   /// callee saved registers on this target. The register should be in the
426   /// order of desired callee-save stack frame offset. The first register is
427   /// closest to the incoming stack pointer if stack grows down, and vice versa.
428   ///
429   virtual const MCPhysReg*
430   getCalleeSavedRegs(const MachineFunction *MF) const = 0;
431
432   /// getCallPreservedMask - Return a mask of call-preserved registers for the
433   /// given calling convention on the current function.  The mask should
434   /// include all call-preserved aliases.  This is used by the register
435   /// allocator to determine which registers can be live across a call.
436   ///
437   /// The mask is an array containing (TRI::getNumRegs()+31)/32 entries.
438   /// A set bit indicates that all bits of the corresponding register are
439   /// preserved across the function call.  The bit mask is expected to be
440   /// sub-register complete, i.e. if A is preserved, so are all its
441   /// sub-registers.
442   ///
443   /// Bits are numbered from the LSB, so the bit for physical register Reg can
444   /// be found as (Mask[Reg / 32] >> Reg % 32) & 1.
445   ///
446   /// A NULL pointer means that no register mask will be used, and call
447   /// instructions should use implicit-def operands to indicate call clobbered
448   /// registers.
449   ///
450   virtual const uint32_t *getCallPreservedMask(const MachineFunction &MF,
451                                                CallingConv::ID) const {
452     // The default mask clobbers everything.  All targets should override.
453     return nullptr;
454   }
455
456   /// getReservedRegs - Returns a bitset indexed by physical register number
457   /// indicating if a register is a special register that has particular uses
458   /// and should be considered unavailable at all times, e.g. SP, RA. This is
459   /// used by register scavenger to determine what registers are free.
460   virtual BitVector getReservedRegs(const MachineFunction &MF) const = 0;
461
462   /// Prior to adding the live-out mask to a stackmap or patchpoint
463   /// instruction, provide the target the opportunity to adjust it (mainly to
464   /// remove pseudo-registers that should be ignored).
465   virtual void adjustStackMapLiveOutMask(uint32_t *Mask) const { }
466
467   /// getMatchingSuperReg - Return a super-register of the specified register
468   /// Reg so its sub-register of index SubIdx is Reg.
469   unsigned getMatchingSuperReg(unsigned Reg, unsigned SubIdx,
470                                const TargetRegisterClass *RC) const {
471     return MCRegisterInfo::getMatchingSuperReg(Reg, SubIdx, RC->MC);
472   }
473
474   /// getMatchingSuperRegClass - Return a subclass of the specified register
475   /// class A so that each register in it has a sub-register of the
476   /// specified sub-register index which is in the specified register class B.
477   ///
478   /// TableGen will synthesize missing A sub-classes.
479   virtual const TargetRegisterClass *
480   getMatchingSuperRegClass(const TargetRegisterClass *A,
481                            const TargetRegisterClass *B, unsigned Idx) const;
482
483   /// getSubClassWithSubReg - Returns the largest legal sub-class of RC that
484   /// supports the sub-register index Idx.
485   /// If no such sub-class exists, return NULL.
486   /// If all registers in RC already have an Idx sub-register, return RC.
487   ///
488   /// TableGen generates a version of this function that is good enough in most
489   /// cases.  Targets can override if they have constraints that TableGen
490   /// doesn't understand.  For example, the x86 sub_8bit sub-register index is
491   /// supported by the full GR32 register class in 64-bit mode, but only by the
492   /// GR32_ABCD regiister class in 32-bit mode.
493   ///
494   /// TableGen will synthesize missing RC sub-classes.
495   virtual const TargetRegisterClass *
496   getSubClassWithSubReg(const TargetRegisterClass *RC, unsigned Idx) const {
497     assert(Idx == 0 && "Target has no sub-registers");
498     return RC;
499   }
500
501   /// composeSubRegIndices - Return the subregister index you get from composing
502   /// two subregister indices.
503   ///
504   /// The special null sub-register index composes as the identity.
505   ///
506   /// If R:a:b is the same register as R:c, then composeSubRegIndices(a, b)
507   /// returns c. Note that composeSubRegIndices does not tell you about illegal
508   /// compositions. If R does not have a subreg a, or R:a does not have a subreg
509   /// b, composeSubRegIndices doesn't tell you.
510   ///
511   /// The ARM register Q0 has two D subregs dsub_0:D0 and dsub_1:D1. It also has
512   /// ssub_0:S0 - ssub_3:S3 subregs.
513   /// If you compose subreg indices dsub_1, ssub_0 you get ssub_2.
514   ///
515   unsigned composeSubRegIndices(unsigned a, unsigned b) const {
516     if (!a) return b;
517     if (!b) return a;
518     return composeSubRegIndicesImpl(a, b);
519   }
520
521   /// Transforms a LaneMask computed for one subregister to the lanemask that
522   /// would have been computed when composing the subsubregisters with IdxA
523   /// first. @sa composeSubRegIndices()
524   unsigned composeSubRegIndexLaneMask(unsigned IdxA, unsigned LaneMask) const {
525     if (!IdxA)
526       return LaneMask;
527     return composeSubRegIndexLaneMaskImpl(IdxA, LaneMask);
528   }
529
530   /// Debugging helper: dump register in human readable form to dbgs() stream.
531   static void dumpReg(unsigned Reg, unsigned SubRegIndex = 0,
532                       const TargetRegisterInfo* TRI = nullptr);
533
534 protected:
535   /// Overridden by TableGen in targets that have sub-registers.
536   virtual unsigned composeSubRegIndicesImpl(unsigned, unsigned) const {
537     llvm_unreachable("Target has no sub-registers");
538   }
539
540   /// Overridden by TableGen in targets that have sub-registers.
541   virtual unsigned
542   composeSubRegIndexLaneMaskImpl(unsigned, unsigned) const {
543     llvm_unreachable("Target has no sub-registers");
544   }
545
546 public:
547   /// getCommonSuperRegClass - Find a common super-register class if it exists.
548   ///
549   /// Find a register class, SuperRC and two sub-register indices, PreA and
550   /// PreB, such that:
551   ///
552   ///   1. PreA + SubA == PreB + SubB  (using composeSubRegIndices()), and
553   ///
554   ///   2. For all Reg in SuperRC: Reg:PreA in RCA and Reg:PreB in RCB, and
555   ///
556   ///   3. SuperRC->getSize() >= max(RCA->getSize(), RCB->getSize()).
557   ///
558   /// SuperRC will be chosen such that no super-class of SuperRC satisfies the
559   /// requirements, and there is no register class with a smaller spill size
560   /// that satisfies the requirements.
561   ///
562   /// SubA and SubB must not be 0. Use getMatchingSuperRegClass() instead.
563   ///
564   /// Either of the PreA and PreB sub-register indices may be returned as 0. In
565   /// that case, the returned register class will be a sub-class of the
566   /// corresponding argument register class.
567   ///
568   /// The function returns NULL if no register class can be found.
569   ///
570   const TargetRegisterClass*
571   getCommonSuperRegClass(const TargetRegisterClass *RCA, unsigned SubA,
572                          const TargetRegisterClass *RCB, unsigned SubB,
573                          unsigned &PreA, unsigned &PreB) const;
574
575   //===--------------------------------------------------------------------===//
576   // Register Class Information
577   //
578
579   /// Register class iterators
580   ///
581   regclass_iterator regclass_begin() const { return RegClassBegin; }
582   regclass_iterator regclass_end() const { return RegClassEnd; }
583
584   unsigned getNumRegClasses() const {
585     return (unsigned)(regclass_end()-regclass_begin());
586   }
587
588   /// getRegClass - Returns the register class associated with the enumeration
589   /// value.  See class MCOperandInfo.
590   const TargetRegisterClass *getRegClass(unsigned i) const {
591     assert(i < getNumRegClasses() && "Register Class ID out of range");
592     return RegClassBegin[i];
593   }
594
595   /// getRegClassName - Returns the name of the register class.
596   const char *getRegClassName(const TargetRegisterClass *Class) const {
597     return MCRegisterInfo::getRegClassName(Class->MC);
598   }
599
600   /// getCommonSubClass - find the largest common subclass of A and B. Return
601   /// NULL if there is no common subclass.
602   const TargetRegisterClass *
603   getCommonSubClass(const TargetRegisterClass *A,
604                     const TargetRegisterClass *B) const;
605
606   /// getPointerRegClass - Returns a TargetRegisterClass used for pointer
607   /// values.  If a target supports multiple different pointer register classes,
608   /// kind specifies which one is indicated.
609   virtual const TargetRegisterClass *
610   getPointerRegClass(const MachineFunction &MF, unsigned Kind=0) const {
611     llvm_unreachable("Target didn't implement getPointerRegClass!");
612   }
613
614   /// getCrossCopyRegClass - Returns a legal register class to copy a register
615   /// in the specified class to or from. If it is possible to copy the register
616   /// directly without using a cross register class copy, return the specified
617   /// RC. Returns NULL if it is not possible to copy between a two registers of
618   /// the specified class.
619   virtual const TargetRegisterClass *
620   getCrossCopyRegClass(const TargetRegisterClass *RC) const {
621     return RC;
622   }
623
624   /// getLargestLegalSuperClass - Returns the largest super class of RC that is
625   /// legal to use in the current sub-target and has the same spill size.
626   /// The returned register class can be used to create virtual registers which
627   /// means that all its registers can be copied and spilled.
628   virtual const TargetRegisterClass *
629   getLargestLegalSuperClass(const TargetRegisterClass *RC,
630                             const MachineFunction &) const {
631     /// The default implementation is very conservative and doesn't allow the
632     /// register allocator to inflate register classes.
633     return RC;
634   }
635
636   /// getRegPressureLimit - Return the register pressure "high water mark" for
637   /// the specific register class. The scheduler is in high register pressure
638   /// mode (for the specific register class) if it goes over the limit.
639   ///
640   /// Note: this is the old register pressure model that relies on a manually
641   /// specified representative register class per value type.
642   virtual unsigned getRegPressureLimit(const TargetRegisterClass *RC,
643                                        MachineFunction &MF) const {
644     return 0;
645   }
646
647   /// Get the weight in units of pressure for this register class.
648   virtual const RegClassWeight &getRegClassWeight(
649     const TargetRegisterClass *RC) const = 0;
650
651   /// Get the weight in units of pressure for this register unit.
652   virtual unsigned getRegUnitWeight(unsigned RegUnit) const = 0;
653
654   /// Get the number of dimensions of register pressure.
655   virtual unsigned getNumRegPressureSets() const = 0;
656
657   /// Get the name of this register unit pressure set.
658   virtual const char *getRegPressureSetName(unsigned Idx) const = 0;
659
660   /// Get the register unit pressure limit for this dimension.
661   /// This limit must be adjusted dynamically for reserved registers.
662   virtual unsigned getRegPressureSetLimit(const MachineFunction &MF,
663                                           unsigned Idx) const = 0;
664
665   /// Get the dimensions of register pressure impacted by this register class.
666   /// Returns a -1 terminated array of pressure set IDs.
667   virtual const int *getRegClassPressureSets(
668     const TargetRegisterClass *RC) const = 0;
669
670   /// Get the dimensions of register pressure impacted by this register unit.
671   /// Returns a -1 terminated array of pressure set IDs.
672   virtual const int *getRegUnitPressureSets(unsigned RegUnit) const = 0;
673
674   /// Get a list of 'hint' registers that the register allocator should try
675   /// first when allocating a physical register for the virtual register
676   /// VirtReg. These registers are effectively moved to the front of the
677   /// allocation order.
678   ///
679   /// The Order argument is the allocation order for VirtReg's register class
680   /// as returned from RegisterClassInfo::getOrder(). The hint registers must
681   /// come from Order, and they must not be reserved.
682   ///
683   /// The default implementation of this function can resolve
684   /// target-independent hints provided to MRI::setRegAllocationHint with
685   /// HintType == 0. Targets that override this function should defer to the
686   /// default implementation if they have no reason to change the allocation
687   /// order for VirtReg. There may be target-independent hints.
688   virtual void getRegAllocationHints(unsigned VirtReg,
689                                      ArrayRef<MCPhysReg> Order,
690                                      SmallVectorImpl<MCPhysReg> &Hints,
691                                      const MachineFunction &MF,
692                                      const VirtRegMap *VRM = nullptr) const;
693
694   /// updateRegAllocHint - A callback to allow target a chance to update
695   /// register allocation hints when a register is "changed" (e.g. coalesced)
696   /// to another register. e.g. On ARM, some virtual registers should target
697   /// register pairs, if one of pair is coalesced to another register, the
698   /// allocation hint of the other half of the pair should be changed to point
699   /// to the new register.
700   virtual void updateRegAllocHint(unsigned Reg, unsigned NewReg,
701                                   MachineFunction &MF) const {
702     // Do nothing.
703   }
704
705   /// Allow the target to reverse allocation order of local live ranges. This
706   /// will generally allocate shorter local live ranges first. For targets with
707   /// many registers, this could reduce regalloc compile time by a large
708   /// factor. It is disabled by default for three reasons:
709   /// (1) Top-down allocation is simpler and easier to debug for targets that
710   /// don't benefit from reversing the order.
711   /// (2) Bottom-up allocation could result in poor evicition decisions on some
712   /// targets affecting the performance of compiled code.
713   /// (3) Bottom-up allocation is no longer guaranteed to optimally color.
714   virtual bool reverseLocalAssignment() const { return false; }
715
716   /// Allow the target to override the cost of using a callee-saved register for
717   /// the first time. Default value of 0 means we will use a callee-saved
718   /// register if it is available.
719   virtual unsigned getCSRFirstUseCost() const { return 0; }
720
721   /// requiresRegisterScavenging - returns true if the target requires (and can
722   /// make use of) the register scavenger.
723   virtual bool requiresRegisterScavenging(const MachineFunction &MF) const {
724     return false;
725   }
726
727   /// useFPForScavengingIndex - returns true if the target wants to use
728   /// frame pointer based accesses to spill to the scavenger emergency spill
729   /// slot.
730   virtual bool useFPForScavengingIndex(const MachineFunction &MF) const {
731     return true;
732   }
733
734   /// requiresFrameIndexScavenging - returns true if the target requires post
735   /// PEI scavenging of registers for materializing frame index constants.
736   virtual bool requiresFrameIndexScavenging(const MachineFunction &MF) const {
737     return false;
738   }
739
740   /// requiresVirtualBaseRegisters - Returns true if the target wants the
741   /// LocalStackAllocation pass to be run and virtual base registers
742   /// used for more efficient stack access.
743   virtual bool requiresVirtualBaseRegisters(const MachineFunction &MF) const {
744     return false;
745   }
746
747   /// hasReservedSpillSlot - Return true if target has reserved a spill slot in
748   /// the stack frame of the given function for the specified register. e.g. On
749   /// x86, if the frame register is required, the first fixed stack object is
750   /// reserved as its spill slot. This tells PEI not to create a new stack frame
751   /// object for the given register. It should be called only after
752   /// processFunctionBeforeCalleeSavedScan().
753   virtual bool hasReservedSpillSlot(const MachineFunction &MF, unsigned Reg,
754                                     int &FrameIdx) const {
755     return false;
756   }
757
758   /// trackLivenessAfterRegAlloc - returns true if the live-ins should be tracked
759   /// after register allocation.
760   virtual bool trackLivenessAfterRegAlloc(const MachineFunction &MF) const {
761     return false;
762   }
763
764   /// needsStackRealignment - true if storage within the function requires the
765   /// stack pointer to be aligned more than the normal calling convention calls
766   /// for.
767   virtual bool needsStackRealignment(const MachineFunction &MF) const {
768     return false;
769   }
770
771   /// getFrameIndexInstrOffset - Get the offset from the referenced frame
772   /// index in the instruction, if there is one.
773   virtual int64_t getFrameIndexInstrOffset(const MachineInstr *MI,
774                                            int Idx) const {
775     return 0;
776   }
777
778   /// needsFrameBaseReg - Returns true if the instruction's frame index
779   /// reference would be better served by a base register other than FP
780   /// or SP. Used by LocalStackFrameAllocation to determine which frame index
781   /// references it should create new base registers for.
782   virtual bool needsFrameBaseReg(MachineInstr *MI, int64_t Offset) const {
783     return false;
784   }
785
786   /// materializeFrameBaseRegister - Insert defining instruction(s) for
787   /// BaseReg to be a pointer to FrameIdx before insertion point I.
788   virtual void materializeFrameBaseRegister(MachineBasicBlock *MBB,
789                                             unsigned BaseReg, int FrameIdx,
790                                             int64_t Offset) const {
791     llvm_unreachable("materializeFrameBaseRegister does not exist on this "
792                      "target");
793   }
794
795   /// resolveFrameIndex - Resolve a frame index operand of an instruction
796   /// to reference the indicated base register plus offset instead.
797   virtual void resolveFrameIndex(MachineInstr &MI, unsigned BaseReg,
798                                  int64_t Offset) const {
799     llvm_unreachable("resolveFrameIndex does not exist on this target");
800   }
801
802   /// isFrameOffsetLegal - Determine whether a given offset immediate is
803   /// encodable to resolve a frame index.
804   virtual bool isFrameOffsetLegal(const MachineInstr *MI,
805                                   int64_t Offset) const {
806     llvm_unreachable("isFrameOffsetLegal does not exist on this target");
807   }
808
809
810   /// saveScavengerRegister - Spill the register so it can be used by the
811   /// register scavenger. Return true if the register was spilled, false
812   /// otherwise. If this function does not spill the register, the scavenger
813   /// will instead spill it to the emergency spill slot.
814   ///
815   virtual bool saveScavengerRegister(MachineBasicBlock &MBB,
816                                      MachineBasicBlock::iterator I,
817                                      MachineBasicBlock::iterator &UseMI,
818                                      const TargetRegisterClass *RC,
819                                      unsigned Reg) const {
820     return false;
821   }
822
823   /// eliminateFrameIndex - This method must be overriden to eliminate abstract
824   /// frame indices from instructions which may use them.  The instruction
825   /// referenced by the iterator contains an MO_FrameIndex operand which must be
826   /// eliminated by this method.  This method may modify or replace the
827   /// specified instruction, as long as it keeps the iterator pointing at the
828   /// finished product.  SPAdj is the SP adjustment due to call frame setup
829   /// instruction.  FIOperandNum is the FI operand number.
830   virtual void eliminateFrameIndex(MachineBasicBlock::iterator MI,
831                                    int SPAdj, unsigned FIOperandNum,
832                                    RegScavenger *RS = nullptr) const = 0;
833
834   //===--------------------------------------------------------------------===//
835   /// Subtarget Hooks
836
837   /// \brief SrcRC and DstRC will be morphed into NewRC if this returns true.
838   virtual bool shouldCoalesce(MachineInstr *MI,
839                               const TargetRegisterClass *SrcRC,
840                               unsigned SubReg,
841                               const TargetRegisterClass *DstRC,
842                               unsigned DstSubReg,
843                               const TargetRegisterClass *NewRC) const
844   { return true; }
845
846   //===--------------------------------------------------------------------===//
847   /// Debug information queries.
848
849   /// getFrameRegister - This method should return the register used as a base
850   /// for values allocated in the current stack frame.
851   virtual unsigned getFrameRegister(const MachineFunction &MF) const = 0;
852 };
853
854
855 //===----------------------------------------------------------------------===//
856 //                           SuperRegClassIterator
857 //===----------------------------------------------------------------------===//
858 //
859 // Iterate over the possible super-registers for a given register class. The
860 // iterator will visit a list of pairs (Idx, Mask) corresponding to the
861 // possible classes of super-registers.
862 //
863 // Each bit mask will have at least one set bit, and each set bit in Mask
864 // corresponds to a SuperRC such that:
865 //
866 //   For all Reg in SuperRC: Reg:Idx is in RC.
867 //
868 // The iterator can include (O, RC->getSubClassMask()) as the first entry which
869 // also satisfies the above requirement, assuming Reg:0 == Reg.
870 //
871 class SuperRegClassIterator {
872   const unsigned RCMaskWords;
873   unsigned SubReg;
874   const uint16_t *Idx;
875   const uint32_t *Mask;
876
877 public:
878   /// Create a SuperRegClassIterator that visits all the super-register classes
879   /// of RC. When IncludeSelf is set, also include the (0, sub-classes) entry.
880   SuperRegClassIterator(const TargetRegisterClass *RC,
881                         const TargetRegisterInfo *TRI,
882                         bool IncludeSelf = false)
883     : RCMaskWords((TRI->getNumRegClasses() + 31) / 32),
884       SubReg(0),
885       Idx(RC->getSuperRegIndices()),
886       Mask(RC->getSubClassMask()) {
887     if (!IncludeSelf)
888       ++*this;
889   }
890
891   /// Returns true if this iterator is still pointing at a valid entry.
892   bool isValid() const { return Idx; }
893
894   /// Returns the current sub-register index.
895   unsigned getSubReg() const { return SubReg; }
896
897   /// Returns the bit mask if register classes that getSubReg() projects into
898   /// RC.
899   const uint32_t *getMask() const { return Mask; }
900
901   /// Advance iterator to the next entry.
902   void operator++() {
903     assert(isValid() && "Cannot move iterator past end.");
904     Mask += RCMaskWords;
905     SubReg = *Idx++;
906     if (!SubReg)
907       Idx = nullptr;
908   }
909 };
910
911 // This is useful when building IndexedMaps keyed on virtual registers
912 struct VirtReg2IndexFunctor : public std::unary_function<unsigned, unsigned> {
913   unsigned operator()(unsigned Reg) const {
914     return TargetRegisterInfo::virtReg2Index(Reg);
915   }
916 };
917
918 /// PrintReg - Helper class for printing registers on a raw_ostream.
919 /// Prints virtual and physical registers with or without a TRI instance.
920 ///
921 /// The format is:
922 ///   %noreg          - NoRegister
923 ///   %vreg5          - a virtual register.
924 ///   %vreg5:sub_8bit - a virtual register with sub-register index (with TRI).
925 ///   %EAX            - a physical register
926 ///   %physreg17      - a physical register when no TRI instance given.
927 ///
928 /// Usage: OS << PrintReg(Reg, TRI) << '\n';
929 ///
930 class PrintReg {
931   const TargetRegisterInfo *TRI;
932   unsigned Reg;
933   unsigned SubIdx;
934 public:
935   explicit PrintReg(unsigned reg, const TargetRegisterInfo *tri = nullptr,
936                     unsigned subidx = 0)
937     : TRI(tri), Reg(reg), SubIdx(subidx) {}
938   void print(raw_ostream&) const;
939 };
940
941 static inline raw_ostream &operator<<(raw_ostream &OS, const PrintReg &PR) {
942   PR.print(OS);
943   return OS;
944 }
945
946 /// PrintRegUnit - Helper class for printing register units on a raw_ostream.
947 ///
948 /// Register units are named after their root registers:
949 ///
950 ///   AL      - Single root.
951 ///   FP0~ST7 - Dual roots.
952 ///
953 /// Usage: OS << PrintRegUnit(Unit, TRI) << '\n';
954 ///
955 class PrintRegUnit {
956 protected:
957   const TargetRegisterInfo *TRI;
958   unsigned Unit;
959 public:
960   PrintRegUnit(unsigned unit, const TargetRegisterInfo *tri)
961     : TRI(tri), Unit(unit) {}
962   void print(raw_ostream&) const;
963 };
964
965 static inline raw_ostream &operator<<(raw_ostream &OS, const PrintRegUnit &PR) {
966   PR.print(OS);
967   return OS;
968 }
969
970 /// PrintVRegOrUnit - It is often convenient to track virtual registers and
971 /// physical register units in the same list.
972 class PrintVRegOrUnit : protected PrintRegUnit {
973 public:
974   PrintVRegOrUnit(unsigned VRegOrUnit, const TargetRegisterInfo *tri)
975     : PrintRegUnit(VRegOrUnit, tri) {}
976   void print(raw_ostream&) const;
977 };
978
979 static inline raw_ostream &operator<<(raw_ostream &OS,
980                                       const PrintVRegOrUnit &PR) {
981   PR.print(OS);
982   return OS;
983 }
984
985 } // End llvm namespace
986
987 #endif