Remove liveout lists from MachineRegisterInfo.
[oota-llvm.git] / lib / CodeGen / MachineRegisterInfo.cpp
1 //===-- lib/Codegen/MachineRegisterInfo.cpp -------------------------------===//
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 // Implementation of the MachineRegisterInfo class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/CodeGen/MachineRegisterInfo.h"
15 #include "llvm/CodeGen/MachineInstrBuilder.h"
16 #include "llvm/Target/TargetInstrInfo.h"
17 #include "llvm/Target/TargetMachine.h"
18 using namespace llvm;
19
20 MachineRegisterInfo::MachineRegisterInfo(const TargetRegisterInfo &TRI)
21   : TRI(&TRI), IsSSA(true), TracksLiveness(true) {
22   VRegInfo.reserve(256);
23   RegAllocHints.reserve(256);
24   UsedRegUnits.resize(TRI.getNumRegUnits());
25   UsedPhysRegMask.resize(TRI.getNumRegs());
26
27   // Create the physreg use/def lists.
28   PhysRegUseDefLists = new MachineOperand*[TRI.getNumRegs()];
29   memset(PhysRegUseDefLists, 0, sizeof(MachineOperand*)*TRI.getNumRegs());
30 }
31
32 MachineRegisterInfo::~MachineRegisterInfo() {
33   delete [] PhysRegUseDefLists;
34 }
35
36 /// setRegClass - Set the register class of the specified virtual register.
37 ///
38 void
39 MachineRegisterInfo::setRegClass(unsigned Reg, const TargetRegisterClass *RC) {
40   VRegInfo[Reg].first = RC;
41 }
42
43 const TargetRegisterClass *
44 MachineRegisterInfo::constrainRegClass(unsigned Reg,
45                                        const TargetRegisterClass *RC,
46                                        unsigned MinNumRegs) {
47   const TargetRegisterClass *OldRC = getRegClass(Reg);
48   if (OldRC == RC)
49     return RC;
50   const TargetRegisterClass *NewRC = TRI->getCommonSubClass(OldRC, RC);
51   if (!NewRC || NewRC == OldRC)
52     return NewRC;
53   if (NewRC->getNumRegs() < MinNumRegs)
54     return 0;
55   setRegClass(Reg, NewRC);
56   return NewRC;
57 }
58
59 bool
60 MachineRegisterInfo::recomputeRegClass(unsigned Reg, const TargetMachine &TM) {
61   const TargetInstrInfo *TII = TM.getInstrInfo();
62   const TargetRegisterClass *OldRC = getRegClass(Reg);
63   const TargetRegisterClass *NewRC = TRI->getLargestLegalSuperClass(OldRC);
64
65   // Stop early if there is no room to grow.
66   if (NewRC == OldRC)
67     return false;
68
69   // Accumulate constraints from all uses.
70   for (reg_nodbg_iterator I = reg_nodbg_begin(Reg), E = reg_nodbg_end(); I != E;
71        ++I) {
72     const TargetRegisterClass *OpRC =
73       I->getRegClassConstraint(I.getOperandNo(), TII, TRI);
74     if (unsigned SubIdx = I.getOperand().getSubReg()) {
75       if (OpRC)
76         NewRC = TRI->getMatchingSuperRegClass(NewRC, OpRC, SubIdx);
77       else
78         NewRC = TRI->getSubClassWithSubReg(NewRC, SubIdx);
79     } else if (OpRC)
80       NewRC = TRI->getCommonSubClass(NewRC, OpRC);
81     if (!NewRC || NewRC == OldRC)
82       return false;
83   }
84   setRegClass(Reg, NewRC);
85   return true;
86 }
87
88 /// createVirtualRegister - Create and return a new virtual register in the
89 /// function with the specified register class.
90 ///
91 unsigned
92 MachineRegisterInfo::createVirtualRegister(const TargetRegisterClass *RegClass){
93   assert(RegClass && "Cannot create register without RegClass!");
94   assert(RegClass->isAllocatable() &&
95          "Virtual register RegClass must be allocatable.");
96
97   // New virtual register number.
98   unsigned Reg = TargetRegisterInfo::index2VirtReg(getNumVirtRegs());
99   VRegInfo.grow(Reg);
100   VRegInfo[Reg].first = RegClass;
101   RegAllocHints.grow(Reg);
102   return Reg;
103 }
104
105 /// clearVirtRegs - Remove all virtual registers (after physreg assignment).
106 void MachineRegisterInfo::clearVirtRegs() {
107 #ifndef NDEBUG
108   for (unsigned i = 0, e = getNumVirtRegs(); i != e; ++i)
109     assert(VRegInfo[TargetRegisterInfo::index2VirtReg(i)].second == 0 &&
110            "Vreg use list non-empty still?");
111 #endif
112   VRegInfo.clear();
113 }
114
115 /// Add MO to the linked list of operands for its register.
116 void MachineRegisterInfo::addRegOperandToUseList(MachineOperand *MO) {
117   assert(!MO->isOnRegUseList() && "Already on list");
118   MachineOperand *&HeadRef = getRegUseDefListHead(MO->getReg());
119   MachineOperand *const Head = HeadRef;
120
121   // Head points to the first list element.
122   // Next is NULL on the last list element.
123   // Prev pointers are circular, so Head->Prev == Last.
124
125   // Head is NULL for an empty list.
126   if (!Head) {
127     MO->Contents.Reg.Prev = MO;
128     MO->Contents.Reg.Next = 0;
129     HeadRef = MO;
130     return;
131   }
132   assert(MO->getReg() == Head->getReg() && "Different regs on the same list!");
133
134   // Insert MO between Last and Head in the circular Prev chain.
135   MachineOperand *Last = Head->Contents.Reg.Prev;
136   assert(Last && "Inconsistent use list");
137   assert(MO->getReg() == Last->getReg() && "Different regs on the same list!");
138   Head->Contents.Reg.Prev = MO;
139   MO->Contents.Reg.Prev = Last;
140
141   // Def operands always precede uses. This allows def_iterator to stop early.
142   // Insert def operands at the front, and use operands at the back.
143   if (MO->isDef()) {
144     // Insert def at the front.
145     MO->Contents.Reg.Next = Head;
146     HeadRef = MO;
147   } else {
148     // Insert use at the end.
149     MO->Contents.Reg.Next = 0;
150     Last->Contents.Reg.Next = MO;
151   }
152 }
153
154 /// Remove MO from its use-def list.
155 void MachineRegisterInfo::removeRegOperandFromUseList(MachineOperand *MO) {
156   assert(MO->isOnRegUseList() && "Operand not on use list");
157   MachineOperand *&HeadRef = getRegUseDefListHead(MO->getReg());
158   MachineOperand *const Head = HeadRef;
159   assert(Head && "List already empty");
160
161   // Unlink this from the doubly linked list of operands.
162   MachineOperand *Next = MO->Contents.Reg.Next;
163   MachineOperand *Prev = MO->Contents.Reg.Prev;
164
165   // Prev links are circular, next link is NULL instead of looping back to Head.
166   if (MO == Head)
167     HeadRef = Next;
168   else
169     Prev->Contents.Reg.Next = Next;
170
171   (Next ? Next : Head)->Contents.Reg.Prev = Prev;
172
173   MO->Contents.Reg.Prev = 0;
174   MO->Contents.Reg.Next = 0;
175 }
176
177 /// Move NumOps operands from Src to Dst, updating use-def lists as needed.
178 ///
179 /// The Dst range is assumed to be uninitialized memory. (Or it may contain
180 /// operands that won't be destroyed, which is OK because the MO destructor is
181 /// trivial anyway).
182 ///
183 /// The Src and Dst ranges may overlap.
184 void MachineRegisterInfo::moveOperands(MachineOperand *Dst,
185                                        MachineOperand *Src,
186                                        unsigned NumOps) {
187   assert(Src != Dst && NumOps && "Noop moveOperands");
188
189   // Copy backwards if Dst is within the Src range.
190   int Stride = 1;
191   if (Dst >= Src && Dst < Src + NumOps) {
192     Stride = -1;
193     Dst += NumOps - 1;
194     Src += NumOps - 1;
195   }
196
197   // Copy one operand at a time.
198   do {
199     new (Dst) MachineOperand(*Src);
200
201     // Dst takes Src's place in the use-def chain.
202     if (Src->isReg()) {
203       MachineOperand *&Head = getRegUseDefListHead(Src->getReg());
204       MachineOperand *Prev = Src->Contents.Reg.Prev;
205       MachineOperand *Next = Src->Contents.Reg.Next;
206       assert(Head && "List empty, but operand is chained");
207       assert(Prev && "Operand was not on use-def list");
208
209       // Prev links are circular, next link is NULL instead of looping back to
210       // Head.
211       if (Src == Head)
212         Head = Dst;
213       else
214         Prev->Contents.Reg.Next = Dst;
215
216       // Update Prev pointer. This also works when Src was pointing to itself
217       // in a 1-element list. In that case Head == Dst.
218       (Next ? Next : Head)->Contents.Reg.Prev = Dst;
219     }
220
221     Dst += Stride;
222     Src += Stride;
223   } while (--NumOps);
224 }
225
226 /// replaceRegWith - Replace all instances of FromReg with ToReg in the
227 /// machine function.  This is like llvm-level X->replaceAllUsesWith(Y),
228 /// except that it also changes any definitions of the register as well.
229 void MachineRegisterInfo::replaceRegWith(unsigned FromReg, unsigned ToReg) {
230   assert(FromReg != ToReg && "Cannot replace a reg with itself");
231
232   // TODO: This could be more efficient by bulk changing the operands.
233   for (reg_iterator I = reg_begin(FromReg), E = reg_end(); I != E; ) {
234     MachineOperand &O = I.getOperand();
235     ++I;
236     O.setReg(ToReg);
237   }
238 }
239
240
241 /// getVRegDef - Return the machine instr that defines the specified virtual
242 /// register or null if none is found.  This assumes that the code is in SSA
243 /// form, so there should only be one definition.
244 MachineInstr *MachineRegisterInfo::getVRegDef(unsigned Reg) const {
245   // Since we are in SSA form, we can use the first definition.
246   def_iterator I = def_begin(Reg);
247   assert((I.atEnd() || llvm::next(I) == def_end()) &&
248          "getVRegDef assumes a single definition or no definition");
249   return !I.atEnd() ? &*I : 0;
250 }
251
252 /// getUniqueVRegDef - Return the unique machine instr that defines the
253 /// specified virtual register or null if none is found.  If there are
254 /// multiple definitions or no definition, return null.
255 MachineInstr *MachineRegisterInfo::getUniqueVRegDef(unsigned Reg) const {
256   if (def_empty(Reg)) return 0;
257   def_iterator I = def_begin(Reg);
258   if (llvm::next(I) != def_end())
259     return 0;
260   return &*I;
261 }
262
263 bool MachineRegisterInfo::hasOneNonDBGUse(unsigned RegNo) const {
264   use_nodbg_iterator UI = use_nodbg_begin(RegNo);
265   if (UI == use_nodbg_end())
266     return false;
267   return ++UI == use_nodbg_end();
268 }
269
270 /// clearKillFlags - Iterate over all the uses of the given register and
271 /// clear the kill flag from the MachineOperand. This function is used by
272 /// optimization passes which extend register lifetimes and need only
273 /// preserve conservative kill flag information.
274 void MachineRegisterInfo::clearKillFlags(unsigned Reg) const {
275   for (use_iterator UI = use_begin(Reg), UE = use_end(); UI != UE; ++UI)
276     UI.getOperand().setIsKill(false);
277 }
278
279 bool MachineRegisterInfo::isLiveIn(unsigned Reg) const {
280   for (livein_iterator I = livein_begin(), E = livein_end(); I != E; ++I)
281     if (I->first == Reg || I->second == Reg)
282       return true;
283   return false;
284 }
285
286 /// getLiveInPhysReg - If VReg is a live-in virtual register, return the
287 /// corresponding live-in physical register.
288 unsigned MachineRegisterInfo::getLiveInPhysReg(unsigned VReg) const {
289   for (livein_iterator I = livein_begin(), E = livein_end(); I != E; ++I)
290     if (I->second == VReg)
291       return I->first;
292   return 0;
293 }
294
295 /// getLiveInVirtReg - If PReg is a live-in physical register, return the
296 /// corresponding live-in physical register.
297 unsigned MachineRegisterInfo::getLiveInVirtReg(unsigned PReg) const {
298   for (livein_iterator I = livein_begin(), E = livein_end(); I != E; ++I)
299     if (I->first == PReg)
300       return I->second;
301   return 0;
302 }
303
304 /// EmitLiveInCopies - Emit copies to initialize livein virtual registers
305 /// into the given entry block.
306 void
307 MachineRegisterInfo::EmitLiveInCopies(MachineBasicBlock *EntryMBB,
308                                       const TargetRegisterInfo &TRI,
309                                       const TargetInstrInfo &TII) {
310   // Emit the copies into the top of the block.
311   for (unsigned i = 0, e = LiveIns.size(); i != e; ++i)
312     if (LiveIns[i].second) {
313       if (use_empty(LiveIns[i].second)) {
314         // The livein has no uses. Drop it.
315         //
316         // It would be preferable to have isel avoid creating live-in
317         // records for unused arguments in the first place, but it's
318         // complicated by the debug info code for arguments.
319         LiveIns.erase(LiveIns.begin() + i);
320         --i; --e;
321       } else {
322         // Emit a copy.
323         BuildMI(*EntryMBB, EntryMBB->begin(), DebugLoc(),
324                 TII.get(TargetOpcode::COPY), LiveIns[i].second)
325           .addReg(LiveIns[i].first);
326
327         // Add the register to the entry block live-in set.
328         EntryMBB->addLiveIn(LiveIns[i].first);
329       }
330     } else {
331       // Add the register to the entry block live-in set.
332       EntryMBB->addLiveIn(LiveIns[i].first);
333     }
334 }
335
336 #ifndef NDEBUG
337 void MachineRegisterInfo::dumpUses(unsigned Reg) const {
338   for (use_iterator I = use_begin(Reg), E = use_end(); I != E; ++I)
339     I.getOperand().getParent()->dump();
340 }
341 #endif
342
343 void MachineRegisterInfo::freezeReservedRegs(const MachineFunction &MF) {
344   ReservedRegs = TRI->getReservedRegs(MF);
345   assert(ReservedRegs.size() == TRI->getNumRegs() &&
346          "Invalid ReservedRegs vector from target");
347 }
348
349 bool MachineRegisterInfo::isConstantPhysReg(unsigned PhysReg,
350                                             const MachineFunction &MF) const {
351   assert(TargetRegisterInfo::isPhysicalRegister(PhysReg));
352
353   // Check if any overlapping register is modified, or allocatable so it may be
354   // used later.
355   for (MCRegAliasIterator AI(PhysReg, TRI, true); AI.isValid(); ++AI)
356     if (!def_empty(*AI) || isAllocatable(*AI))
357       return false;
358   return true;
359 }