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