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