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