TargetRegisterInfo.h revision 89e38f87211f6cf34c8b2e88a06c275a70c05421
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/MC/MCRegisterInfo.h"
20#include "llvm/CodeGen/MachineBasicBlock.h"
21#include "llvm/CodeGen/ValueTypes.h"
22#include "llvm/ADT/ArrayRef.h"
23#include "llvm/CallingConv.h"
24#include <cassert>
25#include <functional>
26
27namespace llvm {
28
29class BitVector;
30class MachineFunction;
31class RegScavenger;
32template<class T> class SmallVectorImpl;
33class raw_ostream;
34
35class TargetRegisterClass {
36public:
37  typedef const uint16_t* iterator;
38  typedef const uint16_t* const_iterator;
39  typedef const MVT::SimpleValueType* vt_iterator;
40  typedef const TargetRegisterClass* const * sc_iterator;
41
42  // Instance variables filled by tablegen, do not use!
43  const MCRegisterClass *MC;
44  const vt_iterator VTs;
45  const uint32_t *SubClassMask;
46  const uint16_t *SuperRegIndices;
47  const sc_iterator SuperClasses;
48  const sc_iterator SuperRegClasses;
49  ArrayRef<uint16_t> (*OrderFunc)(const MachineFunction&);
50
51  /// getID() - Return the register class ID number.
52  ///
53  unsigned getID() const { return MC->getID(); }
54
55  /// getName() - Return the register class name for debugging.
56  ///
57  const char *getName() const { return MC->getName(); }
58
59  /// begin/end - Return all of the registers in this class.
60  ///
61  iterator       begin() const { return MC->begin(); }
62  iterator         end() const { return MC->end(); }
63
64  /// getNumRegs - Return the number of registers in this class.
65  ///
66  unsigned getNumRegs() const { return MC->getNumRegs(); }
67
68  /// getRegister - Return the specified register in the class.
69  ///
70  unsigned getRegister(unsigned i) const {
71    return MC->getRegister(i);
72  }
73
74  /// contains - Return true if the specified register is included in this
75  /// register class.  This does not include virtual registers.
76  bool contains(unsigned Reg) const {
77    return MC->contains(Reg);
78  }
79
80  /// contains - Return true if both registers are in this class.
81  bool contains(unsigned Reg1, unsigned Reg2) const {
82    return MC->contains(Reg1, Reg2);
83  }
84
85  /// getSize - Return the size of the register in bytes, which is also the size
86  /// of a stack slot allocated to hold a spilled copy of this register.
87  unsigned getSize() const { return MC->getSize(); }
88
89  /// getAlignment - Return the minimum required alignment for a register of
90  /// this class.
91  unsigned getAlignment() const { return MC->getAlignment(); }
92
93  /// getCopyCost - Return the cost of copying a value between two registers in
94  /// this class. A negative number means the register class is very expensive
95  /// to copy e.g. status flag register classes.
96  int getCopyCost() const { return MC->getCopyCost(); }
97
98  /// isAllocatable - Return true if this register class may be used to create
99  /// virtual registers.
100  bool isAllocatable() const { return MC->isAllocatable(); }
101
102  /// hasType - return true if this TargetRegisterClass has the ValueType vt.
103  ///
104  bool hasType(EVT vt) const {
105    for(int i = 0; VTs[i] != MVT::Other; ++i)
106      if (EVT(VTs[i]) == vt)
107        return true;
108    return false;
109  }
110
111  /// vt_begin / vt_end - Loop over all of the value types that can be
112  /// represented by values in this register class.
113  vt_iterator vt_begin() const {
114    return VTs;
115  }
116
117  vt_iterator vt_end() const {
118    vt_iterator I = VTs;
119    while (*I != MVT::Other) ++I;
120    return I;
121  }
122
123  /// superregclasses_begin / superregclasses_end - Loop over all of
124  /// the superreg register classes of this register class.
125  sc_iterator superregclasses_begin() const {
126    return SuperRegClasses;
127  }
128
129  sc_iterator superregclasses_end() const {
130    sc_iterator I = SuperRegClasses;
131    while (*I != NULL) ++I;
132    return I;
133  }
134
135  /// hasSubClass - return true if the specified TargetRegisterClass
136  /// is a proper sub-class of this TargetRegisterClass.
137  bool hasSubClass(const TargetRegisterClass *RC) const {
138    return RC != this && hasSubClassEq(RC);
139  }
140
141  /// hasSubClassEq - Returns true if RC is a sub-class of or equal to this
142  /// class.
143  bool hasSubClassEq(const TargetRegisterClass *RC) const {
144    unsigned ID = RC->getID();
145    return (SubClassMask[ID / 32] >> (ID % 32)) & 1;
146  }
147
148  /// hasSuperClass - return true if the specified TargetRegisterClass is a
149  /// proper super-class of this TargetRegisterClass.
150  bool hasSuperClass(const TargetRegisterClass *RC) const {
151    return RC->hasSubClass(this);
152  }
153
154  /// hasSuperClassEq - Returns true if RC is a super-class of or equal to this
155  /// class.
156  bool hasSuperClassEq(const TargetRegisterClass *RC) const {
157    return RC->hasSubClassEq(this);
158  }
159
160  /// getSubClassMask - Returns a bit vector of subclasses, including this one.
161  /// The vector is indexed by class IDs, see hasSubClassEq() above for how to
162  /// use it.
163  const uint32_t *getSubClassMask() const {
164    return SubClassMask;
165  }
166
167  /// getSuperRegIndices - Returns a 0-terminated list of sub-register indices
168  /// that projec some super-register class into this register class. The list
169  /// has an entry for each Idx such that:
170  ///
171  ///   There exists SuperRC where:
172  ///     For all Reg in SuperRC:
173  ///       this->contains(Reg:Idx)
174  ///
175  const uint16_t *getSuperRegIndices() const {
176    return SuperRegIndices;
177  }
178
179  /// getSuperClasses - Returns a NULL terminated list of super-classes.  The
180  /// classes are ordered by ID which is also a topological ordering from large
181  /// to small classes.  The list does NOT include the current class.
182  sc_iterator getSuperClasses() const {
183    return SuperClasses;
184  }
185
186  /// isASubClass - return true if this TargetRegisterClass is a subset
187  /// class of at least one other TargetRegisterClass.
188  bool isASubClass() const {
189    return SuperClasses[0] != 0;
190  }
191
192  /// getRawAllocationOrder - Returns the preferred order for allocating
193  /// registers from this register class in MF. The raw order comes directly
194  /// from the .td file and may include reserved registers that are not
195  /// allocatable. Register allocators should also make sure to allocate
196  /// callee-saved registers only after all the volatiles are used. The
197  /// RegisterClassInfo class provides filtered allocation orders with
198  /// callee-saved registers moved to the end.
199  ///
200  /// The MachineFunction argument can be used to tune the allocatable
201  /// registers based on the characteristics of the function, subtarget, or
202  /// other criteria.
203  ///
204  /// By default, this method returns all registers in the class.
205  ///
206  ArrayRef<uint16_t> getRawAllocationOrder(const MachineFunction &MF) const {
207    return OrderFunc ? OrderFunc(MF) : makeArrayRef(begin(), getNumRegs());
208  }
209};
210
211/// TargetRegisterInfoDesc - Extra information, not in MCRegisterDesc, about
212/// registers. These are used by codegen, not by MC.
213struct TargetRegisterInfoDesc {
214  unsigned CostPerUse;          // Extra cost of instructions using register.
215  bool inAllocatableClass;      // Register belongs to an allocatable regclass.
216};
217
218/// Each TargetRegisterClass has a per register weight, and weight
219/// limit which must be less than the limits of its pressure sets.
220struct RegClassWeight {
221  unsigned RegWeight;
222  unsigned WeightLimit;
223};
224
225/// TargetRegisterInfo base class - We assume that the target defines a static
226/// array of TargetRegisterDesc objects that represent all of the machine
227/// registers that the target has.  As such, we simply have to track a pointer
228/// to this array so that we can turn register number into a register
229/// descriptor.
230///
231class TargetRegisterInfo : public MCRegisterInfo {
232public:
233  typedef const TargetRegisterClass * const * regclass_iterator;
234private:
235  const TargetRegisterInfoDesc *InfoDesc;     // Extra desc array for codegen
236  const char *const *SubRegIndexNames;        // Names of subreg indexes.
237  regclass_iterator RegClassBegin, RegClassEnd;   // List of regclasses
238
239protected:
240  TargetRegisterInfo(const TargetRegisterInfoDesc *ID,
241                     regclass_iterator RegClassBegin,
242                     regclass_iterator RegClassEnd,
243                     const char *const *subregindexnames);
244  virtual ~TargetRegisterInfo();
245public:
246
247  // Register numbers can represent physical registers, virtual registers, and
248  // sometimes stack slots. The unsigned values are divided into these ranges:
249  //
250  //   0           Not a register, can be used as a sentinel.
251  //   [1;2^30)    Physical registers assigned by TableGen.
252  //   [2^30;2^31) Stack slots. (Rarely used.)
253  //   [2^31;2^32) Virtual registers assigned by MachineRegisterInfo.
254  //
255  // Further sentinels can be allocated from the small negative integers.
256  // DenseMapInfo<unsigned> uses -1u and -2u.
257
258  /// isStackSlot - Sometimes it is useful the be able to store a non-negative
259  /// frame index in a variable that normally holds a register. isStackSlot()
260  /// returns true if Reg is in the range used for stack slots.
261  ///
262  /// Note that isVirtualRegister() and isPhysicalRegister() cannot handle stack
263  /// slots, so if a variable may contains a stack slot, always check
264  /// isStackSlot() first.
265  ///
266  static bool isStackSlot(unsigned Reg) {
267    return int(Reg) >= (1 << 30);
268  }
269
270  /// stackSlot2Index - Compute the frame index from a register value
271  /// representing a stack slot.
272  static int stackSlot2Index(unsigned Reg) {
273    assert(isStackSlot(Reg) && "Not a stack slot");
274    return int(Reg - (1u << 30));
275  }
276
277  /// index2StackSlot - Convert a non-negative frame index to a stack slot
278  /// register value.
279  static unsigned index2StackSlot(int FI) {
280    assert(FI >= 0 && "Cannot hold a negative frame index.");
281    return FI + (1u << 30);
282  }
283
284  /// isPhysicalRegister - Return true if the specified register number is in
285  /// the physical register namespace.
286  static bool isPhysicalRegister(unsigned Reg) {
287    assert(!isStackSlot(Reg) && "Not a register! Check isStackSlot() first.");
288    return int(Reg) > 0;
289  }
290
291  /// isVirtualRegister - Return true if the specified register number is in
292  /// the virtual register namespace.
293  static bool isVirtualRegister(unsigned Reg) {
294    assert(!isStackSlot(Reg) && "Not a register! Check isStackSlot() first.");
295    return int(Reg) < 0;
296  }
297
298  /// virtReg2Index - Convert a virtual register number to a 0-based index.
299  /// The first virtual register in a function will get the index 0.
300  static unsigned virtReg2Index(unsigned Reg) {
301    assert(isVirtualRegister(Reg) && "Not a virtual register");
302    return Reg & ~(1u << 31);
303  }
304
305  /// index2VirtReg - Convert a 0-based index to a virtual register number.
306  /// This is the inverse operation of VirtReg2IndexFunctor below.
307  static unsigned index2VirtReg(unsigned Index) {
308    return Index | (1u << 31);
309  }
310
311  /// getMinimalPhysRegClass - Returns the Register Class of a physical
312  /// register of the given type, picking the most sub register class of
313  /// the right type that contains this physreg.
314  const TargetRegisterClass *
315    getMinimalPhysRegClass(unsigned Reg, EVT VT = MVT::Other) const;
316
317  /// getAllocatableClass - Return the maximal subclass of the given register
318  /// class that is alloctable, or NULL.
319  const TargetRegisterClass *
320    getAllocatableClass(const TargetRegisterClass *RC) const;
321
322  /// getAllocatableSet - Returns a bitset indexed by register number
323  /// indicating if a register is allocatable or not. If a register class is
324  /// specified, returns the subset for the class.
325  BitVector getAllocatableSet(const MachineFunction &MF,
326                              const TargetRegisterClass *RC = NULL) const;
327
328  /// getCostPerUse - Return the additional cost of using this register instead
329  /// of other registers in its class.
330  unsigned getCostPerUse(unsigned RegNo) const {
331    return InfoDesc[RegNo].CostPerUse;
332  }
333
334  /// isInAllocatableClass - Return true if the register is in the allocation
335  /// of any register class.
336  bool isInAllocatableClass(unsigned RegNo) const {
337    return InfoDesc[RegNo].inAllocatableClass;
338  }
339
340  /// getSubRegIndexName - Return the human-readable symbolic target-specific
341  /// name for the specified SubRegIndex.
342  const char *getSubRegIndexName(unsigned SubIdx) const {
343    assert(SubIdx && "This is not a subregister index");
344    return SubRegIndexNames[SubIdx-1];
345  }
346
347  /// regsOverlap - Returns true if the two registers are equal or alias each
348  /// other. The registers may be virtual register.
349  bool regsOverlap(unsigned regA, unsigned regB) const {
350    if (regA == regB) return true;
351    if (isVirtualRegister(regA) || isVirtualRegister(regB))
352      return false;
353    for (const uint16_t *regList = getOverlaps(regA)+1; *regList; ++regList) {
354      if (*regList == regB) return true;
355    }
356    return false;
357  }
358
359  /// isSubRegister - Returns true if regB is a sub-register of regA.
360  ///
361  bool isSubRegister(unsigned regA, unsigned regB) const {
362    return isSuperRegister(regB, regA);
363  }
364
365  /// isSuperRegister - Returns true if regB is a super-register of regA.
366  ///
367  bool isSuperRegister(unsigned regA, unsigned regB) const {
368    for (const uint16_t *regList = getSuperRegisters(regA); *regList;++regList){
369      if (*regList == regB) return true;
370    }
371    return false;
372  }
373
374  /// getCalleeSavedRegs - Return a null-terminated list of all of the
375  /// callee saved registers on this target. The register should be in the
376  /// order of desired callee-save stack frame offset. The first register is
377  /// closest to the incoming stack pointer if stack grows down, and vice versa.
378  ///
379  virtual const uint16_t* getCalleeSavedRegs(const MachineFunction *MF = 0)
380                                                                      const = 0;
381
382  /// getCallPreservedMask - Return a mask of call-preserved registers for the
383  /// given calling convention on the current sub-target.  The mask should
384  /// include all call-preserved aliases.  This is used by the register
385  /// allocator to determine which registers can be live across a call.
386  ///
387  /// The mask is an array containing (TRI::getNumRegs()+31)/32 entries.
388  /// A set bit indicates that all bits of the corresponding register are
389  /// preserved across the function call.  The bit mask is expected to be
390  /// sub-register complete, i.e. if A is preserved, so are all its
391  /// sub-registers.
392  ///
393  /// Bits are numbered from the LSB, so the bit for physical register Reg can
394  /// be found as (Mask[Reg / 32] >> Reg % 32) & 1.
395  ///
396  /// A NULL pointer means that no register mask will be used, and call
397  /// instructions should use implicit-def operands to indicate call clobbered
398  /// registers.
399  ///
400  virtual const uint32_t *getCallPreservedMask(CallingConv::ID) const {
401    // The default mask clobbers everything.  All targets should override.
402    return 0;
403  }
404
405  /// getReservedRegs - Returns a bitset indexed by physical register number
406  /// indicating if a register is a special register that has particular uses
407  /// and should be considered unavailable at all times, e.g. SP, RA. This is
408  /// used by register scavenger to determine what registers are free.
409  virtual BitVector getReservedRegs(const MachineFunction &MF) const = 0;
410
411  /// getMatchingSuperReg - Return a super-register of the specified register
412  /// Reg so its sub-register of index SubIdx is Reg.
413  unsigned getMatchingSuperReg(unsigned Reg, unsigned SubIdx,
414                               const TargetRegisterClass *RC) const {
415    return MCRegisterInfo::getMatchingSuperReg(Reg, SubIdx, RC->MC);
416  }
417
418  /// canCombineSubRegIndices - Given a register class and a list of
419  /// subregister indices, return true if it's possible to combine the
420  /// subregister indices into one that corresponds to a larger
421  /// subregister. Return the new subregister index by reference. Note the
422  /// new index may be zero if the given subregisters can be combined to
423  /// form the whole register.
424  virtual bool canCombineSubRegIndices(const TargetRegisterClass *RC,
425                                       SmallVectorImpl<unsigned> &SubIndices,
426                                       unsigned &NewSubIdx) const {
427    return 0;
428  }
429
430  /// getMatchingSuperRegClass - Return a subclass of the specified register
431  /// class A so that each register in it has a sub-register of the
432  /// specified sub-register index which is in the specified register class B.
433  ///
434  /// TableGen will synthesize missing A sub-classes.
435  virtual const TargetRegisterClass *
436  getMatchingSuperRegClass(const TargetRegisterClass *A,
437                           const TargetRegisterClass *B, unsigned Idx) const;
438
439  /// getSubClassWithSubReg - Returns the largest legal sub-class of RC that
440  /// supports the sub-register index Idx.
441  /// If no such sub-class exists, return NULL.
442  /// If all registers in RC already have an Idx sub-register, return RC.
443  ///
444  /// TableGen generates a version of this function that is good enough in most
445  /// cases.  Targets can override if they have constraints that TableGen
446  /// doesn't understand.  For example, the x86 sub_8bit sub-register index is
447  /// supported by the full GR32 register class in 64-bit mode, but only by the
448  /// GR32_ABCD regiister class in 32-bit mode.
449  ///
450  /// TableGen will synthesize missing RC sub-classes.
451  virtual const TargetRegisterClass *
452  getSubClassWithSubReg(const TargetRegisterClass *RC, unsigned Idx) const {
453    assert(Idx == 0 && "Target has no sub-registers");
454    return RC;
455  }
456
457  /// composeSubRegIndices - Return the subregister index you get from composing
458  /// two subregister indices.
459  ///
460  /// If R:a:b is the same register as R:c, then composeSubRegIndices(a, b)
461  /// returns c. Note that composeSubRegIndices does not tell you about illegal
462  /// compositions. If R does not have a subreg a, or R:a does not have a subreg
463  /// b, composeSubRegIndices doesn't tell you.
464  ///
465  /// The ARM register Q0 has two D subregs dsub_0:D0 and dsub_1:D1. It also has
466  /// ssub_0:S0 - ssub_3:S3 subregs.
467  /// If you compose subreg indices dsub_1, ssub_0 you get ssub_2.
468  ///
469  virtual unsigned composeSubRegIndices(unsigned a, unsigned b) const {
470    // This default implementation is correct for most targets.
471    return b;
472  }
473
474  //===--------------------------------------------------------------------===//
475  // Register Class Information
476  //
477
478  /// Register class iterators
479  ///
480  regclass_iterator regclass_begin() const { return RegClassBegin; }
481  regclass_iterator regclass_end() const { return RegClassEnd; }
482
483  unsigned getNumRegClasses() const {
484    return (unsigned)(regclass_end()-regclass_begin());
485  }
486
487  /// getRegClass - Returns the register class associated with the enumeration
488  /// value.  See class MCOperandInfo.
489  const TargetRegisterClass *getRegClass(unsigned i) const {
490    assert(i < getNumRegClasses() && "Register Class ID out of range");
491    return RegClassBegin[i];
492  }
493
494  /// getCommonSubClass - find the largest common subclass of A and B. Return
495  /// NULL if there is no common subclass.
496  const TargetRegisterClass *
497  getCommonSubClass(const TargetRegisterClass *A,
498                    const TargetRegisterClass *B) const;
499
500  /// getPointerRegClass - Returns a TargetRegisterClass used for pointer
501  /// values.  If a target supports multiple different pointer register classes,
502  /// kind specifies which one is indicated.
503  virtual const TargetRegisterClass *getPointerRegClass(unsigned Kind=0) const {
504    llvm_unreachable("Target didn't implement getPointerRegClass!");
505  }
506
507  /// getCrossCopyRegClass - Returns a legal register class to copy a register
508  /// in the specified class to or from. If it is possible to copy the register
509  /// directly without using a cross register class copy, return the specified
510  /// RC. Returns NULL if it is not possible to copy between a two registers of
511  /// the specified class.
512  virtual const TargetRegisterClass *
513  getCrossCopyRegClass(const TargetRegisterClass *RC) const {
514    return RC;
515  }
516
517  /// getLargestLegalSuperClass - Returns the largest super class of RC that is
518  /// legal to use in the current sub-target and has the same spill size.
519  /// The returned register class can be used to create virtual registers which
520  /// means that all its registers can be copied and spilled.
521  virtual const TargetRegisterClass*
522  getLargestLegalSuperClass(const TargetRegisterClass *RC) const {
523    /// The default implementation is very conservative and doesn't allow the
524    /// register allocator to inflate register classes.
525    return RC;
526  }
527
528  /// getRegPressureLimit - Return the register pressure "high water mark" for
529  /// the specific register class. The scheduler is in high register pressure
530  /// mode (for the specific register class) if it goes over the limit.
531  ///
532  /// Note: this is the old register pressure model that relies on a manually
533  /// specified representative register class per value type.
534  virtual unsigned getRegPressureLimit(const TargetRegisterClass *RC,
535                                       MachineFunction &MF) const {
536    return 0;
537  }
538
539// Get the weight in units of pressure for this register class.
540  virtual const RegClassWeight &getRegClassWeight(
541    const TargetRegisterClass *RC) const = 0;
542
543  /// Get the number of dimensions of register pressure.
544  virtual unsigned getNumRegPressureSets() const = 0;
545
546  /// Get the name of this register unit pressure set.
547  virtual const char *getRegPressureSetName(unsigned Idx) const = 0;
548
549  /// Get the register unit pressure limit for this dimension.
550  /// This limit must be adjusted dynamically for reserved registers.
551  virtual unsigned getRegPressureSetLimit(unsigned Idx) const = 0;
552
553  /// Get the dimensions of register pressure impacted by this register class.
554  /// Returns a -1 terminated array of pressure set IDs.
555  virtual const int *getRegClassPressureSets(
556    const TargetRegisterClass *RC) const = 0;
557
558  /// getRawAllocationOrder - Returns the register allocation order for a
559  /// specified register class with a target-dependent hint. The returned list
560  /// may contain reserved registers that cannot be allocated.
561  ///
562  /// Register allocators need only call this function to resolve
563  /// target-dependent hints, but it should work without hinting as well.
564  virtual ArrayRef<uint16_t>
565  getRawAllocationOrder(const TargetRegisterClass *RC,
566                        unsigned HintType, unsigned HintReg,
567                        const MachineFunction &MF) const {
568    return RC->getRawAllocationOrder(MF);
569  }
570
571  /// ResolveRegAllocHint - Resolves the specified register allocation hint
572  /// to a physical register. Returns the physical register if it is successful.
573  virtual unsigned ResolveRegAllocHint(unsigned Type, unsigned Reg,
574                                       const MachineFunction &MF) const {
575    if (Type == 0 && Reg && isPhysicalRegister(Reg))
576      return Reg;
577    return 0;
578  }
579
580  /// avoidWriteAfterWrite - Return true if the register allocator should avoid
581  /// writing a register from RC in two consecutive instructions.
582  /// This can avoid pipeline stalls on certain architectures.
583  /// It does cause increased register pressure, though.
584  virtual bool avoidWriteAfterWrite(const TargetRegisterClass *RC) const {
585    return false;
586  }
587
588  /// UpdateRegAllocHint - A callback to allow target a chance to update
589  /// register allocation hints when a register is "changed" (e.g. coalesced)
590  /// to another register. e.g. On ARM, some virtual registers should target
591  /// register pairs, if one of pair is coalesced to another register, the
592  /// allocation hint of the other half of the pair should be changed to point
593  /// to the new register.
594  virtual void UpdateRegAllocHint(unsigned Reg, unsigned NewReg,
595                                  MachineFunction &MF) const {
596    // Do nothing.
597  }
598
599  /// requiresRegisterScavenging - returns true if the target requires (and can
600  /// make use of) the register scavenger.
601  virtual bool requiresRegisterScavenging(const MachineFunction &MF) const {
602    return false;
603  }
604
605  /// useFPForScavengingIndex - returns true if the target wants to use
606  /// frame pointer based accesses to spill to the scavenger emergency spill
607  /// slot.
608  virtual bool useFPForScavengingIndex(const MachineFunction &MF) const {
609    return true;
610  }
611
612  /// requiresFrameIndexScavenging - returns true if the target requires post
613  /// PEI scavenging of registers for materializing frame index constants.
614  virtual bool requiresFrameIndexScavenging(const MachineFunction &MF) const {
615    return false;
616  }
617
618  /// requiresVirtualBaseRegisters - Returns true if the target wants the
619  /// LocalStackAllocation pass to be run and virtual base registers
620  /// used for more efficient stack access.
621  virtual bool requiresVirtualBaseRegisters(const MachineFunction &MF) const {
622    return false;
623  }
624
625  /// hasReservedSpillSlot - Return true if target has reserved a spill slot in
626  /// the stack frame of the given function for the specified register. e.g. On
627  /// x86, if the frame register is required, the first fixed stack object is
628  /// reserved as its spill slot. This tells PEI not to create a new stack frame
629  /// object for the given register. It should be called only after
630  /// processFunctionBeforeCalleeSavedScan().
631  virtual bool hasReservedSpillSlot(const MachineFunction &MF, unsigned Reg,
632                                    int &FrameIdx) const {
633    return false;
634  }
635
636  /// trackLivenessAfterRegAlloc - returns true if the live-ins should be tracked
637  /// after register allocation.
638  virtual bool trackLivenessAfterRegAlloc(const MachineFunction &MF) const {
639    return false;
640  }
641
642  /// needsStackRealignment - true if storage within the function requires the
643  /// stack pointer to be aligned more than the normal calling convention calls
644  /// for.
645  virtual bool needsStackRealignment(const MachineFunction &MF) const {
646    return false;
647  }
648
649  /// getFrameIndexInstrOffset - Get the offset from the referenced frame
650  /// index in the instruction, if there is one.
651  virtual int64_t getFrameIndexInstrOffset(const MachineInstr *MI,
652                                           int Idx) const {
653    return 0;
654  }
655
656  /// needsFrameBaseReg - Returns true if the instruction's frame index
657  /// reference would be better served by a base register other than FP
658  /// or SP. Used by LocalStackFrameAllocation to determine which frame index
659  /// references it should create new base registers for.
660  virtual bool needsFrameBaseReg(MachineInstr *MI, int64_t Offset) const {
661    return false;
662  }
663
664  /// materializeFrameBaseRegister - Insert defining instruction(s) for
665  /// BaseReg to be a pointer to FrameIdx before insertion point I.
666  virtual void materializeFrameBaseRegister(MachineBasicBlock *MBB,
667                                            unsigned BaseReg, int FrameIdx,
668                                            int64_t Offset) const {
669    llvm_unreachable("materializeFrameBaseRegister does not exist on this "
670                     "target");
671  }
672
673  /// resolveFrameIndex - Resolve a frame index operand of an instruction
674  /// to reference the indicated base register plus offset instead.
675  virtual void resolveFrameIndex(MachineBasicBlock::iterator I,
676                                 unsigned BaseReg, int64_t Offset) const {
677    llvm_unreachable("resolveFrameIndex does not exist on this target");
678  }
679
680  /// isFrameOffsetLegal - Determine whether a given offset immediate is
681  /// encodable to resolve a frame index.
682  virtual bool isFrameOffsetLegal(const MachineInstr *MI,
683                                  int64_t Offset) const {
684    llvm_unreachable("isFrameOffsetLegal does not exist on this target");
685  }
686
687  /// eliminateCallFramePseudoInstr - This method is called during prolog/epilog
688  /// code insertion to eliminate call frame setup and destroy pseudo
689  /// instructions (but only if the Target is using them).  It is responsible
690  /// for eliminating these instructions, replacing them with concrete
691  /// instructions.  This method need only be implemented if using call frame
692  /// setup/destroy pseudo instructions.
693  ///
694  virtual void
695  eliminateCallFramePseudoInstr(MachineFunction &MF,
696                                MachineBasicBlock &MBB,
697                                MachineBasicBlock::iterator MI) const {
698    llvm_unreachable("Call Frame Pseudo Instructions do not exist on this "
699                     "target!");
700  }
701
702
703  /// saveScavengerRegister - Spill the register so it can be used by the
704  /// register scavenger. Return true if the register was spilled, false
705  /// otherwise. If this function does not spill the register, the scavenger
706  /// will instead spill it to the emergency spill slot.
707  ///
708  virtual bool saveScavengerRegister(MachineBasicBlock &MBB,
709                                     MachineBasicBlock::iterator I,
710                                     MachineBasicBlock::iterator &UseMI,
711                                     const TargetRegisterClass *RC,
712                                     unsigned Reg) const {
713    return false;
714  }
715
716  /// eliminateFrameIndex - This method must be overriden to eliminate abstract
717  /// frame indices from instructions which may use them.  The instruction
718  /// referenced by the iterator contains an MO_FrameIndex operand which must be
719  /// eliminated by this method.  This method may modify or replace the
720  /// specified instruction, as long as it keeps the iterator pointing at the
721  /// finished product. SPAdj is the SP adjustment due to call frame setup
722  /// instruction.
723  virtual void eliminateFrameIndex(MachineBasicBlock::iterator MI,
724                                   int SPAdj, RegScavenger *RS=NULL) const = 0;
725
726  //===--------------------------------------------------------------------===//
727  /// Debug information queries.
728
729  /// getFrameRegister - This method should return the register used as a base
730  /// for values allocated in the current stack frame.
731  virtual unsigned getFrameRegister(const MachineFunction &MF) const = 0;
732
733  /// getCompactUnwindRegNum - This function maps the register to the number for
734  /// compact unwind encoding. Return -1 if the register isn't valid.
735  virtual int getCompactUnwindRegNum(unsigned, bool) const {
736    return -1;
737  }
738};
739
740
741//===----------------------------------------------------------------------===//
742//                           SuperRegClassIterator
743//===----------------------------------------------------------------------===//
744//
745// Iterate over the possible super-registers for a given register class. The
746// iterator will visit a list of pairs (Idx, Mask) corresponding to the
747// possible classes of super-registers.
748//
749// Each bit mask will have at least one set bit, and each set bit in Mask
750// corresponds to a SuperRC such that:
751//
752//   For all Reg in SuperRC: Reg:Idx is in RC.
753//
754// The iterator can include (O, RC->getSubClassMask()) as the first entry which
755// also satisfies the above requirement, assuming Reg:0 == Reg.
756//
757class SuperRegClassIterator {
758  const unsigned RCMaskWords;
759  unsigned SubReg;
760  const uint16_t *Idx;
761  const uint32_t *Mask;
762
763public:
764  /// Create a SuperRegClassIterator that visits all the super-register classes
765  /// of RC. When IncludeSelf is set, also include the (0, sub-classes) entry.
766  SuperRegClassIterator(const TargetRegisterClass *RC,
767                        const TargetRegisterInfo *TRI,
768                        bool IncludeSelf = false)
769    : RCMaskWords((TRI->getNumRegClasses() + 31) / 32),
770      SubReg(0),
771      Idx(RC->getSuperRegIndices()),
772      Mask(RC->getSubClassMask()) {
773    if (!IncludeSelf)
774      ++*this;
775  }
776
777  /// Returns true if this iterator is still pointing at a valid entry.
778  bool isValid() const { return Idx; }
779
780  /// Returns the current sub-register index.
781  unsigned getSubReg() const { return SubReg; }
782
783  /// Returns the bit mask if register classes that getSubReg() projects into
784  /// RC.
785  const uint32_t *getMask() const { return Mask; }
786
787  /// Advance iterator to the next entry.
788  void operator++() {
789    assert(isValid() && "Cannot move iterator past end.");
790    Mask += RCMaskWords;
791    SubReg = *Idx++;
792    if (!SubReg)
793      Idx = 0;
794  }
795};
796
797// This is useful when building IndexedMaps keyed on virtual registers
798struct VirtReg2IndexFunctor : public std::unary_function<unsigned, unsigned> {
799  unsigned operator()(unsigned Reg) const {
800    return TargetRegisterInfo::virtReg2Index(Reg);
801  }
802};
803
804/// PrintReg - Helper class for printing registers on a raw_ostream.
805/// Prints virtual and physical registers with or without a TRI instance.
806///
807/// The format is:
808///   %noreg          - NoRegister
809///   %vreg5          - a virtual register.
810///   %vreg5:sub_8bit - a virtual register with sub-register index (with TRI).
811///   %EAX            - a physical register
812///   %physreg17      - a physical register when no TRI instance given.
813///
814/// Usage: OS << PrintReg(Reg, TRI) << '\n';
815///
816class PrintReg {
817  const TargetRegisterInfo *TRI;
818  unsigned Reg;
819  unsigned SubIdx;
820public:
821  PrintReg(unsigned reg, const TargetRegisterInfo *tri = 0, unsigned subidx = 0)
822    : TRI(tri), Reg(reg), SubIdx(subidx) {}
823  void print(raw_ostream&) const;
824};
825
826static inline raw_ostream &operator<<(raw_ostream &OS, const PrintReg &PR) {
827  PR.print(OS);
828  return OS;
829}
830
831} // End llvm namespace
832
833#endif
834