Remove val# defined by a remat'ed def that is now dead.
[oota-llvm.git] / lib / CodeGen / SimpleRegisterCoalescing.h
1 //===-- SimpleRegisterCoalescing.h - Register Coalescing --------*- 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 simple register copy coalescing phase.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_CODEGEN_SIMPLE_REGISTER_COALESCING_H
15 #define LLVM_CODEGEN_SIMPLE_REGISTER_COALESCING_H
16
17 #include "llvm/CodeGen/MachineFunctionPass.h"
18 #include "llvm/CodeGen/LiveInterval.h"
19 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
20 #include "llvm/CodeGen/RegisterCoalescer.h"
21 #include "llvm/ADT/BitVector.h"
22 #include "llvm/ADT/IndexedMap.h"
23 #include <queue>
24
25 namespace llvm {
26   class SimpleRegisterCoalescing;
27   class LiveVariables;
28   class TargetRegisterInfo;
29   class TargetInstrInfo;
30   class VirtRegMap;
31   class MachineLoopInfo;
32
33   /// CopyRec - Representation for copy instructions in coalescer queue.
34   ///
35   struct CopyRec {
36     MachineInstr *MI;
37     unsigned LoopDepth;
38     bool isBackEdge;
39     CopyRec(MachineInstr *mi, unsigned depth, bool be)
40       : MI(mi), LoopDepth(depth), isBackEdge(be) {};
41   };
42
43   template<class SF> class JoinPriorityQueue;
44
45   /// CopyRecSort - Sorting function for coalescer queue.
46   ///
47   struct CopyRecSort : public std::binary_function<CopyRec,CopyRec,bool> {
48     JoinPriorityQueue<CopyRecSort> *JPQ;
49     explicit CopyRecSort(JoinPriorityQueue<CopyRecSort> *jpq) : JPQ(jpq) {}
50     CopyRecSort(const CopyRecSort &RHS) : JPQ(RHS.JPQ) {}
51     bool operator()(CopyRec left, CopyRec right) const;
52   };
53
54   /// JoinQueue - A priority queue of copy instructions the coalescer is
55   /// going to process.
56   template<class SF>
57   class JoinPriorityQueue {
58     SimpleRegisterCoalescing *Rc;
59     std::priority_queue<CopyRec, std::vector<CopyRec>, SF> Queue;
60
61   public:
62     explicit JoinPriorityQueue(SimpleRegisterCoalescing *rc)
63       : Rc(rc), Queue(SF(this)) {}
64
65     bool empty() const { return Queue.empty(); }
66     void push(CopyRec R) { Queue.push(R); }
67     CopyRec pop() {
68       if (empty()) return CopyRec(0, 0, false);
69       CopyRec R = Queue.top();
70       Queue.pop();
71       return R;
72     }
73
74     // Callbacks to SimpleRegisterCoalescing.
75     unsigned getRepIntervalSize(unsigned Reg);
76   };
77
78   class SimpleRegisterCoalescing : public MachineFunctionPass,
79                                    public RegisterCoalescer {
80     MachineFunction* mf_;
81     MachineRegisterInfo* mri_;
82     const TargetMachine* tm_;
83     const TargetRegisterInfo* tri_;
84     const TargetInstrInfo* tii_;
85     LiveIntervals *li_;
86     const MachineLoopInfo* loopInfo;
87     
88     BitVector allocatableRegs_;
89     DenseMap<const TargetRegisterClass*, BitVector> allocatableRCRegs_;
90
91     /// JoinQueue - A priority queue of copy instructions the coalescer is
92     /// going to process.
93     JoinPriorityQueue<CopyRecSort> *JoinQueue;
94
95     /// JoinedCopies - Keep track of copies eliminated due to coalescing.
96     ///
97     SmallPtrSet<MachineInstr*, 32> JoinedCopies;
98
99     /// ReMatCopies - Keep track of copies eliminated due to remat.
100     ///
101     SmallPtrSet<MachineInstr*, 32> ReMatCopies;
102
103     /// ReMatDefs - Keep track of definition instructions which have
104     /// been remat'ed.
105     SmallPtrSet<MachineInstr*, 8> ReMatDefs;
106
107   public:
108     static char ID; // Pass identifcation, replacement for typeid
109     SimpleRegisterCoalescing() : MachineFunctionPass(&ID) {}
110
111     struct InstrSlots {
112       enum {
113         LOAD  = 0,
114         USE   = 1,
115         DEF   = 2,
116         STORE = 3,
117         NUM   = 4
118       };
119     };
120     
121     virtual void getAnalysisUsage(AnalysisUsage &AU) const;
122     virtual void releaseMemory();
123
124     /// runOnMachineFunction - pass entry point
125     virtual bool runOnMachineFunction(MachineFunction&);
126
127     bool coalesceFunction(MachineFunction &mf, RegallocQuery &) {
128       // This runs as an independent pass, so don't do anything.
129       return false;
130     };
131
132     /// getRepIntervalSize - Called from join priority queue sorting function.
133     /// It returns the size of the interval that represent the given register.
134     unsigned getRepIntervalSize(unsigned Reg) {
135       if (!li_->hasInterval(Reg))
136         return 0;
137       return li_->getApproximateInstructionCount(li_->getInterval(Reg)) *
138              LiveIntervals::InstrSlots::NUM;
139     }
140
141     /// print - Implement the dump method.
142     virtual void print(std::ostream &O, const Module* = 0) const;
143     void print(std::ostream *O, const Module* M = 0) const {
144       if (O) print(*O, M);
145     }
146
147   private:
148     /// joinIntervals - join compatible live intervals
149     void joinIntervals();
150
151     /// CopyCoalesceInMBB - Coalesce copies in the specified MBB, putting
152     /// copies that cannot yet be coalesced into the "TryAgain" list.
153     void CopyCoalesceInMBB(MachineBasicBlock *MBB,
154                            std::vector<CopyRec> &TryAgain);
155
156     /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
157     /// which are the src/dst of the copy instruction CopyMI.  This returns true
158     /// if the copy was successfully coalesced away. If it is not currently
159     /// possible to coalesce this interval, but it may be possible if other
160     /// things get coalesced, then it returns true by reference in 'Again'.
161     bool JoinCopy(CopyRec &TheCopy, bool &Again);
162     
163     /// JoinIntervals - Attempt to join these two intervals.  On failure, this
164     /// returns false.  Otherwise, if one of the intervals being joined is a
165     /// physreg, this method always canonicalizes DestInt to be it.  The output
166     /// "SrcInt" will not have been modified, so we can use this information
167     /// below to update aliases.
168     bool JoinIntervals(LiveInterval &LHS, LiveInterval &RHS, bool &Swapped);
169     
170     /// SimpleJoin - Attempt to join the specified interval into this one. The
171     /// caller of this method must guarantee that the RHS only contains a single
172     /// value number and that the RHS is not defined by a copy from this
173     /// interval.  This returns false if the intervals are not joinable, or it
174     /// joins them and returns true.
175     bool SimpleJoin(LiveInterval &LHS, LiveInterval &RHS);
176     
177     /// Return true if the two specified registers belong to different register
178     /// classes.  The registers may be either phys or virt regs. In the
179     /// case where both registers are virtual registers, it would also returns
180     /// true by reference the RegB register class in SubRC if it is a subset of
181     /// RegA's register class.
182     bool differingRegisterClasses(unsigned RegA, unsigned RegB,
183                                   const TargetRegisterClass *&SubRC) const;
184
185
186     /// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy. If
187     /// the source value number is defined by a copy from the destination reg
188     /// see if we can merge these two destination reg valno# into a single
189     /// value number, eliminating a copy.
190     bool AdjustCopiesBackFrom(LiveInterval &IntA, LiveInterval &IntB,
191                               MachineInstr *CopyMI);
192
193     /// HasOtherReachingDefs - Return true if there are definitions of IntB
194     /// other than BValNo val# that can reach uses of AValno val# of IntA.
195     bool HasOtherReachingDefs(LiveInterval &IntA, LiveInterval &IntB,
196                               VNInfo *AValNo, VNInfo *BValNo);
197
198     /// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy.
199     /// If the source value number is defined by a commutable instruction and
200     /// its other operand is coalesced to the copy dest register, see if we
201     /// can transform the copy into a noop by commuting the definition.
202     bool RemoveCopyByCommutingDef(LiveInterval &IntA, LiveInterval &IntB,
203                                   MachineInstr *CopyMI);
204
205     bool ReMaterializeTrivialDef(LiveInterval &SrcInt, unsigned DstReg,
206                                  MachineInstr *CopyMI);
207
208     /// TurnCopyIntoImpDef - If source of the specified copy is an implicit def,
209     /// turn the copy into an implicit def.
210     bool TurnCopyIntoImpDef(MachineBasicBlock::iterator &I,
211                             MachineBasicBlock *MBB,
212                             unsigned DstReg, unsigned SrcReg);
213
214     /// CanCoalesceWithImpDef - Returns true if the specified copy instruction
215     /// from an implicit def to another register can be coalesced away.
216     bool CanCoalesceWithImpDef(MachineInstr *CopyMI,
217                                LiveInterval &li, LiveInterval &ImpLi) const;
218
219     /// RemoveCopiesFromValNo - The specified value# is defined by an implicit
220     /// def and it is being removed. Turn all copies from this value# into
221     /// identity copies so they will be removed.
222     void RemoveCopiesFromValNo(LiveInterval &li, VNInfo *VNI);
223
224     /// isProfitableToCoalesceToSubRC - Given that register class of DstReg is
225     /// a subset of the register class of SrcReg, return true if it's profitable
226     /// to coalesce the two registers.
227     bool isProfitableToCoalesceToSubRC(unsigned SrcReg, unsigned DstReg,
228                                        MachineBasicBlock *MBB);
229
230     /// HasIncompatibleSubRegDefUse - If we are trying to coalesce a virtual
231     /// register with a physical register, check if any of the virtual register
232     /// operand is a sub-register use or def. If so, make sure it won't result
233     /// in an illegal extract_subreg or insert_subreg instruction.
234     bool HasIncompatibleSubRegDefUse(MachineInstr *CopyMI,
235                                      unsigned VirtReg, unsigned PhysReg);
236
237     /// RangeIsDefinedByCopyFromReg - Return true if the specified live range of
238     /// the specified live interval is defined by a copy from the specified
239     /// register.
240     bool RangeIsDefinedByCopyFromReg(LiveInterval &li, LiveRange *LR,
241                                      unsigned Reg);
242
243     /// isBackEdgeCopy - Return true if CopyMI is a back edge copy.
244     ///
245     bool isBackEdgeCopy(MachineInstr *CopyMI, unsigned DstReg) const;
246
247     /// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
248     /// update the subregister number if it is not zero. If DstReg is a
249     /// physical register and the existing subregister number of the def / use
250     /// being updated is not zero, make sure to set it to the correct physical
251     /// subregister.
252     void UpdateRegDefsUses(unsigned SrcReg, unsigned DstReg, unsigned SubIdx);
253
254     /// RemoveDeadImpDef - Remove implicit_def instructions which are
255     /// "re-defining" registers due to insert_subreg coalescing. e.g.
256     void RemoveDeadImpDef(unsigned Reg, LiveInterval &LI);
257
258     /// RemoveUnnecessaryKills - Remove kill markers that are no longer accurate
259     /// due to live range lengthening as the result of coalescing.
260     void RemoveUnnecessaryKills(unsigned Reg, LiveInterval &LI);
261
262     /// ShortenDeadCopyLiveRange - Shorten a live range defined by a dead copy.
263     /// Return true if live interval is removed.
264     bool ShortenDeadCopyLiveRange(LiveInterval &li, MachineInstr *CopyMI);
265
266     /// ShortenDeadCopyLiveRange - Shorten a live range as it's artificially
267     /// extended by a dead copy. Mark the last use (if any) of the val# as kill
268     /// as ends the live range there. If there isn't another use, then this
269     /// live range is dead. Return true if live interval is removed.
270     bool ShortenDeadCopySrcLiveRange(LiveInterval &li, MachineInstr *CopyMI);
271
272     /// RemoveDeadDef - If a def of a live interval is now determined dead,
273     /// remove the val# it defines. If the live interval becomes empty, remove
274     /// it as well.
275     bool RemoveDeadDef(LiveInterval &li, MachineInstr *DefMI);
276
277     /// lastRegisterUse - Returns the last use of the specific register between
278     /// cycles Start and End or NULL if there are no uses.
279     MachineOperand *lastRegisterUse(unsigned Start, unsigned End, unsigned Reg,
280                                     unsigned &LastUseIdx) const;
281
282     void printRegName(unsigned reg) const;
283   };
284
285 } // End llvm namespace
286
287 #endif