1 //===--- BitTracker.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 // SSA-based bit propagation.
11 //
12 // The purpose of this code is, for a given virtual register, to provide
13 // information about the value of each bit in the register. The values
14 // of bits are represented by the class BitValue, and take one of four
15 // cases: 0, 1, "ref" and "bottom". The 0 and 1 are rather clear, the
16 // "ref" value means that the bit is a copy of another bit (which itself
17 // cannot be a copy of yet another bit---such chains are not allowed).
18 // A "ref" value is associated with a BitRef structure, which indicates
19 // which virtual register, and which bit in that register is the origin
20 // of the value. For example, given an instruction
21 //   vreg2 = ASL vreg1, 1
22 // assuming that nothing is known about bits of vreg1, bit 1 of vreg2
23 // will be a "ref" to (vreg1, 0). If there is a subsequent instruction
24 //   vreg3 = ASL vreg2, 2
25 // then bit 3 of vreg3 will be a "ref" to (vreg1, 0) as well.
26 // The "bottom" case means that the bit's value cannot be determined,
27 // and that this virtual register actually defines it. The "bottom" case
28 // is discussed in detail in BitTracker.h. In fact, "bottom" is a "ref
29 // to self", so for the vreg1 above, the bit 0 of it will be a "ref" to
30 // (vreg1, 0), bit 1 will be a "ref" to (vreg1, 1), etc.
31 //
32 // The tracker implements the Wegman-Zadeck algorithm, originally developed
33 // for SSA-based constant propagation. Each register is represented as
34 // a sequence of bits, with the convention that bit 0 is the least signi-
35 // ficant bit. Each bit is propagated individually. The class RegisterCell
36 // implements the register's representation, and is also the subject of
37 // the lattice operations in the tracker.
38 //
39 // The intended usage of the bit tracker is to create a target-specific
40 // machine instruction evaluator, pass the evaluator to the BitTracker
41 // object, and run the tracker. The tracker will then collect the bit
42 // value information for a given machine function. After that, it can be
43 // queried for the cells for each virtual register.
44 // Sample code:
45 //   const TargetSpecificEvaluator TSE(TRI, MRI);
46 //   BitTracker BT(TSE, MF);
47 //   BT.run();
48 //   ...
49 //   unsigned Reg = interestingRegister();
50 //   RegisterCell RC = BT.get(Reg);
51 //   if (RC[3].is(1))
52 //      Reg0bit3 = 1;
53 //
54 // The code below is intended to be fully target-independent.
55 
56 #include "llvm/CodeGen/MachineBasicBlock.h"
57 #include "llvm/CodeGen/MachineFunction.h"
58 #include "llvm/CodeGen/MachineInstr.h"
59 #include "llvm/CodeGen/MachineRegisterInfo.h"
60 #include "llvm/IR/Constants.h"
61 #include "llvm/Support/Debug.h"
62 #include "llvm/Support/raw_ostream.h"
63 #include "llvm/Target/TargetRegisterInfo.h"
64 
65 #include "BitTracker.h"
66 
67 using namespace llvm;
68 
69 typedef BitTracker BT;
70 
71 namespace {
72   // Local trickery to pretty print a register (without the whole "%vreg"
73   // business).
74   struct printv {
75     printv(unsigned r) : R(r) {}
76     unsigned R;
77   };
78   raw_ostream &operator<< (raw_ostream &OS, const printv &PV) {
79     if (PV.R)
80       OS << 'v' << TargetRegisterInfo::virtReg2Index(PV.R);
81     else
82       OS << 's';
83     return OS;
84   }
85 }
86 
87 namespace llvm {
88   raw_ostream &operator<<(raw_ostream &OS, const BT::BitValue &BV) {
89     switch (BV.Type) {
90       case BT::BitValue::Top:
91         OS << 'T';
92         break;
93       case BT::BitValue::Zero:
94         OS << '0';
95         break;
96       case BT::BitValue::One:
97         OS << '1';
98         break;
99       case BT::BitValue::Ref:
100         OS << printv(BV.RefI.Reg) << '[' << BV.RefI.Pos << ']';
101         break;
102     }
103     return OS;
104   }
105 
106   raw_ostream &operator<<(raw_ostream &OS, const BT::RegisterCell &RC) {
107     unsigned n = RC.Bits.size();
108     OS << "{ w:" << n;
109     // Instead of printing each bit value individually, try to group them
110     // into logical segments, such as sequences of 0 or 1 bits or references
111     // to consecutive bits (e.g. "bits 3-5 are same as bits 7-9 of reg xyz").
112     // "Start" will be the index of the beginning of the most recent segment.
113     unsigned Start = 0;
114     bool SeqRef = false;    // A sequence of refs to consecutive bits.
115     bool ConstRef = false;  // A sequence of refs to the same bit.
116 
117     for (unsigned i = 1, n = RC.Bits.size(); i < n; ++i) {
118       const BT::BitValue &V = RC[i];
119       const BT::BitValue &SV = RC[Start];
120       bool IsRef = (V.Type == BT::BitValue::Ref);
121       // If the current value is the same as Start, skip to the next one.
122       if (!IsRef && V == SV)
123         continue;
124       if (IsRef && SV.Type == BT::BitValue::Ref && V.RefI.Reg == SV.RefI.Reg) {
125         if (Start+1 == i) {
126           SeqRef = (V.RefI.Pos == SV.RefI.Pos+1);
127           ConstRef = (V.RefI.Pos == SV.RefI.Pos);
128         }
129         if (SeqRef && V.RefI.Pos == SV.RefI.Pos+(i-Start))
130           continue;
131         if (ConstRef && V.RefI.Pos == SV.RefI.Pos)
132           continue;
133       }
134 
135       // The current value is different. Print the previous one and reset
136       // the Start.
137       OS << " [" << Start;
138       unsigned Count = i - Start;
139       if (Count == 1) {
140         OS << "]:" << SV;
141       } else {
142         OS << '-' << i-1 << "]:";
143         if (SV.Type == BT::BitValue::Ref && SeqRef)
144           OS << printv(SV.RefI.Reg) << '[' << SV.RefI.Pos << '-'
145              << SV.RefI.Pos+(Count-1) << ']';
146         else
147           OS << SV;
148       }
149       Start = i;
150       SeqRef = ConstRef = false;
151     }
152 
153     OS << " [" << Start;
154     unsigned Count = n - Start;
155     if (n-Start == 1) {
156       OS << "]:" << RC[Start];
157     } else {
158       OS << '-' << n-1 << "]:";
159       const BT::BitValue &SV = RC[Start];
160       if (SV.Type == BT::BitValue::Ref && SeqRef)
161         OS << printv(SV.RefI.Reg) << '[' << SV.RefI.Pos << '-'
162            << SV.RefI.Pos+(Count-1) << ']';
163       else
164         OS << SV;
165     }
166     OS << " }";
167 
168     return OS;
169   }
170 }
171 
172 void BitTracker::print_cells(raw_ostream &OS) const {
173   for (CellMapType::iterator I = Map.begin(), E = Map.end(); I != E; ++I)
174     dbgs() << PrintReg(I->first, &ME.TRI) << " -> " << I->second << "\n";
175 }
176 
177 
178 BitTracker::BitTracker(const MachineEvaluator &E, MachineFunction &F)
179     : Trace(false), ME(E), MF(F), MRI(F.getRegInfo()), Map(*new CellMapType) {}
180 
181 BitTracker::~BitTracker() {
182   delete &Map;
183 }
184 
185 
186 // If we were allowed to update a cell for a part of a register, the meet
187 // operation would need to be parametrized by the register number and the
188 // exact part of the register, so that the computer BitRefs correspond to
189 // the actual bits of the "self" register.
190 // While this cannot happen in the current implementation, I'm not sure
191 // if this should be ruled out in the future.
192 bool BT::RegisterCell::meet(const RegisterCell &RC, unsigned SelfR) {
193   // An example when "meet" can be invoked with SelfR == 0 is a phi node
194   // with a physical register as an operand.
195   assert(SelfR == 0 || TargetRegisterInfo::isVirtualRegister(SelfR));
196   bool Changed = false;
197   for (uint16_t i = 0, n = Bits.size(); i < n; ++i) {
198     const BitValue &RCV = RC[i];
199     Changed |= Bits[i].meet(RCV, BitRef(SelfR, i));
200   }
201   return Changed;
202 }
203 
204 
205 // Insert the entire cell RC into the current cell at position given by M.
206 BT::RegisterCell &BT::RegisterCell::insert(const BT::RegisterCell &RC,
207       const BitMask &M) {
208   uint16_t B = M.first(), E = M.last(), W = width();
209   // Sanity: M must be a valid mask for *this.
210   assert(B < W && E < W);
211   // Sanity: the masked part of *this must have the same number of bits
212   // as the source.
213   assert(B > E || E-B+1 == RC.width());      // B <= E  =>  E-B+1 = |RC|.
214   assert(B <= E || E+(W-B)+1 == RC.width()); // E < B   =>  E+(W-B)+1 = |RC|.
215   if (B <= E) {
216     for (uint16_t i = 0; i <= E-B; ++i)
217       Bits[i+B] = RC[i];
218   } else {
219     for (uint16_t i = 0; i < W-B; ++i)
220       Bits[i+B] = RC[i];
221     for (uint16_t i = 0; i <= E; ++i)
222       Bits[i] = RC[i+(W-B)];
223   }
224   return *this;
225 }
226 
227 
228 BT::RegisterCell BT::RegisterCell::extract(const BitMask &M) const {
229   uint16_t B = M.first(), E = M.last(), W = width();
230   assert(B < W && E < W);
231   if (B <= E) {
232     RegisterCell RC(E-B+1);
233     for (uint16_t i = B; i <= E; ++i)
234       RC.Bits[i-B] = Bits[i];
235     return RC;
236   }
237 
238   RegisterCell RC(E+(W-B)+1);
239   for (uint16_t i = 0; i < W-B; ++i)
240     RC.Bits[i] = Bits[i+B];
241   for (uint16_t i = 0; i <= E; ++i)
242     RC.Bits[i+(W-B)] = Bits[i];
243   return RC;
244 }
245 
246 
247 BT::RegisterCell &BT::RegisterCell::rol(uint16_t Sh) {
248   // Rotate left (i.e. towards increasing bit indices).
249   // Swap the two parts:  [0..W-Sh-1] [W-Sh..W-1]
250   uint16_t W = width();
251   Sh = Sh % W;
252   if (Sh == 0)
253     return *this;
254 
255   RegisterCell Tmp(W-Sh);
256   // Tmp = [0..W-Sh-1].
257   for (uint16_t i = 0; i < W-Sh; ++i)
258     Tmp[i] = Bits[i];
259   // Shift [W-Sh..W-1] to [0..Sh-1].
260   for (uint16_t i = 0; i < Sh; ++i)
261     Bits[i] = Bits[W-Sh+i];
262   // Copy Tmp to [Sh..W-1].
263   for (uint16_t i = 0; i < W-Sh; ++i)
264     Bits[i+Sh] = Tmp.Bits[i];
265   return *this;
266 }
267 
268 
269 BT::RegisterCell &BT::RegisterCell::fill(uint16_t B, uint16_t E,
270       const BitValue &V) {
271   assert(B <= E);
272   while (B < E)
273     Bits[B++] = V;
274   return *this;
275 }
276 
277 
278 BT::RegisterCell &BT::RegisterCell::cat(const RegisterCell &RC) {
279   // Append the cell given as the argument to the "this" cell.
280   // Bit 0 of RC becomes bit W of the result, where W is this->width().
281   uint16_t W = width(), WRC = RC.width();
282   Bits.resize(W+WRC);
283   for (uint16_t i = 0; i < WRC; ++i)
284     Bits[i+W] = RC.Bits[i];
285   return *this;
286 }
287 
288 
289 uint16_t BT::RegisterCell::ct(bool B) const {
290   uint16_t W = width();
291   uint16_t C = 0;
292   BitValue V = B;
293   while (C < W && Bits[C] == V)
294     C++;
295   return C;
296 }
297 
298 
299 uint16_t BT::RegisterCell::cl(bool B) const {
300   uint16_t W = width();
301   uint16_t C = 0;
302   BitValue V = B;
303   while (C < W && Bits[W-(C+1)] == V)
304     C++;
305   return C;
306 }
307 
308 
309 bool BT::RegisterCell::operator== (const RegisterCell &RC) const {
310   uint16_t W = Bits.size();
311   if (RC.Bits.size() != W)
312     return false;
313   for (uint16_t i = 0; i < W; ++i)
314     if (Bits[i] != RC[i])
315       return false;
316   return true;
317 }
318 
319 
320 uint16_t BT::MachineEvaluator::getRegBitWidth(const RegisterRef &RR) const {
321   // The general problem is with finding a register class that corresponds
322   // to a given reference reg:sub. There can be several such classes, and
323   // since we only care about the register size, it does not matter which
324   // such class we would find.
325   // The easiest way to accomplish what we want is to
326   // 1. find a physical register PhysR from the same class as RR.Reg,
327   // 2. find a physical register PhysS that corresponds to PhysR:RR.Sub,
328   // 3. find a register class that contains PhysS.
329   unsigned PhysR;
330   if (TargetRegisterInfo::isVirtualRegister(RR.Reg)) {
331     const TargetRegisterClass *VC = MRI.getRegClass(RR.Reg);
332     assert(VC->begin() != VC->end() && "Empty register class");
333     PhysR = *VC->begin();
334   } else {
335     assert(TargetRegisterInfo::isPhysicalRegister(RR.Reg));
336     PhysR = RR.Reg;
337   }
338 
339   unsigned PhysS = (RR.Sub == 0) ? PhysR : TRI.getSubReg(PhysR, RR.Sub);
340   const TargetRegisterClass *RC = TRI.getMinimalPhysRegClass(PhysS);
341   uint16_t BW = RC->getSize()*8;
342   return BW;
343 }
344 
345 
346 BT::RegisterCell BT::MachineEvaluator::getCell(const RegisterRef &RR,
347       const CellMapType &M) const {
348   uint16_t BW = getRegBitWidth(RR);
349 
350   // Physical registers are assumed to be present in the map with an unknown
351   // value. Don't actually insert anything in the map, just return the cell.
352   if (TargetRegisterInfo::isPhysicalRegister(RR.Reg))
353     return RegisterCell::self(0, BW);
354 
355   assert(TargetRegisterInfo::isVirtualRegister(RR.Reg));
356   // For virtual registers that belong to a class that is not tracked,
357   // generate an "unknown" value as well.
358   const TargetRegisterClass *C = MRI.getRegClass(RR.Reg);
359   if (!track(C))
360     return RegisterCell::self(0, BW);
361 
362   CellMapType::const_iterator F = M.find(RR.Reg);
363   if (F != M.end()) {
364     if (!RR.Sub)
365       return F->second;
366     BitMask M = mask(RR.Reg, RR.Sub);
367     return F->second.extract(M);
368   }
369   // If not found, create a "top" entry, but do not insert it in the map.
370   return RegisterCell::top(BW);
371 }
372 
373 
374 void BT::MachineEvaluator::putCell(const RegisterRef &RR, RegisterCell RC,
375       CellMapType &M) const {
376   // While updating the cell map can be done in a meaningful way for
377   // a part of a register, it makes little sense to implement it as the
378   // SSA representation would never contain such "partial definitions".
379   if (!TargetRegisterInfo::isVirtualRegister(RR.Reg))
380     return;
381   assert(RR.Sub == 0 && "Unexpected sub-register in definition");
382   // Eliminate all ref-to-reg-0 bit values: replace them with "self".
383   for (unsigned i = 0, n = RC.width(); i < n; ++i) {
384     const BitValue &V = RC[i];
385     if (V.Type == BitValue::Ref && V.RefI.Reg == 0)
386       RC[i].RefI = BitRef(RR.Reg, i);
387   }
388   M[RR.Reg] = RC;
389 }
390 
391 
392 // Check if the cell represents a compile-time integer value.
393 bool BT::MachineEvaluator::isInt(const RegisterCell &A) const {
394   uint16_t W = A.width();
395   for (uint16_t i = 0; i < W; ++i)
396     if (!A[i].is(0) && !A[i].is(1))
397       return false;
398   return true;
399 }
400 
401 
402 // Convert a cell to the integer value. The result must fit in uint64_t.
403 uint64_t BT::MachineEvaluator::toInt(const RegisterCell &A) const {
404   assert(isInt(A));
405   uint64_t Val = 0;
406   uint16_t W = A.width();
407   for (uint16_t i = 0; i < W; ++i) {
408     Val <<= 1;
409     Val |= A[i].is(1);
410   }
411   return Val;
412 }
413 
414 
415 // Evaluator helper functions. These implement some common operation on
416 // register cells that can be used to implement target-specific instructions
417 // in a target-specific evaluator.
418 
419 BT::RegisterCell BT::MachineEvaluator::eIMM(int64_t V, uint16_t W) const {
420   RegisterCell Res(W);
421   // For bits beyond the 63rd, this will generate the sign bit of V.
422   for (uint16_t i = 0; i < W; ++i) {
423     Res[i] = BitValue(V & 1);
424     V >>= 1;
425   }
426   return Res;
427 }
428 
429 
430 BT::RegisterCell BT::MachineEvaluator::eIMM(const ConstantInt *CI) const {
431   const APInt &A = CI->getValue();
432   uint16_t BW = A.getBitWidth();
433   assert((unsigned)BW == A.getBitWidth() && "BitWidth overflow");
434   RegisterCell Res(BW);
435   for (uint16_t i = 0; i < BW; ++i)
436     Res[i] = A[i];
437   return Res;
438 }
439 
440 
441 BT::RegisterCell BT::MachineEvaluator::eADD(const RegisterCell &A1,
442       const RegisterCell &A2) const {
443   uint16_t W = A1.width();
444   assert(W == A2.width());
445   RegisterCell Res(W);
446   bool Carry = false;
447   uint16_t I;
448   for (I = 0; I < W; ++I) {
449     const BitValue &V1 = A1[I];
450     const BitValue &V2 = A2[I];
451     if (!V1.num() || !V2.num())
452       break;
453     unsigned S = bool(V1) + bool(V2) + Carry;
454     Res[I] = BitValue(S & 1);
455     Carry = (S > 1);
456   }
457   for (; I < W; ++I) {
458     const BitValue &V1 = A1[I];
459     const BitValue &V2 = A2[I];
460     // If the next bit is same as Carry, the result will be 0 plus the
461     // other bit. The Carry bit will remain unchanged.
462     if (V1.is(Carry))
463       Res[I] = BitValue::ref(V2);
464     else if (V2.is(Carry))
465       Res[I] = BitValue::ref(V1);
466     else
467       break;
468   }
469   for (; I < W; ++I)
470     Res[I] = BitValue::self();
471   return Res;
472 }
473 
474 
475 BT::RegisterCell BT::MachineEvaluator::eSUB(const RegisterCell &A1,
476       const RegisterCell &A2) const {
477   uint16_t W = A1.width();
478   assert(W == A2.width());
479   RegisterCell Res(W);
480   bool Borrow = false;
481   uint16_t I;
482   for (I = 0; I < W; ++I) {
483     const BitValue &V1 = A1[I];
484     const BitValue &V2 = A2[I];
485     if (!V1.num() || !V2.num())
486       break;
487     unsigned S = bool(V1) - bool(V2) - Borrow;
488     Res[I] = BitValue(S & 1);
489     Borrow = (S > 1);
490   }
491   for (; I < W; ++I) {
492     const BitValue &V1 = A1[I];
493     const BitValue &V2 = A2[I];
494     if (V1.is(Borrow)) {
495       Res[I] = BitValue::ref(V2);
496       break;
497     }
498     if (V2.is(Borrow))
499       Res[I] = BitValue::ref(V1);
500     else
501       break;
502   }
503   for (; I < W; ++I)
504     Res[I] = BitValue::self();
505   return Res;
506 }
507 
508 
509 BT::RegisterCell BT::MachineEvaluator::eMLS(const RegisterCell &A1,
510       const RegisterCell &A2) const {
511   uint16_t W = A1.width() + A2.width();
512   uint16_t Z = A1.ct(0) + A2.ct(0);
513   RegisterCell Res(W);
514   Res.fill(0, Z, BitValue::Zero);
515   Res.fill(Z, W, BitValue::self());
516   return Res;
517 }
518 
519 
520 BT::RegisterCell BT::MachineEvaluator::eMLU(const RegisterCell &A1,
521       const RegisterCell &A2) const {
522   uint16_t W = A1.width() + A2.width();
523   uint16_t Z = A1.ct(0) + A2.ct(0);
524   RegisterCell Res(W);
525   Res.fill(0, Z, BitValue::Zero);
526   Res.fill(Z, W, BitValue::self());
527   return Res;
528 }
529 
530 
531 BT::RegisterCell BT::MachineEvaluator::eASL(const RegisterCell &A1,
532       uint16_t Sh) const {
533   assert(Sh <= A1.width());
534   RegisterCell Res = RegisterCell::ref(A1);
535   Res.rol(Sh);
536   Res.fill(0, Sh, BitValue::Zero);
537   return Res;
538 }
539 
540 
541 BT::RegisterCell BT::MachineEvaluator::eLSR(const RegisterCell &A1,
542       uint16_t Sh) const {
543   uint16_t W = A1.width();
544   assert(Sh <= W);
545   RegisterCell Res = RegisterCell::ref(A1);
546   Res.rol(W-Sh);
547   Res.fill(W-Sh, W, BitValue::Zero);
548   return Res;
549 }
550 
551 
552 BT::RegisterCell BT::MachineEvaluator::eASR(const RegisterCell &A1,
553       uint16_t Sh) const {
554   uint16_t W = A1.width();
555   assert(Sh <= W);
556   RegisterCell Res = RegisterCell::ref(A1);
557   BitValue Sign = Res[W-1];
558   Res.rol(W-Sh);
559   Res.fill(W-Sh, W, Sign);
560   return Res;
561 }
562 
563 
564 BT::RegisterCell BT::MachineEvaluator::eAND(const RegisterCell &A1,
565       const RegisterCell &A2) const {
566   uint16_t W = A1.width();
567   assert(W == A2.width());
568   RegisterCell Res(W);
569   for (uint16_t i = 0; i < W; ++i) {
570     const BitValue &V1 = A1[i];
571     const BitValue &V2 = A2[i];
572     if (V1.is(1))
573       Res[i] = BitValue::ref(V2);
574     else if (V2.is(1))
575       Res[i] = BitValue::ref(V1);
576     else if (V1.is(0) || V2.is(0))
577       Res[i] = BitValue::Zero;
578     else if (V1 == V2)
579       Res[i] = V1;
580     else
581       Res[i] = BitValue::self();
582   }
583   return Res;
584 }
585 
586 
587 BT::RegisterCell BT::MachineEvaluator::eORL(const RegisterCell &A1,
588       const RegisterCell &A2) const {
589   uint16_t W = A1.width();
590   assert(W == A2.width());
591   RegisterCell Res(W);
592   for (uint16_t i = 0; i < W; ++i) {
593     const BitValue &V1 = A1[i];
594     const BitValue &V2 = A2[i];
595     if (V1.is(1) || V2.is(1))
596       Res[i] = BitValue::One;
597     else if (V1.is(0))
598       Res[i] = BitValue::ref(V2);
599     else if (V2.is(0))
600       Res[i] = BitValue::ref(V1);
601     else if (V1 == V2)
602       Res[i] = V1;
603     else
604       Res[i] = BitValue::self();
605   }
606   return Res;
607 }
608 
609 
610 BT::RegisterCell BT::MachineEvaluator::eXOR(const RegisterCell &A1,
611       const RegisterCell &A2) const {
612   uint16_t W = A1.width();
613   assert(W == A2.width());
614   RegisterCell Res(W);
615   for (uint16_t i = 0; i < W; ++i) {
616     const BitValue &V1 = A1[i];
617     const BitValue &V2 = A2[i];
618     if (V1.is(0))
619       Res[i] = BitValue::ref(V2);
620     else if (V2.is(0))
621       Res[i] = BitValue::ref(V1);
622     else if (V1 == V2)
623       Res[i] = BitValue::Zero;
624     else
625       Res[i] = BitValue::self();
626   }
627   return Res;
628 }
629 
630 
631 BT::RegisterCell BT::MachineEvaluator::eNOT(const RegisterCell &A1) const {
632   uint16_t W = A1.width();
633   RegisterCell Res(W);
634   for (uint16_t i = 0; i < W; ++i) {
635     const BitValue &V = A1[i];
636     if (V.is(0))
637       Res[i] = BitValue::One;
638     else if (V.is(1))
639       Res[i] = BitValue::Zero;
640     else
641       Res[i] = BitValue::self();
642   }
643   return Res;
644 }
645 
646 
647 BT::RegisterCell BT::MachineEvaluator::eSET(const RegisterCell &A1,
648       uint16_t BitN) const {
649   assert(BitN < A1.width());
650   RegisterCell Res = RegisterCell::ref(A1);
651   Res[BitN] = BitValue::One;
652   return Res;
653 }
654 
655 
656 BT::RegisterCell BT::MachineEvaluator::eCLR(const RegisterCell &A1,
657       uint16_t BitN) const {
658   assert(BitN < A1.width());
659   RegisterCell Res = RegisterCell::ref(A1);
660   Res[BitN] = BitValue::Zero;
661   return Res;
662 }
663 
664 
665 BT::RegisterCell BT::MachineEvaluator::eCLB(const RegisterCell &A1, bool B,
666       uint16_t W) const {
667   uint16_t C = A1.cl(B), AW = A1.width();
668   // If the last leading non-B bit is not a constant, then we don't know
669   // the real count.
670   if ((C < AW && A1[AW-1-C].num()) || C == AW)
671     return eIMM(C, W);
672   return RegisterCell::self(0, W);
673 }
674 
675 
676 BT::RegisterCell BT::MachineEvaluator::eCTB(const RegisterCell &A1, bool B,
677       uint16_t W) const {
678   uint16_t C = A1.ct(B), AW = A1.width();
679   // If the last trailing non-B bit is not a constant, then we don't know
680   // the real count.
681   if ((C < AW && A1[C].num()) || C == AW)
682     return eIMM(C, W);
683   return RegisterCell::self(0, W);
684 }
685 
686 
687 BT::RegisterCell BT::MachineEvaluator::eSXT(const RegisterCell &A1,
688       uint16_t FromN) const {
689   uint16_t W = A1.width();
690   assert(FromN <= W);
691   RegisterCell Res = RegisterCell::ref(A1);
692   BitValue Sign = Res[FromN-1];
693   // Sign-extend "inreg".
694   Res.fill(FromN, W, Sign);
695   return Res;
696 }
697 
698 
699 BT::RegisterCell BT::MachineEvaluator::eZXT(const RegisterCell &A1,
700       uint16_t FromN) const {
701   uint16_t W = A1.width();
702   assert(FromN <= W);
703   RegisterCell Res = RegisterCell::ref(A1);
704   Res.fill(FromN, W, BitValue::Zero);
705   return Res;
706 }
707 
708 
709 BT::RegisterCell BT::MachineEvaluator::eXTR(const RegisterCell &A1,
710       uint16_t B, uint16_t E) const {
711   uint16_t W = A1.width();
712   assert(B < W && E <= W);
713   if (B == E)
714     return RegisterCell(0);
715   uint16_t Last = (E > 0) ? E-1 : W-1;
716   RegisterCell Res = RegisterCell::ref(A1).extract(BT::BitMask(B, Last));
717   // Return shorter cell.
718   return Res;
719 }
720 
721 
722 BT::RegisterCell BT::MachineEvaluator::eINS(const RegisterCell &A1,
723       const RegisterCell &A2, uint16_t AtN) const {
724   uint16_t W1 = A1.width(), W2 = A2.width();
725   (void)W1;
726   assert(AtN < W1 && AtN+W2 <= W1);
727   // Copy bits from A1, insert A2 at position AtN.
728   RegisterCell Res = RegisterCell::ref(A1);
729   if (W2 > 0)
730     Res.insert(RegisterCell::ref(A2), BT::BitMask(AtN, AtN+W2-1));
731   return Res;
732 }
733 
734 
735 BT::BitMask BT::MachineEvaluator::mask(unsigned Reg, unsigned Sub) const {
736   assert(Sub == 0 && "Generic BitTracker::mask called for Sub != 0");
737   uint16_t W = getRegBitWidth(Reg);
738   assert(W > 0 && "Cannot generate mask for empty register");
739   return BitMask(0, W-1);
740 }
741 
742 bool BT::MachineEvaluator::evaluate(const MachineInstr &MI,
743                                     const CellMapType &Inputs,
744                                     CellMapType &Outputs) const {
745   unsigned Opc = MI.getOpcode();
746   switch (Opc) {
747     case TargetOpcode::REG_SEQUENCE: {
748       RegisterRef RD = MI.getOperand(0);
749       assert(RD.Sub == 0);
750       RegisterRef RS = MI.getOperand(1);
751       unsigned SS = MI.getOperand(2).getImm();
752       RegisterRef RT = MI.getOperand(3);
753       unsigned ST = MI.getOperand(4).getImm();
754       assert(SS != ST);
755 
756       uint16_t W = getRegBitWidth(RD);
757       RegisterCell Res(W);
758       Res.insert(RegisterCell::ref(getCell(RS, Inputs)), mask(RD.Reg, SS));
759       Res.insert(RegisterCell::ref(getCell(RT, Inputs)), mask(RD.Reg, ST));
760       putCell(RD, Res, Outputs);
761       break;
762     }
763 
764     case TargetOpcode::COPY: {
765       // COPY can transfer a smaller register into a wider one.
766       // If that is the case, fill the remaining high bits with 0.
767       RegisterRef RD = MI.getOperand(0);
768       RegisterRef RS = MI.getOperand(1);
769       assert(RD.Sub == 0);
770       uint16_t WD = getRegBitWidth(RD);
771       uint16_t WS = getRegBitWidth(RS);
772       assert(WD >= WS);
773       RegisterCell Src = getCell(RS, Inputs);
774       RegisterCell Res(WD);
775       Res.insert(Src, BitMask(0, WS-1));
776       Res.fill(WS, WD, BitValue::Zero);
777       putCell(RD, Res, Outputs);
778       break;
779     }
780 
781     default:
782       return false;
783   }
784 
785   return true;
786 }
787 
788 
789 // Main W-Z implementation.
790 
791 void BT::visitPHI(const MachineInstr &PI) {
792   int ThisN = PI.getParent()->getNumber();
793   if (Trace)
794     dbgs() << "Visit FI(BB#" << ThisN << "): " << PI;
795 
796   const MachineOperand &MD = PI.getOperand(0);
797   assert(MD.getSubReg() == 0 && "Unexpected sub-register in definition");
798   RegisterRef DefRR(MD);
799   uint16_t DefBW = ME.getRegBitWidth(DefRR);
800 
801   RegisterCell DefC = ME.getCell(DefRR, Map);
802   if (DefC == RegisterCell::self(DefRR.Reg, DefBW))    // XXX slow
803     return;
804 
805   bool Changed = false;
806 
807   for (unsigned i = 1, n = PI.getNumOperands(); i < n; i += 2) {
808     const MachineBasicBlock *PB = PI.getOperand(i + 1).getMBB();
809     int PredN = PB->getNumber();
810     if (Trace)
811       dbgs() << "  edge BB#" << PredN << "->BB#" << ThisN;
812     if (!EdgeExec.count(CFGEdge(PredN, ThisN))) {
813       if (Trace)
814         dbgs() << " not executable\n";
815       continue;
816     }
817 
818     RegisterRef RU = PI.getOperand(i);
819     RegisterCell ResC = ME.getCell(RU, Map);
820     if (Trace)
821       dbgs() << " input reg: " << PrintReg(RU.Reg, &ME.TRI, RU.Sub)
822              << " cell: " << ResC << "\n";
823     Changed |= DefC.meet(ResC, DefRR.Reg);
824   }
825 
826   if (Changed) {
827     if (Trace)
828       dbgs() << "Output: " << PrintReg(DefRR.Reg, &ME.TRI, DefRR.Sub)
829              << " cell: " << DefC << "\n";
830     ME.putCell(DefRR, DefC, Map);
831     visitUsesOf(DefRR.Reg);
832   }
833 }
834 
835 void BT::visitNonBranch(const MachineInstr &MI) {
836   if (Trace) {
837     int ThisN = MI.getParent()->getNumber();
838     dbgs() << "Visit MI(BB#" << ThisN << "): " << MI;
839   }
840   if (MI.isDebugValue())
841     return;
842   assert(!MI.isBranch() && "Unexpected branch instruction");
843 
844   CellMapType ResMap;
845   bool Eval = ME.evaluate(MI, Map, ResMap);
846 
847   if (Trace && Eval) {
848     for (unsigned i = 0, n = MI.getNumOperands(); i < n; ++i) {
849       const MachineOperand &MO = MI.getOperand(i);
850       if (!MO.isReg() || !MO.isUse())
851         continue;
852       RegisterRef RU(MO);
853       dbgs() << "  input reg: " << PrintReg(RU.Reg, &ME.TRI, RU.Sub)
854              << " cell: " << ME.getCell(RU, Map) << "\n";
855     }
856     dbgs() << "Outputs:\n";
857     for (CellMapType::iterator I = ResMap.begin(), E = ResMap.end();
858          I != E; ++I) {
859       RegisterRef RD(I->first);
860       dbgs() << "  " << PrintReg(I->first, &ME.TRI) << " cell: "
861              << ME.getCell(RD, ResMap) << "\n";
862     }
863   }
864 
865   // Iterate over all definitions of the instruction, and update the
866   // cells accordingly.
867   for (unsigned i = 0, n = MI.getNumOperands(); i < n; ++i) {
868     const MachineOperand &MO = MI.getOperand(i);
869     // Visit register defs only.
870     if (!MO.isReg() || !MO.isDef())
871       continue;
872     RegisterRef RD(MO);
873     assert(RD.Sub == 0 && "Unexpected sub-register in definition");
874     if (!TargetRegisterInfo::isVirtualRegister(RD.Reg))
875       continue;
876 
877     bool Changed = false;
878     if (!Eval || ResMap.count(RD.Reg) == 0) {
879       // Set to "ref" (aka "bottom").
880       uint16_t DefBW = ME.getRegBitWidth(RD);
881       RegisterCell RefC = RegisterCell::self(RD.Reg, DefBW);
882       if (RefC != ME.getCell(RD, Map)) {
883         ME.putCell(RD, RefC, Map);
884         Changed = true;
885       }
886     } else {
887       RegisterCell DefC = ME.getCell(RD, Map);
888       RegisterCell ResC = ME.getCell(RD, ResMap);
889       // This is a non-phi instruction, so the values of the inputs come
890       // from the same registers each time this instruction is evaluated.
891       // During the propagation, the values of the inputs can become lowered
892       // in the sense of the lattice operation, which may cause different
893       // results to be calculated in subsequent evaluations. This should
894       // not cause the bottoming of the result in the map, since the new
895       // result is already reflecting the lowered inputs.
896       for (uint16_t i = 0, w = DefC.width(); i < w; ++i) {
897         BitValue &V = DefC[i];
898         // Bits that are already "bottom" should not be updated.
899         if (V.Type == BitValue::Ref && V.RefI.Reg == RD.Reg)
900           continue;
901         // Same for those that are identical in DefC and ResC.
902         if (V == ResC[i])
903           continue;
904         V = ResC[i];
905         Changed = true;
906       }
907       if (Changed)
908         ME.putCell(RD, DefC, Map);
909     }
910     if (Changed)
911       visitUsesOf(RD.Reg);
912   }
913 }
914 
915 void BT::visitBranchesFrom(const MachineInstr &BI) {
916   const MachineBasicBlock &B = *BI.getParent();
917   MachineBasicBlock::const_iterator It = BI, End = B.end();
918   BranchTargetList Targets, BTs;
919   bool FallsThrough = true, DefaultToAll = false;
920   int ThisN = B.getNumber();
921 
922   do {
923     BTs.clear();
924     const MachineInstr &MI = *It;
925     if (Trace)
926       dbgs() << "Visit BR(BB#" << ThisN << "): " << MI;
927     assert(MI.isBranch() && "Expecting branch instruction");
928     InstrExec.insert(&MI);
929     bool Eval = ME.evaluate(MI, Map, BTs, FallsThrough);
930     if (!Eval) {
931       // If the evaluation failed, we will add all targets. Keep going in
932       // the loop to mark all executable branches as such.
933       DefaultToAll = true;
934       FallsThrough = true;
935       if (Trace)
936         dbgs() << "  failed to evaluate: will add all CFG successors\n";
937     } else if (!DefaultToAll) {
938       // If evaluated successfully add the targets to the cumulative list.
939       if (Trace) {
940         dbgs() << "  adding targets:";
941         for (unsigned i = 0, n = BTs.size(); i < n; ++i)
942           dbgs() << " BB#" << BTs[i]->getNumber();
943         if (FallsThrough)
944           dbgs() << "\n  falls through\n";
945         else
946           dbgs() << "\n  does not fall through\n";
947       }
948       Targets.insert(BTs.begin(), BTs.end());
949     }
950     ++It;
951   } while (FallsThrough && It != End);
952 
953   typedef MachineBasicBlock::const_succ_iterator succ_iterator;
954   if (!DefaultToAll) {
955     // Need to add all CFG successors that lead to EH landing pads.
956     // There won't be explicit branches to these blocks, but they must
957     // be processed.
958     for (succ_iterator I = B.succ_begin(), E = B.succ_end(); I != E; ++I) {
959       const MachineBasicBlock *SB = *I;
960       if (SB->isEHPad())
961         Targets.insert(SB);
962     }
963     if (FallsThrough) {
964       MachineFunction::const_iterator BIt = B.getIterator();
965       MachineFunction::const_iterator Next = std::next(BIt);
966       if (Next != MF.end())
967         Targets.insert(&*Next);
968     }
969   } else {
970     for (succ_iterator I = B.succ_begin(), E = B.succ_end(); I != E; ++I)
971       Targets.insert(*I);
972   }
973 
974   for (unsigned i = 0, n = Targets.size(); i < n; ++i) {
975     int TargetN = Targets[i]->getNumber();
976     FlowQ.push(CFGEdge(ThisN, TargetN));
977   }
978 }
979 
980 
981 void BT::visitUsesOf(unsigned Reg) {
982   if (Trace)
983     dbgs() << "visiting uses of " << PrintReg(Reg, &ME.TRI) << "\n";
984 
985   typedef MachineRegisterInfo::use_nodbg_iterator use_iterator;
986   use_iterator End = MRI.use_nodbg_end();
987   for (use_iterator I = MRI.use_nodbg_begin(Reg); I != End; ++I) {
988     MachineInstr *UseI = I->getParent();
989     if (!InstrExec.count(UseI))
990       continue;
991     if (UseI->isPHI())
992       visitPHI(*UseI);
993     else if (!UseI->isBranch())
994       visitNonBranch(*UseI);
995     else
996       visitBranchesFrom(*UseI);
997   }
998 }
999 
1000 
1001 BT::RegisterCell BT::get(RegisterRef RR) const {
1002   return ME.getCell(RR, Map);
1003 }
1004 
1005 
1006 void BT::put(RegisterRef RR, const RegisterCell &RC) {
1007   ME.putCell(RR, RC, Map);
1008 }
1009 
1010 
1011 // Replace all references to bits from OldRR with the corresponding bits
1012 // in NewRR.
1013 void BT::subst(RegisterRef OldRR, RegisterRef NewRR) {
1014   assert(Map.count(OldRR.Reg) > 0 && "OldRR not present in map");
1015   BitMask OM = ME.mask(OldRR.Reg, OldRR.Sub);
1016   BitMask NM = ME.mask(NewRR.Reg, NewRR.Sub);
1017   uint16_t OMB = OM.first(), OME = OM.last();
1018   uint16_t NMB = NM.first(), NME = NM.last();
1019   (void)NME;
1020   assert((OME-OMB == NME-NMB) &&
1021          "Substituting registers of different lengths");
1022   for (CellMapType::iterator I = Map.begin(), E = Map.end(); I != E; ++I) {
1023     RegisterCell &RC = I->second;
1024     for (uint16_t i = 0, w = RC.width(); i < w; ++i) {
1025       BitValue &V = RC[i];
1026       if (V.Type != BitValue::Ref || V.RefI.Reg != OldRR.Reg)
1027         continue;
1028       if (V.RefI.Pos < OMB || V.RefI.Pos > OME)
1029         continue;
1030       V.RefI.Reg = NewRR.Reg;
1031       V.RefI.Pos += NMB-OMB;
1032     }
1033   }
1034 }
1035 
1036 
1037 // Check if the block has been "executed" during propagation. (If not, the
1038 // block is dead, but it may still appear to be reachable.)
1039 bool BT::reached(const MachineBasicBlock *B) const {
1040   int BN = B->getNumber();
1041   assert(BN >= 0);
1042   for (EdgeSetType::iterator I = EdgeExec.begin(), E = EdgeExec.end();
1043        I != E; ++I) {
1044     if (I->second == BN)
1045       return true;
1046   }
1047   return false;
1048 }
1049 
1050 
1051 // Visit an individual instruction. This could be a newly added instruction,
1052 // or one that has been modified by an optimization.
1053 void BT::visit(const MachineInstr &MI) {
1054   assert(!MI.isBranch() && "Only non-branches are allowed");
1055   InstrExec.insert(&MI);
1056   visitNonBranch(MI);
1057   // The call to visitNonBranch could propagate the changes until a branch
1058   // is actually visited. This could result in adding CFG edges to the flow
1059   // queue. Since the queue won't be processed, clear it.
1060   while (!FlowQ.empty())
1061     FlowQ.pop();
1062 }
1063 
1064 
1065 void BT::reset() {
1066   EdgeExec.clear();
1067   InstrExec.clear();
1068   Map.clear();
1069 }
1070 
1071 
1072 void BT::run() {
1073   reset();
1074   assert(FlowQ.empty());
1075 
1076   typedef GraphTraits<const MachineFunction*> MachineFlowGraphTraits;
1077   const MachineBasicBlock *Entry = MachineFlowGraphTraits::getEntryNode(&MF);
1078 
1079   unsigned MaxBN = 0;
1080   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
1081        I != E; ++I) {
1082     assert(I->getNumber() >= 0 && "Disconnected block");
1083     unsigned BN = I->getNumber();
1084     if (BN > MaxBN)
1085       MaxBN = BN;
1086   }
1087 
1088   // Keep track of visited blocks.
1089   BitVector BlockScanned(MaxBN+1);
1090 
1091   int EntryN = Entry->getNumber();
1092   // Generate a fake edge to get something to start with.
1093   FlowQ.push(CFGEdge(-1, EntryN));
1094 
1095   while (!FlowQ.empty()) {
1096     CFGEdge Edge = FlowQ.front();
1097     FlowQ.pop();
1098 
1099     if (EdgeExec.count(Edge))
1100       continue;
1101     EdgeExec.insert(Edge);
1102 
1103     const MachineBasicBlock &B = *MF.getBlockNumbered(Edge.second);
1104     MachineBasicBlock::const_iterator It = B.begin(), End = B.end();
1105     // Visit PHI nodes first.
1106     while (It != End && It->isPHI()) {
1107       const MachineInstr &PI = *It++;
1108       InstrExec.insert(&PI);
1109       visitPHI(PI);
1110     }
1111 
1112     // If this block has already been visited through a flow graph edge,
1113     // then the instructions have already been processed. Any updates to
1114     // the cells would now only happen through visitUsesOf...
1115     if (BlockScanned[Edge.second])
1116       continue;
1117     BlockScanned[Edge.second] = true;
1118 
1119     // Visit non-branch instructions.
1120     while (It != End && !It->isBranch()) {
1121       const MachineInstr &MI = *It++;
1122       InstrExec.insert(&MI);
1123       visitNonBranch(MI);
1124     }
1125     // If block end has been reached, add the fall-through edge to the queue.
1126     if (It == End) {
1127       MachineFunction::const_iterator BIt = B.getIterator();
1128       MachineFunction::const_iterator Next = std::next(BIt);
1129       if (Next != MF.end() && B.isSuccessor(&*Next)) {
1130         int ThisN = B.getNumber();
1131         int NextN = Next->getNumber();
1132         FlowQ.push(CFGEdge(ThisN, NextN));
1133       }
1134     } else {
1135       // Handle the remaining sequence of branches. This function will update
1136       // the work queue.
1137       visitBranchesFrom(*It);
1138     }
1139   } // while (!FlowQ->empty())
1140 
1141   if (Trace)
1142     print_cells(dbgs() << "Cells after propagation:\n");
1143 }
1144 
1145