MachineRegisterInfo.h revision 90019479f9a3868d8be90564695097a61a725438
1//===-- llvm/CodeGen/MachineRegisterInfo.h ----------------------*- 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 defines the MachineRegisterInfo class.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CODEGEN_MACHINEREGISTERINFO_H
15#define LLVM_CODEGEN_MACHINEREGISTERINFO_H
16
17#include "llvm/Target/TargetRegisterInfo.h"
18#include "llvm/ADT/BitVector.h"
19#include "llvm/ADT/IndexedMap.h"
20#include <vector>
21
22namespace llvm {
23
24/// MachineRegisterInfo - Keep track of information for virtual and physical
25/// registers, including vreg register classes, use/def chains for registers,
26/// etc.
27class MachineRegisterInfo {
28  const TargetRegisterInfo *const TRI;
29
30  /// IsSSA - True when the machine function is in SSA form and virtual
31  /// registers have a single def.
32  bool IsSSA;
33
34  /// VRegInfo - Information we keep for each virtual register.
35  ///
36  /// Each element in this list contains the register class of the vreg and the
37  /// start of the use/def list for the register.
38  IndexedMap<std::pair<const TargetRegisterClass*, MachineOperand*>,
39             VirtReg2IndexFunctor> VRegInfo;
40
41  /// RegAllocHints - This vector records register allocation hints for virtual
42  /// registers. For each virtual register, it keeps a register and hint type
43  /// pair making up the allocation hint. Hint type is target specific except
44  /// for the value 0 which means the second value of the pair is the preferred
45  /// register for allocation. For example, if the hint is <0, 1024>, it means
46  /// the allocator should prefer the physical register allocated to the virtual
47  /// register of the hint.
48  IndexedMap<std::pair<unsigned, unsigned>, VirtReg2IndexFunctor> RegAllocHints;
49
50  /// PhysRegUseDefLists - This is an array of the head of the use/def list for
51  /// physical registers.
52  MachineOperand **PhysRegUseDefLists;
53
54  /// UsedPhysRegs - This is a bit vector that is computed and set by the
55  /// register allocator, and must be kept up to date by passes that run after
56  /// register allocation (though most don't modify this).  This is used
57  /// so that the code generator knows which callee save registers to save and
58  /// for other target specific uses.
59  /// This vector only has bits set for registers explicitly used, not their
60  /// aliases.
61  BitVector UsedPhysRegs;
62
63  /// UsedPhysRegMask - Additional used physregs, but including aliases.
64  BitVector UsedPhysRegMask;
65
66  /// ReservedRegs - This is a bit vector of reserved registers.  The target
67  /// may change its mind about which registers should be reserved.  This
68  /// vector is the frozen set of reserved registers when register allocation
69  /// started.
70  BitVector ReservedRegs;
71
72  /// AllocatableRegs - From TRI->getAllocatableSet.
73  mutable BitVector AllocatableRegs;
74
75  /// LiveIns/LiveOuts - Keep track of the physical registers that are
76  /// livein/liveout of the function.  Live in values are typically arguments in
77  /// registers, live out values are typically return values in registers.
78  /// LiveIn values are allowed to have virtual registers associated with them,
79  /// stored in the second element.
80  std::vector<std::pair<unsigned, unsigned> > LiveIns;
81  std::vector<unsigned> LiveOuts;
82
83  MachineRegisterInfo(const MachineRegisterInfo&); // DO NOT IMPLEMENT
84  void operator=(const MachineRegisterInfo&);      // DO NOT IMPLEMENT
85public:
86  explicit MachineRegisterInfo(const TargetRegisterInfo &TRI);
87  ~MachineRegisterInfo();
88
89  //===--------------------------------------------------------------------===//
90  // Function State
91  //===--------------------------------------------------------------------===//
92
93  // isSSA - Returns true when the machine function is in SSA form. Early
94  // passes require the machine function to be in SSA form where every virtual
95  // register has a single defining instruction.
96  //
97  // The TwoAddressInstructionPass and PHIElimination passes take the machine
98  // function out of SSA form when they introduce multiple defs per virtual
99  // register.
100  bool isSSA() const { return IsSSA; }
101
102  // leaveSSA - Indicates that the machine function is no longer in SSA form.
103  void leaveSSA() { IsSSA = false; }
104
105  //===--------------------------------------------------------------------===//
106  // Register Info
107  //===--------------------------------------------------------------------===//
108
109  /// reg_begin/reg_end - Provide iteration support to walk over all definitions
110  /// and uses of a register within the MachineFunction that corresponds to this
111  /// MachineRegisterInfo object.
112  template<bool Uses, bool Defs, bool SkipDebug>
113  class defusechain_iterator;
114
115  /// reg_iterator/reg_begin/reg_end - Walk all defs and uses of the specified
116  /// register.
117  typedef defusechain_iterator<true,true,false> reg_iterator;
118  reg_iterator reg_begin(unsigned RegNo) const {
119    return reg_iterator(getRegUseDefListHead(RegNo));
120  }
121  static reg_iterator reg_end() { return reg_iterator(0); }
122
123  /// reg_empty - Return true if there are no instructions using or defining the
124  /// specified register (it may be live-in).
125  bool reg_empty(unsigned RegNo) const { return reg_begin(RegNo) == reg_end(); }
126
127  /// reg_nodbg_iterator/reg_nodbg_begin/reg_nodbg_end - Walk all defs and uses
128  /// of the specified register, skipping those marked as Debug.
129  typedef defusechain_iterator<true,true,true> reg_nodbg_iterator;
130  reg_nodbg_iterator reg_nodbg_begin(unsigned RegNo) const {
131    return reg_nodbg_iterator(getRegUseDefListHead(RegNo));
132  }
133  static reg_nodbg_iterator reg_nodbg_end() { return reg_nodbg_iterator(0); }
134
135  /// reg_nodbg_empty - Return true if the only instructions using or defining
136  /// Reg are Debug instructions.
137  bool reg_nodbg_empty(unsigned RegNo) const {
138    return reg_nodbg_begin(RegNo) == reg_nodbg_end();
139  }
140
141  /// def_iterator/def_begin/def_end - Walk all defs of the specified register.
142  typedef defusechain_iterator<false,true,false> def_iterator;
143  def_iterator def_begin(unsigned RegNo) const {
144    return def_iterator(getRegUseDefListHead(RegNo));
145  }
146  static def_iterator def_end() { return def_iterator(0); }
147
148  /// def_empty - Return true if there are no instructions defining the
149  /// specified register (it may be live-in).
150  bool def_empty(unsigned RegNo) const { return def_begin(RegNo) == def_end(); }
151
152  /// use_iterator/use_begin/use_end - Walk all uses of the specified register.
153  typedef defusechain_iterator<true,false,false> use_iterator;
154  use_iterator use_begin(unsigned RegNo) const {
155    return use_iterator(getRegUseDefListHead(RegNo));
156  }
157  static use_iterator use_end() { return use_iterator(0); }
158
159  /// use_empty - Return true if there are no instructions using the specified
160  /// register.
161  bool use_empty(unsigned RegNo) const { return use_begin(RegNo) == use_end(); }
162
163  /// hasOneUse - Return true if there is exactly one instruction using the
164  /// specified register.
165  bool hasOneUse(unsigned RegNo) const;
166
167  /// use_nodbg_iterator/use_nodbg_begin/use_nodbg_end - Walk all uses of the
168  /// specified register, skipping those marked as Debug.
169  typedef defusechain_iterator<true,false,true> use_nodbg_iterator;
170  use_nodbg_iterator use_nodbg_begin(unsigned RegNo) const {
171    return use_nodbg_iterator(getRegUseDefListHead(RegNo));
172  }
173  static use_nodbg_iterator use_nodbg_end() { return use_nodbg_iterator(0); }
174
175  /// use_nodbg_empty - Return true if there are no non-Debug instructions
176  /// using the specified register.
177  bool use_nodbg_empty(unsigned RegNo) const {
178    return use_nodbg_begin(RegNo) == use_nodbg_end();
179  }
180
181  /// hasOneNonDBGUse - Return true if there is exactly one non-Debug
182  /// instruction using the specified register.
183  bool hasOneNonDBGUse(unsigned RegNo) const;
184
185  /// replaceRegWith - Replace all instances of FromReg with ToReg in the
186  /// machine function.  This is like llvm-level X->replaceAllUsesWith(Y),
187  /// except that it also changes any definitions of the register as well.
188  ///
189  /// Note that it is usually necessary to first constrain ToReg's register
190  /// class to match the FromReg constraints using:
191  ///
192  ///   constrainRegClass(ToReg, getRegClass(FromReg))
193  ///
194  /// That function will return NULL if the virtual registers have incompatible
195  /// constraints.
196  void replaceRegWith(unsigned FromReg, unsigned ToReg);
197
198  /// getRegUseDefListHead - Return the head pointer for the register use/def
199  /// list for the specified virtual or physical register.
200  MachineOperand *&getRegUseDefListHead(unsigned RegNo) {
201    if (TargetRegisterInfo::isVirtualRegister(RegNo))
202      return VRegInfo[RegNo].second;
203    return PhysRegUseDefLists[RegNo];
204  }
205
206  MachineOperand *getRegUseDefListHead(unsigned RegNo) const {
207    if (TargetRegisterInfo::isVirtualRegister(RegNo))
208      return VRegInfo[RegNo].second;
209    return PhysRegUseDefLists[RegNo];
210  }
211
212  /// getVRegDef - Return the machine instr that defines the specified virtual
213  /// register or null if none is found.  This assumes that the code is in SSA
214  /// form, so there should only be one definition.
215  MachineInstr *getVRegDef(unsigned Reg) const;
216
217  /// clearKillFlags - Iterate over all the uses of the given register and
218  /// clear the kill flag from the MachineOperand. This function is used by
219  /// optimization passes which extend register lifetimes and need only
220  /// preserve conservative kill flag information.
221  void clearKillFlags(unsigned Reg) const;
222
223#ifndef NDEBUG
224  void dumpUses(unsigned RegNo) const;
225#endif
226
227  /// isConstantPhysReg - Returns true if PhysReg is unallocatable and constant
228  /// throughout the function.  It is safe to move instructions that read such
229  /// a physreg.
230  bool isConstantPhysReg(unsigned PhysReg, const MachineFunction &MF) const;
231
232  //===--------------------------------------------------------------------===//
233  // Virtual Register Info
234  //===--------------------------------------------------------------------===//
235
236  /// getRegClass - Return the register class of the specified virtual register.
237  ///
238  const TargetRegisterClass *getRegClass(unsigned Reg) const {
239    return VRegInfo[Reg].first;
240  }
241
242  /// setRegClass - Set the register class of the specified virtual register.
243  ///
244  void setRegClass(unsigned Reg, const TargetRegisterClass *RC);
245
246  /// constrainRegClass - Constrain the register class of the specified virtual
247  /// register to be a common subclass of RC and the current register class,
248  /// but only if the new class has at least MinNumRegs registers.  Return the
249  /// new register class, or NULL if no such class exists.
250  /// This should only be used when the constraint is known to be trivial, like
251  /// GR32 -> GR32_NOSP. Beware of increasing register pressure.
252  ///
253  const TargetRegisterClass *constrainRegClass(unsigned Reg,
254                                               const TargetRegisterClass *RC,
255                                               unsigned MinNumRegs = 0);
256
257  /// recomputeRegClass - Try to find a legal super-class of Reg's register
258  /// class that still satisfies the constraints from the instructions using
259  /// Reg.  Returns true if Reg was upgraded.
260  ///
261  /// This method can be used after constraints have been removed from a
262  /// virtual register, for example after removing instructions or splitting
263  /// the live range.
264  ///
265  bool recomputeRegClass(unsigned Reg, const TargetMachine&);
266
267  /// createVirtualRegister - Create and return a new virtual register in the
268  /// function with the specified register class.
269  ///
270  unsigned createVirtualRegister(const TargetRegisterClass *RegClass);
271
272  /// getNumVirtRegs - Return the number of virtual registers created.
273  ///
274  unsigned getNumVirtRegs() const { return VRegInfo.size(); }
275
276  /// setRegAllocationHint - Specify a register allocation hint for the
277  /// specified virtual register.
278  void setRegAllocationHint(unsigned Reg, unsigned Type, unsigned PrefReg) {
279    RegAllocHints[Reg].first  = Type;
280    RegAllocHints[Reg].second = PrefReg;
281  }
282
283  /// getRegAllocationHint - Return the register allocation hint for the
284  /// specified virtual register.
285  std::pair<unsigned, unsigned>
286  getRegAllocationHint(unsigned Reg) const {
287    return RegAllocHints[Reg];
288  }
289
290  /// getSimpleHint - Return the preferred register allocation hint, or 0 if a
291  /// standard simple hint (Type == 0) is not set.
292  unsigned getSimpleHint(unsigned Reg) const {
293    std::pair<unsigned, unsigned> Hint = getRegAllocationHint(Reg);
294    return Hint.first ? 0 : Hint.second;
295  }
296
297
298  //===--------------------------------------------------------------------===//
299  // Physical Register Use Info
300  //===--------------------------------------------------------------------===//
301
302  /// isPhysRegUsed - Return true if the specified register is used in this
303  /// function.  This only works after register allocation.
304  bool isPhysRegUsed(unsigned Reg) const {
305    return UsedPhysRegs.test(Reg) || UsedPhysRegMask.test(Reg);
306  }
307
308  /// isPhysRegOrOverlapUsed - Return true if Reg or any overlapping register
309  /// is used in this function.
310  bool isPhysRegOrOverlapUsed(unsigned Reg) const {
311    if (UsedPhysRegMask.test(Reg))
312      return true;
313    for (const unsigned *AI = TRI->getOverlaps(Reg); *AI; ++AI)
314      if (UsedPhysRegs.test(*AI))
315        return true;
316    return false;
317  }
318
319  /// setPhysRegUsed - Mark the specified register used in this function.
320  /// This should only be called during and after register allocation.
321  void setPhysRegUsed(unsigned Reg) { UsedPhysRegs.set(Reg); }
322
323  /// addPhysRegsUsed - Mark the specified registers used in this function.
324  /// This should only be called during and after register allocation.
325  void addPhysRegsUsed(const BitVector &Regs) { UsedPhysRegs |= Regs; }
326
327  /// addPhysRegsUsedFromRegMask - Mark any registers not in RegMask as used.
328  /// This corresponds to the bit mask attached to register mask operands.
329  void addPhysRegsUsedFromRegMask(const uint32_t *RegMask) {
330    UsedPhysRegMask.setBitsNotInMask(RegMask);
331  }
332
333  /// setPhysRegUnused - Mark the specified register unused in this function.
334  /// This should only be called during and after register allocation.
335  void setPhysRegUnused(unsigned Reg) {
336    UsedPhysRegs.reset(Reg);
337    UsedPhysRegMask.reset(Reg);
338  }
339
340
341  //===--------------------------------------------------------------------===//
342  // Reserved Register Info
343  //===--------------------------------------------------------------------===//
344  //
345  // The set of reserved registers must be invariant during register
346  // allocation.  For example, the target cannot suddenly decide it needs a
347  // frame pointer when the register allocator has already used the frame
348  // pointer register for something else.
349  //
350  // These methods can be used by target hooks like hasFP() to avoid changing
351  // the reserved register set during register allocation.
352
353  /// freezeReservedRegs - Called by the register allocator to freeze the set
354  /// of reserved registers before allocation begins.
355  void freezeReservedRegs(const MachineFunction&);
356
357  /// reservedRegsFrozen - Returns true after freezeReservedRegs() was called
358  /// to ensure the set of reserved registers stays constant.
359  bool reservedRegsFrozen() const {
360    return !ReservedRegs.empty();
361  }
362
363  /// canReserveReg - Returns true if PhysReg can be used as a reserved
364  /// register.  Any register can be reserved before freezeReservedRegs() is
365  /// called.
366  bool canReserveReg(unsigned PhysReg) const {
367    return !reservedRegsFrozen() || ReservedRegs.test(PhysReg);
368  }
369
370
371  //===--------------------------------------------------------------------===//
372  // LiveIn/LiveOut Management
373  //===--------------------------------------------------------------------===//
374
375  /// addLiveIn/Out - Add the specified register as a live in/out.  Note that it
376  /// is an error to add the same register to the same set more than once.
377  void addLiveIn(unsigned Reg, unsigned vreg = 0) {
378    LiveIns.push_back(std::make_pair(Reg, vreg));
379  }
380  void addLiveOut(unsigned Reg) { LiveOuts.push_back(Reg); }
381
382  // Iteration support for live in/out sets.  These sets are kept in sorted
383  // order by their register number.
384  typedef std::vector<std::pair<unsigned,unsigned> >::const_iterator
385  livein_iterator;
386  typedef std::vector<unsigned>::const_iterator liveout_iterator;
387  livein_iterator livein_begin() const { return LiveIns.begin(); }
388  livein_iterator livein_end()   const { return LiveIns.end(); }
389  bool            livein_empty() const { return LiveIns.empty(); }
390  liveout_iterator liveout_begin() const { return LiveOuts.begin(); }
391  liveout_iterator liveout_end()   const { return LiveOuts.end(); }
392  bool             liveout_empty() const { return LiveOuts.empty(); }
393
394  bool isLiveIn(unsigned Reg) const;
395  bool isLiveOut(unsigned Reg) const;
396
397  /// getLiveInPhysReg - If VReg is a live-in virtual register, return the
398  /// corresponding live-in physical register.
399  unsigned getLiveInPhysReg(unsigned VReg) const;
400
401  /// getLiveInVirtReg - If PReg is a live-in physical register, return the
402  /// corresponding live-in physical register.
403  unsigned getLiveInVirtReg(unsigned PReg) const;
404
405  /// EmitLiveInCopies - Emit copies to initialize livein virtual registers
406  /// into the given entry block.
407  void EmitLiveInCopies(MachineBasicBlock *EntryMBB,
408                        const TargetRegisterInfo &TRI,
409                        const TargetInstrInfo &TII);
410
411private:
412  void HandleVRegListReallocation();
413
414public:
415  /// defusechain_iterator - This class provides iterator support for machine
416  /// operands in the function that use or define a specific register.  If
417  /// ReturnUses is true it returns uses of registers, if ReturnDefs is true it
418  /// returns defs.  If neither are true then you are silly and it always
419  /// returns end().  If SkipDebug is true it skips uses marked Debug
420  /// when incrementing.
421  template<bool ReturnUses, bool ReturnDefs, bool SkipDebug>
422  class defusechain_iterator
423    : public std::iterator<std::forward_iterator_tag, MachineInstr, ptrdiff_t> {
424    MachineOperand *Op;
425    explicit defusechain_iterator(MachineOperand *op) : Op(op) {
426      // If the first node isn't one we're interested in, advance to one that
427      // we are interested in.
428      if (op) {
429        if ((!ReturnUses && op->isUse()) ||
430            (!ReturnDefs && op->isDef()) ||
431            (SkipDebug && op->isDebug()))
432          ++*this;
433      }
434    }
435    friend class MachineRegisterInfo;
436  public:
437    typedef std::iterator<std::forward_iterator_tag,
438                          MachineInstr, ptrdiff_t>::reference reference;
439    typedef std::iterator<std::forward_iterator_tag,
440                          MachineInstr, ptrdiff_t>::pointer pointer;
441
442    defusechain_iterator(const defusechain_iterator &I) : Op(I.Op) {}
443    defusechain_iterator() : Op(0) {}
444
445    bool operator==(const defusechain_iterator &x) const {
446      return Op == x.Op;
447    }
448    bool operator!=(const defusechain_iterator &x) const {
449      return !operator==(x);
450    }
451
452    /// atEnd - return true if this iterator is equal to reg_end() on the value.
453    bool atEnd() const { return Op == 0; }
454
455    // Iterator traversal: forward iteration only
456    defusechain_iterator &operator++() {          // Preincrement
457      assert(Op && "Cannot increment end iterator!");
458      Op = Op->getNextOperandForReg();
459
460      // If this is an operand we don't care about, skip it.
461      while (Op && ((!ReturnUses && Op->isUse()) ||
462                    (!ReturnDefs && Op->isDef()) ||
463                    (SkipDebug && Op->isDebug())))
464        Op = Op->getNextOperandForReg();
465
466      return *this;
467    }
468    defusechain_iterator operator++(int) {        // Postincrement
469      defusechain_iterator tmp = *this; ++*this; return tmp;
470    }
471
472    /// skipInstruction - move forward until reaching a different instruction.
473    /// Return the skipped instruction that is no longer pointed to, or NULL if
474    /// already pointing to end().
475    MachineInstr *skipInstruction() {
476      if (!Op) return 0;
477      MachineInstr *MI = Op->getParent();
478      do ++*this;
479      while (Op && Op->getParent() == MI);
480      return MI;
481    }
482
483    MachineOperand &getOperand() const {
484      assert(Op && "Cannot dereference end iterator!");
485      return *Op;
486    }
487
488    /// getOperandNo - Return the operand # of this MachineOperand in its
489    /// MachineInstr.
490    unsigned getOperandNo() const {
491      assert(Op && "Cannot dereference end iterator!");
492      return Op - &Op->getParent()->getOperand(0);
493    }
494
495    // Retrieve a reference to the current operand.
496    MachineInstr &operator*() const {
497      assert(Op && "Cannot dereference end iterator!");
498      return *Op->getParent();
499    }
500
501    MachineInstr *operator->() const {
502      assert(Op && "Cannot dereference end iterator!");
503      return Op->getParent();
504    }
505  };
506
507};
508
509} // End llvm namespace
510
511#endif
512