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