MachineScheduler: Add a target hook for deciding which RegPressure sets to
[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   virtual const MCPhysReg*
430   getCalleeSavedRegsViaCopy(const MachineFunction *MF) const {
431     return nullptr;
432   }
433
434   /// Return a mask of call-preserved registers for the given calling convention
435   /// on the current function. The mask should include all call-preserved
436   /// aliases. This is used by the register allocator to determine which
437   /// registers can be live across a call.
438   ///
439   /// The mask is an array containing (TRI::getNumRegs()+31)/32 entries.
440   /// A set bit indicates that all bits of the corresponding register are
441   /// preserved across the function call.  The bit mask is expected to be
442   /// sub-register complete, i.e. if A is preserved, so are all its
443   /// sub-registers.
444   ///
445   /// Bits are numbered from the LSB, so the bit for physical register Reg can
446   /// be found as (Mask[Reg / 32] >> Reg % 32) & 1.
447   ///
448   /// A NULL pointer means that no register mask will be used, and call
449   /// instructions should use implicit-def operands to indicate call clobbered
450   /// registers.
451   ///
452   virtual const uint32_t *getCallPreservedMask(const MachineFunction &MF,
453                                                CallingConv::ID) const {
454     // The default mask clobbers everything.  All targets should override.
455     return nullptr;
456   }
457
458   /// Return a register mask that clobbers everything.
459   virtual const uint32_t *getNoPreservedMask() const {
460     llvm_unreachable("target does not provide no presered mask");
461   }
462
463   /// Return all the call-preserved register masks defined for this target.
464   virtual ArrayRef<const uint32_t *> getRegMasks() const = 0;
465   virtual ArrayRef<const char *> getRegMaskNames() const = 0;
466
467   /// Returns a bitset indexed by physical register number indicating if a
468   /// register is a special register that has particular uses and should be
469   /// considered unavailable at all times, e.g. SP, RA. This is
470   /// used by register scavenger to determine what registers are free.
471   virtual BitVector getReservedRegs(const MachineFunction &MF) const = 0;
472
473   /// Prior to adding the live-out mask to a stackmap or patchpoint
474   /// instruction, provide the target the opportunity to adjust it (mainly to
475   /// remove pseudo-registers that should be ignored).
476   virtual void adjustStackMapLiveOutMask(uint32_t *Mask) const { }
477
478   /// Return a super-register of the specified register
479   /// Reg so its sub-register of index SubIdx is Reg.
480   unsigned getMatchingSuperReg(unsigned Reg, unsigned SubIdx,
481                                const TargetRegisterClass *RC) const {
482     return MCRegisterInfo::getMatchingSuperReg(Reg, SubIdx, RC->MC);
483   }
484
485   /// Return a subclass of the specified register
486   /// class A so that each register in it has a sub-register of the
487   /// specified sub-register index which is in the specified register class B.
488   ///
489   /// TableGen will synthesize missing A sub-classes.
490   virtual const TargetRegisterClass *
491   getMatchingSuperRegClass(const TargetRegisterClass *A,
492                            const TargetRegisterClass *B, unsigned Idx) const;
493
494   // For a copy-like instruction that defines a register of class DefRC with
495   // subreg index DefSubReg, reading from another source with class SrcRC and
496   // subregister SrcSubReg return true if this is a preferrable copy
497   // instruction or an earlier use should be used.
498   virtual bool shouldRewriteCopySrc(const TargetRegisterClass *DefRC,
499                                     unsigned DefSubReg,
500                                     const TargetRegisterClass *SrcRC,
501                                     unsigned SrcSubReg) const;
502
503   /// Returns the largest legal sub-class of RC that
504   /// supports the sub-register index Idx.
505   /// If no such sub-class exists, return NULL.
506   /// If all registers in RC already have an Idx sub-register, return RC.
507   ///
508   /// TableGen generates a version of this function that is good enough in most
509   /// cases.  Targets can override if they have constraints that TableGen
510   /// doesn't understand.  For example, the x86 sub_8bit sub-register index is
511   /// supported by the full GR32 register class in 64-bit mode, but only by the
512   /// GR32_ABCD regiister class in 32-bit mode.
513   ///
514   /// TableGen will synthesize missing RC sub-classes.
515   virtual const TargetRegisterClass *
516   getSubClassWithSubReg(const TargetRegisterClass *RC, unsigned Idx) const {
517     assert(Idx == 0 && "Target has no sub-registers");
518     return RC;
519   }
520
521   /// Return the subregister index you get from composing
522   /// two subregister indices.
523   ///
524   /// The special null sub-register index composes as the identity.
525   ///
526   /// If R:a:b is the same register as R:c, then composeSubRegIndices(a, b)
527   /// returns c. Note that composeSubRegIndices does not tell you about illegal
528   /// compositions. If R does not have a subreg a, or R:a does not have a subreg
529   /// b, composeSubRegIndices doesn't tell you.
530   ///
531   /// The ARM register Q0 has two D subregs dsub_0:D0 and dsub_1:D1. It also has
532   /// ssub_0:S0 - ssub_3:S3 subregs.
533   /// If you compose subreg indices dsub_1, ssub_0 you get ssub_2.
534   ///
535   unsigned composeSubRegIndices(unsigned a, unsigned b) const {
536     if (!a) return b;
537     if (!b) return a;
538     return composeSubRegIndicesImpl(a, b);
539   }
540
541   /// Transforms a LaneMask computed for one subregister to the lanemask that
542   /// would have been computed when composing the subsubregisters with IdxA
543   /// first. @sa composeSubRegIndices()
544   LaneBitmask composeSubRegIndexLaneMask(unsigned IdxA,
545                                          LaneBitmask Mask) const {
546     if (!IdxA)
547       return Mask;
548     return composeSubRegIndexLaneMaskImpl(IdxA, Mask);
549   }
550
551   /// Debugging helper: dump register in human readable form to dbgs() stream.
552   static void dumpReg(unsigned Reg, unsigned SubRegIndex = 0,
553                       const TargetRegisterInfo* TRI = nullptr);
554
555 protected:
556   /// Overridden by TableGen in targets that have sub-registers.
557   virtual unsigned composeSubRegIndicesImpl(unsigned, unsigned) const {
558     llvm_unreachable("Target has no sub-registers");
559   }
560
561   /// Overridden by TableGen in targets that have sub-registers.
562   virtual LaneBitmask
563   composeSubRegIndexLaneMaskImpl(unsigned, LaneBitmask) const {
564     llvm_unreachable("Target has no sub-registers");
565   }
566
567 public:
568   /// Find a common super-register class if it exists.
569   ///
570   /// Find a register class, SuperRC and two sub-register indices, PreA and
571   /// PreB, such that:
572   ///
573   ///   1. PreA + SubA == PreB + SubB  (using composeSubRegIndices()), and
574   ///
575   ///   2. For all Reg in SuperRC: Reg:PreA in RCA and Reg:PreB in RCB, and
576   ///
577   ///   3. SuperRC->getSize() >= max(RCA->getSize(), RCB->getSize()).
578   ///
579   /// SuperRC will be chosen such that no super-class of SuperRC satisfies the
580   /// requirements, and there is no register class with a smaller spill size
581   /// that satisfies the requirements.
582   ///
583   /// SubA and SubB must not be 0. Use getMatchingSuperRegClass() instead.
584   ///
585   /// Either of the PreA and PreB sub-register indices may be returned as 0. In
586   /// that case, the returned register class will be a sub-class of the
587   /// corresponding argument register class.
588   ///
589   /// The function returns NULL if no register class can be found.
590   ///
591   const TargetRegisterClass*
592   getCommonSuperRegClass(const TargetRegisterClass *RCA, unsigned SubA,
593                          const TargetRegisterClass *RCB, unsigned SubB,
594                          unsigned &PreA, unsigned &PreB) const;
595
596   //===--------------------------------------------------------------------===//
597   // Register Class Information
598   //
599
600   /// Register class iterators
601   ///
602   regclass_iterator regclass_begin() const { return RegClassBegin; }
603   regclass_iterator regclass_end() const { return RegClassEnd; }
604
605   unsigned getNumRegClasses() const {
606     return (unsigned)(regclass_end()-regclass_begin());
607   }
608
609   /// Returns the register class associated with the enumeration value.
610   /// See class MCOperandInfo.
611   const TargetRegisterClass *getRegClass(unsigned i) const {
612     assert(i < getNumRegClasses() && "Register Class ID out of range");
613     return RegClassBegin[i];
614   }
615
616   /// Returns the name of the register class.
617   const char *getRegClassName(const TargetRegisterClass *Class) const {
618     return MCRegisterInfo::getRegClassName(Class->MC);
619   }
620
621   /// Find the largest common subclass of A and B.
622   /// Return NULL if there is no common subclass.
623   /// The common subclass should contain
624   /// simple value type SVT if it is not the Any type.
625   const TargetRegisterClass *
626   getCommonSubClass(const TargetRegisterClass *A,
627                     const TargetRegisterClass *B,
628                     const MVT::SimpleValueType SVT =
629                     MVT::SimpleValueType::Any) const;
630
631   /// Returns a TargetRegisterClass used for pointer values.
632   /// If a target supports multiple different pointer register classes,
633   /// kind specifies which one is indicated.
634   virtual const TargetRegisterClass *
635   getPointerRegClass(const MachineFunction &MF, unsigned Kind=0) const {
636     llvm_unreachable("Target didn't implement getPointerRegClass!");
637   }
638
639   /// Returns a legal register class to copy a register in the specified class
640   /// to or from. If it is possible to copy the register directly without using
641   /// a cross register class copy, return the specified RC. Returns NULL if it
642   /// is not possible to copy between two registers of the specified class.
643   virtual const TargetRegisterClass *
644   getCrossCopyRegClass(const TargetRegisterClass *RC) const {
645     return RC;
646   }
647
648   /// Returns the largest super class of RC that is legal to use in the current
649   /// sub-target and has the same spill size.
650   /// The returned register class can be used to create virtual registers which
651   /// means that all its registers can be copied and spilled.
652   virtual const TargetRegisterClass *
653   getLargestLegalSuperClass(const TargetRegisterClass *RC,
654                             const MachineFunction &) const {
655     /// The default implementation is very conservative and doesn't allow the
656     /// register allocator to inflate register classes.
657     return RC;
658   }
659
660   /// Return the register pressure "high water mark" for the specific register
661   /// class. The scheduler is in high register pressure mode (for the specific
662   /// register class) if it goes over the limit.
663   ///
664   /// Note: this is the old register pressure model that relies on a manually
665   /// specified representative register class per value type.
666   virtual unsigned getRegPressureLimit(const TargetRegisterClass *RC,
667                                        MachineFunction &MF) const {
668     return 0;
669   }
670
671   /// Return a heuristic for the machine scheduler to compare the profitability
672   /// of increasing one register pressure set versus another.  The scheduler
673   /// will prefer increasing the register pressure of the set which returns
674   /// the largest value for this function.
675   virtual unsigned getRegPressureSetScore(const MachineFunction &MF,
676                                           unsigned PSetID) const {
677     return PSetID;
678   }
679
680   /// Get the weight in units of pressure for this register class.
681   virtual const RegClassWeight &getRegClassWeight(
682     const TargetRegisterClass *RC) const = 0;
683
684   /// Get the weight in units of pressure for this register unit.
685   virtual unsigned getRegUnitWeight(unsigned RegUnit) const = 0;
686
687   /// Get the number of dimensions of register pressure.
688   virtual unsigned getNumRegPressureSets() const = 0;
689
690   /// Get the name of this register unit pressure set.
691   virtual const char *getRegPressureSetName(unsigned Idx) const = 0;
692
693   /// Get the register unit pressure limit for this dimension.
694   /// This limit must be adjusted dynamically for reserved registers.
695   virtual unsigned getRegPressureSetLimit(const MachineFunction &MF,
696                                           unsigned Idx) const = 0;
697
698   /// Get the dimensions of register pressure impacted by this register class.
699   /// Returns a -1 terminated array of pressure set IDs.
700   virtual const int *getRegClassPressureSets(
701     const TargetRegisterClass *RC) const = 0;
702
703   /// Get the dimensions of register pressure impacted by this register unit.
704   /// Returns a -1 terminated array of pressure set IDs.
705   virtual const int *getRegUnitPressureSets(unsigned RegUnit) const = 0;
706
707   /// Get a list of 'hint' registers that the register allocator should try
708   /// first when allocating a physical register for the virtual register
709   /// VirtReg. These registers are effectively moved to the front of the
710   /// allocation order.
711   ///
712   /// The Order argument is the allocation order for VirtReg's register class
713   /// as returned from RegisterClassInfo::getOrder(). The hint registers must
714   /// come from Order, and they must not be reserved.
715   ///
716   /// The default implementation of this function can resolve
717   /// target-independent hints provided to MRI::setRegAllocationHint with
718   /// HintType == 0. Targets that override this function should defer to the
719   /// default implementation if they have no reason to change the allocation
720   /// order for VirtReg. There may be target-independent hints.
721   virtual void getRegAllocationHints(unsigned VirtReg,
722                                      ArrayRef<MCPhysReg> Order,
723                                      SmallVectorImpl<MCPhysReg> &Hints,
724                                      const MachineFunction &MF,
725                                      const VirtRegMap *VRM = nullptr,
726                                      const LiveRegMatrix *Matrix = nullptr)
727     const;
728
729   /// A callback to allow target a chance to update register allocation hints
730   /// when a register is "changed" (e.g. coalesced) to another register.
731   /// e.g. On ARM, some virtual registers should target register pairs,
732   /// if one of pair is coalesced to another register, the allocation hint of
733   /// the other half of the pair should be changed to point to the new register.
734   virtual void updateRegAllocHint(unsigned Reg, unsigned NewReg,
735                                   MachineFunction &MF) const {
736     // Do nothing.
737   }
738
739   /// Allow the target to reverse allocation order of local live ranges. This
740   /// will generally allocate shorter local live ranges first. For targets with
741   /// many registers, this could reduce regalloc compile time by a large
742   /// factor. It is disabled by default for three reasons:
743   /// (1) Top-down allocation is simpler and easier to debug for targets that
744   /// don't benefit from reversing the order.
745   /// (2) Bottom-up allocation could result in poor evicition decisions on some
746   /// targets affecting the performance of compiled code.
747   /// (3) Bottom-up allocation is no longer guaranteed to optimally color.
748   virtual bool reverseLocalAssignment() const { return false; }
749
750   /// Allow the target to override the cost of using a callee-saved register for
751   /// the first time. Default value of 0 means we will use a callee-saved
752   /// register if it is available.
753   virtual unsigned getCSRFirstUseCost() const { return 0; }
754
755   /// Returns true if the target requires (and can make use of) the register
756   /// scavenger.
757   virtual bool requiresRegisterScavenging(const MachineFunction &MF) const {
758     return false;
759   }
760
761   /// Returns true if the target wants to use frame pointer based accesses to
762   /// spill to the scavenger emergency spill slot.
763   virtual bool useFPForScavengingIndex(const MachineFunction &MF) const {
764     return true;
765   }
766
767   /// Returns true if the target requires post PEI scavenging of registers for
768   /// materializing frame index constants.
769   virtual bool requiresFrameIndexScavenging(const MachineFunction &MF) const {
770     return false;
771   }
772
773   /// Returns true if the target wants the LocalStackAllocation pass to be run
774   /// and virtual base registers used for more efficient stack access.
775   virtual bool requiresVirtualBaseRegisters(const MachineFunction &MF) const {
776     return false;
777   }
778
779   /// Return true if target has reserved a spill slot in the stack frame of
780   /// the given function for the specified register. e.g. On x86, if the frame
781   /// register is required, the first fixed stack object is reserved as its
782   /// spill slot. This tells PEI not to create a new stack frame
783   /// object for the given register. It should be called only after
784   /// determineCalleeSaves().
785   virtual bool hasReservedSpillSlot(const MachineFunction &MF, unsigned Reg,
786                                     int &FrameIdx) const {
787     return false;
788   }
789
790   /// Returns true if the live-ins should be tracked after register allocation.
791   virtual bool trackLivenessAfterRegAlloc(const MachineFunction &MF) const {
792     return false;
793   }
794
795   /// True if the stack can be realigned for the target.
796   virtual bool canRealignStack(const MachineFunction &MF) const;
797
798   /// True if storage within the function requires the stack pointer to be
799   /// aligned more than the normal calling convention calls for.
800   /// This cannot be overriden by the target, but canRealignStack can be
801   /// overridden.
802   bool needsStackRealignment(const MachineFunction &MF) const;
803
804   /// Get the offset from the referenced frame index in the instruction,
805   /// if there is one.
806   virtual int64_t getFrameIndexInstrOffset(const MachineInstr *MI,
807                                            int Idx) const {
808     return 0;
809   }
810
811   /// Returns true if the instruction's frame index reference would be better
812   /// served by a base register other than FP or SP.
813   /// Used by LocalStackFrameAllocation to determine which frame index
814   /// references it should create new base registers for.
815   virtual bool needsFrameBaseReg(MachineInstr *MI, int64_t Offset) const {
816     return false;
817   }
818
819   /// Insert defining instruction(s) for BaseReg to be a pointer to FrameIdx
820   /// before insertion point I.
821   virtual void materializeFrameBaseRegister(MachineBasicBlock *MBB,
822                                             unsigned BaseReg, int FrameIdx,
823                                             int64_t Offset) const {
824     llvm_unreachable("materializeFrameBaseRegister does not exist on this "
825                      "target");
826   }
827
828   /// Resolve a frame index operand of an instruction
829   /// to reference the indicated base register plus offset instead.
830   virtual void resolveFrameIndex(MachineInstr &MI, unsigned BaseReg,
831                                  int64_t Offset) const {
832     llvm_unreachable("resolveFrameIndex does not exist on this target");
833   }
834
835   /// Determine whether a given base register plus offset immediate is
836   /// encodable to resolve a frame index.
837   virtual bool isFrameOffsetLegal(const MachineInstr *MI, unsigned BaseReg,
838                                   int64_t Offset) const {
839     llvm_unreachable("isFrameOffsetLegal does not exist on this target");
840   }
841
842   /// Spill the register so it can be used by the register scavenger.
843   /// Return true if the register was spilled, false otherwise.
844   /// If this function does not spill the register, the scavenger
845   /// will instead spill it to the emergency spill slot.
846   ///
847   virtual bool saveScavengerRegister(MachineBasicBlock &MBB,
848                                      MachineBasicBlock::iterator I,
849                                      MachineBasicBlock::iterator &UseMI,
850                                      const TargetRegisterClass *RC,
851                                      unsigned Reg) const {
852     return false;
853   }
854
855   /// This method must be overriden to eliminate abstract frame indices from
856   /// instructions which may use them. The instruction referenced by the
857   /// iterator contains an MO_FrameIndex operand which must be eliminated by
858   /// this method. This method may modify or replace the specified instruction,
859   /// as long as it keeps the iterator pointing at the finished product.
860   /// SPAdj is the SP adjustment due to call frame setup instruction.
861   /// FIOperandNum is the FI operand number.
862   virtual void eliminateFrameIndex(MachineBasicBlock::iterator MI,
863                                    int SPAdj, unsigned FIOperandNum,
864                                    RegScavenger *RS = nullptr) const = 0;
865
866   //===--------------------------------------------------------------------===//
867   /// Subtarget Hooks
868
869   /// \brief SrcRC and DstRC will be morphed into NewRC if this returns true.
870   virtual bool shouldCoalesce(MachineInstr *MI,
871                               const TargetRegisterClass *SrcRC,
872                               unsigned SubReg,
873                               const TargetRegisterClass *DstRC,
874                               unsigned DstSubReg,
875                               const TargetRegisterClass *NewRC) const
876   { return true; }
877
878   //===--------------------------------------------------------------------===//
879   /// Debug information queries.
880
881   /// getFrameRegister - This method should return the register used as a base
882   /// for values allocated in the current stack frame.
883   virtual unsigned getFrameRegister(const MachineFunction &MF) const = 0;
884 };
885
886
887 //===----------------------------------------------------------------------===//
888 //                           SuperRegClassIterator
889 //===----------------------------------------------------------------------===//
890 //
891 // Iterate over the possible super-registers for a given register class. The
892 // iterator will visit a list of pairs (Idx, Mask) corresponding to the
893 // possible classes of super-registers.
894 //
895 // Each bit mask will have at least one set bit, and each set bit in Mask
896 // corresponds to a SuperRC such that:
897 //
898 //   For all Reg in SuperRC: Reg:Idx is in RC.
899 //
900 // The iterator can include (O, RC->getSubClassMask()) as the first entry which
901 // also satisfies the above requirement, assuming Reg:0 == Reg.
902 //
903 class SuperRegClassIterator {
904   const unsigned RCMaskWords;
905   unsigned SubReg;
906   const uint16_t *Idx;
907   const uint32_t *Mask;
908
909 public:
910   /// Create a SuperRegClassIterator that visits all the super-register classes
911   /// of RC. When IncludeSelf is set, also include the (0, sub-classes) entry.
912   SuperRegClassIterator(const TargetRegisterClass *RC,
913                         const TargetRegisterInfo *TRI,
914                         bool IncludeSelf = false)
915     : RCMaskWords((TRI->getNumRegClasses() + 31) / 32),
916       SubReg(0),
917       Idx(RC->getSuperRegIndices()),
918       Mask(RC->getSubClassMask()) {
919     if (!IncludeSelf)
920       ++*this;
921   }
922
923   /// Returns true if this iterator is still pointing at a valid entry.
924   bool isValid() const { return Idx; }
925
926   /// Returns the current sub-register index.
927   unsigned getSubReg() const { return SubReg; }
928
929   /// Returns the bit mask if register classes that getSubReg() projects into
930   /// RC.
931   const uint32_t *getMask() const { return Mask; }
932
933   /// Advance iterator to the next entry.
934   void operator++() {
935     assert(isValid() && "Cannot move iterator past end.");
936     Mask += RCMaskWords;
937     SubReg = *Idx++;
938     if (!SubReg)
939       Idx = nullptr;
940   }
941 };
942
943 // This is useful when building IndexedMaps keyed on virtual registers
944 struct VirtReg2IndexFunctor : public std::unary_function<unsigned, unsigned> {
945   unsigned operator()(unsigned Reg) const {
946     return TargetRegisterInfo::virtReg2Index(Reg);
947   }
948 };
949
950 /// Prints virtual and physical registers with or without a TRI instance.
951 ///
952 /// The format is:
953 ///   %noreg          - NoRegister
954 ///   %vreg5          - a virtual register.
955 ///   %vreg5:sub_8bit - a virtual register with sub-register index (with TRI).
956 ///   %EAX            - a physical register
957 ///   %physreg17      - a physical register when no TRI instance given.
958 ///
959 /// Usage: OS << PrintReg(Reg, TRI) << '\n';
960 Printable PrintReg(unsigned Reg, const TargetRegisterInfo *TRI = nullptr,
961                    unsigned SubRegIdx = 0);
962
963 /// Create Printable object to print register units on a \ref raw_ostream.
964 ///
965 /// Register units are named after their root registers:
966 ///
967 ///   AL      - Single root.
968 ///   FP0~ST7 - Dual roots.
969 ///
970 /// Usage: OS << PrintRegUnit(Unit, TRI) << '\n';
971 Printable PrintRegUnit(unsigned Unit, const TargetRegisterInfo *TRI);
972
973 /// \brief Create Printable object to print virtual registers and physical
974 /// registers on a \ref raw_ostream.
975 Printable PrintVRegOrUnit(unsigned VRegOrUnit, const TargetRegisterInfo *TRI);
976
977 /// Create Printable object to print LaneBitmasks on a \ref raw_ostream.
978 Printable PrintLaneMask(LaneBitmask LaneMask);
979
980 } // End llvm namespace
981
982 #endif