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