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