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