TargetRegisterInfo.h revision 79c890f64f3b67f9b11341aa452c4302b75184aa
1fed90b6d097d50881afb45e4d79f430db66dd741Dan Gohman//=== Target/TargetRegisterInfo.h - Target Register Information -*- C++ -*-===//
23a54b3dc87a581c203b18050b4f787b4ca28a12cMisha Brukman//
3fed90b6d097d50881afb45e4d79f430db66dd741Dan Gohman//                     The LLVM Compiler Infrastructure
4fed90b6d097d50881afb45e4d79f430db66dd741Dan Gohman//
5fed90b6d097d50881afb45e4d79f430db66dd741Dan Gohman// This file is distributed under the University of Illinois Open Source
6fed90b6d097d50881afb45e4d79f430db66dd741Dan Gohman// License. See LICENSE.TXT for details.
73a54b3dc87a581c203b18050b4f787b4ca28a12cMisha Brukman//
8fed90b6d097d50881afb45e4d79f430db66dd741Dan Gohman//===----------------------------------------------------------------------===//
9fed90b6d097d50881afb45e4d79f430db66dd741Dan Gohman//
10fed90b6d097d50881afb45e4d79f430db66dd741Dan Gohman// This file describes an abstract interface used to get information about a
11fed90b6d097d50881afb45e4d79f430db66dd741Dan Gohman// target machines register file.  This information is used for a variety of
12fed90b6d097d50881afb45e4d79f430db66dd741Dan Gohman// purposed, especially register allocation.
13fed90b6d097d50881afb45e4d79f430db66dd741Dan Gohman//
14fed90b6d097d50881afb45e4d79f430db66dd741Dan Gohman//===----------------------------------------------------------------------===//
15674be02d525d4e24bc6943ed9274958c580bcfbcJakub Staszak
16674be02d525d4e24bc6943ed9274958c580bcfbcJakub Staszak#ifndef LLVM_TARGET_TARGETREGISTERINFO_H
17fed90b6d097d50881afb45e4d79f430db66dd741Dan Gohman#define LLVM_TARGET_TARGETREGISTERINFO_H
18fed90b6d097d50881afb45e4d79f430db66dd741Dan Gohman
19fed90b6d097d50881afb45e4d79f430db66dd741Dan Gohman#include "llvm/CodeGen/MachineBasicBlock.h"
20fed90b6d097d50881afb45e4d79f430db66dd741Dan Gohman#include "llvm/CodeGen/ValueTypes.h"
212600ca8b3f3602d0904289eeed3d26f3d7aad2aeGabor Greif#include "llvm/ADT/ArrayRef.h"
22fd7a918e5890a6c0611ab6b3fca7001d16593844Gabor Greif#include "llvm/ADT/DenseSet.h"
232600ca8b3f3602d0904289eeed3d26f3d7aad2aeGabor Greif#include <cassert>
242600ca8b3f3602d0904289eeed3d26f3d7aad2aeGabor Greif#include <functional>
25fd7a918e5890a6c0611ab6b3fca7001d16593844Gabor Greif
262600ca8b3f3602d0904289eeed3d26f3d7aad2aeGabor Greifnamespace llvm {
272600ca8b3f3602d0904289eeed3d26f3d7aad2aeGabor Greif
282600ca8b3f3602d0904289eeed3d26f3d7aad2aeGabor Greifclass BitVector;
292600ca8b3f3602d0904289eeed3d26f3d7aad2aeGabor Greifclass MachineFunction;
302600ca8b3f3602d0904289eeed3d26f3d7aad2aeGabor Greifclass MachineMove;
312600ca8b3f3602d0904289eeed3d26f3d7aad2aeGabor Greifclass RegScavenger;
322600ca8b3f3602d0904289eeed3d26f3d7aad2aeGabor Greiftemplate<class T> class SmallVectorImpl;
332600ca8b3f3602d0904289eeed3d26f3d7aad2aeGabor Greifclass raw_ostream;
342600ca8b3f3602d0904289eeed3d26f3d7aad2aeGabor Greif
352600ca8b3f3602d0904289eeed3d26f3d7aad2aeGabor Greif/// TargetRegisterDesc - This record contains all of the information known about
362600ca8b3f3602d0904289eeed3d26f3d7aad2aeGabor Greif/// a particular register.  The Overlaps field contains a pointer to a zero
372600ca8b3f3602d0904289eeed3d26f3d7aad2aeGabor Greif/// terminated array of registers that this register aliases, starting with
380a0e68a7eac0513505aff3079e2d5d6864e51895Gabor Greif/// itself. This is needed for architectures like X86 which have AL alias AX
39fed90b6d097d50881afb45e4d79f430db66dd741Dan Gohman/// alias EAX. The SubRegs field is a zero terminated array of registers that
40fed90b6d097d50881afb45e4d79f430db66dd741Dan Gohman/// are sub-registers of the specific register, e.g. AL, AH are sub-registers of
41fed90b6d097d50881afb45e4d79f430db66dd741Dan Gohman/// AX. The SuperRegs field is a zero terminated array of registers that are
42fed90b6d097d50881afb45e4d79f430db66dd741Dan Gohman/// super-registers of the specific register, e.g. RAX, EAX, are super-registers
4359bf4fcc0680e75b408579064d1205a132361196Duncan Sands/// of AX.
44fed90b6d097d50881afb45e4d79f430db66dd741Dan Gohman///
45a05764c4fb1ff4fc6013dcfd71fc83fb25cdcd27Gabor Greifstruct TargetRegisterDesc {
462600ca8b3f3602d0904289eeed3d26f3d7aad2aeGabor Greif  const char     *Name;         // Printable name for the reg (for debugging)
47fed90b6d097d50881afb45e4d79f430db66dd741Dan Gohman  const unsigned *Overlaps;     // Overlapping registers, described above
48fed90b6d097d50881afb45e4d79f430db66dd741Dan Gohman  const unsigned *SubRegs;      // Sub-register set, described above
49fed90b6d097d50881afb45e4d79f430db66dd741Dan Gohman  const unsigned *SuperRegs;    // Super-register set, described above
50fed90b6d097d50881afb45e4d79f430db66dd741Dan Gohman  unsigned CostPerUse;          // Extra cost of instructions using register.
512600ca8b3f3602d0904289eeed3d26f3d7aad2aeGabor Greif  bool inAllocatableClass;      // Register belongs to an allocatable regclass.
52aa81380353a27d9d216cafdd88df08a5eef43b74Daniel Dunbar};
53aa81380353a27d9d216cafdd88df08a5eef43b74Daniel Dunbar
54aa81380353a27d9d216cafdd88df08a5eef43b74Daniel Dunbarclass TargetRegisterClass {
55aa81380353a27d9d216cafdd88df08a5eef43b74Daniel Dunbarpublic:
56aa81380353a27d9d216cafdd88df08a5eef43b74Daniel Dunbar  typedef const unsigned* iterator;
57aa81380353a27d9d216cafdd88df08a5eef43b74Daniel Dunbar  typedef const unsigned* const_iterator;
58aa81380353a27d9d216cafdd88df08a5eef43b74Daniel Dunbar
59aa81380353a27d9d216cafdd88df08a5eef43b74Daniel Dunbar  typedef const EVT* vt_iterator;
60aa81380353a27d9d216cafdd88df08a5eef43b74Daniel Dunbar  typedef const TargetRegisterClass* const * sc_iterator;
61aa81380353a27d9d216cafdd88df08a5eef43b74Daniel Dunbarprivate:
62aa81380353a27d9d216cafdd88df08a5eef43b74Daniel Dunbar  unsigned ID;
63aa81380353a27d9d216cafdd88df08a5eef43b74Daniel Dunbar  const char *Name;
64aa81380353a27d9d216cafdd88df08a5eef43b74Daniel Dunbar  const vt_iterator VTs;
65aa81380353a27d9d216cafdd88df08a5eef43b74Daniel Dunbar  const sc_iterator SubClasses;
66aa81380353a27d9d216cafdd88df08a5eef43b74Daniel Dunbar  const sc_iterator SuperClasses;
67aa81380353a27d9d216cafdd88df08a5eef43b74Daniel Dunbar  const sc_iterator SubRegClasses;
68aa81380353a27d9d216cafdd88df08a5eef43b74Daniel Dunbar  const sc_iterator SuperRegClasses;
69aa81380353a27d9d216cafdd88df08a5eef43b74Daniel Dunbar  const unsigned RegSize, Alignment;    // Size & Alignment of register in bytes
70f1fd2288f36b58b8979761ba09e2a398c6afd110Daniel Dunbar  const int CopyCost;
71aa81380353a27d9d216cafdd88df08a5eef43b74Daniel Dunbar  const bool Allocatable;
72aa81380353a27d9d216cafdd88df08a5eef43b74Daniel Dunbar  const iterator RegsBegin, RegsEnd;
73aa81380353a27d9d216cafdd88df08a5eef43b74Daniel Dunbar  DenseSet<unsigned> RegSet;
74aa81380353a27d9d216cafdd88df08a5eef43b74Daniel Dunbarpublic:
75aa81380353a27d9d216cafdd88df08a5eef43b74Daniel Dunbar  TargetRegisterClass(unsigned id,
76aa81380353a27d9d216cafdd88df08a5eef43b74Daniel Dunbar                      const char *name,
77aa81380353a27d9d216cafdd88df08a5eef43b74Daniel Dunbar                      const EVT *vts,
78aa81380353a27d9d216cafdd88df08a5eef43b74Daniel Dunbar                      const TargetRegisterClass * const *subcs,
79aa81380353a27d9d216cafdd88df08a5eef43b74Daniel Dunbar                      const TargetRegisterClass * const *supcs,
80aa81380353a27d9d216cafdd88df08a5eef43b74Daniel Dunbar                      const TargetRegisterClass * const *subregcs,
81aa81380353a27d9d216cafdd88df08a5eef43b74Daniel Dunbar                      const TargetRegisterClass * const *superregcs,
82aa81380353a27d9d216cafdd88df08a5eef43b74Daniel Dunbar                      unsigned RS, unsigned Al, int CC, bool Allocable,
83aa81380353a27d9d216cafdd88df08a5eef43b74Daniel Dunbar                      iterator RB, iterator RE)
84aa81380353a27d9d216cafdd88df08a5eef43b74Daniel Dunbar    : ID(id), Name(name), VTs(vts), SubClasses(subcs), SuperClasses(supcs),
85aa81380353a27d9d216cafdd88df08a5eef43b74Daniel Dunbar    SubRegClasses(subregcs), SuperRegClasses(superregcs),
86aa81380353a27d9d216cafdd88df08a5eef43b74Daniel Dunbar    RegSize(RS), Alignment(Al), CopyCost(CC), Allocatable(Allocable),
87aa81380353a27d9d216cafdd88df08a5eef43b74Daniel Dunbar    RegsBegin(RB), RegsEnd(RE) {
88aa81380353a27d9d216cafdd88df08a5eef43b74Daniel Dunbar      for (iterator I = RegsBegin, E = RegsEnd; I != E; ++I)
89aa81380353a27d9d216cafdd88df08a5eef43b74Daniel Dunbar        RegSet.insert(*I);
90aa81380353a27d9d216cafdd88df08a5eef43b74Daniel Dunbar    }
91aa81380353a27d9d216cafdd88df08a5eef43b74Daniel Dunbar  virtual ~TargetRegisterClass() {}     // Allow subclasses
92f1fd2288f36b58b8979761ba09e2a398c6afd110Daniel Dunbar
93aa81380353a27d9d216cafdd88df08a5eef43b74Daniel Dunbar  /// getID() - Return the register class ID number.
94aa81380353a27d9d216cafdd88df08a5eef43b74Daniel Dunbar  ///
95aa81380353a27d9d216cafdd88df08a5eef43b74Daniel Dunbar  unsigned getID() const { return ID; }
96aa81380353a27d9d216cafdd88df08a5eef43b74Daniel Dunbar
97aa81380353a27d9d216cafdd88df08a5eef43b74Daniel Dunbar  /// getName() - Return the register class name for debugging.
98aa81380353a27d9d216cafdd88df08a5eef43b74Daniel Dunbar  ///
99aa81380353a27d9d216cafdd88df08a5eef43b74Daniel Dunbar  const char *getName() const { return Name; }
100aa81380353a27d9d216cafdd88df08a5eef43b74Daniel Dunbar
101aa81380353a27d9d216cafdd88df08a5eef43b74Daniel Dunbar  /// begin/end - Return all of the registers in this class.
102fed90b6d097d50881afb45e4d79f430db66dd741Dan Gohman  ///
103fed90b6d097d50881afb45e4d79f430db66dd741Dan Gohman  iterator       begin() const { return RegsBegin; }
104fed90b6d097d50881afb45e4d79f430db66dd741Dan Gohman  iterator         end() const { return RegsEnd; }
105fed90b6d097d50881afb45e4d79f430db66dd741Dan Gohman
106fed90b6d097d50881afb45e4d79f430db66dd741Dan Gohman  /// getNumRegs - Return the number of registers in this class.
107  ///
108  unsigned getNumRegs() const { return (unsigned)(RegsEnd-RegsBegin); }
109
110  /// getRegister - Return the specified register in the class.
111  ///
112  unsigned getRegister(unsigned i) const {
113    assert(i < getNumRegs() && "Register number out of range!");
114    return RegsBegin[i];
115  }
116
117  /// contains - Return true if the specified register is included in this
118  /// register class.  This does not include virtual registers.
119  bool contains(unsigned Reg) const {
120    return RegSet.count(Reg);
121  }
122
123  /// contains - Return true if both registers are in this class.
124  bool contains(unsigned Reg1, unsigned Reg2) const {
125    return contains(Reg1) && contains(Reg2);
126  }
127
128  /// hasType - return true if this TargetRegisterClass has the ValueType vt.
129  ///
130  bool hasType(EVT vt) const {
131    for(int i = 0; VTs[i] != MVT::Other; ++i)
132      if (VTs[i] == vt)
133        return true;
134    return false;
135  }
136
137  /// vt_begin / vt_end - Loop over all of the value types that can be
138  /// represented by values in this register class.
139  vt_iterator vt_begin() const {
140    return VTs;
141  }
142
143  vt_iterator vt_end() const {
144    vt_iterator I = VTs;
145    while (*I != MVT::Other) ++I;
146    return I;
147  }
148
149  /// subregclasses_begin / subregclasses_end - Loop over all of
150  /// the subreg register classes of this register class.
151  sc_iterator subregclasses_begin() const {
152    return SubRegClasses;
153  }
154
155  sc_iterator subregclasses_end() const {
156    sc_iterator I = SubRegClasses;
157    while (*I != NULL) ++I;
158    return I;
159  }
160
161  /// getSubRegisterRegClass - Return the register class of subregisters with
162  /// index SubIdx, or NULL if no such class exists.
163  const TargetRegisterClass* getSubRegisterRegClass(unsigned SubIdx) const {
164    assert(SubIdx>0 && "Invalid subregister index");
165    return SubRegClasses[SubIdx-1];
166  }
167
168  /// superregclasses_begin / superregclasses_end - Loop over all of
169  /// the superreg register classes of this register class.
170  sc_iterator superregclasses_begin() const {
171    return SuperRegClasses;
172  }
173
174  sc_iterator superregclasses_end() const {
175    sc_iterator I = SuperRegClasses;
176    while (*I != NULL) ++I;
177    return I;
178  }
179
180  /// hasSubClass - return true if the specified TargetRegisterClass
181  /// is a proper subset of this TargetRegisterClass.
182  bool hasSubClass(const TargetRegisterClass *cs) const {
183    for (int i = 0; SubClasses[i] != NULL; ++i)
184      if (SubClasses[i] == cs)
185        return true;
186    return false;
187  }
188
189  /// hasSubClassEq - Returns true if RC is a subclass of or equal to this
190  /// class.
191  bool hasSubClassEq(const TargetRegisterClass *RC) const {
192    return RC == this || hasSubClass(RC);
193  }
194
195  /// subclasses_begin / subclasses_end - Loop over all of the classes
196  /// that are proper subsets of this register class.
197  sc_iterator subclasses_begin() const {
198    return SubClasses;
199  }
200
201  sc_iterator subclasses_end() const {
202    sc_iterator I = SubClasses;
203    while (*I != NULL) ++I;
204    return I;
205  }
206
207  /// hasSuperClass - return true if the specified TargetRegisterClass is a
208  /// proper superset of this TargetRegisterClass.
209  bool hasSuperClass(const TargetRegisterClass *cs) const {
210    for (int i = 0; SuperClasses[i] != NULL; ++i)
211      if (SuperClasses[i] == cs)
212        return true;
213    return false;
214  }
215
216  /// hasSuperClassEq - Returns true if RC is a superclass of or equal to this
217  /// class.
218  bool hasSuperClassEq(const TargetRegisterClass *RC) const {
219    return RC == this || hasSuperClass(RC);
220  }
221
222  /// superclasses_begin / superclasses_end - Loop over all of the classes
223  /// that are proper supersets of this register class.
224  sc_iterator superclasses_begin() const {
225    return SuperClasses;
226  }
227
228  sc_iterator superclasses_end() const {
229    sc_iterator I = SuperClasses;
230    while (*I != NULL) ++I;
231    return I;
232  }
233
234  /// isASubClass - return true if this TargetRegisterClass is a subset
235  /// class of at least one other TargetRegisterClass.
236  bool isASubClass() const {
237    return SuperClasses[0] != 0;
238  }
239
240  /// allocation_order_begin/end - These methods define a range of registers
241  /// which specify the registers in this class that are valid to register
242  /// allocate, and the preferred order to allocate them in.  For example,
243  /// callee saved registers should be at the end of the list, because it is
244  /// cheaper to allocate caller saved registers.
245  ///
246  /// These methods take a MachineFunction argument, which can be used to tune
247  /// the allocatable registers based on the characteristics of the function,
248  /// subtarget, or other criteria.
249  ///
250  /// Register allocators should account for the fact that an allocation
251  /// order iterator may return a reserved register and always check
252  /// if the register is allocatable (getAllocatableSet()) before using it.
253  ///
254  /// By default, these methods return all registers in the class.
255  ///
256  virtual iterator allocation_order_begin(const MachineFunction &MF) const {
257    return begin();
258  }
259  virtual iterator allocation_order_end(const MachineFunction &MF)   const {
260    return end();
261  }
262
263  /// getRawAllocationOrder - Returns the preferred order for allocating
264  /// registers from this register class in MF. The raw order comes directly
265  /// from the .td file and may include reserved registers that are not
266  /// allocatable. Register allocators should also make sure to allocate
267  /// callee-saved registers only after all the volatiles are used. The
268  /// RegisterClassInfo class provides filtered allocation orders with
269  /// callee-saved registers moved to the end.
270  ///
271  /// The MachineFunction argument can be used to tune the allocatable
272  /// registers based on the characteristics of the function, subtarget, or
273  /// other criteria.
274  ///
275  /// By default, this method returns all registers in the class.
276  ///
277  virtual
278  ArrayRef<unsigned> getRawAllocationOrder(const MachineFunction &MF) const {
279    iterator B = allocation_order_begin(MF);
280    iterator E = allocation_order_end(MF);
281    return ArrayRef<unsigned>(B, E - B);
282  }
283
284  /// getSize - Return the size of the register in bytes, which is also the size
285  /// of a stack slot allocated to hold a spilled copy of this register.
286  unsigned getSize() const { return RegSize; }
287
288  /// getAlignment - Return the minimum required alignment for a register of
289  /// this class.
290  unsigned getAlignment() const { return Alignment; }
291
292  /// getCopyCost - Return the cost of copying a value between two registers in
293  /// this class. A negative number means the register class is very expensive
294  /// to copy e.g. status flag register classes.
295  int getCopyCost() const { return CopyCost; }
296
297  /// isAllocatable - Return true if this register class may be used to create
298  /// virtual registers.
299  bool isAllocatable() const { return Allocatable; }
300};
301
302
303/// TargetRegisterInfo base class - We assume that the target defines a static
304/// array of TargetRegisterDesc objects that represent all of the machine
305/// registers that the target has.  As such, we simply have to track a pointer
306/// to this array so that we can turn register number into a register
307/// descriptor.
308///
309class TargetRegisterInfo {
310public:
311  typedef const TargetRegisterClass * const * regclass_iterator;
312private:
313  const TargetRegisterDesc *Desc;             // Pointer to the descriptor array
314  const char *const *SubRegIndexNames;        // Names of subreg indexes.
315  unsigned NumRegs;                           // Number of entries in the array
316
317  regclass_iterator RegClassBegin, RegClassEnd;   // List of regclasses
318
319  int CallFrameSetupOpcode, CallFrameDestroyOpcode;
320
321protected:
322  TargetRegisterInfo(const TargetRegisterDesc *D, unsigned NR,
323                     regclass_iterator RegClassBegin,
324                     regclass_iterator RegClassEnd,
325                     const char *const *subregindexnames,
326                     int CallFrameSetupOpcode = -1,
327                     int CallFrameDestroyOpcode = -1);
328  virtual ~TargetRegisterInfo();
329public:
330
331  // Register numbers can represent physical registers, virtual registers, and
332  // sometimes stack slots. The unsigned values are divided into these ranges:
333  //
334  //   0           Not a register, can be used as a sentinel.
335  //   [1;2^30)    Physical registers assigned by TableGen.
336  //   [2^30;2^31) Stack slots. (Rarely used.)
337  //   [2^31;2^32) Virtual registers assigned by MachineRegisterInfo.
338  //
339  // Further sentinels can be allocated from the small negative integers.
340  // DenseMapInfo<unsigned> uses -1u and -2u.
341
342  /// isStackSlot - Sometimes it is useful the be able to store a non-negative
343  /// frame index in a variable that normally holds a register. isStackSlot()
344  /// returns true if Reg is in the range used for stack slots.
345  ///
346  /// Note that isVirtualRegister() and isPhysicalRegister() cannot handle stack
347  /// slots, so if a variable may contains a stack slot, always check
348  /// isStackSlot() first.
349  ///
350  static bool isStackSlot(unsigned Reg) {
351    return int(Reg) >= (1 << 30);
352  }
353
354  /// stackSlot2Index - Compute the frame index from a register value
355  /// representing a stack slot.
356  static int stackSlot2Index(unsigned Reg) {
357    assert(isStackSlot(Reg) && "Not a stack slot");
358    return int(Reg - (1u << 30));
359  }
360
361  /// index2StackSlot - Convert a non-negative frame index to a stack slot
362  /// register value.
363  static unsigned index2StackSlot(int FI) {
364    assert(FI >= 0 && "Cannot hold a negative frame index.");
365    return FI + (1u << 30);
366  }
367
368  /// isPhysicalRegister - Return true if the specified register number is in
369  /// the physical register namespace.
370  static bool isPhysicalRegister(unsigned Reg) {
371    assert(!isStackSlot(Reg) && "Not a register! Check isStackSlot() first.");
372    return int(Reg) > 0;
373  }
374
375  /// isVirtualRegister - Return true if the specified register number is in
376  /// the virtual register namespace.
377  static bool isVirtualRegister(unsigned Reg) {
378    assert(!isStackSlot(Reg) && "Not a register! Check isStackSlot() first.");
379    return int(Reg) < 0;
380  }
381
382  /// virtReg2Index - Convert a virtual register number to a 0-based index.
383  /// The first virtual register in a function will get the index 0.
384  static unsigned virtReg2Index(unsigned Reg) {
385    assert(isVirtualRegister(Reg) && "Not a virtual register");
386    return Reg & ~(1u << 31);
387  }
388
389  /// index2VirtReg - Convert a 0-based index to a virtual register number.
390  /// This is the inverse operation of VirtReg2IndexFunctor below.
391  static unsigned index2VirtReg(unsigned Index) {
392    return Index | (1u << 31);
393  }
394
395  /// getMinimalPhysRegClass - Returns the Register Class of a physical
396  /// register of the given type, picking the most sub register class of
397  /// the right type that contains this physreg.
398  const TargetRegisterClass *
399    getMinimalPhysRegClass(unsigned Reg, EVT VT = MVT::Other) const;
400
401  /// getAllocatableSet - Returns a bitset indexed by register number
402  /// indicating if a register is allocatable or not. If a register class is
403  /// specified, returns the subset for the class.
404  BitVector getAllocatableSet(const MachineFunction &MF,
405                              const TargetRegisterClass *RC = NULL) const;
406
407  const TargetRegisterDesc &operator[](unsigned RegNo) const {
408    assert(RegNo < NumRegs &&
409           "Attempting to access record for invalid register number!");
410    return Desc[RegNo];
411  }
412
413  /// Provide a get method, equivalent to [], but more useful if we have a
414  /// pointer to this object.
415  ///
416  const TargetRegisterDesc &get(unsigned RegNo) const {
417    return operator[](RegNo);
418  }
419
420  /// getAliasSet - Return the set of registers aliased by the specified
421  /// register, or a null list of there are none.  The list returned is zero
422  /// terminated.
423  ///
424  const unsigned *getAliasSet(unsigned RegNo) const {
425    // The Overlaps set always begins with Reg itself.
426    return get(RegNo).Overlaps + 1;
427  }
428
429  /// getOverlaps - Return a list of registers that overlap Reg, including
430  /// itself. This is the same as the alias set except Reg is included in the
431  /// list.
432  /// These are exactly the registers in { x | regsOverlap(x, Reg) }.
433  ///
434  const unsigned *getOverlaps(unsigned RegNo) const {
435    return get(RegNo).Overlaps;
436  }
437
438  /// getSubRegisters - Return the list of registers that are sub-registers of
439  /// the specified register, or a null list of there are none. The list
440  /// returned is zero terminated and sorted according to super-sub register
441  /// relations. e.g. X86::RAX's sub-register list is EAX, AX, AL, AH.
442  ///
443  const unsigned *getSubRegisters(unsigned RegNo) const {
444    return get(RegNo).SubRegs;
445  }
446
447  /// getSuperRegisters - Return the list of registers that are super-registers
448  /// of the specified register, or a null list of there are none. The list
449  /// returned is zero terminated and sorted according to super-sub register
450  /// relations. e.g. X86::AL's super-register list is AX, EAX, RAX.
451  ///
452  const unsigned *getSuperRegisters(unsigned RegNo) const {
453    return get(RegNo).SuperRegs;
454  }
455
456  /// getName - Return the human-readable symbolic target-specific name for the
457  /// specified physical register.
458  const char *getName(unsigned RegNo) const {
459    return get(RegNo).Name;
460  }
461
462  /// getCostPerUse - Return the additional cost of using this register instead
463  /// of other registers in its class.
464  unsigned getCostPerUse(unsigned RegNo) const {
465    return get(RegNo).CostPerUse;
466  }
467
468  /// getNumRegs - Return the number of registers this target has (useful for
469  /// sizing arrays holding per register information)
470  unsigned getNumRegs() const {
471    return NumRegs;
472  }
473
474  /// getSubRegIndexName - Return the human-readable symbolic target-specific
475  /// name for the specified SubRegIndex.
476  const char *getSubRegIndexName(unsigned SubIdx) const {
477    assert(SubIdx && "This is not a subregister index");
478    return SubRegIndexNames[SubIdx-1];
479  }
480
481  /// regsOverlap - Returns true if the two registers are equal or alias each
482  /// other. The registers may be virtual register.
483  bool regsOverlap(unsigned regA, unsigned regB) const {
484    if (regA == regB) return true;
485    if (isVirtualRegister(regA) || isVirtualRegister(regB))
486      return false;
487    for (const unsigned *regList = getOverlaps(regA)+1; *regList; ++regList) {
488      if (*regList == regB) return true;
489    }
490    return false;
491  }
492
493  /// isSubRegister - Returns true if regB is a sub-register of regA.
494  ///
495  bool isSubRegister(unsigned regA, unsigned regB) const {
496    return isSuperRegister(regB, regA);
497  }
498
499  /// isSuperRegister - Returns true if regB is a super-register of regA.
500  ///
501  bool isSuperRegister(unsigned regA, unsigned regB) const {
502    for (const unsigned *regList = getSuperRegisters(regA); *regList;++regList){
503      if (*regList == regB) return true;
504    }
505    return false;
506  }
507
508  /// getCalleeSavedRegs - Return a null-terminated list of all of the
509  /// callee saved registers on this target. The register should be in the
510  /// order of desired callee-save stack frame offset. The first register is
511  /// closed to the incoming stack pointer if stack grows down, and vice versa.
512  virtual const unsigned* getCalleeSavedRegs(const MachineFunction *MF = 0)
513                                                                      const = 0;
514
515
516  /// getReservedRegs - Returns a bitset indexed by physical register number
517  /// indicating if a register is a special register that has particular uses
518  /// and should be considered unavailable at all times, e.g. SP, RA. This is
519  /// used by register scavenger to determine what registers are free.
520  virtual BitVector getReservedRegs(const MachineFunction &MF) const = 0;
521
522  /// getSubReg - Returns the physical register number of sub-register "Index"
523  /// for physical register RegNo. Return zero if the sub-register does not
524  /// exist.
525  virtual unsigned getSubReg(unsigned RegNo, unsigned Index) const = 0;
526
527  /// getSubRegIndex - For a given register pair, return the sub-register index
528  /// if the second register is a sub-register of the first. Return zero
529  /// otherwise.
530  virtual unsigned getSubRegIndex(unsigned RegNo, unsigned SubRegNo) const = 0;
531
532  /// getMatchingSuperReg - Return a super-register of the specified register
533  /// Reg so its sub-register of index SubIdx is Reg.
534  unsigned getMatchingSuperReg(unsigned Reg, unsigned SubIdx,
535                               const TargetRegisterClass *RC) const {
536    for (const unsigned *SRs = getSuperRegisters(Reg); unsigned SR = *SRs;++SRs)
537      if (Reg == getSubReg(SR, SubIdx) && RC->contains(SR))
538        return SR;
539    return 0;
540  }
541
542  /// canCombineSubRegIndices - Given a register class and a list of
543  /// subregister indices, return true if it's possible to combine the
544  /// subregister indices into one that corresponds to a larger
545  /// subregister. Return the new subregister index by reference. Note the
546  /// new index may be zero if the given subregisters can be combined to
547  /// form the whole register.
548  virtual bool canCombineSubRegIndices(const TargetRegisterClass *RC,
549                                       SmallVectorImpl<unsigned> &SubIndices,
550                                       unsigned &NewSubIdx) const {
551    return 0;
552  }
553
554  /// getMatchingSuperRegClass - Return a subclass of the specified register
555  /// class A so that each register in it has a sub-register of the
556  /// specified sub-register index which is in the specified register class B.
557  virtual const TargetRegisterClass *
558  getMatchingSuperRegClass(const TargetRegisterClass *A,
559                           const TargetRegisterClass *B, unsigned Idx) const {
560    return 0;
561  }
562
563  /// composeSubRegIndices - Return the subregister index you get from composing
564  /// two subregister indices.
565  ///
566  /// If R:a:b is the same register as R:c, then composeSubRegIndices(a, b)
567  /// returns c. Note that composeSubRegIndices does not tell you about illegal
568  /// compositions. If R does not have a subreg a, or R:a does not have a subreg
569  /// b, composeSubRegIndices doesn't tell you.
570  ///
571  /// The ARM register Q0 has two D subregs dsub_0:D0 and dsub_1:D1. It also has
572  /// ssub_0:S0 - ssub_3:S3 subregs.
573  /// If you compose subreg indices dsub_1, ssub_0 you get ssub_2.
574  ///
575  virtual unsigned composeSubRegIndices(unsigned a, unsigned b) const {
576    // This default implementation is correct for most targets.
577    return b;
578  }
579
580  //===--------------------------------------------------------------------===//
581  // Register Class Information
582  //
583
584  /// Register class iterators
585  ///
586  regclass_iterator regclass_begin() const { return RegClassBegin; }
587  regclass_iterator regclass_end() const { return RegClassEnd; }
588
589  unsigned getNumRegClasses() const {
590    return (unsigned)(regclass_end()-regclass_begin());
591  }
592
593  /// getRegClass - Returns the register class associated with the enumeration
594  /// value.  See class TargetOperandInfo.
595  const TargetRegisterClass *getRegClass(unsigned i) const {
596    assert(i < getNumRegClasses() && "Register Class ID out of range");
597    return RegClassBegin[i];
598  }
599
600  /// getPointerRegClass - Returns a TargetRegisterClass used for pointer
601  /// values.  If a target supports multiple different pointer register classes,
602  /// kind specifies which one is indicated.
603  virtual const TargetRegisterClass *getPointerRegClass(unsigned Kind=0) const {
604    assert(0 && "Target didn't implement getPointerRegClass!");
605    return 0; // Must return a value in order to compile with VS 2005
606  }
607
608  /// getCrossCopyRegClass - Returns a legal register class to copy a register
609  /// in the specified class to or from. If it is possible to copy the register
610  /// directly without using a cross register class copy, return the specified
611  /// RC. Returns NULL if it is not possible to copy between a two registers of
612  /// the specified class.
613  virtual const TargetRegisterClass *
614  getCrossCopyRegClass(const TargetRegisterClass *RC) const {
615    return RC;
616  }
617
618  /// getLargestLegalSuperClass - Returns the largest super class of RC that is
619  /// legal to use in the current sub-target and has the same spill size.
620  /// The returned register class can be used to create virtual registers which
621  /// means that all its registers can be copied and spilled.
622  virtual const TargetRegisterClass*
623  getLargestLegalSuperClass(const TargetRegisterClass *RC) const {
624    /// The default implementation is very conservative and doesn't allow the
625    /// register allocator to inflate register classes.
626    return RC;
627  }
628
629  /// getRegPressureLimit - Return the register pressure "high water mark" for
630  /// the specific register class. The scheduler is in high register pressure
631  /// mode (for the specific register class) if it goes over the limit.
632  virtual unsigned getRegPressureLimit(const TargetRegisterClass *RC,
633                                       MachineFunction &MF) const {
634    return 0;
635  }
636
637  /// getAllocationOrder - Returns the register allocation order for a specified
638  /// register class in the form of a pair of TargetRegisterClass iterators.
639  virtual std::pair<TargetRegisterClass::iterator,TargetRegisterClass::iterator>
640  getAllocationOrder(const TargetRegisterClass *RC,
641                     unsigned HintType, unsigned HintReg,
642                     const MachineFunction &MF) const {
643    return std::make_pair(RC->allocation_order_begin(MF),
644                          RC->allocation_order_end(MF));
645  }
646
647  /// ResolveRegAllocHint - Resolves the specified register allocation hint
648  /// to a physical register. Returns the physical register if it is successful.
649  virtual unsigned ResolveRegAllocHint(unsigned Type, unsigned Reg,
650                                       const MachineFunction &MF) const {
651    if (Type == 0 && Reg && isPhysicalRegister(Reg))
652      return Reg;
653    return 0;
654  }
655
656  /// avoidWriteAfterWrite - Return true if the register allocator should avoid
657  /// writing a register from RC in two consecutive instructions.
658  /// This can avoid pipeline stalls on certain architectures.
659  /// It does cause increased register pressure, though.
660  virtual bool avoidWriteAfterWrite(const TargetRegisterClass *RC) const {
661    return false;
662  }
663
664  /// UpdateRegAllocHint - A callback to allow target a chance to update
665  /// register allocation hints when a register is "changed" (e.g. coalesced)
666  /// to another register. e.g. On ARM, some virtual registers should target
667  /// register pairs, if one of pair is coalesced to another register, the
668  /// allocation hint of the other half of the pair should be changed to point
669  /// to the new register.
670  virtual void UpdateRegAllocHint(unsigned Reg, unsigned NewReg,
671                                  MachineFunction &MF) const {
672    // Do nothing.
673  }
674
675  /// requiresRegisterScavenging - returns true if the target requires (and can
676  /// make use of) the register scavenger.
677  virtual bool requiresRegisterScavenging(const MachineFunction &MF) const {
678    return false;
679  }
680
681  /// useFPForScavengingIndex - returns true if the target wants to use
682  /// frame pointer based accesses to spill to the scavenger emergency spill
683  /// slot.
684  virtual bool useFPForScavengingIndex(const MachineFunction &MF) const {
685    return true;
686  }
687
688  /// requiresFrameIndexScavenging - returns true if the target requires post
689  /// PEI scavenging of registers for materializing frame index constants.
690  virtual bool requiresFrameIndexScavenging(const MachineFunction &MF) const {
691    return false;
692  }
693
694  /// requiresVirtualBaseRegisters - Returns true if the target wants the
695  /// LocalStackAllocation pass to be run and virtual base registers
696  /// used for more efficient stack access.
697  virtual bool requiresVirtualBaseRegisters(const MachineFunction &MF) const {
698    return false;
699  }
700
701  /// hasReservedSpillSlot - Return true if target has reserved a spill slot in
702  /// the stack frame of the given function for the specified register. e.g. On
703  /// x86, if the frame register is required, the first fixed stack object is
704  /// reserved as its spill slot. This tells PEI not to create a new stack frame
705  /// object for the given register. It should be called only after
706  /// processFunctionBeforeCalleeSavedScan().
707  virtual bool hasReservedSpillSlot(const MachineFunction &MF, unsigned Reg,
708                                    int &FrameIdx) const {
709    return false;
710  }
711
712  /// needsStackRealignment - true if storage within the function requires the
713  /// stack pointer to be aligned more than the normal calling convention calls
714  /// for.
715  virtual bool needsStackRealignment(const MachineFunction &MF) const {
716    return false;
717  }
718
719  /// getFrameIndexInstrOffset - Get the offset from the referenced frame
720  /// index in the instruction, if there is one.
721  virtual int64_t getFrameIndexInstrOffset(const MachineInstr *MI,
722                                           int Idx) const {
723    return 0;
724  }
725
726  /// needsFrameBaseReg - Returns true if the instruction's frame index
727  /// reference would be better served by a base register other than FP
728  /// or SP. Used by LocalStackFrameAllocation to determine which frame index
729  /// references it should create new base registers for.
730  virtual bool needsFrameBaseReg(MachineInstr *MI, int64_t Offset) const {
731    return false;
732  }
733
734  /// materializeFrameBaseRegister - Insert defining instruction(s) for
735  /// BaseReg to be a pointer to FrameIdx before insertion point I.
736  virtual void materializeFrameBaseRegister(MachineBasicBlock *MBB,
737                                            unsigned BaseReg, int FrameIdx,
738                                            int64_t Offset) const {
739    assert(0 && "materializeFrameBaseRegister does not exist on this target");
740  }
741
742  /// resolveFrameIndex - Resolve a frame index operand of an instruction
743  /// to reference the indicated base register plus offset instead.
744  virtual void resolveFrameIndex(MachineBasicBlock::iterator I,
745                                 unsigned BaseReg, int64_t Offset) const {
746    assert(0 && "resolveFrameIndex does not exist on this target");
747  }
748
749  /// isFrameOffsetLegal - Determine whether a given offset immediate is
750  /// encodable to resolve a frame index.
751  virtual bool isFrameOffsetLegal(const MachineInstr *MI,
752                                  int64_t Offset) const {
753    assert(0 && "isFrameOffsetLegal does not exist on this target");
754    return false; // Must return a value in order to compile with VS 2005
755  }
756
757  /// getCallFrameSetup/DestroyOpcode - These methods return the opcode of the
758  /// frame setup/destroy instructions if they exist (-1 otherwise).  Some
759  /// targets use pseudo instructions in order to abstract away the difference
760  /// between operating with a frame pointer and operating without, through the
761  /// use of these two instructions.
762  ///
763  int getCallFrameSetupOpcode() const { return CallFrameSetupOpcode; }
764  int getCallFrameDestroyOpcode() const { return CallFrameDestroyOpcode; }
765
766  /// eliminateCallFramePseudoInstr - This method is called during prolog/epilog
767  /// code insertion to eliminate call frame setup and destroy pseudo
768  /// instructions (but only if the Target is using them).  It is responsible
769  /// for eliminating these instructions, replacing them with concrete
770  /// instructions.  This method need only be implemented if using call frame
771  /// setup/destroy pseudo instructions.
772  ///
773  virtual void
774  eliminateCallFramePseudoInstr(MachineFunction &MF,
775                                MachineBasicBlock &MBB,
776                                MachineBasicBlock::iterator MI) const {
777    assert(getCallFrameSetupOpcode()== -1 && getCallFrameDestroyOpcode()== -1 &&
778           "eliminateCallFramePseudoInstr must be implemented if using"
779           " call frame setup/destroy pseudo instructions!");
780    assert(0 && "Call Frame Pseudo Instructions do not exist on this target!");
781  }
782
783
784  /// saveScavengerRegister - Spill the register so it can be used by the
785  /// register scavenger. Return true if the register was spilled, false
786  /// otherwise. If this function does not spill the register, the scavenger
787  /// will instead spill it to the emergency spill slot.
788  ///
789  virtual bool saveScavengerRegister(MachineBasicBlock &MBB,
790                                     MachineBasicBlock::iterator I,
791                                     MachineBasicBlock::iterator &UseMI,
792                                     const TargetRegisterClass *RC,
793                                     unsigned Reg) const {
794    return false;
795  }
796
797  /// eliminateFrameIndex - This method must be overriden to eliminate abstract
798  /// frame indices from instructions which may use them.  The instruction
799  /// referenced by the iterator contains an MO_FrameIndex operand which must be
800  /// eliminated by this method.  This method may modify or replace the
801  /// specified instruction, as long as it keeps the iterator pointing at the
802  /// finished product. SPAdj is the SP adjustment due to call frame setup
803  /// instruction.
804  virtual void eliminateFrameIndex(MachineBasicBlock::iterator MI,
805                                   int SPAdj, RegScavenger *RS=NULL) const = 0;
806
807  //===--------------------------------------------------------------------===//
808  /// Debug information queries.
809
810  /// getDwarfRegNum - Map a target register to an equivalent dwarf register
811  /// number.  Returns -1 if there is no equivalent value.  The second
812  /// parameter allows targets to use different numberings for EH info and
813  /// debugging info.
814  virtual int getDwarfRegNum(unsigned RegNum, bool isEH) const = 0;
815
816  virtual int getLLVMRegNum(unsigned RegNum, bool isEH) const = 0;
817
818  /// getFrameRegister - This method should return the register used as a base
819  /// for values allocated in the current stack frame.
820  virtual unsigned getFrameRegister(const MachineFunction &MF) const = 0;
821
822  /// getRARegister - This method should return the register where the return
823  /// address can be found.
824  virtual unsigned getRARegister() const = 0;
825
826  /// getSEHRegNum - Map a target register to an equivalent SEH register
827  /// number.  Returns -1 if there is no equivalent value.
828  virtual int getSEHRegNum(unsigned i) const {
829    return i;
830  }
831};
832
833
834// This is useful when building IndexedMaps keyed on virtual registers
835struct VirtReg2IndexFunctor : public std::unary_function<unsigned, unsigned> {
836  unsigned operator()(unsigned Reg) const {
837    return TargetRegisterInfo::virtReg2Index(Reg);
838  }
839};
840
841/// getCommonSubClass - find the largest common subclass of A and B. Return NULL
842/// if there is no common subclass.
843const TargetRegisterClass *getCommonSubClass(const TargetRegisterClass *A,
844                                             const TargetRegisterClass *B);
845
846/// PrintReg - Helper class for printing registers on a raw_ostream.
847/// Prints virtual and physical registers with or without a TRI instance.
848///
849/// The format is:
850///   %noreg          - NoRegister
851///   %vreg5          - a virtual register.
852///   %vreg5:sub_8bit - a virtual register with sub-register index (with TRI).
853///   %EAX            - a physical register
854///   %physreg17      - a physical register when no TRI instance given.
855///
856/// Usage: OS << PrintReg(Reg, TRI) << '\n';
857///
858class PrintReg {
859  const TargetRegisterInfo *TRI;
860  unsigned Reg;
861  unsigned SubIdx;
862public:
863  PrintReg(unsigned reg, const TargetRegisterInfo *tri = 0, unsigned subidx = 0)
864    : TRI(tri), Reg(reg), SubIdx(subidx) {}
865  void print(raw_ostream&) const;
866};
867
868static inline raw_ostream &operator<<(raw_ostream &OS, const PrintReg &PR) {
869  PR.print(OS);
870  return OS;
871}
872
873} // End llvm namespace
874
875#endif
876