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