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/TargetMachine.h"
21 #include "llvm/Target/TargetRegisterInfo.h"
26 /// MachineRegisterInfo - Keep track of information for virtual and physical
27 /// registers, including vreg register classes, use/def chains for registers,
29 class MachineRegisterInfo {
30 const TargetMachine &TM;
32 /// IsSSA - True when the machine function is in SSA form and virtual
33 /// registers have a single def.
36 /// TracksLiveness - True while register liveness is being tracked accurately.
37 /// Basic block live-in lists, kill flags, and implicit defs may not be
38 /// accurate when after this flag is cleared.
41 /// VRegInfo - Information we keep for each virtual register.
43 /// Each element in this list contains the register class of the vreg and the
44 /// start of the use/def list for the register.
45 IndexedMap<std::pair<const TargetRegisterClass*, MachineOperand*>,
46 VirtReg2IndexFunctor> VRegInfo;
48 /// RegAllocHints - This vector records register allocation hints for virtual
49 /// registers. For each virtual register, it keeps a register and hint type
50 /// pair making up the allocation hint. Hint type is target specific except
51 /// for the value 0 which means the second value of the pair is the preferred
52 /// register for allocation. For example, if the hint is <0, 1024>, it means
53 /// the allocator should prefer the physical register allocated to the virtual
54 /// register of the hint.
55 IndexedMap<std::pair<unsigned, unsigned>, VirtReg2IndexFunctor> RegAllocHints;
57 /// PhysRegUseDefLists - This is an array of the head of the use/def list for
58 /// physical registers.
59 MachineOperand **PhysRegUseDefLists;
61 /// getRegUseDefListHead - Return the head pointer for the register use/def
62 /// list for the specified virtual or physical register.
63 MachineOperand *&getRegUseDefListHead(unsigned RegNo) {
64 if (TargetRegisterInfo::isVirtualRegister(RegNo))
65 return VRegInfo[RegNo].second;
66 return PhysRegUseDefLists[RegNo];
69 MachineOperand *getRegUseDefListHead(unsigned RegNo) const {
70 if (TargetRegisterInfo::isVirtualRegister(RegNo))
71 return VRegInfo[RegNo].second;
72 return PhysRegUseDefLists[RegNo];
75 /// Get the next element in the use-def chain.
76 static MachineOperand *getNextOperandForReg(const MachineOperand *MO) {
77 assert(MO && MO->isReg() && "This is not a register operand!");
78 return MO->Contents.Reg.Next;
81 /// UsedRegUnits - This is a bit vector that is computed and set by the
82 /// register allocator, and must be kept up to date by passes that run after
83 /// register allocation (though most don't modify this). This is used
84 /// so that the code generator knows which callee save registers to save and
85 /// for other target specific uses.
86 /// This vector has bits set for register units that are modified in the
87 /// current function. It doesn't include registers clobbered by function
88 /// calls with register mask operands.
89 BitVector UsedRegUnits;
91 /// UsedPhysRegMask - Additional used physregs including aliases.
92 /// This bit vector represents all the registers clobbered by function calls.
93 /// It can model things that UsedRegUnits can't, such as function calls that
94 /// clobber ymm7 but preserve the low half in xmm7.
95 BitVector UsedPhysRegMask;
97 /// ReservedRegs - This is a bit vector of reserved registers. The target
98 /// may change its mind about which registers should be reserved. This
99 /// vector is the frozen set of reserved registers when register allocation
101 BitVector ReservedRegs;
103 /// Keep track of the physical registers that are live in to the function.
104 /// Live in values are typically arguments in registers. LiveIn values are
105 /// allowed to have virtual registers associated with them, stored in the
107 std::vector<std::pair<unsigned, unsigned> > LiveIns;
109 MachineRegisterInfo(const MachineRegisterInfo&) LLVM_DELETED_FUNCTION;
110 void operator=(const MachineRegisterInfo&) LLVM_DELETED_FUNCTION;
112 explicit MachineRegisterInfo(const TargetMachine &TM);
113 ~MachineRegisterInfo();
115 const TargetRegisterInfo *getTargetRegisterInfo() const {
116 return TM.getRegisterInfo();
119 //===--------------------------------------------------------------------===//
121 //===--------------------------------------------------------------------===//
123 // isSSA - Returns true when the machine function is in SSA form. Early
124 // passes require the machine function to be in SSA form where every virtual
125 // register has a single defining instruction.
127 // The TwoAddressInstructionPass and PHIElimination passes take the machine
128 // function out of SSA form when they introduce multiple defs per virtual
130 bool isSSA() const { return IsSSA; }
132 // leaveSSA - Indicates that the machine function is no longer in SSA form.
133 void leaveSSA() { IsSSA = false; }
135 /// tracksLiveness - Returns true when tracking register liveness accurately.
137 /// While this flag is true, register liveness information in basic block
138 /// live-in lists and machine instruction operands is accurate. This means it
139 /// can be used to change the code in ways that affect the values in
140 /// registers, for example by the register scavenger.
142 /// When this flag is false, liveness is no longer reliable.
143 bool tracksLiveness() const { return TracksLiveness; }
145 /// invalidateLiveness - Indicates that register liveness is no longer being
146 /// tracked accurately.
148 /// This should be called by late passes that invalidate the liveness
150 void invalidateLiveness() { TracksLiveness = false; }
152 //===--------------------------------------------------------------------===//
154 //===--------------------------------------------------------------------===//
156 // Strictly for use by MachineInstr.cpp.
157 void addRegOperandToUseList(MachineOperand *MO);
159 // Strictly for use by MachineInstr.cpp.
160 void removeRegOperandFromUseList(MachineOperand *MO);
162 // Strictly for use by MachineInstr.cpp.
163 void moveOperands(MachineOperand *Dst, MachineOperand *Src, unsigned NumOps);
165 /// Verify the sanity of the use list for Reg.
166 void verifyUseList(unsigned Reg) const;
168 /// Verify the use list of all registers.
169 void verifyUseLists() const;
171 /// reg_begin/reg_end - Provide iteration support to walk over all definitions
172 /// and uses of a register within the MachineFunction that corresponds to this
173 /// MachineRegisterInfo object.
174 template<bool Uses, bool Defs, bool SkipDebug>
175 class defusechain_iterator;
177 // Make it a friend so it can access getNextOperandForReg().
178 template<bool, bool, bool> friend class defusechain_iterator;
180 /// reg_iterator/reg_begin/reg_end - Walk all defs and uses of the specified
182 typedef defusechain_iterator<true,true,false> reg_iterator;
183 reg_iterator reg_begin(unsigned RegNo) const {
184 return reg_iterator(getRegUseDefListHead(RegNo));
186 static reg_iterator reg_end() { return reg_iterator(0); }
188 /// reg_empty - Return true if there are no instructions using or defining the
189 /// specified register (it may be live-in).
190 bool reg_empty(unsigned RegNo) const { return reg_begin(RegNo) == reg_end(); }
192 /// reg_nodbg_iterator/reg_nodbg_begin/reg_nodbg_end - Walk all defs and uses
193 /// of the specified register, skipping those marked as Debug.
194 typedef defusechain_iterator<true,true,true> reg_nodbg_iterator;
195 reg_nodbg_iterator reg_nodbg_begin(unsigned RegNo) const {
196 return reg_nodbg_iterator(getRegUseDefListHead(RegNo));
198 static reg_nodbg_iterator reg_nodbg_end() { return reg_nodbg_iterator(0); }
200 /// reg_nodbg_empty - Return true if the only instructions using or defining
201 /// Reg are Debug instructions.
202 bool reg_nodbg_empty(unsigned RegNo) const {
203 return reg_nodbg_begin(RegNo) == reg_nodbg_end();
206 /// def_iterator/def_begin/def_end - Walk all defs of the specified register.
207 typedef defusechain_iterator<false,true,false> def_iterator;
208 def_iterator def_begin(unsigned RegNo) const {
209 return def_iterator(getRegUseDefListHead(RegNo));
211 static def_iterator def_end() { return def_iterator(0); }
213 /// def_empty - Return true if there are no instructions defining the
214 /// specified register (it may be live-in).
215 bool def_empty(unsigned RegNo) const { return def_begin(RegNo) == def_end(); }
217 /// hasOneDef - Return true if there is exactly one instruction defining the
218 /// specified register.
219 bool hasOneDef(unsigned RegNo) const {
220 def_iterator DI = def_begin(RegNo);
223 return ++DI == def_end();
226 /// use_iterator/use_begin/use_end - Walk all uses of the specified register.
227 typedef defusechain_iterator<true,false,false> use_iterator;
228 use_iterator use_begin(unsigned RegNo) const {
229 return use_iterator(getRegUseDefListHead(RegNo));
231 static use_iterator use_end() { return use_iterator(0); }
233 /// use_empty - Return true if there are no instructions using the specified
235 bool use_empty(unsigned RegNo) const { return use_begin(RegNo) == use_end(); }
237 /// hasOneUse - Return true if there is exactly one instruction using the
238 /// specified register.
239 bool hasOneUse(unsigned RegNo) const {
240 use_iterator UI = use_begin(RegNo);
243 return ++UI == use_end();
246 /// use_nodbg_iterator/use_nodbg_begin/use_nodbg_end - Walk all uses of the
247 /// specified register, skipping those marked as Debug.
248 typedef defusechain_iterator<true,false,true> use_nodbg_iterator;
249 use_nodbg_iterator use_nodbg_begin(unsigned RegNo) const {
250 return use_nodbg_iterator(getRegUseDefListHead(RegNo));
252 static use_nodbg_iterator use_nodbg_end() { return use_nodbg_iterator(0); }
254 /// use_nodbg_empty - Return true if there are no non-Debug instructions
255 /// using the specified register.
256 bool use_nodbg_empty(unsigned RegNo) const {
257 return use_nodbg_begin(RegNo) == use_nodbg_end();
260 /// hasOneNonDBGUse - Return true if there is exactly one non-Debug
261 /// instruction using the specified register.
262 bool hasOneNonDBGUse(unsigned RegNo) const;
264 /// replaceRegWith - Replace all instances of FromReg with ToReg in the
265 /// machine function. This is like llvm-level X->replaceAllUsesWith(Y),
266 /// except that it also changes any definitions of the register as well.
268 /// Note that it is usually necessary to first constrain ToReg's register
269 /// class to match the FromReg constraints using:
271 /// constrainRegClass(ToReg, getRegClass(FromReg))
273 /// That function will return NULL if the virtual registers have incompatible
275 void replaceRegWith(unsigned FromReg, unsigned ToReg);
277 /// getVRegDef - Return the machine instr that defines the specified virtual
278 /// register or null if none is found. This assumes that the code is in SSA
279 /// form, so there should only be one definition.
280 MachineInstr *getVRegDef(unsigned Reg) const;
282 /// getUniqueVRegDef - Return the unique machine instr that defines the
283 /// specified virtual register or null if none is found. If there are
284 /// multiple definitions or no definition, return null.
285 MachineInstr *getUniqueVRegDef(unsigned Reg) const;
287 /// clearKillFlags - Iterate over all the uses of the given register and
288 /// clear the kill flag from the MachineOperand. This function is used by
289 /// optimization passes which extend register lifetimes and need only
290 /// preserve conservative kill flag information.
291 void clearKillFlags(unsigned Reg) const;
294 void dumpUses(unsigned RegNo) const;
297 /// isConstantPhysReg - Returns true if PhysReg is unallocatable and constant
298 /// throughout the function. It is safe to move instructions that read such
300 bool isConstantPhysReg(unsigned PhysReg, const MachineFunction &MF) const;
302 //===--------------------------------------------------------------------===//
303 // Virtual Register Info
304 //===--------------------------------------------------------------------===//
306 /// getRegClass - Return the register class of the specified virtual register.
308 const TargetRegisterClass *getRegClass(unsigned Reg) const {
309 return VRegInfo[Reg].first;
312 /// setRegClass - Set the register class of the specified virtual register.
314 void setRegClass(unsigned Reg, const TargetRegisterClass *RC);
316 /// constrainRegClass - Constrain the register class of the specified virtual
317 /// register to be a common subclass of RC and the current register class,
318 /// but only if the new class has at least MinNumRegs registers. Return the
319 /// new register class, or NULL if no such class exists.
320 /// This should only be used when the constraint is known to be trivial, like
321 /// GR32 -> GR32_NOSP. Beware of increasing register pressure.
323 const TargetRegisterClass *constrainRegClass(unsigned Reg,
324 const TargetRegisterClass *RC,
325 unsigned MinNumRegs = 0);
327 /// recomputeRegClass - Try to find a legal super-class of Reg's register
328 /// class that still satisfies the constraints from the instructions using
329 /// Reg. Returns true if Reg was upgraded.
331 /// This method can be used after constraints have been removed from a
332 /// virtual register, for example after removing instructions or splitting
335 bool recomputeRegClass(unsigned Reg, const TargetMachine&);
337 /// createVirtualRegister - Create and return a new virtual register in the
338 /// function with the specified register class.
340 unsigned createVirtualRegister(const TargetRegisterClass *RegClass);
342 /// getNumVirtRegs - Return the number of virtual registers created.
344 unsigned getNumVirtRegs() const { return VRegInfo.size(); }
346 /// clearVirtRegs - Remove all virtual registers (after physreg assignment).
347 void clearVirtRegs();
349 /// setRegAllocationHint - Specify a register allocation hint for the
350 /// specified virtual register.
351 void setRegAllocationHint(unsigned Reg, unsigned Type, unsigned PrefReg) {
352 RegAllocHints[Reg].first = Type;
353 RegAllocHints[Reg].second = PrefReg;
356 /// getRegAllocationHint - Return the register allocation hint for the
357 /// specified virtual register.
358 std::pair<unsigned, unsigned>
359 getRegAllocationHint(unsigned Reg) const {
360 return RegAllocHints[Reg];
363 /// getSimpleHint - Return the preferred register allocation hint, or 0 if a
364 /// standard simple hint (Type == 0) is not set.
365 unsigned getSimpleHint(unsigned Reg) const {
366 std::pair<unsigned, unsigned> Hint = getRegAllocationHint(Reg);
367 return Hint.first ? 0 : Hint.second;
371 //===--------------------------------------------------------------------===//
372 // Physical Register Use Info
373 //===--------------------------------------------------------------------===//
375 /// isPhysRegUsed - Return true if the specified register is used in this
376 /// function. Also check for clobbered aliases and registers clobbered by
377 /// function calls with register mask operands.
379 /// This only works after register allocation. It is primarily used by
380 /// PrologEpilogInserter to determine which callee-saved registers need
382 bool isPhysRegUsed(unsigned Reg) const {
383 if (UsedPhysRegMask.test(Reg))
385 for (MCRegUnitIterator Units(Reg, getTargetRegisterInfo());
386 Units.isValid(); ++Units)
387 if (UsedRegUnits.test(*Units))
392 /// Mark the specified register unit as used in this function.
393 /// This should only be called during and after register allocation.
394 void setRegUnitUsed(unsigned RegUnit) {
395 UsedRegUnits.set(RegUnit);
398 /// setPhysRegUsed - Mark the specified register used in this function.
399 /// This should only be called during and after register allocation.
400 void setPhysRegUsed(unsigned Reg) {
401 for (MCRegUnitIterator Units(Reg, getTargetRegisterInfo());
402 Units.isValid(); ++Units)
403 UsedRegUnits.set(*Units);
406 /// addPhysRegsUsedFromRegMask - Mark any registers not in RegMask as used.
407 /// This corresponds to the bit mask attached to register mask operands.
408 void addPhysRegsUsedFromRegMask(const uint32_t *RegMask) {
409 UsedPhysRegMask.setBitsNotInMask(RegMask);
412 /// setPhysRegUnused - Mark the specified register unused in this function.
413 /// This should only be called during and after register allocation.
414 void setPhysRegUnused(unsigned Reg) {
415 UsedPhysRegMask.reset(Reg);
416 for (MCRegUnitIterator Units(Reg, getTargetRegisterInfo());
417 Units.isValid(); ++Units)
418 UsedRegUnits.reset(*Units);
422 //===--------------------------------------------------------------------===//
423 // Reserved Register Info
424 //===--------------------------------------------------------------------===//
426 // The set of reserved registers must be invariant during register
427 // allocation. For example, the target cannot suddenly decide it needs a
428 // frame pointer when the register allocator has already used the frame
429 // pointer register for something else.
431 // These methods can be used by target hooks like hasFP() to avoid changing
432 // the reserved register set during register allocation.
434 /// freezeReservedRegs - Called by the register allocator to freeze the set
435 /// of reserved registers before allocation begins.
436 void freezeReservedRegs(const MachineFunction&);
438 /// reservedRegsFrozen - Returns true after freezeReservedRegs() was called
439 /// to ensure the set of reserved registers stays constant.
440 bool reservedRegsFrozen() const {
441 return !ReservedRegs.empty();
444 /// canReserveReg - Returns true if PhysReg can be used as a reserved
445 /// register. Any register can be reserved before freezeReservedRegs() is
447 bool canReserveReg(unsigned PhysReg) const {
448 return !reservedRegsFrozen() || ReservedRegs.test(PhysReg);
451 /// getReservedRegs - Returns a reference to the frozen set of reserved
452 /// registers. This method should always be preferred to calling
453 /// TRI::getReservedRegs() when possible.
454 const BitVector &getReservedRegs() const {
455 assert(reservedRegsFrozen() &&
456 "Reserved registers haven't been frozen yet. "
457 "Use TRI::getReservedRegs().");
461 /// isReserved - Returns true when PhysReg is a reserved register.
463 /// Reserved registers may belong to an allocatable register class, but the
464 /// target has explicitly requested that they are not used.
466 bool isReserved(unsigned PhysReg) const {
467 return getReservedRegs().test(PhysReg);
470 /// isAllocatable - Returns true when PhysReg belongs to an allocatable
471 /// register class and it hasn't been reserved.
473 /// Allocatable registers may show up in the allocation order of some virtual
474 /// register, so a register allocator needs to track its liveness and
476 bool isAllocatable(unsigned PhysReg) const {
477 return getTargetRegisterInfo()->isInAllocatableClass(PhysReg) &&
478 !isReserved(PhysReg);
481 //===--------------------------------------------------------------------===//
483 //===--------------------------------------------------------------------===//
485 /// addLiveIn - Add the specified register as a live-in. Note that it
486 /// is an error to add the same register to the same set more than once.
487 void addLiveIn(unsigned Reg, unsigned vreg = 0) {
488 LiveIns.push_back(std::make_pair(Reg, vreg));
491 // Iteration support for the live-ins set. It's kept in sorted order
492 // by register number.
493 typedef std::vector<std::pair<unsigned,unsigned> >::const_iterator
495 livein_iterator livein_begin() const { return LiveIns.begin(); }
496 livein_iterator livein_end() const { return LiveIns.end(); }
497 bool livein_empty() const { return LiveIns.empty(); }
499 bool isLiveIn(unsigned Reg) const;
501 /// getLiveInPhysReg - If VReg is a live-in virtual register, return the
502 /// corresponding live-in physical register.
503 unsigned getLiveInPhysReg(unsigned VReg) const;
505 /// getLiveInVirtReg - If PReg is a live-in physical register, return the
506 /// corresponding live-in physical register.
507 unsigned getLiveInVirtReg(unsigned PReg) const;
509 /// EmitLiveInCopies - Emit copies to initialize livein virtual registers
510 /// into the given entry block.
511 void EmitLiveInCopies(MachineBasicBlock *EntryMBB,
512 const TargetRegisterInfo &TRI,
513 const TargetInstrInfo &TII);
515 /// defusechain_iterator - This class provides iterator support for machine
516 /// operands in the function that use or define a specific register. If
517 /// ReturnUses is true it returns uses of registers, if ReturnDefs is true it
518 /// returns defs. If neither are true then you are silly and it always
519 /// returns end(). If SkipDebug is true it skips uses marked Debug
520 /// when incrementing.
521 template<bool ReturnUses, bool ReturnDefs, bool SkipDebug>
522 class defusechain_iterator
523 : public std::iterator<std::forward_iterator_tag, MachineInstr, ptrdiff_t> {
525 explicit defusechain_iterator(MachineOperand *op) : Op(op) {
526 // If the first node isn't one we're interested in, advance to one that
527 // we are interested in.
529 if ((!ReturnUses && op->isUse()) ||
530 (!ReturnDefs && op->isDef()) ||
531 (SkipDebug && op->isDebug()))
535 friend class MachineRegisterInfo;
537 typedef std::iterator<std::forward_iterator_tag,
538 MachineInstr, ptrdiff_t>::reference reference;
539 typedef std::iterator<std::forward_iterator_tag,
540 MachineInstr, ptrdiff_t>::pointer pointer;
542 defusechain_iterator(const defusechain_iterator &I) : Op(I.Op) {}
543 defusechain_iterator() : Op(0) {}
545 bool operator==(const defusechain_iterator &x) const {
548 bool operator!=(const defusechain_iterator &x) const {
549 return !operator==(x);
552 /// atEnd - return true if this iterator is equal to reg_end() on the value.
553 bool atEnd() const { return Op == 0; }
555 // Iterator traversal: forward iteration only
556 defusechain_iterator &operator++() { // Preincrement
557 assert(Op && "Cannot increment end iterator!");
558 Op = getNextOperandForReg(Op);
560 // All defs come before the uses, so stop def_iterator early.
566 assert(!Op->isDebug() && "Can't have debug defs");
569 // If this is an operand we don't care about, skip it.
570 while (Op && ((!ReturnDefs && Op->isDef()) ||
571 (SkipDebug && Op->isDebug())))
572 Op = getNextOperandForReg(Op);
577 defusechain_iterator operator++(int) { // Postincrement
578 defusechain_iterator tmp = *this; ++*this; return tmp;
581 /// skipInstruction - move forward until reaching a different instruction.
582 /// Return the skipped instruction that is no longer pointed to, or NULL if
583 /// already pointing to end().
584 MachineInstr *skipInstruction() {
586 MachineInstr *MI = Op->getParent();
588 while (Op && Op->getParent() == MI);
592 MachineInstr *skipBundle() {
594 MachineInstr *MI = getBundleStart(Op->getParent());
596 while (Op && getBundleStart(Op->getParent()) == MI);
600 MachineOperand &getOperand() const {
601 assert(Op && "Cannot dereference end iterator!");
605 /// getOperandNo - Return the operand # of this MachineOperand in its
607 unsigned getOperandNo() const {
608 assert(Op && "Cannot dereference end iterator!");
609 return Op - &Op->getParent()->getOperand(0);
612 // Retrieve a reference to the current operand.
613 MachineInstr &operator*() const {
614 assert(Op && "Cannot dereference end iterator!");
615 return *Op->getParent();
618 MachineInstr *operator->() const {
619 assert(Op && "Cannot dereference end iterator!");
620 return Op->getParent();
626 } // End llvm namespace