In some rare cases, the register allocator can spill registers but end up not utilizi...
[oota-llvm.git] / lib / CodeGen / VirtRegMap.h
1 //===-- llvm/CodeGen/VirtRegMap.h - Virtual Register Map -*- 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 implements a virtual register map. This maps virtual registers to
11 // physical registers and virtual registers to stack slots. It is created and
12 // updated by a register allocator and then used by a machine code rewriter that
13 // adds spill code and rewrites virtual into physical register references.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #ifndef LLVM_CODEGEN_VIRTREGMAP_H
18 #define LLVM_CODEGEN_VIRTREGMAP_H
19
20 #include "llvm/CodeGen/MachineFunctionPass.h"
21 #include "llvm/Target/TargetRegisterInfo.h"
22 #include "llvm/ADT/BitVector.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/IndexedMap.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/Support/Streams.h"
28 #include <map>
29
30 namespace llvm {
31   class LiveIntervals;
32   class MachineInstr;
33   class MachineFunction;
34   class TargetInstrInfo;
35
36   class VirtRegMap : public MachineFunctionPass {
37   public:
38     enum {
39       NO_PHYS_REG = 0,
40       NO_STACK_SLOT = (1L << 30)-1,
41       MAX_STACK_SLOT = (1L << 18)-1
42     };
43
44     enum ModRef { isRef = 1, isMod = 2, isModRef = 3 };
45     typedef std::multimap<MachineInstr*,
46                           std::pair<unsigned, ModRef> > MI2VirtMapTy;
47
48   private:
49     const TargetInstrInfo *TII;
50
51     MachineFunction *MF;
52     /// Virt2PhysMap - This is a virtual to physical register
53     /// mapping. Each virtual register is required to have an entry in
54     /// it; even spilled virtual registers (the register mapped to a
55     /// spilled register is the temporary used to load it from the
56     /// stack).
57     IndexedMap<unsigned, VirtReg2IndexFunctor> Virt2PhysMap;
58
59     /// Virt2StackSlotMap - This is virtual register to stack slot
60     /// mapping. Each spilled virtual register has an entry in it
61     /// which corresponds to the stack slot this register is spilled
62     /// at.
63     IndexedMap<int, VirtReg2IndexFunctor> Virt2StackSlotMap;
64
65     /// Virt2ReMatIdMap - This is virtual register to rematerialization id
66     /// mapping. Each spilled virtual register that should be remat'd has an
67     /// entry in it which corresponds to the remat id.
68     IndexedMap<int, VirtReg2IndexFunctor> Virt2ReMatIdMap;
69
70     /// Virt2SplitMap - This is virtual register to splitted virtual register
71     /// mapping.
72     IndexedMap<unsigned, VirtReg2IndexFunctor> Virt2SplitMap;
73
74     /// Virt2SplitKillMap - This is splitted virtual register to its last use
75     /// (kill) index mapping.
76     IndexedMap<unsigned> Virt2SplitKillMap;
77
78     /// ReMatMap - This is virtual register to re-materialized instruction
79     /// mapping. Each virtual register whose definition is going to be
80     /// re-materialized has an entry in it.
81     IndexedMap<MachineInstr*, VirtReg2IndexFunctor> ReMatMap;
82
83     /// MI2VirtMap - This is MachineInstr to virtual register
84     /// mapping. In the case of memory spill code being folded into
85     /// instructions, we need to know which virtual register was
86     /// read/written by this instruction.
87     MI2VirtMapTy MI2VirtMap;
88
89     /// SpillPt2VirtMap - This records the virtual registers which should
90     /// be spilled right after the MachineInstr due to live interval
91     /// splitting.
92     std::map<MachineInstr*, std::vector<std::pair<unsigned,bool> > >
93     SpillPt2VirtMap;
94
95     /// RestorePt2VirtMap - This records the virtual registers which should
96     /// be restored right before the MachineInstr due to live interval
97     /// splitting.
98     std::map<MachineInstr*, std::vector<unsigned> > RestorePt2VirtMap;
99
100     /// EmergencySpillMap - This records the physical registers that should
101     /// be spilled / restored around the MachineInstr since the register
102     /// allocator has run out of registers.
103     std::map<MachineInstr*, std::vector<unsigned> > EmergencySpillMap;
104
105     /// EmergencySpillSlots - This records emergency spill slots used to
106     /// spill physical registers when the register allocator runs out of
107     /// registers. Ideally only one stack slot is used per function per
108     /// register class.
109     std::map<const TargetRegisterClass*, int> EmergencySpillSlots;
110
111     /// ReMatId - Instead of assigning a stack slot to a to be rematerialized
112     /// virtual register, an unique id is being assigned. This keeps track of
113     /// the highest id used so far. Note, this starts at (1<<18) to avoid
114     /// conflicts with stack slot numbers.
115     int ReMatId;
116
117     /// LowSpillSlot, HighSpillSlot - Lowest and highest spill slot indexes.
118     int LowSpillSlot, HighSpillSlot;
119
120     /// SpillSlotToUsesMap - Records uses for each register spill slot.
121     SmallVector<SmallPtrSet<MachineInstr*, 4>, 8> SpillSlotToUsesMap;
122
123     /// ImplicitDefed - One bit for each virtual register. If set it indicates
124     /// the register is implicitly defined.
125     BitVector ImplicitDefed;
126
127     /// UnusedRegs - A list of physical registers that have not been used.
128     BitVector UnusedRegs;
129
130     VirtRegMap(const VirtRegMap&);     // DO NOT IMPLEMENT
131     void operator=(const VirtRegMap&); // DO NOT IMPLEMENT
132
133   public:
134     static char ID;
135     VirtRegMap() : MachineFunctionPass(&ID), Virt2PhysMap(NO_PHYS_REG),
136                    Virt2StackSlotMap(NO_STACK_SLOT), 
137                    Virt2ReMatIdMap(NO_STACK_SLOT), Virt2SplitMap(0),
138                    Virt2SplitKillMap(0), ReMatMap(NULL),
139                    ReMatId(MAX_STACK_SLOT+1),
140                    LowSpillSlot(NO_STACK_SLOT), HighSpillSlot(NO_STACK_SLOT) { }
141     virtual bool runOnMachineFunction(MachineFunction &MF);
142
143     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
144       AU.setPreservesAll();
145       MachineFunctionPass::getAnalysisUsage(AU);
146     }
147
148     void grow();
149
150     /// @brief returns true if the specified virtual register is
151     /// mapped to a physical register
152     bool hasPhys(unsigned virtReg) const {
153       return getPhys(virtReg) != NO_PHYS_REG;
154     }
155
156     /// @brief returns the physical register mapped to the specified
157     /// virtual register
158     unsigned getPhys(unsigned virtReg) const {
159       assert(TargetRegisterInfo::isVirtualRegister(virtReg));
160       return Virt2PhysMap[virtReg];
161     }
162
163     /// @brief creates a mapping for the specified virtual register to
164     /// the specified physical register
165     void assignVirt2Phys(unsigned virtReg, unsigned physReg) {
166       assert(TargetRegisterInfo::isVirtualRegister(virtReg) &&
167              TargetRegisterInfo::isPhysicalRegister(physReg));
168       assert(Virt2PhysMap[virtReg] == NO_PHYS_REG &&
169              "attempt to assign physical register to already mapped "
170              "virtual register");
171       Virt2PhysMap[virtReg] = physReg;
172     }
173
174     /// @brief clears the specified virtual register's, physical
175     /// register mapping
176     void clearVirt(unsigned virtReg) {
177       assert(TargetRegisterInfo::isVirtualRegister(virtReg));
178       assert(Virt2PhysMap[virtReg] != NO_PHYS_REG &&
179              "attempt to clear a not assigned virtual register");
180       Virt2PhysMap[virtReg] = NO_PHYS_REG;
181     }
182
183     /// @brief clears all virtual to physical register mappings
184     void clearAllVirt() {
185       Virt2PhysMap.clear();
186       grow();
187     }
188
189     /// @brief records virtReg is a split live interval from SReg.
190     void setIsSplitFromReg(unsigned virtReg, unsigned SReg) {
191       Virt2SplitMap[virtReg] = SReg;
192     }
193
194     /// @brief returns the live interval virtReg is split from.
195     unsigned getPreSplitReg(unsigned virtReg) {
196       return Virt2SplitMap[virtReg];
197     }
198
199     /// @brief returns true if the specified virtual register is not
200     /// mapped to a stack slot or rematerialized.
201     bool isAssignedReg(unsigned virtReg) const {
202       if (getStackSlot(virtReg) == NO_STACK_SLOT &&
203           getReMatId(virtReg) == NO_STACK_SLOT)
204         return true;
205       // Split register can be assigned a physical register as well as a
206       // stack slot or remat id.
207       return (Virt2SplitMap[virtReg] && Virt2PhysMap[virtReg] != NO_PHYS_REG);
208     }
209
210     /// @brief returns the stack slot mapped to the specified virtual
211     /// register
212     int getStackSlot(unsigned virtReg) const {
213       assert(TargetRegisterInfo::isVirtualRegister(virtReg));
214       return Virt2StackSlotMap[virtReg];
215     }
216
217     /// @brief returns the rematerialization id mapped to the specified virtual
218     /// register
219     int getReMatId(unsigned virtReg) const {
220       assert(TargetRegisterInfo::isVirtualRegister(virtReg));
221       return Virt2ReMatIdMap[virtReg];
222     }
223
224     /// @brief create a mapping for the specifed virtual register to
225     /// the next available stack slot
226     int assignVirt2StackSlot(unsigned virtReg);
227     /// @brief create a mapping for the specified virtual register to
228     /// the specified stack slot
229     void assignVirt2StackSlot(unsigned virtReg, int frameIndex);
230
231     /// @brief assign an unique re-materialization id to the specified
232     /// virtual register.
233     int assignVirtReMatId(unsigned virtReg);
234     /// @brief assign an unique re-materialization id to the specified
235     /// virtual register.
236     void assignVirtReMatId(unsigned virtReg, int id);
237
238     /// @brief returns true if the specified virtual register is being
239     /// re-materialized.
240     bool isReMaterialized(unsigned virtReg) const {
241       return ReMatMap[virtReg] != NULL;
242     }
243
244     /// @brief returns the original machine instruction being re-issued
245     /// to re-materialize the specified virtual register.
246     MachineInstr *getReMaterializedMI(unsigned virtReg) const {
247       return ReMatMap[virtReg];
248     }
249
250     /// @brief records the specified virtual register will be
251     /// re-materialized and the original instruction which will be re-issed
252     /// for this purpose.  If parameter all is true, then all uses of the
253     /// registers are rematerialized and it's safe to delete the definition.
254     void setVirtIsReMaterialized(unsigned virtReg, MachineInstr *def) {
255       ReMatMap[virtReg] = def;
256     }
257
258     /// @brief record the last use (kill) of a split virtual register.
259     void addKillPoint(unsigned virtReg, unsigned index) {
260       Virt2SplitKillMap[virtReg] = index;
261     }
262
263     unsigned getKillPoint(unsigned virtReg) const {
264       return Virt2SplitKillMap[virtReg];
265     }
266
267     /// @brief remove the last use (kill) of a split virtual register.
268     void removeKillPoint(unsigned virtReg) {
269       Virt2SplitKillMap[virtReg] = 0;
270     }
271
272     /// @brief returns true if the specified MachineInstr is a spill point.
273     bool isSpillPt(MachineInstr *Pt) const {
274       return SpillPt2VirtMap.find(Pt) != SpillPt2VirtMap.end();
275     }
276
277     /// @brief returns the virtual registers that should be spilled due to
278     /// splitting right after the specified MachineInstr.
279     std::vector<std::pair<unsigned,bool> > &getSpillPtSpills(MachineInstr *Pt) {
280       return SpillPt2VirtMap[Pt];
281     }
282
283     /// @brief records the specified MachineInstr as a spill point for virtReg.
284     void addSpillPoint(unsigned virtReg, bool isKill, MachineInstr *Pt) {
285       std::map<MachineInstr*, std::vector<std::pair<unsigned,bool> > >::iterator
286         I = SpillPt2VirtMap.find(Pt);
287       if (I != SpillPt2VirtMap.end())
288         I->second.push_back(std::make_pair(virtReg, isKill));
289       else {
290         std::vector<std::pair<unsigned,bool> > Virts;
291         Virts.push_back(std::make_pair(virtReg, isKill));
292         SpillPt2VirtMap.insert(std::make_pair(Pt, Virts));
293       }
294     }
295
296     /// @brief - transfer spill point information from one instruction to
297     /// another.
298     void transferSpillPts(MachineInstr *Old, MachineInstr *New) {
299       std::map<MachineInstr*, std::vector<std::pair<unsigned,bool> > >::iterator
300         I = SpillPt2VirtMap.find(Old);
301       if (I == SpillPt2VirtMap.end())
302         return;
303       while (!I->second.empty()) {
304         unsigned virtReg = I->second.back().first;
305         bool isKill = I->second.back().second;
306         I->second.pop_back();
307         addSpillPoint(virtReg, isKill, New);
308       }
309       SpillPt2VirtMap.erase(I);
310     }
311
312     /// @brief returns true if the specified MachineInstr is a restore point.
313     bool isRestorePt(MachineInstr *Pt) const {
314       return RestorePt2VirtMap.find(Pt) != RestorePt2VirtMap.end();
315     }
316
317     /// @brief returns the virtual registers that should be restoreed due to
318     /// splitting right after the specified MachineInstr.
319     std::vector<unsigned> &getRestorePtRestores(MachineInstr *Pt) {
320       return RestorePt2VirtMap[Pt];
321     }
322
323     /// @brief records the specified MachineInstr as a restore point for virtReg.
324     void addRestorePoint(unsigned virtReg, MachineInstr *Pt) {
325       std::map<MachineInstr*, std::vector<unsigned> >::iterator I =
326         RestorePt2VirtMap.find(Pt);
327       if (I != RestorePt2VirtMap.end())
328         I->second.push_back(virtReg);
329       else {
330         std::vector<unsigned> Virts;
331         Virts.push_back(virtReg);
332         RestorePt2VirtMap.insert(std::make_pair(Pt, Virts));
333       }
334     }
335
336     /// @brief - transfer restore point information from one instruction to
337     /// another.
338     void transferRestorePts(MachineInstr *Old, MachineInstr *New) {
339       std::map<MachineInstr*, std::vector<unsigned> >::iterator I =
340         RestorePt2VirtMap.find(Old);
341       if (I == RestorePt2VirtMap.end())
342         return;
343       while (!I->second.empty()) {
344         unsigned virtReg = I->second.back();
345         I->second.pop_back();
346         addRestorePoint(virtReg, New);
347       }
348       RestorePt2VirtMap.erase(I);
349     }
350
351     /// @brief records that the specified physical register must be spilled
352     /// around the specified machine instr.
353     void addEmergencySpill(unsigned PhysReg, MachineInstr *MI) {
354       if (EmergencySpillMap.find(MI) != EmergencySpillMap.end())
355         EmergencySpillMap[MI].push_back(PhysReg);
356       else {
357         std::vector<unsigned> PhysRegs;
358         PhysRegs.push_back(PhysReg);
359         EmergencySpillMap.insert(std::make_pair(MI, PhysRegs));
360       }
361     }
362
363     /// @brief returns true if one or more physical registers must be spilled
364     /// around the specified instruction.
365     bool hasEmergencySpills(MachineInstr *MI) const {
366       return EmergencySpillMap.find(MI) != EmergencySpillMap.end();
367     }
368
369     /// @brief returns the physical registers to be spilled and restored around
370     /// the instruction.
371     std::vector<unsigned> &getEmergencySpills(MachineInstr *MI) {
372       return EmergencySpillMap[MI];
373     }
374
375     /// @brief - transfer emergency spill information from one instruction to
376     /// another.
377     void transferEmergencySpills(MachineInstr *Old, MachineInstr *New) {
378       std::map<MachineInstr*,std::vector<unsigned> >::iterator I =
379         EmergencySpillMap.find(Old);
380       if (I == EmergencySpillMap.end())
381         return;
382       while (!I->second.empty()) {
383         unsigned virtReg = I->second.back();
384         I->second.pop_back();
385         addEmergencySpill(virtReg, New);
386       }
387       EmergencySpillMap.erase(I);
388     }
389
390     /// @brief return or get a emergency spill slot for the register class.
391     int getEmergencySpillSlot(const TargetRegisterClass *RC);
392
393     /// @brief Return lowest spill slot index.
394     int getLowSpillSlot() const {
395       return LowSpillSlot;
396     }
397
398     /// @brief Return highest spill slot index.
399     int getHighSpillSlot() const {
400       return HighSpillSlot;
401     }
402
403     /// @brief Records a spill slot use.
404     void addSpillSlotUse(int FrameIndex, MachineInstr *MI);
405
406     /// @brief Returns true if spill slot has been used.
407     bool isSpillSlotUsed(int FrameIndex) const {
408       assert(FrameIndex >= 0 && "Spill slot index should not be negative!");
409       return !SpillSlotToUsesMap[FrameIndex-LowSpillSlot].empty();
410     }
411
412     /// @brief Mark the specified register as being implicitly defined.
413     void setIsImplicitlyDefined(unsigned VirtReg) {
414       ImplicitDefed.set(VirtReg-TargetRegisterInfo::FirstVirtualRegister);
415     }
416
417     /// @brief Returns true if the virtual register is implicitly defined.
418     bool isImplicitlyDefined(unsigned VirtReg) const {
419       return ImplicitDefed[VirtReg-TargetRegisterInfo::FirstVirtualRegister];
420     }
421
422     /// @brief Updates information about the specified virtual register's value
423     /// folded into newMI machine instruction.
424     void virtFolded(unsigned VirtReg, MachineInstr *OldMI, MachineInstr *NewMI,
425                     ModRef MRInfo);
426
427     /// @brief Updates information about the specified virtual register's value
428     /// folded into the specified machine instruction.
429     void virtFolded(unsigned VirtReg, MachineInstr *MI, ModRef MRInfo);
430
431     /// @brief returns the virtual registers' values folded in memory
432     /// operands of this instruction
433     std::pair<MI2VirtMapTy::const_iterator, MI2VirtMapTy::const_iterator>
434     getFoldedVirts(MachineInstr* MI) const {
435       return MI2VirtMap.equal_range(MI);
436     }
437     
438     /// RemoveMachineInstrFromMaps - MI is being erased, remove it from the
439     /// the folded instruction map and spill point map.
440     void RemoveMachineInstrFromMaps(MachineInstr *MI);
441
442     /// FindUnusedRegisters - Gather a list of allocatable registers that
443     /// have not been allocated to any virtual register.
444     bool FindUnusedRegisters(const TargetRegisterInfo *TRI,
445                              LiveIntervals* LIs);
446
447     /// HasUnusedRegisters - Return true if there are any allocatable registers
448     /// that have not been allocated to any virtual register.
449     bool HasUnusedRegisters() const {
450       return !UnusedRegs.none();
451     }
452
453     /// setRegisterUsed - Remember the physical register is now used.
454     void setRegisterUsed(unsigned Reg) {
455       UnusedRegs.reset(Reg);
456     }
457
458     /// isRegisterUnused - Return true if the physical register has not been
459     /// used.
460     bool isRegisterUnused(unsigned Reg) const {
461       return UnusedRegs[Reg];
462     }
463
464     /// getFirstUnusedRegister - Return the first physical register that has not
465     /// been used.
466     unsigned getFirstUnusedRegister(const TargetRegisterClass *RC) {
467       int Reg = UnusedRegs.find_first();
468       while (Reg != -1) {
469         if (RC->contains(Reg))
470           return (unsigned)Reg;
471         Reg = UnusedRegs.find_next(Reg);
472       }
473       return 0;
474     }
475
476     void print(std::ostream &OS, const Module* M = 0) const;
477     void print(std::ostream *OS) const { if (OS) print(*OS); }
478     void dump() const;
479   };
480
481   inline std::ostream *operator<<(std::ostream *OS, const VirtRegMap &VRM) {
482     VRM.print(OS);
483     return OS;
484   }
485   inline std::ostream &operator<<(std::ostream &OS, const VirtRegMap &VRM) {
486     VRM.print(OS);
487     return OS;
488   }
489 } // End llvm namespace
490
491 #endif