fd3a68f43854a4e8023ddaef67008ee84491063f
[oota-llvm.git] / lib / Target / Hexagon / BitTracker.h
1 //===--- BitTracker.h -----------------------------------------------------===//
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 #ifndef BITTRACKER_H
11 #define BITTRACKER_H
12
13 #include "llvm/ADT/SetVector.h"
14 #include "llvm/ADT/SmallVector.h"
15 #include "llvm/CodeGen/MachineFunction.h"
16
17 #include <map>
18 #include <queue>
19 #include <set>
20
21 namespace llvm {
22   class ConstantInt;
23   class MachineRegisterInfo;
24   class MachineBasicBlock;
25   class MachineInstr;
26   class MachineOperand;
27   class raw_ostream;
28
29 struct BitTracker {
30   struct BitRef;
31   struct RegisterRef;
32   struct BitValue;
33   struct BitMask;
34   struct RegisterCell;
35   struct MachineEvaluator;
36
37   typedef SetVector<const MachineBasicBlock *> BranchTargetList;
38
39   typedef std::map<unsigned, RegisterCell> CellMapType;
40
41   BitTracker(const MachineEvaluator &E, MachineFunction &F);
42   ~BitTracker();
43
44   void run();
45   void trace(bool On = false) { Trace = On; }
46   bool has(unsigned Reg) const;
47   const RegisterCell &lookup(unsigned Reg) const;
48   RegisterCell get(RegisterRef RR) const;
49   void put(RegisterRef RR, const RegisterCell &RC);
50   void subst(RegisterRef OldRR, RegisterRef NewRR);
51   bool reached(const MachineBasicBlock *B) const;
52
53 private:
54   void visitPHI(const MachineInstr *PI);
55   void visitNonBranch(const MachineInstr *MI);
56   void visitBranchesFrom(const MachineInstr *BI);
57   void visitUsesOf(unsigned Reg);
58   void reset();
59
60   typedef std::pair<int,int> CFGEdge;
61   typedef std::set<CFGEdge> EdgeSetType;
62   typedef std::set<const MachineInstr *> InstrSetType;
63   typedef std::queue<CFGEdge> EdgeQueueType;
64
65   EdgeSetType EdgeExec;       // Executable flow graph edges.
66   InstrSetType InstrExec;     // Executable instructions.
67   EdgeQueueType FlowQ;        // Work queue of CFG edges.
68   bool Trace;                 // Enable tracing for debugging.
69
70   const MachineEvaluator &ME;
71   MachineFunction &MF;
72   MachineRegisterInfo &MRI;
73   CellMapType &Map;
74 };
75
76
77 // Abstraction of a reference to bit at position Pos from a register Reg.
78 struct BitTracker::BitRef {
79   BitRef(unsigned R = 0, uint16_t P = 0) : Reg(R), Pos(P) {}
80   BitRef(const BitRef &BR) : Reg(BR.Reg), Pos(BR.Pos) {}
81   bool operator== (const BitRef &BR) const {
82     // If Reg is 0, disregard Pos.
83     return Reg == BR.Reg && (Reg == 0 || Pos == BR.Pos);
84   }
85   unsigned Reg;
86   uint16_t Pos;
87 };
88
89
90 // Abstraction of a register reference in MachineOperand.  It contains the
91 // register number and the subregister index.
92 struct BitTracker::RegisterRef {
93   RegisterRef(unsigned R = 0, unsigned S = 0)
94     : Reg(R), Sub(S) {}
95   RegisterRef(const MachineOperand &MO)
96       : Reg(MO.getReg()), Sub(MO.getSubReg()) {}
97   unsigned Reg, Sub;
98 };
99
100
101 // Value that a single bit can take.  This is outside of the context of
102 // any register, it is more of an abstraction of the two-element set of
103 // possible bit values.  One extension here is the "Ref" type, which
104 // indicates that this bit takes the same value as the bit described by
105 // RefInfo.
106 struct BitTracker::BitValue {
107   enum ValueType {
108     Top,    // Bit not yet defined.
109     Zero,   // Bit = 0.
110     One,    // Bit = 1.
111     Ref     // Bit value same as the one described in RefI.
112     // Conceptually, there is no explicit "bottom" value: the lattice's
113     // bottom will be expressed as a "ref to itself", which, in the context
114     // of registers, could be read as "this value of this bit is defined by
115     // this bit".
116     // The ordering is:
117     //   x <= Top,
118     //   Self <= x, where "Self" is "ref to itself".
119     // This makes the value lattice different for each virtual register
120     // (even for each bit in the same virtual register), since the "bottom"
121     // for one register will be a simple "ref" for another register.
122     // Since we do not store the "Self" bit and register number, the meet
123     // operation will need to take it as a parameter.
124     //
125     // In practice there is a special case for values that are not associa-
126     // ted with any specific virtual register. An example would be a value
127     // corresponding to a bit of a physical register, or an intermediate
128     // value obtained in some computation (such as instruction evaluation).
129     // Such cases are identical to the usual Ref type, but the register
130     // number is 0. In such case the Pos field of the reference is ignored.
131     //
132     // What is worthy of notice is that in value V (that is a "ref"), as long
133     // as the RefI.Reg is not 0, it may actually be the same register as the
134     // one in which V will be contained.  If the RefI.Pos refers to the posi-
135     // tion of V, then V is assumed to be "bottom" (as a "ref to itself"),
136     // otherwise V is taken to be identical to the referenced bit of the
137     // same register.
138     // If RefI.Reg is 0, however, such a reference to the same register is
139     // not possible.  Any value V that is a "ref", and whose RefI.Reg is 0
140     // is treated as "bottom".
141   };
142   ValueType Type;
143   BitRef RefI;
144
145   BitValue(ValueType T = Top) : Type(T) {}
146   BitValue(bool B) : Type(B ? One : Zero) {}
147   BitValue(const BitValue &V) : Type(V.Type), RefI(V.RefI) {}
148   BitValue(unsigned Reg, uint16_t Pos) : Type(Ref), RefI(Reg, Pos) {}
149
150   bool operator== (const BitValue &V) const {
151     if (Type != V.Type)
152       return false;
153     if (Type == Ref && !(RefI == V.RefI))
154       return false;
155     return true;
156   }
157   bool operator!= (const BitValue &V) const {
158     return !operator==(V);
159   }
160   bool is(unsigned T) const {
161     assert(T == 0 || T == 1);
162     return T == 0 ? Type == Zero
163                   : (T == 1 ? Type == One : false);
164   }
165
166   // The "meet" operation is the "." operation in a semilattice (L, ., T, B):
167   // (1)  x.x = x
168   // (2)  x.y = y.x
169   // (3)  x.(y.z) = (x.y).z
170   // (4)  x.T = x  (i.e. T = "top")
171   // (5)  x.B = B  (i.e. B = "bottom")
172   //
173   // This "meet" function will update the value of the "*this" object with
174   // the newly calculated one, and return "true" if the value of *this has
175   // changed, and "false" otherwise.
176   // To prove that it satisfies the conditions (1)-(5), it is sufficient
177   // to show that a relation
178   //   x <= y  <=>  x.y = x
179   // defines a partial order (i.e. that "meet" is same as "infimum").
180   bool meet(const BitValue &V, const BitRef &Self) {
181     // First, check the cases where there is nothing to be done.
182     if (Type == Ref && RefI == Self)    // Bottom.meet(V) = Bottom (i.e. This)
183       return false;
184     if (V.Type == Top)                  // This.meet(Top) = This
185       return false;
186     if (*this == V)                     // This.meet(This) = This
187       return false;
188
189     // At this point, we know that the value of "this" will change.
190     // If it is Top, it will become the same as V, otherwise it will
191     // become "bottom" (i.e. Self).
192     if (Type == Top) {
193       Type = V.Type;
194       RefI = V.RefI;  // This may be irrelevant, but copy anyway.
195       return true;
196     }
197     // Become "bottom".
198     Type = Ref;
199     RefI = Self;
200     return true;
201   }
202
203   // Create a reference to the bit value V.
204   static BitValue ref(const BitValue &V);
205   // Create a "self".
206   static BitValue self(const BitRef &Self = BitRef());
207
208   bool num() const {
209     return Type == Zero || Type == One;
210   }
211   operator bool() const {
212     assert(Type == Zero || Type == One);
213     return Type == One;
214   }
215
216   friend raw_ostream &operator<<(raw_ostream &OS, const BitValue &BV);
217 };
218
219
220 // This operation must be idempotent, i.e. ref(ref(V)) == ref(V).
221 inline BitTracker::BitValue
222 BitTracker::BitValue::ref(const BitValue &V) {
223   if (V.Type != Ref)
224     return BitValue(V.Type);
225   if (V.RefI.Reg != 0)
226     return BitValue(V.RefI.Reg, V.RefI.Pos);
227   return self();
228 }
229
230
231 inline BitTracker::BitValue
232 BitTracker::BitValue::self(const BitRef &Self) {
233   return BitValue(Self.Reg, Self.Pos);
234 }
235
236
237 // A sequence of bits starting from index B up to and including index E.
238 // If E < B, the mask represents two sections: [0..E] and [B..W) where
239 // W is the width of the register.
240 struct BitTracker::BitMask {
241   BitMask() : B(0), E(0) {}
242   BitMask(uint16_t b, uint16_t e) : B(b), E(e) {}
243   uint16_t first() const { return B; }
244   uint16_t last() const { return E; }
245 private:
246   uint16_t B, E;
247 };
248
249
250 // Representation of a register: a list of BitValues.
251 struct BitTracker::RegisterCell {
252   RegisterCell(uint16_t Width = DefaultBitN) : Bits(Width) {}
253
254   uint16_t width() const {
255     return Bits.size();
256   }
257   const BitValue &operator[](uint16_t BitN) const {
258     assert(BitN < Bits.size());
259     return Bits[BitN];
260   }
261   BitValue &operator[](uint16_t BitN) {
262     assert(BitN < Bits.size());
263     return Bits[BitN];
264   }
265
266   bool meet(const RegisterCell &RC, unsigned SelfR);
267   RegisterCell &insert(const RegisterCell &RC, const BitMask &M);
268   RegisterCell extract(const BitMask &M) const;  // Returns a new cell.
269   RegisterCell &rol(uint16_t Sh);    // Rotate left.
270   RegisterCell &fill(uint16_t B, uint16_t E, const BitValue &V);
271   RegisterCell &cat(const RegisterCell &RC);  // Concatenate.
272   uint16_t cl(bool B) const;
273   uint16_t ct(bool B) const;
274
275   bool operator== (const RegisterCell &RC) const;
276   bool operator!= (const RegisterCell &RC) const {
277     return !operator==(RC);
278   }
279
280   const RegisterCell &operator=(const RegisterCell &RC) {
281     Bits = RC.Bits;
282     return *this;
283   }
284
285   // Generate a "ref" cell for the corresponding register. In the resulting
286   // cell each bit will be described as being the same as the corresponding
287   // bit in register Reg (i.e. the cell is "defined" by register Reg).
288   static RegisterCell self(unsigned Reg, uint16_t Width);
289   // Generate a "top" cell of given size.
290   static RegisterCell top(uint16_t Width);
291   // Generate a cell that is a "ref" to another cell.
292   static RegisterCell ref(const RegisterCell &C);
293
294 private:
295   // The DefaultBitN is here only to avoid frequent reallocation of the
296   // memory in the vector.
297   static const unsigned DefaultBitN = 32;
298   typedef SmallVector<BitValue, DefaultBitN> BitValueList;
299   BitValueList Bits;
300
301   friend raw_ostream &operator<<(raw_ostream &OS, const RegisterCell &RC);
302 };
303
304
305 inline bool BitTracker::has(unsigned Reg) const {
306   return Map.find(Reg) != Map.end();
307 }
308
309
310 inline const BitTracker::RegisterCell&
311 BitTracker::lookup(unsigned Reg) const {
312   CellMapType::const_iterator F = Map.find(Reg);
313   assert(F != Map.end());
314   return F->second;
315 }
316
317
318 inline BitTracker::RegisterCell
319 BitTracker::RegisterCell::self(unsigned Reg, uint16_t Width) {
320   RegisterCell RC(Width);
321   for (uint16_t i = 0; i < Width; ++i)
322     RC.Bits[i] = BitValue::self(BitRef(Reg, i));
323   return RC;
324 }
325
326
327 inline BitTracker::RegisterCell
328 BitTracker::RegisterCell::top(uint16_t Width) {
329   RegisterCell RC(Width);
330   for (uint16_t i = 0; i < Width; ++i)
331     RC.Bits[i] = BitValue(BitValue::Top);
332   return RC;
333 }
334
335
336 inline BitTracker::RegisterCell
337 BitTracker::RegisterCell::ref(const RegisterCell &C) {
338   uint16_t W = C.width();
339   RegisterCell RC(W);
340   for (unsigned i = 0; i < W; ++i)
341     RC[i] = BitValue::ref(C[i]);
342   return RC;
343 }
344
345 // A class to evaluate target's instructions and update the cell maps.
346 // This is used internally by the bit tracker.  A target that wants to
347 // utilize this should implement the evaluation functions (noted below)
348 // in a subclass of this class.
349 struct BitTracker::MachineEvaluator {
350   MachineEvaluator(const TargetRegisterInfo &T, MachineRegisterInfo &M)
351       : TRI(T), MRI(M) {}
352   virtual ~MachineEvaluator() {}
353
354   uint16_t getRegBitWidth(const RegisterRef &RR) const;
355
356   RegisterCell getCell(const RegisterRef &RR, const CellMapType &M) const;
357   void putCell(const RegisterRef &RR, RegisterCell RC, CellMapType &M) const;
358   // A result of any operation should use refs to the source cells, not
359   // the cells directly. This function is a convenience wrapper to quickly
360   // generate a ref for a cell corresponding to a register reference.
361   RegisterCell getRef(const RegisterRef &RR, const CellMapType &M) const {
362     RegisterCell RC = getCell(RR, M);
363     return RegisterCell::ref(RC);
364   }
365
366   // Helper functions.
367   // Check if a cell is an immediate value (i.e. all bits are either 0 or 1).
368   bool isInt(const RegisterCell &A) const;
369   // Convert cell to an immediate value.
370   uint64_t toInt(const RegisterCell &A) const;
371
372   // Generate cell from an immediate value.
373   RegisterCell eIMM(int64_t V, uint16_t W) const;
374   RegisterCell eIMM(const ConstantInt *CI) const;
375
376   // Arithmetic.
377   RegisterCell eADD(const RegisterCell &A1, const RegisterCell &A2) const;
378   RegisterCell eSUB(const RegisterCell &A1, const RegisterCell &A2) const;
379   RegisterCell eMLS(const RegisterCell &A1, const RegisterCell &A2) const;
380   RegisterCell eMLU(const RegisterCell &A1, const RegisterCell &A2) const;
381
382   // Shifts.
383   RegisterCell eASL(const RegisterCell &A1, uint16_t Sh) const;
384   RegisterCell eLSR(const RegisterCell &A1, uint16_t Sh) const;
385   RegisterCell eASR(const RegisterCell &A1, uint16_t Sh) const;
386
387   // Logical.
388   RegisterCell eAND(const RegisterCell &A1, const RegisterCell &A2) const;
389   RegisterCell eORL(const RegisterCell &A1, const RegisterCell &A2) const;
390   RegisterCell eXOR(const RegisterCell &A1, const RegisterCell &A2) const;
391   RegisterCell eNOT(const RegisterCell &A1) const;
392
393   // Set bit, clear bit.
394   RegisterCell eSET(const RegisterCell &A1, uint16_t BitN) const;
395   RegisterCell eCLR(const RegisterCell &A1, uint16_t BitN) const;
396
397   // Count leading/trailing bits (zeros/ones).
398   RegisterCell eCLB(const RegisterCell &A1, bool B, uint16_t W) const;
399   RegisterCell eCTB(const RegisterCell &A1, bool B, uint16_t W) const;
400
401   // Sign/zero extension.
402   RegisterCell eSXT(const RegisterCell &A1, uint16_t FromN) const;
403   RegisterCell eZXT(const RegisterCell &A1, uint16_t FromN) const;
404
405   // Extract/insert
406   // XTR R,b,e:  extract bits from A1 starting at bit b, ending at e-1.
407   // INS R,S,b:  take R and replace bits starting from b with S.
408   RegisterCell eXTR(const RegisterCell &A1, uint16_t B, uint16_t E) const;
409   RegisterCell eINS(const RegisterCell &A1, const RegisterCell &A2,
410                     uint16_t AtN) const;
411
412   // User-provided functions for individual targets:
413
414   // Return a sub-register mask that indicates which bits in Reg belong
415   // to the subregister Sub. These bits are assumed to be contiguous in
416   // the super-register, and have the same ordering in the sub-register
417   // as in the super-register. It is valid to call this function with
418   // Sub == 0, in this case, the function should return a mask that spans
419   // the entire register Reg (which is what the default implementation
420   // does).
421   virtual BitMask mask(unsigned Reg, unsigned Sub) const;
422   // Indicate whether a given register class should be tracked.
423   virtual bool track(const TargetRegisterClass *RC) const { return true; }
424   // Evaluate a non-branching machine instruction, given the cell map with
425   // the input values. Place the results in the Outputs map. Return "true"
426   // if evaluation succeeded, "false" otherwise.
427   virtual bool evaluate(const MachineInstr *MI, const CellMapType &Inputs,
428                         CellMapType &Outputs) const;
429   // Evaluate a branch, given the cell map with the input values. Fill out
430   // a list of all possible branch targets and indicate (through a flag)
431   // whether the branch could fall-through. Return "true" if this information
432   // has been successfully computed, "false" otherwise.
433   virtual bool evaluate(const MachineInstr *BI, const CellMapType &Inputs,
434                         BranchTargetList &Targets, bool &FallsThru) const = 0;
435
436   const TargetRegisterInfo &TRI;
437   MachineRegisterInfo &MRI;
438 };
439
440 } // end namespace llvm
441
442 #endif