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