36fac85b46536e398634977096242f97a74214b2
[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   /// 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
85 public:
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   /// clearVirtRegs - Remove all virtual registers (after physreg assignment).
277   void clearVirtRegs();
278
279   /// setRegAllocationHint - Specify a register allocation hint for the
280   /// specified virtual register.
281   void setRegAllocationHint(unsigned Reg, unsigned Type, unsigned PrefReg) {
282     RegAllocHints[Reg].first  = Type;
283     RegAllocHints[Reg].second = PrefReg;
284   }
285
286   /// getRegAllocationHint - Return the register allocation hint for the
287   /// specified virtual register.
288   std::pair<unsigned, unsigned>
289   getRegAllocationHint(unsigned Reg) const {
290     return RegAllocHints[Reg];
291   }
292
293   /// getSimpleHint - Return the preferred register allocation hint, or 0 if a
294   /// standard simple hint (Type == 0) is not set.
295   unsigned getSimpleHint(unsigned Reg) const {
296     std::pair<unsigned, unsigned> Hint = getRegAllocationHint(Reg);
297     return Hint.first ? 0 : Hint.second;
298   }
299
300
301   //===--------------------------------------------------------------------===//
302   // Physical Register Use Info
303   //===--------------------------------------------------------------------===//
304
305   /// isPhysRegUsed - Return true if the specified register is used in this
306   /// function.  This only works after register allocation.
307   bool isPhysRegUsed(unsigned Reg) const {
308     return UsedPhysRegs.test(Reg) || UsedPhysRegMask.test(Reg);
309   }
310
311   /// isPhysRegOrOverlapUsed - Return true if Reg or any overlapping register
312   /// is used in this function.
313   bool isPhysRegOrOverlapUsed(unsigned Reg) const {
314     if (UsedPhysRegMask.test(Reg))
315       return true;
316     for (const unsigned *AI = TRI->getOverlaps(Reg); *AI; ++AI)
317       if (UsedPhysRegs.test(*AI))
318         return true;
319     return false;
320   }
321
322   /// setPhysRegUsed - Mark the specified register used in this function.
323   /// This should only be called during and after register allocation.
324   void setPhysRegUsed(unsigned Reg) { UsedPhysRegs.set(Reg); }
325
326   /// addPhysRegsUsed - Mark the specified registers used in this function.
327   /// This should only be called during and after register allocation.
328   void addPhysRegsUsed(const BitVector &Regs) { UsedPhysRegs |= Regs; }
329
330   /// addPhysRegsUsedFromRegMask - Mark any registers not in RegMask as used.
331   /// This corresponds to the bit mask attached to register mask operands.
332   void addPhysRegsUsedFromRegMask(const uint32_t *RegMask) {
333     UsedPhysRegMask.setBitsNotInMask(RegMask);
334   }
335
336   /// setPhysRegUnused - Mark the specified register unused in this function.
337   /// This should only be called during and after register allocation.
338   void setPhysRegUnused(unsigned Reg) {
339     UsedPhysRegs.reset(Reg);
340     UsedPhysRegMask.reset(Reg);
341   }
342
343
344   //===--------------------------------------------------------------------===//
345   // Reserved Register Info
346   //===--------------------------------------------------------------------===//
347   //
348   // The set of reserved registers must be invariant during register
349   // allocation.  For example, the target cannot suddenly decide it needs a
350   // frame pointer when the register allocator has already used the frame
351   // pointer register for something else.
352   //
353   // These methods can be used by target hooks like hasFP() to avoid changing
354   // the reserved register set during register allocation.
355
356   /// freezeReservedRegs - Called by the register allocator to freeze the set
357   /// of reserved registers before allocation begins.
358   void freezeReservedRegs(const MachineFunction&);
359
360   /// reservedRegsFrozen - Returns true after freezeReservedRegs() was called
361   /// to ensure the set of reserved registers stays constant.
362   bool reservedRegsFrozen() const {
363     return !ReservedRegs.empty();
364   }
365
366   /// canReserveReg - Returns true if PhysReg can be used as a reserved
367   /// register.  Any register can be reserved before freezeReservedRegs() is
368   /// called.
369   bool canReserveReg(unsigned PhysReg) const {
370     return !reservedRegsFrozen() || ReservedRegs.test(PhysReg);
371   }
372
373
374   //===--------------------------------------------------------------------===//
375   // LiveIn/LiveOut Management
376   //===--------------------------------------------------------------------===//
377
378   /// addLiveIn/Out - Add the specified register as a live in/out.  Note that it
379   /// is an error to add the same register to the same set more than once.
380   void addLiveIn(unsigned Reg, unsigned vreg = 0) {
381     LiveIns.push_back(std::make_pair(Reg, vreg));
382   }
383   void addLiveOut(unsigned Reg) { LiveOuts.push_back(Reg); }
384
385   // Iteration support for live in/out sets.  These sets are kept in sorted
386   // order by their register number.
387   typedef std::vector<std::pair<unsigned,unsigned> >::const_iterator
388   livein_iterator;
389   typedef std::vector<unsigned>::const_iterator liveout_iterator;
390   livein_iterator livein_begin() const { return LiveIns.begin(); }
391   livein_iterator livein_end()   const { return LiveIns.end(); }
392   bool            livein_empty() const { return LiveIns.empty(); }
393   liveout_iterator liveout_begin() const { return LiveOuts.begin(); }
394   liveout_iterator liveout_end()   const { return LiveOuts.end(); }
395   bool             liveout_empty() const { return LiveOuts.empty(); }
396
397   bool isLiveIn(unsigned Reg) const;
398   bool isLiveOut(unsigned Reg) const;
399
400   /// getLiveInPhysReg - If VReg is a live-in virtual register, return the
401   /// corresponding live-in physical register.
402   unsigned getLiveInPhysReg(unsigned VReg) const;
403
404   /// getLiveInVirtReg - If PReg is a live-in physical register, return the
405   /// corresponding live-in physical register.
406   unsigned getLiveInVirtReg(unsigned PReg) const;
407
408   /// EmitLiveInCopies - Emit copies to initialize livein virtual registers
409   /// into the given entry block.
410   void EmitLiveInCopies(MachineBasicBlock *EntryMBB,
411                         const TargetRegisterInfo &TRI,
412                         const TargetInstrInfo &TII);
413
414 private:
415   void HandleVRegListReallocation();
416
417 public:
418   /// defusechain_iterator - This class provides iterator support for machine
419   /// operands in the function that use or define a specific register.  If
420   /// ReturnUses is true it returns uses of registers, if ReturnDefs is true it
421   /// returns defs.  If neither are true then you are silly and it always
422   /// returns end().  If SkipDebug is true it skips uses marked Debug
423   /// when incrementing.
424   template<bool ReturnUses, bool ReturnDefs, bool SkipDebug>
425   class defusechain_iterator
426     : public std::iterator<std::forward_iterator_tag, MachineInstr, ptrdiff_t> {
427     MachineOperand *Op;
428     explicit defusechain_iterator(MachineOperand *op) : Op(op) {
429       // If the first node isn't one we're interested in, advance to one that
430       // we are interested in.
431       if (op) {
432         if ((!ReturnUses && op->isUse()) ||
433             (!ReturnDefs && op->isDef()) ||
434             (SkipDebug && op->isDebug()))
435           ++*this;
436       }
437     }
438     friend class MachineRegisterInfo;
439   public:
440     typedef std::iterator<std::forward_iterator_tag,
441                           MachineInstr, ptrdiff_t>::reference reference;
442     typedef std::iterator<std::forward_iterator_tag,
443                           MachineInstr, ptrdiff_t>::pointer pointer;
444
445     defusechain_iterator(const defusechain_iterator &I) : Op(I.Op) {}
446     defusechain_iterator() : Op(0) {}
447
448     bool operator==(const defusechain_iterator &x) const {
449       return Op == x.Op;
450     }
451     bool operator!=(const defusechain_iterator &x) const {
452       return !operator==(x);
453     }
454
455     /// atEnd - return true if this iterator is equal to reg_end() on the value.
456     bool atEnd() const { return Op == 0; }
457
458     // Iterator traversal: forward iteration only
459     defusechain_iterator &operator++() {          // Preincrement
460       assert(Op && "Cannot increment end iterator!");
461       Op = Op->getNextOperandForReg();
462
463       // If this is an operand we don't care about, skip it.
464       while (Op && ((!ReturnUses && Op->isUse()) ||
465                     (!ReturnDefs && Op->isDef()) ||
466                     (SkipDebug && Op->isDebug())))
467         Op = Op->getNextOperandForReg();
468
469       return *this;
470     }
471     defusechain_iterator operator++(int) {        // Postincrement
472       defusechain_iterator tmp = *this; ++*this; return tmp;
473     }
474
475     /// skipInstruction - move forward until reaching a different instruction.
476     /// Return the skipped instruction that is no longer pointed to, or NULL if
477     /// already pointing to end().
478     MachineInstr *skipInstruction() {
479       if (!Op) return 0;
480       MachineInstr *MI = Op->getParent();
481       do ++*this;
482       while (Op && Op->getParent() == MI);
483       return MI;
484     }
485
486     MachineOperand &getOperand() const {
487       assert(Op && "Cannot dereference end iterator!");
488       return *Op;
489     }
490
491     /// getOperandNo - Return the operand # of this MachineOperand in its
492     /// MachineInstr.
493     unsigned getOperandNo() const {
494       assert(Op && "Cannot dereference end iterator!");
495       return Op - &Op->getParent()->getOperand(0);
496     }
497
498     // Retrieve a reference to the current operand.
499     MachineInstr &operator*() const {
500       assert(Op && "Cannot dereference end iterator!");
501       return *Op->getParent();
502     }
503
504     MachineInstr *operator->() const {
505       assert(Op && "Cannot dereference end iterator!");
506       return Op->getParent();
507     }
508   };
509
510 };
511
512 } // End llvm namespace
513
514 #endif