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