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