1 //===-- llvm/CodeGen/MachineRegisterInfo.h ----------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the MachineRegisterInfo class.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CODEGEN_MACHINEREGISTERINFO_H
15 #define LLVM_CODEGEN_MACHINEREGISTERINFO_H
17 #include "llvm/ADT/BitVector.h"
18 #include "llvm/ADT/IndexedMap.h"
19 #include "llvm/CodeGen/MachineInstrBundle.h"
20 #include "llvm/Target/TargetRegisterInfo.h"
25 /// MachineRegisterInfo - Keep track of information for virtual and physical
26 /// registers, including vreg register classes, use/def chains for registers,
28 class MachineRegisterInfo {
29 const TargetRegisterInfo *const TRI;
31 /// IsSSA - True when the machine function is in SSA form and virtual
32 /// registers have a single def.
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.
40 /// VRegInfo - Information we keep for each virtual register.
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;
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;
56 /// PhysRegUseDefLists - This is an array of the head of the use/def list for
57 /// physical registers.
58 MachineOperand **PhysRegUseDefLists;
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];
68 MachineOperand *getRegUseDefListHead(unsigned RegNo) const {
69 if (TargetRegisterInfo::isVirtualRegister(RegNo))
70 return VRegInfo[RegNo].second;
71 return PhysRegUseDefLists[RegNo];
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;
80 /// UsedRegUnits - 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 has bits set for register units that are modified in the
86 /// current function. It doesn't include registers clobbered by function
87 /// calls with register mask operands.
88 BitVector UsedRegUnits;
90 /// UsedPhysRegMask - Additional used physregs including aliases.
91 /// This bit vector represents all the registers clobbered by function calls.
92 /// It can model things that UsedRegUnits can't, such as function calls that
93 /// clobber ymm7 but preserve the low half in xmm7.
94 BitVector UsedPhysRegMask;
96 /// ReservedRegs - This is a bit vector of reserved registers. The target
97 /// may change its mind about which registers should be reserved. This
98 /// vector is the frozen set of reserved registers when register allocation
100 BitVector ReservedRegs;
102 /// LiveIns/LiveOuts - Keep track of the physical registers that are
103 /// livein/liveout of the function. Live in values are typically arguments in
104 /// registers, live out values are typically return values in registers.
105 /// LiveIn values are allowed to have virtual registers associated with them,
106 /// stored in the second element.
107 std::vector<std::pair<unsigned, unsigned> > LiveIns;
108 std::vector<unsigned> LiveOuts;
110 MachineRegisterInfo(const MachineRegisterInfo&) LLVM_DELETED_FUNCTION;
111 void operator=(const MachineRegisterInfo&) LLVM_DELETED_FUNCTION;
113 explicit MachineRegisterInfo(const TargetRegisterInfo &TRI);
114 ~MachineRegisterInfo();
116 //===--------------------------------------------------------------------===//
118 //===--------------------------------------------------------------------===//
120 // isSSA - Returns true when the machine function is in SSA form. Early
121 // passes require the machine function to be in SSA form where every virtual
122 // register has a single defining instruction.
124 // The TwoAddressInstructionPass and PHIElimination passes take the machine
125 // function out of SSA form when they introduce multiple defs per virtual
127 bool isSSA() const { return IsSSA; }
129 // leaveSSA - Indicates that the machine function is no longer in SSA form.
130 void leaveSSA() { IsSSA = false; }
132 /// tracksLiveness - Returns true when tracking register liveness accurately.
134 /// While this flag is true, register liveness information in basic block
135 /// live-in lists and machine instruction operands is accurate. This means it
136 /// can be used to change the code in ways that affect the values in
137 /// registers, for example by the register scavenger.
139 /// When this flag is false, liveness is no longer reliable.
140 bool tracksLiveness() const { return TracksLiveness; }
142 /// invalidateLiveness - Indicates that register liveness is no longer being
143 /// tracked accurately.
145 /// This should be called by late passes that invalidate the liveness
147 void invalidateLiveness() { TracksLiveness = false; }
149 //===--------------------------------------------------------------------===//
151 //===--------------------------------------------------------------------===//
153 // Strictly for use by MachineInstr.cpp.
154 void addRegOperandToUseList(MachineOperand *MO);
156 // Strictly for use by MachineInstr.cpp.
157 void removeRegOperandFromUseList(MachineOperand *MO);
159 // Strictly for use by MachineInstr.cpp.
160 void moveOperands(MachineOperand *Dst, MachineOperand *Src, unsigned NumOps);
162 /// reg_begin/reg_end - Provide iteration support to walk over all definitions
163 /// and uses of a register within the MachineFunction that corresponds to this
164 /// MachineRegisterInfo object.
165 template<bool Uses, bool Defs, bool SkipDebug>
166 class defusechain_iterator;
168 // Make it a friend so it can access getNextOperandForReg().
169 template<bool, bool, bool> friend class defusechain_iterator;
171 /// reg_iterator/reg_begin/reg_end - Walk all defs and uses of the specified
173 typedef defusechain_iterator<true,true,false> reg_iterator;
174 reg_iterator reg_begin(unsigned RegNo) const {
175 return reg_iterator(getRegUseDefListHead(RegNo));
177 static reg_iterator reg_end() { return reg_iterator(0); }
179 /// reg_empty - Return true if there are no instructions using or defining the
180 /// specified register (it may be live-in).
181 bool reg_empty(unsigned RegNo) const { return reg_begin(RegNo) == reg_end(); }
183 /// reg_nodbg_iterator/reg_nodbg_begin/reg_nodbg_end - Walk all defs and uses
184 /// of the specified register, skipping those marked as Debug.
185 typedef defusechain_iterator<true,true,true> reg_nodbg_iterator;
186 reg_nodbg_iterator reg_nodbg_begin(unsigned RegNo) const {
187 return reg_nodbg_iterator(getRegUseDefListHead(RegNo));
189 static reg_nodbg_iterator reg_nodbg_end() { return reg_nodbg_iterator(0); }
191 /// reg_nodbg_empty - Return true if the only instructions using or defining
192 /// Reg are Debug instructions.
193 bool reg_nodbg_empty(unsigned RegNo) const {
194 return reg_nodbg_begin(RegNo) == reg_nodbg_end();
197 /// def_iterator/def_begin/def_end - Walk all defs of the specified register.
198 typedef defusechain_iterator<false,true,false> def_iterator;
199 def_iterator def_begin(unsigned RegNo) const {
200 return def_iterator(getRegUseDefListHead(RegNo));
202 static def_iterator def_end() { return def_iterator(0); }
204 /// def_empty - Return true if there are no instructions defining the
205 /// specified register (it may be live-in).
206 bool def_empty(unsigned RegNo) const { return def_begin(RegNo) == def_end(); }
208 /// hasOneDef - Return true if there is exactly one instruction defining the
209 /// specified register.
210 bool hasOneDef(unsigned RegNo) const {
211 def_iterator DI = def_begin(RegNo);
214 return ++DI == def_end();
217 /// use_iterator/use_begin/use_end - Walk all uses of the specified register.
218 typedef defusechain_iterator<true,false,false> use_iterator;
219 use_iterator use_begin(unsigned RegNo) const {
220 return use_iterator(getRegUseDefListHead(RegNo));
222 static use_iterator use_end() { return use_iterator(0); }
224 /// use_empty - Return true if there are no instructions using the specified
226 bool use_empty(unsigned RegNo) const { return use_begin(RegNo) == use_end(); }
228 /// hasOneUse - Return true if there is exactly one instruction using the
229 /// specified register.
230 bool hasOneUse(unsigned RegNo) const {
231 use_iterator UI = use_begin(RegNo);
234 return ++UI == use_end();
237 /// use_nodbg_iterator/use_nodbg_begin/use_nodbg_end - Walk all uses of the
238 /// specified register, skipping those marked as Debug.
239 typedef defusechain_iterator<true,false,true> use_nodbg_iterator;
240 use_nodbg_iterator use_nodbg_begin(unsigned RegNo) const {
241 return use_nodbg_iterator(getRegUseDefListHead(RegNo));
243 static use_nodbg_iterator use_nodbg_end() { return use_nodbg_iterator(0); }
245 /// use_nodbg_empty - Return true if there are no non-Debug instructions
246 /// using the specified register.
247 bool use_nodbg_empty(unsigned RegNo) const {
248 return use_nodbg_begin(RegNo) == use_nodbg_end();
251 /// hasOneNonDBGUse - Return true if there is exactly one non-Debug
252 /// instruction using the specified register.
253 bool hasOneNonDBGUse(unsigned RegNo) const;
255 /// replaceRegWith - Replace all instances of FromReg with ToReg in the
256 /// machine function. This is like llvm-level X->replaceAllUsesWith(Y),
257 /// except that it also changes any definitions of the register as well.
259 /// Note that it is usually necessary to first constrain ToReg's register
260 /// class to match the FromReg constraints using:
262 /// constrainRegClass(ToReg, getRegClass(FromReg))
264 /// That function will return NULL if the virtual registers have incompatible
266 void replaceRegWith(unsigned FromReg, unsigned ToReg);
268 /// getVRegDef - Return the machine instr that defines the specified virtual
269 /// register or null if none is found. This assumes that the code is in SSA
270 /// form, so there should only be one definition.
271 MachineInstr *getVRegDef(unsigned Reg) const;
273 /// getUniqueVRegDef - Return the unique machine instr that defines the
274 /// specified virtual register or null if none is found. If there are
275 /// multiple definitions or no definition, return null.
276 MachineInstr *getUniqueVRegDef(unsigned Reg) const;
278 /// clearKillFlags - Iterate over all the uses of the given register and
279 /// clear the kill flag from the MachineOperand. This function is used by
280 /// optimization passes which extend register lifetimes and need only
281 /// preserve conservative kill flag information.
282 void clearKillFlags(unsigned Reg) const;
285 void dumpUses(unsigned RegNo) const;
288 /// isConstantPhysReg - Returns true if PhysReg is unallocatable and constant
289 /// throughout the function. It is safe to move instructions that read such
291 bool isConstantPhysReg(unsigned PhysReg, const MachineFunction &MF) const;
293 //===--------------------------------------------------------------------===//
294 // Virtual Register Info
295 //===--------------------------------------------------------------------===//
297 /// getRegClass - Return the register class of the specified virtual register.
299 const TargetRegisterClass *getRegClass(unsigned Reg) const {
300 return VRegInfo[Reg].first;
303 /// setRegClass - Set the register class of the specified virtual register.
305 void setRegClass(unsigned Reg, const TargetRegisterClass *RC);
307 /// constrainRegClass - Constrain the register class of the specified virtual
308 /// register to be a common subclass of RC and the current register class,
309 /// but only if the new class has at least MinNumRegs registers. Return the
310 /// new register class, or NULL if no such class exists.
311 /// This should only be used when the constraint is known to be trivial, like
312 /// GR32 -> GR32_NOSP. Beware of increasing register pressure.
314 const TargetRegisterClass *constrainRegClass(unsigned Reg,
315 const TargetRegisterClass *RC,
316 unsigned MinNumRegs = 0);
318 /// recomputeRegClass - Try to find a legal super-class of Reg's register
319 /// class that still satisfies the constraints from the instructions using
320 /// Reg. Returns true if Reg was upgraded.
322 /// This method can be used after constraints have been removed from a
323 /// virtual register, for example after removing instructions or splitting
326 bool recomputeRegClass(unsigned Reg, const TargetMachine&);
328 /// createVirtualRegister - Create and return a new virtual register in the
329 /// function with the specified register class.
331 unsigned createVirtualRegister(const TargetRegisterClass *RegClass);
333 /// getNumVirtRegs - Return the number of virtual registers created.
335 unsigned getNumVirtRegs() const { return VRegInfo.size(); }
337 /// clearVirtRegs - Remove all virtual registers (after physreg assignment).
338 void clearVirtRegs();
340 /// setRegAllocationHint - Specify a register allocation hint for the
341 /// specified virtual register.
342 void setRegAllocationHint(unsigned Reg, unsigned Type, unsigned PrefReg) {
343 RegAllocHints[Reg].first = Type;
344 RegAllocHints[Reg].second = PrefReg;
347 /// getRegAllocationHint - Return the register allocation hint for the
348 /// specified virtual register.
349 std::pair<unsigned, unsigned>
350 getRegAllocationHint(unsigned Reg) const {
351 return RegAllocHints[Reg];
354 /// getSimpleHint - Return the preferred register allocation hint, or 0 if a
355 /// standard simple hint (Type == 0) is not set.
356 unsigned getSimpleHint(unsigned Reg) const {
357 std::pair<unsigned, unsigned> Hint = getRegAllocationHint(Reg);
358 return Hint.first ? 0 : Hint.second;
362 //===--------------------------------------------------------------------===//
363 // Physical Register Use Info
364 //===--------------------------------------------------------------------===//
366 /// isPhysRegUsed - Return true if the specified register is used in this
367 /// function. Also check for clobbered aliases and registers clobbered by
368 /// function calls with register mask operands.
370 /// This only works after register allocation. It is primarily used by
371 /// PrologEpilogInserter to determine which callee-saved registers need
373 bool isPhysRegUsed(unsigned Reg) const {
374 if (UsedPhysRegMask.test(Reg))
376 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
377 if (UsedRegUnits.test(*Units))
382 /// setPhysRegUsed - Mark the specified register used in this function.
383 /// This should only be called during and after register allocation.
384 void setPhysRegUsed(unsigned Reg) {
385 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
386 UsedRegUnits.set(*Units);
389 /// addPhysRegsUsedFromRegMask - Mark any registers not in RegMask as used.
390 /// This corresponds to the bit mask attached to register mask operands.
391 void addPhysRegsUsedFromRegMask(const uint32_t *RegMask) {
392 UsedPhysRegMask.setBitsNotInMask(RegMask);
395 /// setPhysRegUnused - Mark the specified register unused in this function.
396 /// This should only be called during and after register allocation.
397 void setPhysRegUnused(unsigned Reg) {
398 UsedPhysRegMask.reset(Reg);
399 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
400 UsedRegUnits.reset(*Units);
404 //===--------------------------------------------------------------------===//
405 // Reserved Register Info
406 //===--------------------------------------------------------------------===//
408 // The set of reserved registers must be invariant during register
409 // allocation. For example, the target cannot suddenly decide it needs a
410 // frame pointer when the register allocator has already used the frame
411 // pointer register for something else.
413 // These methods can be used by target hooks like hasFP() to avoid changing
414 // the reserved register set during register allocation.
416 /// freezeReservedRegs - Called by the register allocator to freeze the set
417 /// of reserved registers before allocation begins.
418 void freezeReservedRegs(const MachineFunction&);
420 /// reservedRegsFrozen - Returns true after freezeReservedRegs() was called
421 /// to ensure the set of reserved registers stays constant.
422 bool reservedRegsFrozen() const {
423 return !ReservedRegs.empty();
426 /// canReserveReg - Returns true if PhysReg can be used as a reserved
427 /// register. Any register can be reserved before freezeReservedRegs() is
429 bool canReserveReg(unsigned PhysReg) const {
430 return !reservedRegsFrozen() || ReservedRegs.test(PhysReg);
433 /// getReservedRegs - Returns a reference to the frozen set of reserved
434 /// registers. This method should always be preferred to calling
435 /// TRI::getReservedRegs() when possible.
436 const BitVector &getReservedRegs() const {
437 assert(reservedRegsFrozen() &&
438 "Reserved registers haven't been frozen yet. "
439 "Use TRI::getReservedRegs().");
443 /// isReserved - Returns true when PhysReg is a reserved register.
445 /// Reserved registers may belong to an allocatable register class, but the
446 /// target has explicitly requested that they are not used.
448 bool isReserved(unsigned PhysReg) const {
449 return getReservedRegs().test(PhysReg);
452 /// isAllocatable - Returns true when PhysReg belongs to an allocatable
453 /// register class and it hasn't been reserved.
455 /// Allocatable registers may show up in the allocation order of some virtual
456 /// register, so a register allocator needs to track its liveness and
458 bool isAllocatable(unsigned PhysReg) const {
459 return TRI->isInAllocatableClass(PhysReg) && !isReserved(PhysReg);
462 //===--------------------------------------------------------------------===//
463 // LiveIn/LiveOut Management
464 //===--------------------------------------------------------------------===//
466 /// addLiveIn/Out - Add the specified register as a live in/out. Note that it
467 /// is an error to add the same register to the same set more than once.
468 void addLiveIn(unsigned Reg, unsigned vreg = 0) {
469 LiveIns.push_back(std::make_pair(Reg, vreg));
471 void addLiveOut(unsigned Reg) { LiveOuts.push_back(Reg); }
473 // Iteration support for live in/out sets. These sets are kept in sorted
474 // order by their register number.
475 typedef std::vector<std::pair<unsigned,unsigned> >::const_iterator
477 typedef std::vector<unsigned>::const_iterator liveout_iterator;
478 livein_iterator livein_begin() const { return LiveIns.begin(); }
479 livein_iterator livein_end() const { return LiveIns.end(); }
480 bool livein_empty() const { return LiveIns.empty(); }
481 liveout_iterator liveout_begin() const { return LiveOuts.begin(); }
482 liveout_iterator liveout_end() const { return LiveOuts.end(); }
483 bool liveout_empty() const { return LiveOuts.empty(); }
485 bool isLiveIn(unsigned Reg) const;
486 bool isLiveOut(unsigned Reg) const;
488 /// getLiveInPhysReg - If VReg is a live-in virtual register, return the
489 /// corresponding live-in physical register.
490 unsigned getLiveInPhysReg(unsigned VReg) const;
492 /// getLiveInVirtReg - If PReg is a live-in physical register, return the
493 /// corresponding live-in physical register.
494 unsigned getLiveInVirtReg(unsigned PReg) const;
496 /// EmitLiveInCopies - Emit copies to initialize livein virtual registers
497 /// into the given entry block.
498 void EmitLiveInCopies(MachineBasicBlock *EntryMBB,
499 const TargetRegisterInfo &TRI,
500 const TargetInstrInfo &TII);
502 /// defusechain_iterator - This class provides iterator support for machine
503 /// operands in the function that use or define a specific register. If
504 /// ReturnUses is true it returns uses of registers, if ReturnDefs is true it
505 /// returns defs. If neither are true then you are silly and it always
506 /// returns end(). If SkipDebug is true it skips uses marked Debug
507 /// when incrementing.
508 template<bool ReturnUses, bool ReturnDefs, bool SkipDebug>
509 class defusechain_iterator
510 : public std::iterator<std::forward_iterator_tag, MachineInstr, ptrdiff_t> {
512 explicit defusechain_iterator(MachineOperand *op) : Op(op) {
513 // If the first node isn't one we're interested in, advance to one that
514 // we are interested in.
516 if ((!ReturnUses && op->isUse()) ||
517 (!ReturnDefs && op->isDef()) ||
518 (SkipDebug && op->isDebug()))
522 friend class MachineRegisterInfo;
524 typedef std::iterator<std::forward_iterator_tag,
525 MachineInstr, ptrdiff_t>::reference reference;
526 typedef std::iterator<std::forward_iterator_tag,
527 MachineInstr, ptrdiff_t>::pointer pointer;
529 defusechain_iterator(const defusechain_iterator &I) : Op(I.Op) {}
530 defusechain_iterator() : Op(0) {}
532 bool operator==(const defusechain_iterator &x) const {
535 bool operator!=(const defusechain_iterator &x) const {
536 return !operator==(x);
539 /// atEnd - return true if this iterator is equal to reg_end() on the value.
540 bool atEnd() const { return Op == 0; }
542 // Iterator traversal: forward iteration only
543 defusechain_iterator &operator++() { // Preincrement
544 assert(Op && "Cannot increment end iterator!");
545 Op = getNextOperandForReg(Op);
547 // All defs come before the uses, so stop def_iterator early.
553 assert(!Op->isDebug() && "Can't have debug defs");
556 // If this is an operand we don't care about, skip it.
557 while (Op && ((!ReturnDefs && Op->isDef()) ||
558 (SkipDebug && Op->isDebug())))
559 Op = getNextOperandForReg(Op);
564 defusechain_iterator operator++(int) { // Postincrement
565 defusechain_iterator tmp = *this; ++*this; return tmp;
568 /// skipInstruction - move forward until reaching a different instruction.
569 /// Return the skipped instruction that is no longer pointed to, or NULL if
570 /// already pointing to end().
571 MachineInstr *skipInstruction() {
573 MachineInstr *MI = Op->getParent();
575 while (Op && Op->getParent() == MI);
579 MachineInstr *skipBundle() {
581 MachineInstr *MI = getBundleStart(Op->getParent());
583 while (Op && getBundleStart(Op->getParent()) == MI);
587 MachineOperand &getOperand() const {
588 assert(Op && "Cannot dereference end iterator!");
592 /// getOperandNo - Return the operand # of this MachineOperand in its
594 unsigned getOperandNo() const {
595 assert(Op && "Cannot dereference end iterator!");
596 return Op - &Op->getParent()->getOperand(0);
599 // Retrieve a reference to the current operand.
600 MachineInstr &operator*() const {
601 assert(Op && "Cannot dereference end iterator!");
602 return *Op->getParent();
605 MachineInstr *operator->() const {
606 assert(Op && "Cannot dereference end iterator!");
607 return Op->getParent();
613 } // End llvm namespace