Sink DwarfUnit::LabelBegin down into DwarfCompileUnit since that's the only place...
[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/Support/raw_os_ostream.h"
17 #include "llvm/Target/TargetInstrInfo.h"
18 #include "llvm/Target/TargetMachine.h"
19 #include "llvm/Target/TargetSubtargetInfo.h"
20
21 using namespace llvm;
22
23 // Pin the vtable to this file.
24 void MachineRegisterInfo::Delegate::anchor() {}
25
26 MachineRegisterInfo::MachineRegisterInfo(const MachineFunction *MF)
27   : MF(MF), TheDelegate(nullptr), IsSSA(true), TracksLiveness(true) {
28   VRegInfo.reserve(256);
29   RegAllocHints.reserve(256);
30   UsedRegUnits.resize(getTargetRegisterInfo()->getNumRegUnits());
31   UsedPhysRegMask.resize(getTargetRegisterInfo()->getNumRegs());
32
33   // Create the physreg use/def lists.
34   PhysRegUseDefLists.resize(getTargetRegisterInfo()->getNumRegs(), nullptr);
35 }
36
37 /// setRegClass - Set the register class of the specified virtual register.
38 ///
39 void
40 MachineRegisterInfo::setRegClass(unsigned Reg, const TargetRegisterClass *RC) {
41   assert(RC && RC->isAllocatable() && "Invalid RC for virtual register");
42   VRegInfo[Reg].first = RC;
43 }
44
45 const TargetRegisterClass *
46 MachineRegisterInfo::constrainRegClass(unsigned Reg,
47                                        const TargetRegisterClass *RC,
48                                        unsigned MinNumRegs) {
49   const TargetRegisterClass *OldRC = getRegClass(Reg);
50   if (OldRC == RC)
51     return RC;
52   const TargetRegisterClass *NewRC =
53     getTargetRegisterInfo()->getCommonSubClass(OldRC, RC);
54   if (!NewRC || NewRC == OldRC)
55     return NewRC;
56   if (NewRC->getNumRegs() < MinNumRegs)
57     return nullptr;
58   setRegClass(Reg, NewRC);
59   return NewRC;
60 }
61
62 bool
63 MachineRegisterInfo::recomputeRegClass(unsigned Reg, const TargetMachine &TM) {
64   const TargetInstrInfo *TII = TM.getSubtargetImpl()->getInstrInfo();
65   const TargetRegisterClass *OldRC = getRegClass(Reg);
66   const TargetRegisterClass *NewRC =
67     getTargetRegisterInfo()->getLargestLegalSuperClass(OldRC);
68
69   // Stop early if there is no room to grow.
70   if (NewRC == OldRC)
71     return false;
72
73   // Accumulate constraints from all uses.
74   for (MachineOperand &MO : reg_nodbg_operands(Reg)) {
75     // Apply the effect of the given operand to NewRC.
76     MachineInstr *MI = MO.getParent();
77     unsigned OpNo = &MO - &MI->getOperand(0);
78     NewRC = MI->getRegClassConstraintEffect(OpNo, NewRC, TII,
79                                             getTargetRegisterInfo());
80     if (!NewRC || NewRC == OldRC)
81       return false;
82   }
83   setRegClass(Reg, NewRC);
84   return true;
85 }
86
87 /// createVirtualRegister - Create and return a new virtual register in the
88 /// function with the specified register class.
89 ///
90 unsigned
91 MachineRegisterInfo::createVirtualRegister(const TargetRegisterClass *RegClass){
92   assert(RegClass && "Cannot create register without RegClass!");
93   assert(RegClass->isAllocatable() &&
94          "Virtual register RegClass must be allocatable.");
95
96   // New virtual register number.
97   unsigned Reg = TargetRegisterInfo::index2VirtReg(getNumVirtRegs());
98   VRegInfo.grow(Reg);
99   VRegInfo[Reg].first = RegClass;
100   RegAllocHints.grow(Reg);
101   if (TheDelegate)
102     TheDelegate->MRI_NoteNewVirtualRegister(Reg);
103   return Reg;
104 }
105
106 /// clearVirtRegs - Remove all virtual registers (after physreg assignment).
107 void MachineRegisterInfo::clearVirtRegs() {
108 #ifndef NDEBUG
109   for (unsigned i = 0, e = getNumVirtRegs(); i != e; ++i) {
110     unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
111     if (!VRegInfo[Reg].second)
112       continue;
113     verifyUseList(Reg);
114     llvm_unreachable("Remaining virtual register operands");
115   }
116 #endif
117   VRegInfo.clear();
118 }
119
120 void MachineRegisterInfo::verifyUseList(unsigned Reg) const {
121 #ifndef NDEBUG
122   bool Valid = true;
123   for (MachineOperand &M : reg_operands(Reg)) {
124     MachineOperand *MO = &M;
125     MachineInstr *MI = MO->getParent();
126     if (!MI) {
127       errs() << PrintReg(Reg, getTargetRegisterInfo())
128              << " use list MachineOperand " << MO
129              << " has no parent instruction.\n";
130       Valid = false;
131     }
132     MachineOperand *MO0 = &MI->getOperand(0);
133     unsigned NumOps = MI->getNumOperands();
134     if (!(MO >= MO0 && MO < MO0+NumOps)) {
135       errs() << PrintReg(Reg, getTargetRegisterInfo())
136              << " use list MachineOperand " << MO
137              << " doesn't belong to parent MI: " << *MI;
138       Valid = false;
139     }
140     if (!MO->isReg()) {
141       errs() << PrintReg(Reg, getTargetRegisterInfo())
142              << " MachineOperand " << MO << ": " << *MO
143              << " is not a register\n";
144       Valid = false;
145     }
146     if (MO->getReg() != Reg) {
147       errs() << PrintReg(Reg, getTargetRegisterInfo())
148              << " use-list MachineOperand " << MO << ": "
149              << *MO << " is the wrong register\n";
150       Valid = false;
151     }
152   }
153   assert(Valid && "Invalid use list");
154 #endif
155 }
156
157 void MachineRegisterInfo::verifyUseLists() const {
158 #ifndef NDEBUG
159   for (unsigned i = 0, e = getNumVirtRegs(); i != e; ++i)
160     verifyUseList(TargetRegisterInfo::index2VirtReg(i));
161   for (unsigned i = 1, e = getTargetRegisterInfo()->getNumRegs(); i != e; ++i)
162     verifyUseList(i);
163 #endif
164 }
165
166 /// Add MO to the linked list of operands for its register.
167 void MachineRegisterInfo::addRegOperandToUseList(MachineOperand *MO) {
168   assert(!MO->isOnRegUseList() && "Already on list");
169   MachineOperand *&HeadRef = getRegUseDefListHead(MO->getReg());
170   MachineOperand *const Head = HeadRef;
171
172   // Head points to the first list element.
173   // Next is NULL on the last list element.
174   // Prev pointers are circular, so Head->Prev == Last.
175
176   // Head is NULL for an empty list.
177   if (!Head) {
178     MO->Contents.Reg.Prev = MO;
179     MO->Contents.Reg.Next = nullptr;
180     HeadRef = MO;
181     return;
182   }
183   assert(MO->getReg() == Head->getReg() && "Different regs on the same list!");
184
185   // Insert MO between Last and Head in the circular Prev chain.
186   MachineOperand *Last = Head->Contents.Reg.Prev;
187   assert(Last && "Inconsistent use list");
188   assert(MO->getReg() == Last->getReg() && "Different regs on the same list!");
189   Head->Contents.Reg.Prev = MO;
190   MO->Contents.Reg.Prev = Last;
191
192   // Def operands always precede uses. This allows def_iterator to stop early.
193   // Insert def operands at the front, and use operands at the back.
194   if (MO->isDef()) {
195     // Insert def at the front.
196     MO->Contents.Reg.Next = Head;
197     HeadRef = MO;
198   } else {
199     // Insert use at the end.
200     MO->Contents.Reg.Next = nullptr;
201     Last->Contents.Reg.Next = MO;
202   }
203 }
204
205 /// Remove MO from its use-def list.
206 void MachineRegisterInfo::removeRegOperandFromUseList(MachineOperand *MO) {
207   assert(MO->isOnRegUseList() && "Operand not on use list");
208   MachineOperand *&HeadRef = getRegUseDefListHead(MO->getReg());
209   MachineOperand *const Head = HeadRef;
210   assert(Head && "List already empty");
211
212   // Unlink this from the doubly linked list of operands.
213   MachineOperand *Next = MO->Contents.Reg.Next;
214   MachineOperand *Prev = MO->Contents.Reg.Prev;
215
216   // Prev links are circular, next link is NULL instead of looping back to Head.
217   if (MO == Head)
218     HeadRef = Next;
219   else
220     Prev->Contents.Reg.Next = Next;
221
222   (Next ? Next : Head)->Contents.Reg.Prev = Prev;
223
224   MO->Contents.Reg.Prev = nullptr;
225   MO->Contents.Reg.Next = nullptr;
226 }
227
228 /// Move NumOps operands from Src to Dst, updating use-def lists as needed.
229 ///
230 /// The Dst range is assumed to be uninitialized memory. (Or it may contain
231 /// operands that won't be destroyed, which is OK because the MO destructor is
232 /// trivial anyway).
233 ///
234 /// The Src and Dst ranges may overlap.
235 void MachineRegisterInfo::moveOperands(MachineOperand *Dst,
236                                        MachineOperand *Src,
237                                        unsigned NumOps) {
238   assert(Src != Dst && NumOps && "Noop moveOperands");
239
240   // Copy backwards if Dst is within the Src range.
241   int Stride = 1;
242   if (Dst >= Src && Dst < Src + NumOps) {
243     Stride = -1;
244     Dst += NumOps - 1;
245     Src += NumOps - 1;
246   }
247
248   // Copy one operand at a time.
249   do {
250     new (Dst) MachineOperand(*Src);
251
252     // Dst takes Src's place in the use-def chain.
253     if (Src->isReg()) {
254       MachineOperand *&Head = getRegUseDefListHead(Src->getReg());
255       MachineOperand *Prev = Src->Contents.Reg.Prev;
256       MachineOperand *Next = Src->Contents.Reg.Next;
257       assert(Head && "List empty, but operand is chained");
258       assert(Prev && "Operand was not on use-def list");
259
260       // Prev links are circular, next link is NULL instead of looping back to
261       // Head.
262       if (Src == Head)
263         Head = Dst;
264       else
265         Prev->Contents.Reg.Next = Dst;
266
267       // Update Prev pointer. This also works when Src was pointing to itself
268       // in a 1-element list. In that case Head == Dst.
269       (Next ? Next : Head)->Contents.Reg.Prev = Dst;
270     }
271
272     Dst += Stride;
273     Src += Stride;
274   } while (--NumOps);
275 }
276
277 /// replaceRegWith - Replace all instances of FromReg with ToReg in the
278 /// machine function.  This is like llvm-level X->replaceAllUsesWith(Y),
279 /// except that it also changes any definitions of the register as well.
280 /// If ToReg is a physical register we apply the sub register to obtain the
281 /// final/proper physical register.
282 void MachineRegisterInfo::replaceRegWith(unsigned FromReg, unsigned ToReg) {
283   assert(FromReg != ToReg && "Cannot replace a reg with itself");
284
285   const TargetRegisterInfo *TRI = getTargetRegisterInfo();
286   
287   // TODO: This could be more efficient by bulk changing the operands.
288   for (reg_iterator I = reg_begin(FromReg), E = reg_end(); I != E; ) {
289     MachineOperand &O = *I;
290     ++I;
291     if (TargetRegisterInfo::isPhysicalRegister(ToReg)) {
292       O.substPhysReg(ToReg, *TRI);
293     } else {
294       O.setReg(ToReg);
295     }
296   }
297 }
298
299 /// getVRegDef - Return the machine instr that defines the specified virtual
300 /// register or null if none is found.  This assumes that the code is in SSA
301 /// form, so there should only be one definition.
302 MachineInstr *MachineRegisterInfo::getVRegDef(unsigned Reg) const {
303   // Since we are in SSA form, we can use the first definition.
304   def_instr_iterator I = def_instr_begin(Reg);
305   assert((I.atEnd() || std::next(I) == def_instr_end()) &&
306          "getVRegDef assumes a single definition or no definition");
307   return !I.atEnd() ? &*I : nullptr;
308 }
309
310 /// getUniqueVRegDef - Return the unique machine instr that defines the
311 /// specified virtual register or null if none is found.  If there are
312 /// multiple definitions or no definition, return null.
313 MachineInstr *MachineRegisterInfo::getUniqueVRegDef(unsigned Reg) const {
314   if (def_empty(Reg)) return nullptr;
315   def_instr_iterator I = def_instr_begin(Reg);
316   if (std::next(I) != def_instr_end())
317     return nullptr;
318   return &*I;
319 }
320
321 bool MachineRegisterInfo::hasOneNonDBGUse(unsigned RegNo) const {
322   use_nodbg_iterator UI = use_nodbg_begin(RegNo);
323   if (UI == use_nodbg_end())
324     return false;
325   return ++UI == use_nodbg_end();
326 }
327
328 /// clearKillFlags - Iterate over all the uses of the given register and
329 /// clear the kill flag from the MachineOperand. This function is used by
330 /// optimization passes which extend register lifetimes and need only
331 /// preserve conservative kill flag information.
332 void MachineRegisterInfo::clearKillFlags(unsigned Reg) const {
333   for (MachineOperand &MO : use_operands(Reg))
334     MO.setIsKill(false);
335 }
336
337 bool MachineRegisterInfo::isLiveIn(unsigned Reg) const {
338   for (livein_iterator I = livein_begin(), E = livein_end(); I != E; ++I)
339     if (I->first == Reg || I->second == Reg)
340       return true;
341   return false;
342 }
343
344 /// getLiveInPhysReg - If VReg is a live-in virtual register, return the
345 /// corresponding live-in physical register.
346 unsigned MachineRegisterInfo::getLiveInPhysReg(unsigned VReg) const {
347   for (livein_iterator I = livein_begin(), E = livein_end(); I != E; ++I)
348     if (I->second == VReg)
349       return I->first;
350   return 0;
351 }
352
353 /// getLiveInVirtReg - If PReg is a live-in physical register, return the
354 /// corresponding live-in physical register.
355 unsigned MachineRegisterInfo::getLiveInVirtReg(unsigned PReg) const {
356   for (livein_iterator I = livein_begin(), E = livein_end(); I != E; ++I)
357     if (I->first == PReg)
358       return I->second;
359   return 0;
360 }
361
362 /// EmitLiveInCopies - Emit copies to initialize livein virtual registers
363 /// into the given entry block.
364 void
365 MachineRegisterInfo::EmitLiveInCopies(MachineBasicBlock *EntryMBB,
366                                       const TargetRegisterInfo &TRI,
367                                       const TargetInstrInfo &TII) {
368   // Emit the copies into the top of the block.
369   for (unsigned i = 0, e = LiveIns.size(); i != e; ++i)
370     if (LiveIns[i].second) {
371       if (use_empty(LiveIns[i].second)) {
372         // The livein has no uses. Drop it.
373         //
374         // It would be preferable to have isel avoid creating live-in
375         // records for unused arguments in the first place, but it's
376         // complicated by the debug info code for arguments.
377         LiveIns.erase(LiveIns.begin() + i);
378         --i; --e;
379       } else {
380         // Emit a copy.
381         BuildMI(*EntryMBB, EntryMBB->begin(), DebugLoc(),
382                 TII.get(TargetOpcode::COPY), LiveIns[i].second)
383           .addReg(LiveIns[i].first);
384
385         // Add the register to the entry block live-in set.
386         EntryMBB->addLiveIn(LiveIns[i].first);
387       }
388     } else {
389       // Add the register to the entry block live-in set.
390       EntryMBB->addLiveIn(LiveIns[i].first);
391     }
392 }
393
394 #ifndef NDEBUG
395 void MachineRegisterInfo::dumpUses(unsigned Reg) const {
396   for (MachineInstr &I : use_instructions(Reg))
397     I.dump();
398 }
399 #endif
400
401 void MachineRegisterInfo::freezeReservedRegs(const MachineFunction &MF) {
402   ReservedRegs = getTargetRegisterInfo()->getReservedRegs(MF);
403   assert(ReservedRegs.size() == getTargetRegisterInfo()->getNumRegs() &&
404          "Invalid ReservedRegs vector from target");
405 }
406
407 bool MachineRegisterInfo::isConstantPhysReg(unsigned PhysReg,
408                                             const MachineFunction &MF) const {
409   assert(TargetRegisterInfo::isPhysicalRegister(PhysReg));
410
411   // Check if any overlapping register is modified, or allocatable so it may be
412   // used later.
413   for (MCRegAliasIterator AI(PhysReg, getTargetRegisterInfo(), true);
414        AI.isValid(); ++AI)
415     if (!def_empty(*AI) || isAllocatable(*AI))
416       return false;
417   return true;
418 }
419
420 /// markUsesInDebugValueAsUndef - Mark every DBG_VALUE referencing the
421 /// specified register as undefined which causes the DBG_VALUE to be
422 /// deleted during LiveDebugVariables analysis.
423 void MachineRegisterInfo::markUsesInDebugValueAsUndef(unsigned Reg) const {
424   // Mark any DBG_VALUE that uses Reg as undef (but don't delete it.)
425   MachineRegisterInfo::use_instr_iterator nextI;
426   for (use_instr_iterator I = use_instr_begin(Reg), E = use_instr_end();
427        I != E; I = nextI) {
428     nextI = std::next(I);  // I is invalidated by the setReg
429     MachineInstr *UseMI = &*I;
430     if (UseMI->isDebugValue())
431       UseMI->getOperand(0).setReg(0U);
432   }
433 }