1 //===- HexagonBitSimplify.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 #include "BitTracker.h"
11 #include "HexagonBitTracker.h"
12 #include "HexagonInstrInfo.h"
13 #include "HexagonRegisterInfo.h"
14 #include "HexagonSubtarget.h"
15 #include "llvm/ADT/BitVector.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/GraphTraits.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/CodeGen/MachineBasicBlock.h"
22 #include "llvm/CodeGen/MachineDominators.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineFunctionPass.h"
25 #include "llvm/CodeGen/MachineInstr.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineOperand.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/IR/DebugLoc.h"
30 #include "llvm/MC/MCInstrDesc.h"
31 #include "llvm/Pass.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Compiler.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include <algorithm>
40 #include <cassert>
41 #include <cstdint>
42 #include <iterator>
43 #include <limits>
44 #include <utility>
45 #include <vector>
46 
47 #define DEBUG_TYPE "hexbit"
48 
49 using namespace llvm;
50 
51 static cl::opt<bool> PreserveTiedOps("hexbit-keep-tied", cl::Hidden,
52   cl::init(true), cl::desc("Preserve subregisters in tied operands"));
53 static cl::opt<bool> GenExtract("hexbit-extract", cl::Hidden,
54   cl::init(true), cl::desc("Generate extract instructions"));
55 static cl::opt<bool> GenBitSplit("hexbit-bitsplit", cl::Hidden,
56   cl::init(true), cl::desc("Generate bitsplit instructions"));
57 
58 static cl::opt<unsigned> MaxExtract("hexbit-max-extract", cl::Hidden,
59   cl::init(std::numeric_limits<unsigned>::max()));
60 static unsigned CountExtract = 0;
61 static cl::opt<unsigned> MaxBitSplit("hexbit-max-bitsplit", cl::Hidden,
62   cl::init(std::numeric_limits<unsigned>::max()));
63 static unsigned CountBitSplit = 0;
64 
65 namespace llvm {
66 
67   void initializeHexagonBitSimplifyPass(PassRegistry& Registry);
68   FunctionPass *createHexagonBitSimplify();
69 
70 } // end namespace llvm
71 
72 namespace {
73 
74   // Set of virtual registers, based on BitVector.
75   struct RegisterSet : private BitVector {
76     RegisterSet() = default;
77     explicit RegisterSet(unsigned s, bool t = false) : BitVector(s, t) {}
78     RegisterSet(const RegisterSet &RS) = default;
79 
80     using BitVector::clear;
81     using BitVector::count;
82 
83     unsigned find_first() const {
84       int First = BitVector::find_first();
85       if (First < 0)
86         return 0;
87       return x2v(First);
88     }
89 
90     unsigned find_next(unsigned Prev) const {
91       int Next = BitVector::find_next(v2x(Prev));
92       if (Next < 0)
93         return 0;
94       return x2v(Next);
95     }
96 
97     RegisterSet &insert(unsigned R) {
98       unsigned Idx = v2x(R);
99       ensure(Idx);
100       return static_cast<RegisterSet&>(BitVector::set(Idx));
101     }
102     RegisterSet &remove(unsigned R) {
103       unsigned Idx = v2x(R);
104       if (Idx >= size())
105         return *this;
106       return static_cast<RegisterSet&>(BitVector::reset(Idx));
107     }
108 
109     RegisterSet &insert(const RegisterSet &Rs) {
110       return static_cast<RegisterSet&>(BitVector::operator|=(Rs));
111     }
112     RegisterSet &remove(const RegisterSet &Rs) {
113       return static_cast<RegisterSet&>(BitVector::reset(Rs));
114     }
115 
116     reference operator[](unsigned R) {
117       unsigned Idx = v2x(R);
118       ensure(Idx);
119       return BitVector::operator[](Idx);
120     }
121     bool operator[](unsigned R) const {
122       unsigned Idx = v2x(R);
123       assert(Idx < size());
124       return BitVector::operator[](Idx);
125     }
126     bool has(unsigned R) const {
127       unsigned Idx = v2x(R);
128       if (Idx >= size())
129         return false;
130       return BitVector::test(Idx);
131     }
132 
133     bool empty() const {
134       return !BitVector::any();
135     }
136     bool includes(const RegisterSet &Rs) const {
137       // A.BitVector::test(B)  <=>  A-B != {}
138       return !Rs.BitVector::test(*this);
139     }
140     bool intersects(const RegisterSet &Rs) const {
141       return BitVector::anyCommon(Rs);
142     }
143 
144   private:
145     void ensure(unsigned Idx) {
146       if (size() <= Idx)
147         resize(std::max(Idx+1, 32U));
148     }
149 
150     static inline unsigned v2x(unsigned v) {
151       return TargetRegisterInfo::virtReg2Index(v);
152     }
153 
154     static inline unsigned x2v(unsigned x) {
155       return TargetRegisterInfo::index2VirtReg(x);
156     }
157   };
158 
159   struct PrintRegSet {
160     PrintRegSet(const RegisterSet &S, const TargetRegisterInfo *RI)
161       : RS(S), TRI(RI) {}
162 
163     friend raw_ostream &operator<< (raw_ostream &OS,
164           const PrintRegSet &P);
165 
166   private:
167     const RegisterSet &RS;
168     const TargetRegisterInfo *TRI;
169   };
170 
171   raw_ostream &operator<< (raw_ostream &OS, const PrintRegSet &P)
172     LLVM_ATTRIBUTE_UNUSED;
173   raw_ostream &operator<< (raw_ostream &OS, const PrintRegSet &P) {
174     OS << '{';
175     for (unsigned R = P.RS.find_first(); R; R = P.RS.find_next(R))
176       OS << ' ' << PrintReg(R, P.TRI);
177     OS << " }";
178     return OS;
179   }
180 
181   class Transformation;
182 
183   class HexagonBitSimplify : public MachineFunctionPass {
184   public:
185     static char ID;
186 
187     HexagonBitSimplify() : MachineFunctionPass(ID) {
188       initializeHexagonBitSimplifyPass(*PassRegistry::getPassRegistry());
189     }
190 
191     StringRef getPassName() const override {
192       return "Hexagon bit simplification";
193     }
194 
195     void getAnalysisUsage(AnalysisUsage &AU) const override {
196       AU.addRequired<MachineDominatorTree>();
197       AU.addPreserved<MachineDominatorTree>();
198       MachineFunctionPass::getAnalysisUsage(AU);
199     }
200 
201     bool runOnMachineFunction(MachineFunction &MF) override;
202 
203     static void getInstrDefs(const MachineInstr &MI, RegisterSet &Defs);
204     static void getInstrUses(const MachineInstr &MI, RegisterSet &Uses);
205     static bool isEqual(const BitTracker::RegisterCell &RC1, uint16_t B1,
206         const BitTracker::RegisterCell &RC2, uint16_t B2, uint16_t W);
207     static bool isZero(const BitTracker::RegisterCell &RC, uint16_t B,
208         uint16_t W);
209     static bool getConst(const BitTracker::RegisterCell &RC, uint16_t B,
210         uint16_t W, uint64_t &U);
211     static bool replaceReg(unsigned OldR, unsigned NewR,
212         MachineRegisterInfo &MRI);
213     static bool getSubregMask(const BitTracker::RegisterRef &RR,
214         unsigned &Begin, unsigned &Width, MachineRegisterInfo &MRI);
215     static bool replaceRegWithSub(unsigned OldR, unsigned NewR,
216         unsigned NewSR, MachineRegisterInfo &MRI);
217     static bool replaceSubWithSub(unsigned OldR, unsigned OldSR,
218         unsigned NewR, unsigned NewSR, MachineRegisterInfo &MRI);
219     static bool parseRegSequence(const MachineInstr &I,
220         BitTracker::RegisterRef &SL, BitTracker::RegisterRef &SH,
221         const MachineRegisterInfo &MRI);
222 
223     static bool getUsedBitsInStore(unsigned Opc, BitVector &Bits,
224         uint16_t Begin);
225     static bool getUsedBits(unsigned Opc, unsigned OpN, BitVector &Bits,
226         uint16_t Begin, const HexagonInstrInfo &HII);
227 
228     static const TargetRegisterClass *getFinalVRegClass(
229         const BitTracker::RegisterRef &RR, MachineRegisterInfo &MRI);
230     static bool isTransparentCopy(const BitTracker::RegisterRef &RD,
231         const BitTracker::RegisterRef &RS, MachineRegisterInfo &MRI);
232 
233   private:
234     MachineDominatorTree *MDT = nullptr;
235 
236     bool visitBlock(MachineBasicBlock &B, Transformation &T, RegisterSet &AVs);
237     static bool hasTiedUse(unsigned Reg, MachineRegisterInfo &MRI,
238         unsigned NewSub = Hexagon::NoSubRegister);
239   };
240 
241   using HBS = HexagonBitSimplify;
242 
243   // The purpose of this class is to provide a common facility to traverse
244   // the function top-down or bottom-up via the dominator tree, and keep
245   // track of the available registers.
246   class Transformation {
247   public:
248     bool TopDown;
249 
250     Transformation(bool TD) : TopDown(TD) {}
251     virtual ~Transformation() = default;
252 
253     virtual bool processBlock(MachineBasicBlock &B, const RegisterSet &AVs) = 0;
254   };
255 
256 } // end anonymous namespace
257 
258 char HexagonBitSimplify::ID = 0;
259 
260 INITIALIZE_PASS_BEGIN(HexagonBitSimplify, "hexbit",
261       "Hexagon bit simplification", false, false)
262 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
263 INITIALIZE_PASS_END(HexagonBitSimplify, "hexbit",
264       "Hexagon bit simplification", false, false)
265 
266 bool HexagonBitSimplify::visitBlock(MachineBasicBlock &B, Transformation &T,
267       RegisterSet &AVs) {
268   bool Changed = false;
269 
270   if (T.TopDown)
271     Changed = T.processBlock(B, AVs);
272 
273   RegisterSet Defs;
274   for (auto &I : B)
275     getInstrDefs(I, Defs);
276   RegisterSet NewAVs = AVs;
277   NewAVs.insert(Defs);
278 
279   for (auto *DTN : children<MachineDomTreeNode*>(MDT->getNode(&B)))
280     Changed |= visitBlock(*(DTN->getBlock()), T, NewAVs);
281 
282   if (!T.TopDown)
283     Changed |= T.processBlock(B, AVs);
284 
285   return Changed;
286 }
287 
288 //
289 // Utility functions:
290 //
291 void HexagonBitSimplify::getInstrDefs(const MachineInstr &MI,
292       RegisterSet &Defs) {
293   for (auto &Op : MI.operands()) {
294     if (!Op.isReg() || !Op.isDef())
295       continue;
296     unsigned R = Op.getReg();
297     if (!TargetRegisterInfo::isVirtualRegister(R))
298       continue;
299     Defs.insert(R);
300   }
301 }
302 
303 void HexagonBitSimplify::getInstrUses(const MachineInstr &MI,
304       RegisterSet &Uses) {
305   for (auto &Op : MI.operands()) {
306     if (!Op.isReg() || !Op.isUse())
307       continue;
308     unsigned R = Op.getReg();
309     if (!TargetRegisterInfo::isVirtualRegister(R))
310       continue;
311     Uses.insert(R);
312   }
313 }
314 
315 // Check if all the bits in range [B, E) in both cells are equal.
316 bool HexagonBitSimplify::isEqual(const BitTracker::RegisterCell &RC1,
317       uint16_t B1, const BitTracker::RegisterCell &RC2, uint16_t B2,
318       uint16_t W) {
319   for (uint16_t i = 0; i < W; ++i) {
320     // If RC1[i] is "bottom", it cannot be proven equal to RC2[i].
321     if (RC1[B1+i].Type == BitTracker::BitValue::Ref && RC1[B1+i].RefI.Reg == 0)
322       return false;
323     // Same for RC2[i].
324     if (RC2[B2+i].Type == BitTracker::BitValue::Ref && RC2[B2+i].RefI.Reg == 0)
325       return false;
326     if (RC1[B1+i] != RC2[B2+i])
327       return false;
328   }
329   return true;
330 }
331 
332 bool HexagonBitSimplify::isZero(const BitTracker::RegisterCell &RC,
333       uint16_t B, uint16_t W) {
334   assert(B < RC.width() && B+W <= RC.width());
335   for (uint16_t i = B; i < B+W; ++i)
336     if (!RC[i].is(0))
337       return false;
338   return true;
339 }
340 
341 bool HexagonBitSimplify::getConst(const BitTracker::RegisterCell &RC,
342         uint16_t B, uint16_t W, uint64_t &U) {
343   assert(B < RC.width() && B+W <= RC.width());
344   int64_t T = 0;
345   for (uint16_t i = B+W; i > B; --i) {
346     const BitTracker::BitValue &BV = RC[i-1];
347     T <<= 1;
348     if (BV.is(1))
349       T |= 1;
350     else if (!BV.is(0))
351       return false;
352   }
353   U = T;
354   return true;
355 }
356 
357 bool HexagonBitSimplify::replaceReg(unsigned OldR, unsigned NewR,
358       MachineRegisterInfo &MRI) {
359   if (!TargetRegisterInfo::isVirtualRegister(OldR) ||
360       !TargetRegisterInfo::isVirtualRegister(NewR))
361     return false;
362   auto Begin = MRI.use_begin(OldR), End = MRI.use_end();
363   decltype(End) NextI;
364   for (auto I = Begin; I != End; I = NextI) {
365     NextI = std::next(I);
366     I->setReg(NewR);
367   }
368   return Begin != End;
369 }
370 
371 bool HexagonBitSimplify::replaceRegWithSub(unsigned OldR, unsigned NewR,
372       unsigned NewSR, MachineRegisterInfo &MRI) {
373   if (!TargetRegisterInfo::isVirtualRegister(OldR) ||
374       !TargetRegisterInfo::isVirtualRegister(NewR))
375     return false;
376   if (hasTiedUse(OldR, MRI, NewSR))
377     return false;
378   auto Begin = MRI.use_begin(OldR), End = MRI.use_end();
379   decltype(End) NextI;
380   for (auto I = Begin; I != End; I = NextI) {
381     NextI = std::next(I);
382     I->setReg(NewR);
383     I->setSubReg(NewSR);
384   }
385   return Begin != End;
386 }
387 
388 bool HexagonBitSimplify::replaceSubWithSub(unsigned OldR, unsigned OldSR,
389       unsigned NewR, unsigned NewSR, MachineRegisterInfo &MRI) {
390   if (!TargetRegisterInfo::isVirtualRegister(OldR) ||
391       !TargetRegisterInfo::isVirtualRegister(NewR))
392     return false;
393   if (OldSR != NewSR && hasTiedUse(OldR, MRI, NewSR))
394     return false;
395   auto Begin = MRI.use_begin(OldR), End = MRI.use_end();
396   decltype(End) NextI;
397   for (auto I = Begin; I != End; I = NextI) {
398     NextI = std::next(I);
399     if (I->getSubReg() != OldSR)
400       continue;
401     I->setReg(NewR);
402     I->setSubReg(NewSR);
403   }
404   return Begin != End;
405 }
406 
407 // For a register ref (pair Reg:Sub), set Begin to the position of the LSB
408 // of Sub in Reg, and set Width to the size of Sub in bits. Return true,
409 // if this succeeded, otherwise return false.
410 bool HexagonBitSimplify::getSubregMask(const BitTracker::RegisterRef &RR,
411       unsigned &Begin, unsigned &Width, MachineRegisterInfo &MRI) {
412   const TargetRegisterClass *RC = MRI.getRegClass(RR.Reg);
413   if (RR.Sub == 0) {
414     Begin = 0;
415     Width = MRI.getTargetRegisterInfo()->getRegSizeInBits(*RC);
416     return true;
417   }
418 
419   Begin = 0;
420 
421   switch (RC->getID()) {
422     case Hexagon::DoubleRegsRegClassID:
423     case Hexagon::VecDblRegsRegClassID:
424     case Hexagon::VecDblRegs128BRegClassID:
425       Width = MRI.getTargetRegisterInfo()->getRegSizeInBits(*RC) / 2;
426       if (RR.Sub == Hexagon::isub_hi || RR.Sub == Hexagon::vsub_hi)
427         Begin = Width;
428       break;
429     default:
430       return false;
431   }
432   return true;
433 }
434 
435 
436 // For a REG_SEQUENCE, set SL to the low subregister and SH to the high
437 // subregister.
438 bool HexagonBitSimplify::parseRegSequence(const MachineInstr &I,
439       BitTracker::RegisterRef &SL, BitTracker::RegisterRef &SH,
440       const MachineRegisterInfo &MRI) {
441   assert(I.getOpcode() == TargetOpcode::REG_SEQUENCE);
442   unsigned Sub1 = I.getOperand(2).getImm(), Sub2 = I.getOperand(4).getImm();
443   auto *DstRC = MRI.getRegClass(I.getOperand(0).getReg());
444   auto &HRI = static_cast<const HexagonRegisterInfo&>(
445                   *MRI.getTargetRegisterInfo());
446   unsigned SubLo = HRI.getHexagonSubRegIndex(DstRC, Hexagon::ps_sub_lo);
447   unsigned SubHi = HRI.getHexagonSubRegIndex(DstRC, Hexagon::ps_sub_hi);
448   assert((Sub1 == SubLo && Sub2 == SubHi) || (Sub1 == SubHi && Sub2 == SubLo));
449   if (Sub1 == SubLo && Sub2 == SubHi) {
450     SL = I.getOperand(1);
451     SH = I.getOperand(3);
452     return true;
453   }
454   if (Sub1 == SubHi && Sub2 == SubLo) {
455     SH = I.getOperand(1);
456     SL = I.getOperand(3);
457     return true;
458   }
459   return false;
460 }
461 
462 // All stores (except 64-bit stores) take a 32-bit register as the source
463 // of the value to be stored. If the instruction stores into a location
464 // that is shorter than 32 bits, some bits of the source register are not
465 // used. For each store instruction, calculate the set of used bits in
466 // the source register, and set appropriate bits in Bits. Return true if
467 // the bits are calculated, false otherwise.
468 bool HexagonBitSimplify::getUsedBitsInStore(unsigned Opc, BitVector &Bits,
469       uint16_t Begin) {
470   using namespace Hexagon;
471 
472   switch (Opc) {
473     // Store byte
474     case S2_storerb_io:           // memb(Rs32+#s11:0)=Rt32
475     case S2_storerbnew_io:        // memb(Rs32+#s11:0)=Nt8.new
476     case S2_pstorerbt_io:         // if (Pv4) memb(Rs32+#u6:0)=Rt32
477     case S2_pstorerbf_io:         // if (!Pv4) memb(Rs32+#u6:0)=Rt32
478     case S4_pstorerbtnew_io:      // if (Pv4.new) memb(Rs32+#u6:0)=Rt32
479     case S4_pstorerbfnew_io:      // if (!Pv4.new) memb(Rs32+#u6:0)=Rt32
480     case S2_pstorerbnewt_io:      // if (Pv4) memb(Rs32+#u6:0)=Nt8.new
481     case S2_pstorerbnewf_io:      // if (!Pv4) memb(Rs32+#u6:0)=Nt8.new
482     case S4_pstorerbnewtnew_io:   // if (Pv4.new) memb(Rs32+#u6:0)=Nt8.new
483     case S4_pstorerbnewfnew_io:   // if (!Pv4.new) memb(Rs32+#u6:0)=Nt8.new
484     case S2_storerb_pi:           // memb(Rx32++#s4:0)=Rt32
485     case S2_storerbnew_pi:        // memb(Rx32++#s4:0)=Nt8.new
486     case S2_pstorerbt_pi:         // if (Pv4) memb(Rx32++#s4:0)=Rt32
487     case S2_pstorerbf_pi:         // if (!Pv4) memb(Rx32++#s4:0)=Rt32
488     case S2_pstorerbtnew_pi:      // if (Pv4.new) memb(Rx32++#s4:0)=Rt32
489     case S2_pstorerbfnew_pi:      // if (!Pv4.new) memb(Rx32++#s4:0)=Rt32
490     case S2_pstorerbnewt_pi:      // if (Pv4) memb(Rx32++#s4:0)=Nt8.new
491     case S2_pstorerbnewf_pi:      // if (!Pv4) memb(Rx32++#s4:0)=Nt8.new
492     case S2_pstorerbnewtnew_pi:   // if (Pv4.new) memb(Rx32++#s4:0)=Nt8.new
493     case S2_pstorerbnewfnew_pi:   // if (!Pv4.new) memb(Rx32++#s4:0)=Nt8.new
494     case S4_storerb_ap:           // memb(Re32=#U6)=Rt32
495     case S4_storerbnew_ap:        // memb(Re32=#U6)=Nt8.new
496     case S2_storerb_pr:           // memb(Rx32++Mu2)=Rt32
497     case S2_storerbnew_pr:        // memb(Rx32++Mu2)=Nt8.new
498     case S4_storerb_ur:           // memb(Ru32<<#u2+#U6)=Rt32
499     case S4_storerbnew_ur:        // memb(Ru32<<#u2+#U6)=Nt8.new
500     case S2_storerb_pbr:          // memb(Rx32++Mu2:brev)=Rt32
501     case S2_storerbnew_pbr:       // memb(Rx32++Mu2:brev)=Nt8.new
502     case S2_storerb_pci:          // memb(Rx32++#s4:0:circ(Mu2))=Rt32
503     case S2_storerbnew_pci:       // memb(Rx32++#s4:0:circ(Mu2))=Nt8.new
504     case S2_storerb_pcr:          // memb(Rx32++I:circ(Mu2))=Rt32
505     case S2_storerbnew_pcr:       // memb(Rx32++I:circ(Mu2))=Nt8.new
506     case S4_storerb_rr:           // memb(Rs32+Ru32<<#u2)=Rt32
507     case S4_storerbnew_rr:        // memb(Rs32+Ru32<<#u2)=Nt8.new
508     case S4_pstorerbt_rr:         // if (Pv4) memb(Rs32+Ru32<<#u2)=Rt32
509     case S4_pstorerbf_rr:         // if (!Pv4) memb(Rs32+Ru32<<#u2)=Rt32
510     case S4_pstorerbtnew_rr:      // if (Pv4.new) memb(Rs32+Ru32<<#u2)=Rt32
511     case S4_pstorerbfnew_rr:      // if (!Pv4.new) memb(Rs32+Ru32<<#u2)=Rt32
512     case S4_pstorerbnewt_rr:      // if (Pv4) memb(Rs32+Ru32<<#u2)=Nt8.new
513     case S4_pstorerbnewf_rr:      // if (!Pv4) memb(Rs32+Ru32<<#u2)=Nt8.new
514     case S4_pstorerbnewtnew_rr:   // if (Pv4.new) memb(Rs32+Ru32<<#u2)=Nt8.new
515     case S4_pstorerbnewfnew_rr:   // if (!Pv4.new) memb(Rs32+Ru32<<#u2)=Nt8.new
516     case S2_storerbgp:            // memb(gp+#u16:0)=Rt32
517     case S2_storerbnewgp:         // memb(gp+#u16:0)=Nt8.new
518     case S4_pstorerbt_abs:        // if (Pv4) memb(#u6)=Rt32
519     case S4_pstorerbf_abs:        // if (!Pv4) memb(#u6)=Rt32
520     case S4_pstorerbtnew_abs:     // if (Pv4.new) memb(#u6)=Rt32
521     case S4_pstorerbfnew_abs:     // if (!Pv4.new) memb(#u6)=Rt32
522     case S4_pstorerbnewt_abs:     // if (Pv4) memb(#u6)=Nt8.new
523     case S4_pstorerbnewf_abs:     // if (!Pv4) memb(#u6)=Nt8.new
524     case S4_pstorerbnewtnew_abs:  // if (Pv4.new) memb(#u6)=Nt8.new
525     case S4_pstorerbnewfnew_abs:  // if (!Pv4.new) memb(#u6)=Nt8.new
526       Bits.set(Begin, Begin+8);
527       return true;
528 
529     // Store low half
530     case S2_storerh_io:           // memh(Rs32+#s11:1)=Rt32
531     case S2_storerhnew_io:        // memh(Rs32+#s11:1)=Nt8.new
532     case S2_pstorerht_io:         // if (Pv4) memh(Rs32+#u6:1)=Rt32
533     case S2_pstorerhf_io:         // if (!Pv4) memh(Rs32+#u6:1)=Rt32
534     case S4_pstorerhtnew_io:      // if (Pv4.new) memh(Rs32+#u6:1)=Rt32
535     case S4_pstorerhfnew_io:      // if (!Pv4.new) memh(Rs32+#u6:1)=Rt32
536     case S2_pstorerhnewt_io:      // if (Pv4) memh(Rs32+#u6:1)=Nt8.new
537     case S2_pstorerhnewf_io:      // if (!Pv4) memh(Rs32+#u6:1)=Nt8.new
538     case S4_pstorerhnewtnew_io:   // if (Pv4.new) memh(Rs32+#u6:1)=Nt8.new
539     case S4_pstorerhnewfnew_io:   // if (!Pv4.new) memh(Rs32+#u6:1)=Nt8.new
540     case S2_storerh_pi:           // memh(Rx32++#s4:1)=Rt32
541     case S2_storerhnew_pi:        // memh(Rx32++#s4:1)=Nt8.new
542     case S2_pstorerht_pi:         // if (Pv4) memh(Rx32++#s4:1)=Rt32
543     case S2_pstorerhf_pi:         // if (!Pv4) memh(Rx32++#s4:1)=Rt32
544     case S2_pstorerhtnew_pi:      // if (Pv4.new) memh(Rx32++#s4:1)=Rt32
545     case S2_pstorerhfnew_pi:      // if (!Pv4.new) memh(Rx32++#s4:1)=Rt32
546     case S2_pstorerhnewt_pi:      // if (Pv4) memh(Rx32++#s4:1)=Nt8.new
547     case S2_pstorerhnewf_pi:      // if (!Pv4) memh(Rx32++#s4:1)=Nt8.new
548     case S2_pstorerhnewtnew_pi:   // if (Pv4.new) memh(Rx32++#s4:1)=Nt8.new
549     case S2_pstorerhnewfnew_pi:   // if (!Pv4.new) memh(Rx32++#s4:1)=Nt8.new
550     case S4_storerh_ap:           // memh(Re32=#U6)=Rt32
551     case S4_storerhnew_ap:        // memh(Re32=#U6)=Nt8.new
552     case S2_storerh_pr:           // memh(Rx32++Mu2)=Rt32
553     case S2_storerhnew_pr:        // memh(Rx32++Mu2)=Nt8.new
554     case S4_storerh_ur:           // memh(Ru32<<#u2+#U6)=Rt32
555     case S4_storerhnew_ur:        // memh(Ru32<<#u2+#U6)=Nt8.new
556     case S2_storerh_pbr:          // memh(Rx32++Mu2:brev)=Rt32
557     case S2_storerhnew_pbr:       // memh(Rx32++Mu2:brev)=Nt8.new
558     case S2_storerh_pci:          // memh(Rx32++#s4:1:circ(Mu2))=Rt32
559     case S2_storerhnew_pci:       // memh(Rx32++#s4:1:circ(Mu2))=Nt8.new
560     case S2_storerh_pcr:          // memh(Rx32++I:circ(Mu2))=Rt32
561     case S2_storerhnew_pcr:       // memh(Rx32++I:circ(Mu2))=Nt8.new
562     case S4_storerh_rr:           // memh(Rs32+Ru32<<#u2)=Rt32
563     case S4_pstorerht_rr:         // if (Pv4) memh(Rs32+Ru32<<#u2)=Rt32
564     case S4_pstorerhf_rr:         // if (!Pv4) memh(Rs32+Ru32<<#u2)=Rt32
565     case S4_pstorerhtnew_rr:      // if (Pv4.new) memh(Rs32+Ru32<<#u2)=Rt32
566     case S4_pstorerhfnew_rr:      // if (!Pv4.new) memh(Rs32+Ru32<<#u2)=Rt32
567     case S4_storerhnew_rr:        // memh(Rs32+Ru32<<#u2)=Nt8.new
568     case S4_pstorerhnewt_rr:      // if (Pv4) memh(Rs32+Ru32<<#u2)=Nt8.new
569     case S4_pstorerhnewf_rr:      // if (!Pv4) memh(Rs32+Ru32<<#u2)=Nt8.new
570     case S4_pstorerhnewtnew_rr:   // if (Pv4.new) memh(Rs32+Ru32<<#u2)=Nt8.new
571     case S4_pstorerhnewfnew_rr:   // if (!Pv4.new) memh(Rs32+Ru32<<#u2)=Nt8.new
572     case S2_storerhgp:            // memh(gp+#u16:1)=Rt32
573     case S2_storerhnewgp:         // memh(gp+#u16:1)=Nt8.new
574     case S4_pstorerht_abs:        // if (Pv4) memh(#u6)=Rt32
575     case S4_pstorerhf_abs:        // if (!Pv4) memh(#u6)=Rt32
576     case S4_pstorerhtnew_abs:     // if (Pv4.new) memh(#u6)=Rt32
577     case S4_pstorerhfnew_abs:     // if (!Pv4.new) memh(#u6)=Rt32
578     case S4_pstorerhnewt_abs:     // if (Pv4) memh(#u6)=Nt8.new
579     case S4_pstorerhnewf_abs:     // if (!Pv4) memh(#u6)=Nt8.new
580     case S4_pstorerhnewtnew_abs:  // if (Pv4.new) memh(#u6)=Nt8.new
581     case S4_pstorerhnewfnew_abs:  // if (!Pv4.new) memh(#u6)=Nt8.new
582       Bits.set(Begin, Begin+16);
583       return true;
584 
585     // Store high half
586     case S2_storerf_io:           // memh(Rs32+#s11:1)=Rt.H32
587     case S2_pstorerft_io:         // if (Pv4) memh(Rs32+#u6:1)=Rt.H32
588     case S2_pstorerff_io:         // if (!Pv4) memh(Rs32+#u6:1)=Rt.H32
589     case S4_pstorerftnew_io:      // if (Pv4.new) memh(Rs32+#u6:1)=Rt.H32
590     case S4_pstorerffnew_io:      // if (!Pv4.new) memh(Rs32+#u6:1)=Rt.H32
591     case S2_storerf_pi:           // memh(Rx32++#s4:1)=Rt.H32
592     case S2_pstorerft_pi:         // if (Pv4) memh(Rx32++#s4:1)=Rt.H32
593     case S2_pstorerff_pi:         // if (!Pv4) memh(Rx32++#s4:1)=Rt.H32
594     case S2_pstorerftnew_pi:      // if (Pv4.new) memh(Rx32++#s4:1)=Rt.H32
595     case S2_pstorerffnew_pi:      // if (!Pv4.new) memh(Rx32++#s4:1)=Rt.H32
596     case S4_storerf_ap:           // memh(Re32=#U6)=Rt.H32
597     case S2_storerf_pr:           // memh(Rx32++Mu2)=Rt.H32
598     case S4_storerf_ur:           // memh(Ru32<<#u2+#U6)=Rt.H32
599     case S2_storerf_pbr:          // memh(Rx32++Mu2:brev)=Rt.H32
600     case S2_storerf_pci:          // memh(Rx32++#s4:1:circ(Mu2))=Rt.H32
601     case S2_storerf_pcr:          // memh(Rx32++I:circ(Mu2))=Rt.H32
602     case S4_storerf_rr:           // memh(Rs32+Ru32<<#u2)=Rt.H32
603     case S4_pstorerft_rr:         // if (Pv4) memh(Rs32+Ru32<<#u2)=Rt.H32
604     case S4_pstorerff_rr:         // if (!Pv4) memh(Rs32+Ru32<<#u2)=Rt.H32
605     case S4_pstorerftnew_rr:      // if (Pv4.new) memh(Rs32+Ru32<<#u2)=Rt.H32
606     case S4_pstorerffnew_rr:      // if (!Pv4.new) memh(Rs32+Ru32<<#u2)=Rt.H32
607     case S2_storerfgp:            // memh(gp+#u16:1)=Rt.H32
608     case S4_pstorerft_abs:        // if (Pv4) memh(#u6)=Rt.H32
609     case S4_pstorerff_abs:        // if (!Pv4) memh(#u6)=Rt.H32
610     case S4_pstorerftnew_abs:     // if (Pv4.new) memh(#u6)=Rt.H32
611     case S4_pstorerffnew_abs:     // if (!Pv4.new) memh(#u6)=Rt.H32
612       Bits.set(Begin+16, Begin+32);
613       return true;
614   }
615 
616   return false;
617 }
618 
619 // For an instruction with opcode Opc, calculate the set of bits that it
620 // uses in a register in operand OpN. This only calculates the set of used
621 // bits for cases where it does not depend on any operands (as is the case
622 // in shifts, for example). For concrete instructions from a program, the
623 // operand may be a subregister of a larger register, while Bits would
624 // correspond to the larger register in its entirety. Because of that,
625 // the parameter Begin can be used to indicate which bit of Bits should be
626 // considered the LSB of of the operand.
627 bool HexagonBitSimplify::getUsedBits(unsigned Opc, unsigned OpN,
628       BitVector &Bits, uint16_t Begin, const HexagonInstrInfo &HII) {
629   using namespace Hexagon;
630 
631   const MCInstrDesc &D = HII.get(Opc);
632   if (D.mayStore()) {
633     if (OpN == D.getNumOperands()-1)
634       return getUsedBitsInStore(Opc, Bits, Begin);
635     return false;
636   }
637 
638   switch (Opc) {
639     // One register source. Used bits: R1[0-7].
640     case A2_sxtb:
641     case A2_zxtb:
642     case A4_cmpbeqi:
643     case A4_cmpbgti:
644     case A4_cmpbgtui:
645       if (OpN == 1) {
646         Bits.set(Begin, Begin+8);
647         return true;
648       }
649       break;
650 
651     // One register source. Used bits: R1[0-15].
652     case A2_aslh:
653     case A2_sxth:
654     case A2_zxth:
655     case A4_cmpheqi:
656     case A4_cmphgti:
657     case A4_cmphgtui:
658       if (OpN == 1) {
659         Bits.set(Begin, Begin+16);
660         return true;
661       }
662       break;
663 
664     // One register source. Used bits: R1[16-31].
665     case A2_asrh:
666       if (OpN == 1) {
667         Bits.set(Begin+16, Begin+32);
668         return true;
669       }
670       break;
671 
672     // Two register sources. Used bits: R1[0-7], R2[0-7].
673     case A4_cmpbeq:
674     case A4_cmpbgt:
675     case A4_cmpbgtu:
676       if (OpN == 1) {
677         Bits.set(Begin, Begin+8);
678         return true;
679       }
680       break;
681 
682     // Two register sources. Used bits: R1[0-15], R2[0-15].
683     case A4_cmpheq:
684     case A4_cmphgt:
685     case A4_cmphgtu:
686     case A2_addh_h16_ll:
687     case A2_addh_h16_sat_ll:
688     case A2_addh_l16_ll:
689     case A2_addh_l16_sat_ll:
690     case A2_combine_ll:
691     case A2_subh_h16_ll:
692     case A2_subh_h16_sat_ll:
693     case A2_subh_l16_ll:
694     case A2_subh_l16_sat_ll:
695     case M2_mpy_acc_ll_s0:
696     case M2_mpy_acc_ll_s1:
697     case M2_mpy_acc_sat_ll_s0:
698     case M2_mpy_acc_sat_ll_s1:
699     case M2_mpy_ll_s0:
700     case M2_mpy_ll_s1:
701     case M2_mpy_nac_ll_s0:
702     case M2_mpy_nac_ll_s1:
703     case M2_mpy_nac_sat_ll_s0:
704     case M2_mpy_nac_sat_ll_s1:
705     case M2_mpy_rnd_ll_s0:
706     case M2_mpy_rnd_ll_s1:
707     case M2_mpy_sat_ll_s0:
708     case M2_mpy_sat_ll_s1:
709     case M2_mpy_sat_rnd_ll_s0:
710     case M2_mpy_sat_rnd_ll_s1:
711     case M2_mpyd_acc_ll_s0:
712     case M2_mpyd_acc_ll_s1:
713     case M2_mpyd_ll_s0:
714     case M2_mpyd_ll_s1:
715     case M2_mpyd_nac_ll_s0:
716     case M2_mpyd_nac_ll_s1:
717     case M2_mpyd_rnd_ll_s0:
718     case M2_mpyd_rnd_ll_s1:
719     case M2_mpyu_acc_ll_s0:
720     case M2_mpyu_acc_ll_s1:
721     case M2_mpyu_ll_s0:
722     case M2_mpyu_ll_s1:
723     case M2_mpyu_nac_ll_s0:
724     case M2_mpyu_nac_ll_s1:
725     case M2_mpyud_acc_ll_s0:
726     case M2_mpyud_acc_ll_s1:
727     case M2_mpyud_ll_s0:
728     case M2_mpyud_ll_s1:
729     case M2_mpyud_nac_ll_s0:
730     case M2_mpyud_nac_ll_s1:
731       if (OpN == 1 || OpN == 2) {
732         Bits.set(Begin, Begin+16);
733         return true;
734       }
735       break;
736 
737     // Two register sources. Used bits: R1[0-15], R2[16-31].
738     case A2_addh_h16_lh:
739     case A2_addh_h16_sat_lh:
740     case A2_combine_lh:
741     case A2_subh_h16_lh:
742     case A2_subh_h16_sat_lh:
743     case M2_mpy_acc_lh_s0:
744     case M2_mpy_acc_lh_s1:
745     case M2_mpy_acc_sat_lh_s0:
746     case M2_mpy_acc_sat_lh_s1:
747     case M2_mpy_lh_s0:
748     case M2_mpy_lh_s1:
749     case M2_mpy_nac_lh_s0:
750     case M2_mpy_nac_lh_s1:
751     case M2_mpy_nac_sat_lh_s0:
752     case M2_mpy_nac_sat_lh_s1:
753     case M2_mpy_rnd_lh_s0:
754     case M2_mpy_rnd_lh_s1:
755     case M2_mpy_sat_lh_s0:
756     case M2_mpy_sat_lh_s1:
757     case M2_mpy_sat_rnd_lh_s0:
758     case M2_mpy_sat_rnd_lh_s1:
759     case M2_mpyd_acc_lh_s0:
760     case M2_mpyd_acc_lh_s1:
761     case M2_mpyd_lh_s0:
762     case M2_mpyd_lh_s1:
763     case M2_mpyd_nac_lh_s0:
764     case M2_mpyd_nac_lh_s1:
765     case M2_mpyd_rnd_lh_s0:
766     case M2_mpyd_rnd_lh_s1:
767     case M2_mpyu_acc_lh_s0:
768     case M2_mpyu_acc_lh_s1:
769     case M2_mpyu_lh_s0:
770     case M2_mpyu_lh_s1:
771     case M2_mpyu_nac_lh_s0:
772     case M2_mpyu_nac_lh_s1:
773     case M2_mpyud_acc_lh_s0:
774     case M2_mpyud_acc_lh_s1:
775     case M2_mpyud_lh_s0:
776     case M2_mpyud_lh_s1:
777     case M2_mpyud_nac_lh_s0:
778     case M2_mpyud_nac_lh_s1:
779     // These four are actually LH.
780     case A2_addh_l16_hl:
781     case A2_addh_l16_sat_hl:
782     case A2_subh_l16_hl:
783     case A2_subh_l16_sat_hl:
784       if (OpN == 1) {
785         Bits.set(Begin, Begin+16);
786         return true;
787       }
788       if (OpN == 2) {
789         Bits.set(Begin+16, Begin+32);
790         return true;
791       }
792       break;
793 
794     // Two register sources, used bits: R1[16-31], R2[0-15].
795     case A2_addh_h16_hl:
796     case A2_addh_h16_sat_hl:
797     case A2_combine_hl:
798     case A2_subh_h16_hl:
799     case A2_subh_h16_sat_hl:
800     case M2_mpy_acc_hl_s0:
801     case M2_mpy_acc_hl_s1:
802     case M2_mpy_acc_sat_hl_s0:
803     case M2_mpy_acc_sat_hl_s1:
804     case M2_mpy_hl_s0:
805     case M2_mpy_hl_s1:
806     case M2_mpy_nac_hl_s0:
807     case M2_mpy_nac_hl_s1:
808     case M2_mpy_nac_sat_hl_s0:
809     case M2_mpy_nac_sat_hl_s1:
810     case M2_mpy_rnd_hl_s0:
811     case M2_mpy_rnd_hl_s1:
812     case M2_mpy_sat_hl_s0:
813     case M2_mpy_sat_hl_s1:
814     case M2_mpy_sat_rnd_hl_s0:
815     case M2_mpy_sat_rnd_hl_s1:
816     case M2_mpyd_acc_hl_s0:
817     case M2_mpyd_acc_hl_s1:
818     case M2_mpyd_hl_s0:
819     case M2_mpyd_hl_s1:
820     case M2_mpyd_nac_hl_s0:
821     case M2_mpyd_nac_hl_s1:
822     case M2_mpyd_rnd_hl_s0:
823     case M2_mpyd_rnd_hl_s1:
824     case M2_mpyu_acc_hl_s0:
825     case M2_mpyu_acc_hl_s1:
826     case M2_mpyu_hl_s0:
827     case M2_mpyu_hl_s1:
828     case M2_mpyu_nac_hl_s0:
829     case M2_mpyu_nac_hl_s1:
830     case M2_mpyud_acc_hl_s0:
831     case M2_mpyud_acc_hl_s1:
832     case M2_mpyud_hl_s0:
833     case M2_mpyud_hl_s1:
834     case M2_mpyud_nac_hl_s0:
835     case M2_mpyud_nac_hl_s1:
836       if (OpN == 1) {
837         Bits.set(Begin+16, Begin+32);
838         return true;
839       }
840       if (OpN == 2) {
841         Bits.set(Begin, Begin+16);
842         return true;
843       }
844       break;
845 
846     // Two register sources, used bits: R1[16-31], R2[16-31].
847     case A2_addh_h16_hh:
848     case A2_addh_h16_sat_hh:
849     case A2_combine_hh:
850     case A2_subh_h16_hh:
851     case A2_subh_h16_sat_hh:
852     case M2_mpy_acc_hh_s0:
853     case M2_mpy_acc_hh_s1:
854     case M2_mpy_acc_sat_hh_s0:
855     case M2_mpy_acc_sat_hh_s1:
856     case M2_mpy_hh_s0:
857     case M2_mpy_hh_s1:
858     case M2_mpy_nac_hh_s0:
859     case M2_mpy_nac_hh_s1:
860     case M2_mpy_nac_sat_hh_s0:
861     case M2_mpy_nac_sat_hh_s1:
862     case M2_mpy_rnd_hh_s0:
863     case M2_mpy_rnd_hh_s1:
864     case M2_mpy_sat_hh_s0:
865     case M2_mpy_sat_hh_s1:
866     case M2_mpy_sat_rnd_hh_s0:
867     case M2_mpy_sat_rnd_hh_s1:
868     case M2_mpyd_acc_hh_s0:
869     case M2_mpyd_acc_hh_s1:
870     case M2_mpyd_hh_s0:
871     case M2_mpyd_hh_s1:
872     case M2_mpyd_nac_hh_s0:
873     case M2_mpyd_nac_hh_s1:
874     case M2_mpyd_rnd_hh_s0:
875     case M2_mpyd_rnd_hh_s1:
876     case M2_mpyu_acc_hh_s0:
877     case M2_mpyu_acc_hh_s1:
878     case M2_mpyu_hh_s0:
879     case M2_mpyu_hh_s1:
880     case M2_mpyu_nac_hh_s0:
881     case M2_mpyu_nac_hh_s1:
882     case M2_mpyud_acc_hh_s0:
883     case M2_mpyud_acc_hh_s1:
884     case M2_mpyud_hh_s0:
885     case M2_mpyud_hh_s1:
886     case M2_mpyud_nac_hh_s0:
887     case M2_mpyud_nac_hh_s1:
888       if (OpN == 1 || OpN == 2) {
889         Bits.set(Begin+16, Begin+32);
890         return true;
891       }
892       break;
893   }
894 
895   return false;
896 }
897 
898 // Calculate the register class that matches Reg:Sub. For example, if
899 // vreg1 is a double register, then vreg1:isub_hi would match the "int"
900 // register class.
901 const TargetRegisterClass *HexagonBitSimplify::getFinalVRegClass(
902       const BitTracker::RegisterRef &RR, MachineRegisterInfo &MRI) {
903   if (!TargetRegisterInfo::isVirtualRegister(RR.Reg))
904     return nullptr;
905   auto *RC = MRI.getRegClass(RR.Reg);
906   if (RR.Sub == 0)
907     return RC;
908   auto &HRI = static_cast<const HexagonRegisterInfo&>(
909                   *MRI.getTargetRegisterInfo());
910 
911   auto VerifySR = [&HRI] (const TargetRegisterClass *RC, unsigned Sub) -> void {
912     (void)HRI;
913     assert(Sub == HRI.getHexagonSubRegIndex(RC, Hexagon::ps_sub_lo) ||
914            Sub == HRI.getHexagonSubRegIndex(RC, Hexagon::ps_sub_hi));
915   };
916 
917   switch (RC->getID()) {
918     case Hexagon::DoubleRegsRegClassID:
919       VerifySR(RC, RR.Sub);
920       return &Hexagon::IntRegsRegClass;
921     case Hexagon::VecDblRegsRegClassID:
922       VerifySR(RC, RR.Sub);
923       return &Hexagon::VectorRegsRegClass;
924     case Hexagon::VecDblRegs128BRegClassID:
925       VerifySR(RC, RR.Sub);
926       return &Hexagon::VectorRegs128BRegClass;
927   }
928   return nullptr;
929 }
930 
931 // Check if RD could be replaced with RS at any possible use of RD.
932 // For example a predicate register cannot be replaced with a integer
933 // register, but a 64-bit register with a subregister can be replaced
934 // with a 32-bit register.
935 bool HexagonBitSimplify::isTransparentCopy(const BitTracker::RegisterRef &RD,
936       const BitTracker::RegisterRef &RS, MachineRegisterInfo &MRI) {
937   if (!TargetRegisterInfo::isVirtualRegister(RD.Reg) ||
938       !TargetRegisterInfo::isVirtualRegister(RS.Reg))
939     return false;
940   // Return false if one (or both) classes are nullptr.
941   auto *DRC = getFinalVRegClass(RD, MRI);
942   if (!DRC)
943     return false;
944 
945   return DRC == getFinalVRegClass(RS, MRI);
946 }
947 
948 bool HexagonBitSimplify::hasTiedUse(unsigned Reg, MachineRegisterInfo &MRI,
949       unsigned NewSub) {
950   if (!PreserveTiedOps)
951     return false;
952   return llvm::any_of(MRI.use_operands(Reg),
953                       [NewSub] (const MachineOperand &Op) -> bool {
954                         return Op.getSubReg() != NewSub && Op.isTied();
955                       });
956 }
957 
958 namespace {
959 
960   class DeadCodeElimination {
961   public:
962     DeadCodeElimination(MachineFunction &mf, MachineDominatorTree &mdt)
963       : MF(mf), HII(*MF.getSubtarget<HexagonSubtarget>().getInstrInfo()),
964         MDT(mdt), MRI(mf.getRegInfo()) {}
965 
966     bool run() {
967       return runOnNode(MDT.getRootNode());
968     }
969 
970   private:
971     bool isDead(unsigned R) const;
972     bool runOnNode(MachineDomTreeNode *N);
973 
974     MachineFunction &MF;
975     const HexagonInstrInfo &HII;
976     MachineDominatorTree &MDT;
977     MachineRegisterInfo &MRI;
978   };
979 
980 } // end anonymous namespace
981 
982 bool DeadCodeElimination::isDead(unsigned R) const {
983   for (auto I = MRI.use_begin(R), E = MRI.use_end(); I != E; ++I) {
984     MachineInstr *UseI = I->getParent();
985     if (UseI->isDebugValue())
986       continue;
987     if (UseI->isPHI()) {
988       assert(!UseI->getOperand(0).getSubReg());
989       unsigned DR = UseI->getOperand(0).getReg();
990       if (DR == R)
991         continue;
992     }
993     return false;
994   }
995   return true;
996 }
997 
998 bool DeadCodeElimination::runOnNode(MachineDomTreeNode *N) {
999   bool Changed = false;
1000 
1001   for (auto *DTN : children<MachineDomTreeNode*>(N))
1002     Changed |= runOnNode(DTN);
1003 
1004   MachineBasicBlock *B = N->getBlock();
1005   std::vector<MachineInstr*> Instrs;
1006   for (auto I = B->rbegin(), E = B->rend(); I != E; ++I)
1007     Instrs.push_back(&*I);
1008 
1009   for (auto MI : Instrs) {
1010     unsigned Opc = MI->getOpcode();
1011     // Do not touch lifetime markers. This is why the target-independent DCE
1012     // cannot be used.
1013     if (Opc == TargetOpcode::LIFETIME_START ||
1014         Opc == TargetOpcode::LIFETIME_END)
1015       continue;
1016     bool Store = false;
1017     if (MI->isInlineAsm())
1018       continue;
1019     // Delete PHIs if possible.
1020     if (!MI->isPHI() && !MI->isSafeToMove(nullptr, Store))
1021       continue;
1022 
1023     bool AllDead = true;
1024     SmallVector<unsigned,2> Regs;
1025     for (auto &Op : MI->operands()) {
1026       if (!Op.isReg() || !Op.isDef())
1027         continue;
1028       unsigned R = Op.getReg();
1029       if (!TargetRegisterInfo::isVirtualRegister(R) || !isDead(R)) {
1030         AllDead = false;
1031         break;
1032       }
1033       Regs.push_back(R);
1034     }
1035     if (!AllDead)
1036       continue;
1037 
1038     B->erase(MI);
1039     for (unsigned i = 0, n = Regs.size(); i != n; ++i)
1040       MRI.markUsesInDebugValueAsUndef(Regs[i]);
1041     Changed = true;
1042   }
1043 
1044   return Changed;
1045 }
1046 
1047 namespace {
1048 
1049 // Eliminate redundant instructions
1050 //
1051 // This transformation will identify instructions where the output register
1052 // is the same as one of its input registers. This only works on instructions
1053 // that define a single register (unlike post-increment loads, for example).
1054 // The equality check is actually more detailed: the code calculates which
1055 // bits of the output are used, and only compares these bits with the input
1056 // registers.
1057 // If the output matches an input, the instruction is replaced with COPY.
1058 // The copies will be removed by another transformation.
1059   class RedundantInstrElimination : public Transformation {
1060   public:
1061     RedundantInstrElimination(BitTracker &bt, const HexagonInstrInfo &hii,
1062           const HexagonRegisterInfo &hri, MachineRegisterInfo &mri)
1063         : Transformation(true), HII(hii), HRI(hri), MRI(mri), BT(bt) {}
1064 
1065     bool processBlock(MachineBasicBlock &B, const RegisterSet &AVs) override;
1066 
1067   private:
1068     bool isLossyShiftLeft(const MachineInstr &MI, unsigned OpN,
1069           unsigned &LostB, unsigned &LostE);
1070     bool isLossyShiftRight(const MachineInstr &MI, unsigned OpN,
1071           unsigned &LostB, unsigned &LostE);
1072     bool computeUsedBits(unsigned Reg, BitVector &Bits);
1073     bool computeUsedBits(const MachineInstr &MI, unsigned OpN, BitVector &Bits,
1074           uint16_t Begin);
1075     bool usedBitsEqual(BitTracker::RegisterRef RD, BitTracker::RegisterRef RS);
1076 
1077     const HexagonInstrInfo &HII;
1078     const HexagonRegisterInfo &HRI;
1079     MachineRegisterInfo &MRI;
1080     BitTracker &BT;
1081   };
1082 
1083 } // end anonymous namespace
1084 
1085 // Check if the instruction is a lossy shift left, where the input being
1086 // shifted is the operand OpN of MI. If true, [LostB, LostE) is the range
1087 // of bit indices that are lost.
1088 bool RedundantInstrElimination::isLossyShiftLeft(const MachineInstr &MI,
1089       unsigned OpN, unsigned &LostB, unsigned &LostE) {
1090   using namespace Hexagon;
1091 
1092   unsigned Opc = MI.getOpcode();
1093   unsigned ImN, RegN, Width;
1094   switch (Opc) {
1095     case S2_asl_i_p:
1096       ImN = 2;
1097       RegN = 1;
1098       Width = 64;
1099       break;
1100     case S2_asl_i_p_acc:
1101     case S2_asl_i_p_and:
1102     case S2_asl_i_p_nac:
1103     case S2_asl_i_p_or:
1104     case S2_asl_i_p_xacc:
1105       ImN = 3;
1106       RegN = 2;
1107       Width = 64;
1108       break;
1109     case S2_asl_i_r:
1110       ImN = 2;
1111       RegN = 1;
1112       Width = 32;
1113       break;
1114     case S2_addasl_rrri:
1115     case S4_andi_asl_ri:
1116     case S4_ori_asl_ri:
1117     case S4_addi_asl_ri:
1118     case S4_subi_asl_ri:
1119     case S2_asl_i_r_acc:
1120     case S2_asl_i_r_and:
1121     case S2_asl_i_r_nac:
1122     case S2_asl_i_r_or:
1123     case S2_asl_i_r_sat:
1124     case S2_asl_i_r_xacc:
1125       ImN = 3;
1126       RegN = 2;
1127       Width = 32;
1128       break;
1129     default:
1130       return false;
1131   }
1132 
1133   if (RegN != OpN)
1134     return false;
1135 
1136   assert(MI.getOperand(ImN).isImm());
1137   unsigned S = MI.getOperand(ImN).getImm();
1138   if (S == 0)
1139     return false;
1140   LostB = Width-S;
1141   LostE = Width;
1142   return true;
1143 }
1144 
1145 // Check if the instruction is a lossy shift right, where the input being
1146 // shifted is the operand OpN of MI. If true, [LostB, LostE) is the range
1147 // of bit indices that are lost.
1148 bool RedundantInstrElimination::isLossyShiftRight(const MachineInstr &MI,
1149       unsigned OpN, unsigned &LostB, unsigned &LostE) {
1150   using namespace Hexagon;
1151 
1152   unsigned Opc = MI.getOpcode();
1153   unsigned ImN, RegN;
1154   switch (Opc) {
1155     case S2_asr_i_p:
1156     case S2_lsr_i_p:
1157       ImN = 2;
1158       RegN = 1;
1159       break;
1160     case S2_asr_i_p_acc:
1161     case S2_asr_i_p_and:
1162     case S2_asr_i_p_nac:
1163     case S2_asr_i_p_or:
1164     case S2_lsr_i_p_acc:
1165     case S2_lsr_i_p_and:
1166     case S2_lsr_i_p_nac:
1167     case S2_lsr_i_p_or:
1168     case S2_lsr_i_p_xacc:
1169       ImN = 3;
1170       RegN = 2;
1171       break;
1172     case S2_asr_i_r:
1173     case S2_lsr_i_r:
1174       ImN = 2;
1175       RegN = 1;
1176       break;
1177     case S4_andi_lsr_ri:
1178     case S4_ori_lsr_ri:
1179     case S4_addi_lsr_ri:
1180     case S4_subi_lsr_ri:
1181     case S2_asr_i_r_acc:
1182     case S2_asr_i_r_and:
1183     case S2_asr_i_r_nac:
1184     case S2_asr_i_r_or:
1185     case S2_lsr_i_r_acc:
1186     case S2_lsr_i_r_and:
1187     case S2_lsr_i_r_nac:
1188     case S2_lsr_i_r_or:
1189     case S2_lsr_i_r_xacc:
1190       ImN = 3;
1191       RegN = 2;
1192       break;
1193 
1194     default:
1195       return false;
1196   }
1197 
1198   if (RegN != OpN)
1199     return false;
1200 
1201   assert(MI.getOperand(ImN).isImm());
1202   unsigned S = MI.getOperand(ImN).getImm();
1203   LostB = 0;
1204   LostE = S;
1205   return true;
1206 }
1207 
1208 // Calculate the bit vector that corresponds to the used bits of register Reg.
1209 // The vector Bits has the same size, as the size of Reg in bits. If the cal-
1210 // culation fails (i.e. the used bits are unknown), it returns false. Other-
1211 // wise, it returns true and sets the corresponding bits in Bits.
1212 bool RedundantInstrElimination::computeUsedBits(unsigned Reg, BitVector &Bits) {
1213   BitVector Used(Bits.size());
1214   RegisterSet Visited;
1215   std::vector<unsigned> Pending;
1216   Pending.push_back(Reg);
1217 
1218   for (unsigned i = 0; i < Pending.size(); ++i) {
1219     unsigned R = Pending[i];
1220     if (Visited.has(R))
1221       continue;
1222     Visited.insert(R);
1223     for (auto I = MRI.use_begin(R), E = MRI.use_end(); I != E; ++I) {
1224       BitTracker::RegisterRef UR = *I;
1225       unsigned B, W;
1226       if (!HBS::getSubregMask(UR, B, W, MRI))
1227         return false;
1228       MachineInstr &UseI = *I->getParent();
1229       if (UseI.isPHI() || UseI.isCopy()) {
1230         unsigned DefR = UseI.getOperand(0).getReg();
1231         if (!TargetRegisterInfo::isVirtualRegister(DefR))
1232           return false;
1233         Pending.push_back(DefR);
1234       } else {
1235         if (!computeUsedBits(UseI, I.getOperandNo(), Used, B))
1236           return false;
1237       }
1238     }
1239   }
1240   Bits |= Used;
1241   return true;
1242 }
1243 
1244 // Calculate the bits used by instruction MI in a register in operand OpN.
1245 // Return true/false if the calculation succeeds/fails. If is succeeds, set
1246 // used bits in Bits. This function does not reset any bits in Bits, so
1247 // subsequent calls over different instructions will result in the union
1248 // of the used bits in all these instructions.
1249 // The register in question may be used with a sub-register, whereas Bits
1250 // holds the bits for the entire register. To keep track of that, the
1251 // argument Begin indicates where in Bits is the lowest-significant bit
1252 // of the register used in operand OpN. For example, in instruction:
1253 //   vreg1 = S2_lsr_i_r vreg2:isub_hi, 10
1254 // the operand 1 is a 32-bit register, which happens to be a subregister
1255 // of the 64-bit register vreg2, and that subregister starts at position 32.
1256 // In this case Begin=32, since Bits[32] would be the lowest-significant bit
1257 // of vreg2:isub_hi.
1258 bool RedundantInstrElimination::computeUsedBits(const MachineInstr &MI,
1259       unsigned OpN, BitVector &Bits, uint16_t Begin) {
1260   unsigned Opc = MI.getOpcode();
1261   BitVector T(Bits.size());
1262   bool GotBits = HBS::getUsedBits(Opc, OpN, T, Begin, HII);
1263   // Even if we don't have bits yet, we could still provide some information
1264   // if the instruction is a lossy shift: the lost bits will be marked as
1265   // not used.
1266   unsigned LB, LE;
1267   if (isLossyShiftLeft(MI, OpN, LB, LE) || isLossyShiftRight(MI, OpN, LB, LE)) {
1268     assert(MI.getOperand(OpN).isReg());
1269     BitTracker::RegisterRef RR = MI.getOperand(OpN);
1270     const TargetRegisterClass *RC = HBS::getFinalVRegClass(RR, MRI);
1271     uint16_t Width = HRI.getRegSizeInBits(*RC);
1272 
1273     if (!GotBits)
1274       T.set(Begin, Begin+Width);
1275     assert(LB <= LE && LB < Width && LE <= Width);
1276     T.reset(Begin+LB, Begin+LE);
1277     GotBits = true;
1278   }
1279   if (GotBits)
1280     Bits |= T;
1281   return GotBits;
1282 }
1283 
1284 // Calculates the used bits in RD ("defined register"), and checks if these
1285 // bits in RS ("used register") and RD are identical.
1286 bool RedundantInstrElimination::usedBitsEqual(BitTracker::RegisterRef RD,
1287       BitTracker::RegisterRef RS) {
1288   const BitTracker::RegisterCell &DC = BT.lookup(RD.Reg);
1289   const BitTracker::RegisterCell &SC = BT.lookup(RS.Reg);
1290 
1291   unsigned DB, DW;
1292   if (!HBS::getSubregMask(RD, DB, DW, MRI))
1293     return false;
1294   unsigned SB, SW;
1295   if (!HBS::getSubregMask(RS, SB, SW, MRI))
1296     return false;
1297   if (SW != DW)
1298     return false;
1299 
1300   BitVector Used(DC.width());
1301   if (!computeUsedBits(RD.Reg, Used))
1302     return false;
1303 
1304   for (unsigned i = 0; i != DW; ++i)
1305     if (Used[i+DB] && DC[DB+i] != SC[SB+i])
1306       return false;
1307   return true;
1308 }
1309 
1310 bool RedundantInstrElimination::processBlock(MachineBasicBlock &B,
1311       const RegisterSet&) {
1312   if (!BT.reached(&B))
1313     return false;
1314   bool Changed = false;
1315 
1316   for (auto I = B.begin(), E = B.end(), NextI = I; I != E; ++I) {
1317     NextI = std::next(I);
1318     MachineInstr *MI = &*I;
1319 
1320     if (MI->getOpcode() == TargetOpcode::COPY)
1321       continue;
1322     if (MI->hasUnmodeledSideEffects() || MI->isInlineAsm())
1323       continue;
1324     unsigned NumD = MI->getDesc().getNumDefs();
1325     if (NumD != 1)
1326       continue;
1327 
1328     BitTracker::RegisterRef RD = MI->getOperand(0);
1329     if (!BT.has(RD.Reg))
1330       continue;
1331     const BitTracker::RegisterCell &DC = BT.lookup(RD.Reg);
1332     auto At = MI->isPHI() ? B.getFirstNonPHI()
1333                           : MachineBasicBlock::iterator(MI);
1334 
1335     // Find a source operand that is equal to the result.
1336     for (auto &Op : MI->uses()) {
1337       if (!Op.isReg())
1338         continue;
1339       BitTracker::RegisterRef RS = Op;
1340       if (!BT.has(RS.Reg))
1341         continue;
1342       if (!HBS::isTransparentCopy(RD, RS, MRI))
1343         continue;
1344 
1345       unsigned BN, BW;
1346       if (!HBS::getSubregMask(RS, BN, BW, MRI))
1347         continue;
1348 
1349       const BitTracker::RegisterCell &SC = BT.lookup(RS.Reg);
1350       if (!usedBitsEqual(RD, RS) && !HBS::isEqual(DC, 0, SC, BN, BW))
1351         continue;
1352 
1353       // If found, replace the instruction with a COPY.
1354       const DebugLoc &DL = MI->getDebugLoc();
1355       const TargetRegisterClass *FRC = HBS::getFinalVRegClass(RD, MRI);
1356       unsigned NewR = MRI.createVirtualRegister(FRC);
1357       MachineInstr *CopyI =
1358           BuildMI(B, At, DL, HII.get(TargetOpcode::COPY), NewR)
1359             .addReg(RS.Reg, 0, RS.Sub);
1360       HBS::replaceSubWithSub(RD.Reg, RD.Sub, NewR, 0, MRI);
1361       // This pass can create copies between registers that don't have the
1362       // exact same values. Updating the tracker has to involve updating
1363       // all dependent cells. Example:
1364       //   vreg1 = inst vreg2     ; vreg1 != vreg2, but used bits are equal
1365       //
1366       //   vreg3 = copy vreg2     ; <- inserted
1367       //     ... = vreg3          ; <- replaced from vreg2
1368       // Indirectly, we can create a "copy" between vreg1 and vreg2 even
1369       // though their exact values do not match.
1370       BT.visit(*CopyI);
1371       Changed = true;
1372       break;
1373     }
1374   }
1375 
1376   return Changed;
1377 }
1378 
1379 namespace {
1380 
1381 // Recognize instructions that produce constant values known at compile-time.
1382 // Replace them with register definitions that load these constants directly.
1383   class ConstGeneration : public Transformation {
1384   public:
1385     ConstGeneration(BitTracker &bt, const HexagonInstrInfo &hii,
1386         MachineRegisterInfo &mri)
1387       : Transformation(true), HII(hii), MRI(mri), BT(bt) {}
1388 
1389     bool processBlock(MachineBasicBlock &B, const RegisterSet &AVs) override;
1390     static bool isTfrConst(const MachineInstr &MI);
1391 
1392   private:
1393     unsigned genTfrConst(const TargetRegisterClass *RC, int64_t C,
1394         MachineBasicBlock &B, MachineBasicBlock::iterator At, DebugLoc &DL);
1395 
1396     const HexagonInstrInfo &HII;
1397     MachineRegisterInfo &MRI;
1398     BitTracker &BT;
1399   };
1400 
1401 } // end anonymous namespace
1402 
1403 bool ConstGeneration::isTfrConst(const MachineInstr &MI) {
1404   unsigned Opc = MI.getOpcode();
1405   switch (Opc) {
1406     case Hexagon::A2_combineii:
1407     case Hexagon::A4_combineii:
1408     case Hexagon::A2_tfrsi:
1409     case Hexagon::A2_tfrpi:
1410     case Hexagon::PS_true:
1411     case Hexagon::PS_false:
1412     case Hexagon::CONST32:
1413     case Hexagon::CONST64:
1414       return true;
1415   }
1416   return false;
1417 }
1418 
1419 // Generate a transfer-immediate instruction that is appropriate for the
1420 // register class and the actual value being transferred.
1421 unsigned ConstGeneration::genTfrConst(const TargetRegisterClass *RC, int64_t C,
1422       MachineBasicBlock &B, MachineBasicBlock::iterator At, DebugLoc &DL) {
1423   unsigned Reg = MRI.createVirtualRegister(RC);
1424   if (RC == &Hexagon::IntRegsRegClass) {
1425     BuildMI(B, At, DL, HII.get(Hexagon::A2_tfrsi), Reg)
1426         .addImm(int32_t(C));
1427     return Reg;
1428   }
1429 
1430   if (RC == &Hexagon::DoubleRegsRegClass) {
1431     if (isInt<8>(C)) {
1432       BuildMI(B, At, DL, HII.get(Hexagon::A2_tfrpi), Reg)
1433           .addImm(C);
1434       return Reg;
1435     }
1436 
1437     unsigned Lo = Lo_32(C), Hi = Hi_32(C);
1438     if (isInt<8>(Lo) || isInt<8>(Hi)) {
1439       unsigned Opc = isInt<8>(Lo) ? Hexagon::A2_combineii
1440                                   : Hexagon::A4_combineii;
1441       BuildMI(B, At, DL, HII.get(Opc), Reg)
1442           .addImm(int32_t(Hi))
1443           .addImm(int32_t(Lo));
1444       return Reg;
1445     }
1446 
1447     BuildMI(B, At, DL, HII.get(Hexagon::CONST64), Reg)
1448         .addImm(C);
1449     return Reg;
1450   }
1451 
1452   if (RC == &Hexagon::PredRegsRegClass) {
1453     unsigned Opc;
1454     if (C == 0)
1455       Opc = Hexagon::PS_false;
1456     else if ((C & 0xFF) == 0xFF)
1457       Opc = Hexagon::PS_true;
1458     else
1459       return 0;
1460     BuildMI(B, At, DL, HII.get(Opc), Reg);
1461     return Reg;
1462   }
1463 
1464   return 0;
1465 }
1466 
1467 bool ConstGeneration::processBlock(MachineBasicBlock &B, const RegisterSet&) {
1468   if (!BT.reached(&B))
1469     return false;
1470   bool Changed = false;
1471   RegisterSet Defs;
1472 
1473   for (auto I = B.begin(), E = B.end(); I != E; ++I) {
1474     if (isTfrConst(*I))
1475       continue;
1476     Defs.clear();
1477     HBS::getInstrDefs(*I, Defs);
1478     if (Defs.count() != 1)
1479       continue;
1480     unsigned DR = Defs.find_first();
1481     if (!TargetRegisterInfo::isVirtualRegister(DR))
1482       continue;
1483     uint64_t U;
1484     const BitTracker::RegisterCell &DRC = BT.lookup(DR);
1485     if (HBS::getConst(DRC, 0, DRC.width(), U)) {
1486       int64_t C = U;
1487       DebugLoc DL = I->getDebugLoc();
1488       auto At = I->isPHI() ? B.getFirstNonPHI() : I;
1489       unsigned ImmReg = genTfrConst(MRI.getRegClass(DR), C, B, At, DL);
1490       if (ImmReg) {
1491         HBS::replaceReg(DR, ImmReg, MRI);
1492         BT.put(ImmReg, DRC);
1493         Changed = true;
1494       }
1495     }
1496   }
1497   return Changed;
1498 }
1499 
1500 namespace {
1501 
1502 // Identify pairs of available registers which hold identical values.
1503 // In such cases, only one of them needs to be calculated, the other one
1504 // will be defined as a copy of the first.
1505   class CopyGeneration : public Transformation {
1506   public:
1507     CopyGeneration(BitTracker &bt, const HexagonInstrInfo &hii,
1508         const HexagonRegisterInfo &hri, MachineRegisterInfo &mri)
1509       : Transformation(true), HII(hii), HRI(hri), MRI(mri), BT(bt) {}
1510 
1511     bool processBlock(MachineBasicBlock &B, const RegisterSet &AVs) override;
1512 
1513   private:
1514     bool findMatch(const BitTracker::RegisterRef &Inp,
1515         BitTracker::RegisterRef &Out, const RegisterSet &AVs);
1516 
1517     const HexagonInstrInfo &HII;
1518     const HexagonRegisterInfo &HRI;
1519     MachineRegisterInfo &MRI;
1520     BitTracker &BT;
1521     RegisterSet Forbidden;
1522   };
1523 
1524 // Eliminate register copies RD = RS, by replacing the uses of RD with
1525 // with uses of RS.
1526   class CopyPropagation : public Transformation {
1527   public:
1528     CopyPropagation(const HexagonRegisterInfo &hri, MachineRegisterInfo &mri)
1529         : Transformation(false), HRI(hri), MRI(mri) {}
1530 
1531     bool processBlock(MachineBasicBlock &B, const RegisterSet &AVs) override;
1532 
1533     static bool isCopyReg(unsigned Opc, bool NoConv);
1534 
1535   private:
1536     bool propagateRegCopy(MachineInstr &MI);
1537 
1538     const HexagonRegisterInfo &HRI;
1539     MachineRegisterInfo &MRI;
1540   };
1541 
1542 } // end anonymous namespace
1543 
1544 /// Check if there is a register in AVs that is identical to Inp. If so,
1545 /// set Out to the found register. The output may be a pair Reg:Sub.
1546 bool CopyGeneration::findMatch(const BitTracker::RegisterRef &Inp,
1547       BitTracker::RegisterRef &Out, const RegisterSet &AVs) {
1548   if (!BT.has(Inp.Reg))
1549     return false;
1550   const BitTracker::RegisterCell &InpRC = BT.lookup(Inp.Reg);
1551   auto *FRC = HBS::getFinalVRegClass(Inp, MRI);
1552   unsigned B, W;
1553   if (!HBS::getSubregMask(Inp, B, W, MRI))
1554     return false;
1555 
1556   for (unsigned R = AVs.find_first(); R; R = AVs.find_next(R)) {
1557     if (!BT.has(R) || Forbidden[R])
1558       continue;
1559     const BitTracker::RegisterCell &RC = BT.lookup(R);
1560     unsigned RW = RC.width();
1561     if (W == RW) {
1562       if (FRC != MRI.getRegClass(R))
1563         continue;
1564       if (!HBS::isTransparentCopy(R, Inp, MRI))
1565         continue;
1566       if (!HBS::isEqual(InpRC, B, RC, 0, W))
1567         continue;
1568       Out.Reg = R;
1569       Out.Sub = 0;
1570       return true;
1571     }
1572     // Check if there is a super-register, whose part (with a subregister)
1573     // is equal to the input.
1574     // Only do double registers for now.
1575     if (W*2 != RW)
1576       continue;
1577     if (MRI.getRegClass(R) != &Hexagon::DoubleRegsRegClass)
1578       continue;
1579 
1580     if (HBS::isEqual(InpRC, B, RC, 0, W))
1581       Out.Sub = Hexagon::isub_lo;
1582     else if (HBS::isEqual(InpRC, B, RC, W, W))
1583       Out.Sub = Hexagon::isub_hi;
1584     else
1585       continue;
1586     Out.Reg = R;
1587     if (HBS::isTransparentCopy(Out, Inp, MRI))
1588       return true;
1589   }
1590   return false;
1591 }
1592 
1593 bool CopyGeneration::processBlock(MachineBasicBlock &B,
1594       const RegisterSet &AVs) {
1595   if (!BT.reached(&B))
1596     return false;
1597   RegisterSet AVB(AVs);
1598   bool Changed = false;
1599   RegisterSet Defs;
1600 
1601   for (auto I = B.begin(), E = B.end(), NextI = I; I != E;
1602        ++I, AVB.insert(Defs)) {
1603     NextI = std::next(I);
1604     Defs.clear();
1605     HBS::getInstrDefs(*I, Defs);
1606 
1607     unsigned Opc = I->getOpcode();
1608     if (CopyPropagation::isCopyReg(Opc, false) ||
1609         ConstGeneration::isTfrConst(*I))
1610       continue;
1611 
1612     DebugLoc DL = I->getDebugLoc();
1613     auto At = I->isPHI() ? B.getFirstNonPHI() : I;
1614 
1615     for (unsigned R = Defs.find_first(); R; R = Defs.find_next(R)) {
1616       BitTracker::RegisterRef MR;
1617       auto *FRC = HBS::getFinalVRegClass(R, MRI);
1618 
1619       if (findMatch(R, MR, AVB)) {
1620         unsigned NewR = MRI.createVirtualRegister(FRC);
1621         BuildMI(B, At, DL, HII.get(TargetOpcode::COPY), NewR)
1622           .addReg(MR.Reg, 0, MR.Sub);
1623         BT.put(BitTracker::RegisterRef(NewR), BT.get(MR));
1624         HBS::replaceReg(R, NewR, MRI);
1625         Forbidden.insert(R);
1626         continue;
1627       }
1628 
1629       if (FRC == &Hexagon::DoubleRegsRegClass ||
1630           FRC == &Hexagon::VecDblRegsRegClass ||
1631           FRC == &Hexagon::VecDblRegs128BRegClass) {
1632         // Try to generate REG_SEQUENCE.
1633         unsigned SubLo = HRI.getHexagonSubRegIndex(FRC, Hexagon::ps_sub_lo);
1634         unsigned SubHi = HRI.getHexagonSubRegIndex(FRC, Hexagon::ps_sub_hi);
1635         BitTracker::RegisterRef TL = { R, SubLo };
1636         BitTracker::RegisterRef TH = { R, SubHi };
1637         BitTracker::RegisterRef ML, MH;
1638         if (findMatch(TL, ML, AVB) && findMatch(TH, MH, AVB)) {
1639           auto *FRC = HBS::getFinalVRegClass(R, MRI);
1640           unsigned NewR = MRI.createVirtualRegister(FRC);
1641           BuildMI(B, At, DL, HII.get(TargetOpcode::REG_SEQUENCE), NewR)
1642             .addReg(ML.Reg, 0, ML.Sub)
1643             .addImm(SubLo)
1644             .addReg(MH.Reg, 0, MH.Sub)
1645             .addImm(SubHi);
1646           BT.put(BitTracker::RegisterRef(NewR), BT.get(R));
1647           HBS::replaceReg(R, NewR, MRI);
1648           Forbidden.insert(R);
1649         }
1650       }
1651     }
1652   }
1653 
1654   return Changed;
1655 }
1656 
1657 bool CopyPropagation::isCopyReg(unsigned Opc, bool NoConv) {
1658   switch (Opc) {
1659     case TargetOpcode::COPY:
1660     case TargetOpcode::REG_SEQUENCE:
1661     case Hexagon::A4_combineir:
1662     case Hexagon::A4_combineri:
1663       return true;
1664     case Hexagon::A2_tfr:
1665     case Hexagon::A2_tfrp:
1666     case Hexagon::A2_combinew:
1667     case Hexagon::V6_vcombine:
1668     case Hexagon::V6_vcombine_128B:
1669       return NoConv;
1670     default:
1671       break;
1672   }
1673   return false;
1674 }
1675 
1676 bool CopyPropagation::propagateRegCopy(MachineInstr &MI) {
1677   bool Changed = false;
1678   unsigned Opc = MI.getOpcode();
1679   BitTracker::RegisterRef RD = MI.getOperand(0);
1680   assert(MI.getOperand(0).getSubReg() == 0);
1681 
1682   switch (Opc) {
1683     case TargetOpcode::COPY:
1684     case Hexagon::A2_tfr:
1685     case Hexagon::A2_tfrp: {
1686       BitTracker::RegisterRef RS = MI.getOperand(1);
1687       if (!HBS::isTransparentCopy(RD, RS, MRI))
1688         break;
1689       if (RS.Sub != 0)
1690         Changed = HBS::replaceRegWithSub(RD.Reg, RS.Reg, RS.Sub, MRI);
1691       else
1692         Changed = HBS::replaceReg(RD.Reg, RS.Reg, MRI);
1693       break;
1694     }
1695     case TargetOpcode::REG_SEQUENCE: {
1696       BitTracker::RegisterRef SL, SH;
1697       if (HBS::parseRegSequence(MI, SL, SH, MRI)) {
1698         const TargetRegisterClass *RC = MRI.getRegClass(RD.Reg);
1699         unsigned SubLo = HRI.getHexagonSubRegIndex(RC, Hexagon::ps_sub_lo);
1700         unsigned SubHi = HRI.getHexagonSubRegIndex(RC, Hexagon::ps_sub_hi);
1701         Changed  = HBS::replaceSubWithSub(RD.Reg, SubLo, SL.Reg, SL.Sub, MRI);
1702         Changed |= HBS::replaceSubWithSub(RD.Reg, SubHi, SH.Reg, SH.Sub, MRI);
1703       }
1704       break;
1705     }
1706     case Hexagon::A2_combinew:
1707     case Hexagon::V6_vcombine:
1708     case Hexagon::V6_vcombine_128B: {
1709       const TargetRegisterClass *RC = MRI.getRegClass(RD.Reg);
1710       unsigned SubLo = HRI.getHexagonSubRegIndex(RC, Hexagon::ps_sub_lo);
1711       unsigned SubHi = HRI.getHexagonSubRegIndex(RC, Hexagon::ps_sub_hi);
1712       BitTracker::RegisterRef RH = MI.getOperand(1), RL = MI.getOperand(2);
1713       Changed  = HBS::replaceSubWithSub(RD.Reg, SubLo, RL.Reg, RL.Sub, MRI);
1714       Changed |= HBS::replaceSubWithSub(RD.Reg, SubHi, RH.Reg, RH.Sub, MRI);
1715       break;
1716     }
1717     case Hexagon::A4_combineir:
1718     case Hexagon::A4_combineri: {
1719       unsigned SrcX = (Opc == Hexagon::A4_combineir) ? 2 : 1;
1720       unsigned Sub = (Opc == Hexagon::A4_combineir) ? Hexagon::isub_lo
1721                                                     : Hexagon::isub_hi;
1722       BitTracker::RegisterRef RS = MI.getOperand(SrcX);
1723       Changed = HBS::replaceSubWithSub(RD.Reg, Sub, RS.Reg, RS.Sub, MRI);
1724       break;
1725     }
1726   }
1727   return Changed;
1728 }
1729 
1730 bool CopyPropagation::processBlock(MachineBasicBlock &B, const RegisterSet&) {
1731   std::vector<MachineInstr*> Instrs;
1732   for (auto I = B.rbegin(), E = B.rend(); I != E; ++I)
1733     Instrs.push_back(&*I);
1734 
1735   bool Changed = false;
1736   for (auto I : Instrs) {
1737     unsigned Opc = I->getOpcode();
1738     if (!CopyPropagation::isCopyReg(Opc, true))
1739       continue;
1740     Changed |= propagateRegCopy(*I);
1741   }
1742 
1743   return Changed;
1744 }
1745 
1746 namespace {
1747 
1748 // Recognize patterns that can be simplified and replace them with the
1749 // simpler forms.
1750 // This is by no means complete
1751   class BitSimplification : public Transformation {
1752   public:
1753     BitSimplification(BitTracker &bt, const MachineDominatorTree &mdt,
1754         const HexagonInstrInfo &hii, const HexagonRegisterInfo &hri,
1755         MachineRegisterInfo &mri, MachineFunction &mf)
1756       : Transformation(true), MDT(mdt), HII(hii), HRI(hri), MRI(mri),
1757         MF(mf), BT(bt) {}
1758 
1759     bool processBlock(MachineBasicBlock &B, const RegisterSet &AVs) override;
1760 
1761   private:
1762     struct RegHalf : public BitTracker::RegisterRef {
1763       bool Low;  // Low/High halfword.
1764     };
1765 
1766     bool matchHalf(unsigned SelfR, const BitTracker::RegisterCell &RC,
1767           unsigned B, RegHalf &RH);
1768     bool validateReg(BitTracker::RegisterRef R, unsigned Opc, unsigned OpNum);
1769 
1770     bool matchPackhl(unsigned SelfR, const BitTracker::RegisterCell &RC,
1771           BitTracker::RegisterRef &Rs, BitTracker::RegisterRef &Rt);
1772     unsigned getCombineOpcode(bool HLow, bool LLow);
1773 
1774     bool genStoreUpperHalf(MachineInstr *MI);
1775     bool genStoreImmediate(MachineInstr *MI);
1776     bool genPackhl(MachineInstr *MI, BitTracker::RegisterRef RD,
1777           const BitTracker::RegisterCell &RC);
1778     bool genExtractHalf(MachineInstr *MI, BitTracker::RegisterRef RD,
1779           const BitTracker::RegisterCell &RC);
1780     bool genCombineHalf(MachineInstr *MI, BitTracker::RegisterRef RD,
1781           const BitTracker::RegisterCell &RC);
1782     bool genExtractLow(MachineInstr *MI, BitTracker::RegisterRef RD,
1783           const BitTracker::RegisterCell &RC);
1784     bool genBitSplit(MachineInstr *MI, BitTracker::RegisterRef RD,
1785           const BitTracker::RegisterCell &RC, const RegisterSet &AVs);
1786     bool simplifyTstbit(MachineInstr *MI, BitTracker::RegisterRef RD,
1787           const BitTracker::RegisterCell &RC);
1788     bool simplifyExtractLow(MachineInstr *MI, BitTracker::RegisterRef RD,
1789           const BitTracker::RegisterCell &RC, const RegisterSet &AVs);
1790 
1791     // Cache of created instructions to avoid creating duplicates.
1792     // XXX Currently only used by genBitSplit.
1793     std::vector<MachineInstr*> NewMIs;
1794 
1795     const MachineDominatorTree &MDT;
1796     const HexagonInstrInfo &HII;
1797     const HexagonRegisterInfo &HRI;
1798     MachineRegisterInfo &MRI;
1799     MachineFunction &MF;
1800     BitTracker &BT;
1801   };
1802 
1803 } // end anonymous namespace
1804 
1805 // Check if the bits [B..B+16) in register cell RC form a valid halfword,
1806 // i.e. [0..16), [16..32), etc. of some register. If so, return true and
1807 // set the information about the found register in RH.
1808 bool BitSimplification::matchHalf(unsigned SelfR,
1809       const BitTracker::RegisterCell &RC, unsigned B, RegHalf &RH) {
1810   // XXX This could be searching in the set of available registers, in case
1811   // the match is not exact.
1812 
1813   // Match 16-bit chunks, where the RC[B..B+15] references exactly one
1814   // register and all the bits B..B+15 match between RC and the register.
1815   // This is meant to match "v1[0-15]", where v1 = { [0]:0 [1-15]:v1... },
1816   // and RC = { [0]:0 [1-15]:v1[1-15]... }.
1817   bool Low = false;
1818   unsigned I = B;
1819   while (I < B+16 && RC[I].num())
1820     I++;
1821   if (I == B+16)
1822     return false;
1823 
1824   unsigned Reg = RC[I].RefI.Reg;
1825   unsigned P = RC[I].RefI.Pos;    // The RefI.Pos will be advanced by I-B.
1826   if (P < I-B)
1827     return false;
1828   unsigned Pos = P - (I-B);
1829 
1830   if (Reg == 0 || Reg == SelfR)    // Don't match "self".
1831     return false;
1832   if (!TargetRegisterInfo::isVirtualRegister(Reg))
1833     return false;
1834   if (!BT.has(Reg))
1835     return false;
1836 
1837   const BitTracker::RegisterCell &SC = BT.lookup(Reg);
1838   if (Pos+16 > SC.width())
1839     return false;
1840 
1841   for (unsigned i = 0; i < 16; ++i) {
1842     const BitTracker::BitValue &RV = RC[i+B];
1843     if (RV.Type == BitTracker::BitValue::Ref) {
1844       if (RV.RefI.Reg != Reg)
1845         return false;
1846       if (RV.RefI.Pos != i+Pos)
1847         return false;
1848       continue;
1849     }
1850     if (RC[i+B] != SC[i+Pos])
1851       return false;
1852   }
1853 
1854   unsigned Sub = 0;
1855   switch (Pos) {
1856     case 0:
1857       Sub = Hexagon::isub_lo;
1858       Low = true;
1859       break;
1860     case 16:
1861       Sub = Hexagon::isub_lo;
1862       Low = false;
1863       break;
1864     case 32:
1865       Sub = Hexagon::isub_hi;
1866       Low = true;
1867       break;
1868     case 48:
1869       Sub = Hexagon::isub_hi;
1870       Low = false;
1871       break;
1872     default:
1873       return false;
1874   }
1875 
1876   RH.Reg = Reg;
1877   RH.Sub = Sub;
1878   RH.Low = Low;
1879   // If the subregister is not valid with the register, set it to 0.
1880   if (!HBS::getFinalVRegClass(RH, MRI))
1881     RH.Sub = 0;
1882 
1883   return true;
1884 }
1885 
1886 bool BitSimplification::validateReg(BitTracker::RegisterRef R, unsigned Opc,
1887       unsigned OpNum) {
1888   auto *OpRC = HII.getRegClass(HII.get(Opc), OpNum, &HRI, MF);
1889   auto *RRC = HBS::getFinalVRegClass(R, MRI);
1890   return OpRC->hasSubClassEq(RRC);
1891 }
1892 
1893 // Check if RC matches the pattern of a S2_packhl. If so, return true and
1894 // set the inputs Rs and Rt.
1895 bool BitSimplification::matchPackhl(unsigned SelfR,
1896       const BitTracker::RegisterCell &RC, BitTracker::RegisterRef &Rs,
1897       BitTracker::RegisterRef &Rt) {
1898   RegHalf L1, H1, L2, H2;
1899 
1900   if (!matchHalf(SelfR, RC, 0, L2)  || !matchHalf(SelfR, RC, 16, L1))
1901     return false;
1902   if (!matchHalf(SelfR, RC, 32, H2) || !matchHalf(SelfR, RC, 48, H1))
1903     return false;
1904 
1905   // Rs = H1.L1, Rt = H2.L2
1906   if (H1.Reg != L1.Reg || H1.Sub != L1.Sub || H1.Low || !L1.Low)
1907     return false;
1908   if (H2.Reg != L2.Reg || H2.Sub != L2.Sub || H2.Low || !L2.Low)
1909     return false;
1910 
1911   Rs = H1;
1912   Rt = H2;
1913   return true;
1914 }
1915 
1916 unsigned BitSimplification::getCombineOpcode(bool HLow, bool LLow) {
1917   return HLow ? LLow ? Hexagon::A2_combine_ll
1918                      : Hexagon::A2_combine_lh
1919               : LLow ? Hexagon::A2_combine_hl
1920                      : Hexagon::A2_combine_hh;
1921 }
1922 
1923 // If MI stores the upper halfword of a register (potentially obtained via
1924 // shifts or extracts), replace it with a storerf instruction. This could
1925 // cause the "extraction" code to become dead.
1926 bool BitSimplification::genStoreUpperHalf(MachineInstr *MI) {
1927   unsigned Opc = MI->getOpcode();
1928   if (Opc != Hexagon::S2_storerh_io)
1929     return false;
1930 
1931   MachineOperand &ValOp = MI->getOperand(2);
1932   BitTracker::RegisterRef RS = ValOp;
1933   if (!BT.has(RS.Reg))
1934     return false;
1935   const BitTracker::RegisterCell &RC = BT.lookup(RS.Reg);
1936   RegHalf H;
1937   if (!matchHalf(0, RC, 0, H))
1938     return false;
1939   if (H.Low)
1940     return false;
1941   MI->setDesc(HII.get(Hexagon::S2_storerf_io));
1942   ValOp.setReg(H.Reg);
1943   ValOp.setSubReg(H.Sub);
1944   return true;
1945 }
1946 
1947 // If MI stores a value known at compile-time, and the value is within a range
1948 // that avoids using constant-extenders, replace it with a store-immediate.
1949 bool BitSimplification::genStoreImmediate(MachineInstr *MI) {
1950   unsigned Opc = MI->getOpcode();
1951   unsigned Align = 0;
1952   switch (Opc) {
1953     case Hexagon::S2_storeri_io:
1954       Align++;
1955       LLVM_FALLTHROUGH;
1956     case Hexagon::S2_storerh_io:
1957       Align++;
1958       LLVM_FALLTHROUGH;
1959     case Hexagon::S2_storerb_io:
1960       break;
1961     default:
1962       return false;
1963   }
1964 
1965   // Avoid stores to frame-indices (due to an unknown offset).
1966   if (!MI->getOperand(0).isReg())
1967     return false;
1968   MachineOperand &OffOp = MI->getOperand(1);
1969   if (!OffOp.isImm())
1970     return false;
1971 
1972   int64_t Off = OffOp.getImm();
1973   // Offset is u6:a. Sadly, there is no isShiftedUInt(n,x).
1974   if (!isUIntN(6+Align, Off) || (Off & ((1<<Align)-1)))
1975     return false;
1976   // Source register:
1977   BitTracker::RegisterRef RS = MI->getOperand(2);
1978   if (!BT.has(RS.Reg))
1979     return false;
1980   const BitTracker::RegisterCell &RC = BT.lookup(RS.Reg);
1981   uint64_t U;
1982   if (!HBS::getConst(RC, 0, RC.width(), U))
1983     return false;
1984 
1985   // Only consider 8-bit values to avoid constant-extenders.
1986   int V;
1987   switch (Opc) {
1988     case Hexagon::S2_storerb_io:
1989       V = int8_t(U);
1990       break;
1991     case Hexagon::S2_storerh_io:
1992       V = int16_t(U);
1993       break;
1994     case Hexagon::S2_storeri_io:
1995       V = int32_t(U);
1996       break;
1997   }
1998   if (!isInt<8>(V))
1999     return false;
2000 
2001   MI->RemoveOperand(2);
2002   switch (Opc) {
2003     case Hexagon::S2_storerb_io:
2004       MI->setDesc(HII.get(Hexagon::S4_storeirb_io));
2005       break;
2006     case Hexagon::S2_storerh_io:
2007       MI->setDesc(HII.get(Hexagon::S4_storeirh_io));
2008       break;
2009     case Hexagon::S2_storeri_io:
2010       MI->setDesc(HII.get(Hexagon::S4_storeiri_io));
2011       break;
2012   }
2013   MI->addOperand(MachineOperand::CreateImm(V));
2014   return true;
2015 }
2016 
2017 // If MI is equivalent o S2_packhl, generate the S2_packhl. MI could be the
2018 // last instruction in a sequence that results in something equivalent to
2019 // the pack-halfwords. The intent is to cause the entire sequence to become
2020 // dead.
2021 bool BitSimplification::genPackhl(MachineInstr *MI,
2022       BitTracker::RegisterRef RD, const BitTracker::RegisterCell &RC) {
2023   unsigned Opc = MI->getOpcode();
2024   if (Opc == Hexagon::S2_packhl)
2025     return false;
2026   BitTracker::RegisterRef Rs, Rt;
2027   if (!matchPackhl(RD.Reg, RC, Rs, Rt))
2028     return false;
2029   if (!validateReg(Rs, Hexagon::S2_packhl, 1) ||
2030       !validateReg(Rt, Hexagon::S2_packhl, 2))
2031     return false;
2032 
2033   MachineBasicBlock &B = *MI->getParent();
2034   unsigned NewR = MRI.createVirtualRegister(&Hexagon::DoubleRegsRegClass);
2035   DebugLoc DL = MI->getDebugLoc();
2036   auto At = MI->isPHI() ? B.getFirstNonPHI()
2037                         : MachineBasicBlock::iterator(MI);
2038   BuildMI(B, At, DL, HII.get(Hexagon::S2_packhl), NewR)
2039       .addReg(Rs.Reg, 0, Rs.Sub)
2040       .addReg(Rt.Reg, 0, Rt.Sub);
2041   HBS::replaceSubWithSub(RD.Reg, RD.Sub, NewR, 0, MRI);
2042   BT.put(BitTracker::RegisterRef(NewR), RC);
2043   return true;
2044 }
2045 
2046 // If MI produces halfword of the input in the low half of the output,
2047 // replace it with zero-extend or extractu.
2048 bool BitSimplification::genExtractHalf(MachineInstr *MI,
2049       BitTracker::RegisterRef RD, const BitTracker::RegisterCell &RC) {
2050   RegHalf L;
2051   // Check for halfword in low 16 bits, zeros elsewhere.
2052   if (!matchHalf(RD.Reg, RC, 0, L) || !HBS::isZero(RC, 16, 16))
2053     return false;
2054 
2055   unsigned Opc = MI->getOpcode();
2056   MachineBasicBlock &B = *MI->getParent();
2057   DebugLoc DL = MI->getDebugLoc();
2058 
2059   // Prefer zxth, since zxth can go in any slot, while extractu only in
2060   // slots 2 and 3.
2061   unsigned NewR = 0;
2062   auto At = MI->isPHI() ? B.getFirstNonPHI()
2063                         : MachineBasicBlock::iterator(MI);
2064   if (L.Low && Opc != Hexagon::A2_zxth) {
2065     if (validateReg(L, Hexagon::A2_zxth, 1)) {
2066       NewR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
2067       BuildMI(B, At, DL, HII.get(Hexagon::A2_zxth), NewR)
2068           .addReg(L.Reg, 0, L.Sub);
2069     }
2070   } else if (!L.Low && Opc != Hexagon::S2_lsr_i_r) {
2071     if (validateReg(L, Hexagon::S2_lsr_i_r, 1)) {
2072       NewR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
2073       BuildMI(B, MI, DL, HII.get(Hexagon::S2_lsr_i_r), NewR)
2074           .addReg(L.Reg, 0, L.Sub)
2075           .addImm(16);
2076     }
2077   }
2078   if (NewR == 0)
2079     return false;
2080   HBS::replaceSubWithSub(RD.Reg, RD.Sub, NewR, 0, MRI);
2081   BT.put(BitTracker::RegisterRef(NewR), RC);
2082   return true;
2083 }
2084 
2085 // If MI is equivalent to a combine(.L/.H, .L/.H) replace with with the
2086 // combine.
2087 bool BitSimplification::genCombineHalf(MachineInstr *MI,
2088       BitTracker::RegisterRef RD, const BitTracker::RegisterCell &RC) {
2089   RegHalf L, H;
2090   // Check for combine h/l
2091   if (!matchHalf(RD.Reg, RC, 0, L) || !matchHalf(RD.Reg, RC, 16, H))
2092     return false;
2093   // Do nothing if this is just a reg copy.
2094   if (L.Reg == H.Reg && L.Sub == H.Sub && !H.Low && L.Low)
2095     return false;
2096 
2097   unsigned Opc = MI->getOpcode();
2098   unsigned COpc = getCombineOpcode(H.Low, L.Low);
2099   if (COpc == Opc)
2100     return false;
2101   if (!validateReg(H, COpc, 1) || !validateReg(L, COpc, 2))
2102     return false;
2103 
2104   MachineBasicBlock &B = *MI->getParent();
2105   DebugLoc DL = MI->getDebugLoc();
2106   unsigned NewR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
2107   auto At = MI->isPHI() ? B.getFirstNonPHI()
2108                         : MachineBasicBlock::iterator(MI);
2109   BuildMI(B, At, DL, HII.get(COpc), NewR)
2110       .addReg(H.Reg, 0, H.Sub)
2111       .addReg(L.Reg, 0, L.Sub);
2112   HBS::replaceSubWithSub(RD.Reg, RD.Sub, NewR, 0, MRI);
2113   BT.put(BitTracker::RegisterRef(NewR), RC);
2114   return true;
2115 }
2116 
2117 // If MI resets high bits of a register and keeps the lower ones, replace it
2118 // with zero-extend byte/half, and-immediate, or extractu, as appropriate.
2119 bool BitSimplification::genExtractLow(MachineInstr *MI,
2120       BitTracker::RegisterRef RD, const BitTracker::RegisterCell &RC) {
2121   unsigned Opc = MI->getOpcode();
2122   switch (Opc) {
2123     case Hexagon::A2_zxtb:
2124     case Hexagon::A2_zxth:
2125     case Hexagon::S2_extractu:
2126       return false;
2127   }
2128   if (Opc == Hexagon::A2_andir && MI->getOperand(2).isImm()) {
2129     int32_t Imm = MI->getOperand(2).getImm();
2130     if (isInt<10>(Imm))
2131       return false;
2132   }
2133 
2134   if (MI->hasUnmodeledSideEffects() || MI->isInlineAsm())
2135     return false;
2136   unsigned W = RC.width();
2137   while (W > 0 && RC[W-1].is(0))
2138     W--;
2139   if (W == 0 || W == RC.width())
2140     return false;
2141   unsigned NewOpc = (W == 8)  ? Hexagon::A2_zxtb
2142                   : (W == 16) ? Hexagon::A2_zxth
2143                   : (W < 10)  ? Hexagon::A2_andir
2144                   : Hexagon::S2_extractu;
2145   MachineBasicBlock &B = *MI->getParent();
2146   DebugLoc DL = MI->getDebugLoc();
2147 
2148   for (auto &Op : MI->uses()) {
2149     if (!Op.isReg())
2150       continue;
2151     BitTracker::RegisterRef RS = Op;
2152     if (!BT.has(RS.Reg))
2153       continue;
2154     const BitTracker::RegisterCell &SC = BT.lookup(RS.Reg);
2155     unsigned BN, BW;
2156     if (!HBS::getSubregMask(RS, BN, BW, MRI))
2157       continue;
2158     if (BW < W || !HBS::isEqual(RC, 0, SC, BN, W))
2159       continue;
2160     if (!validateReg(RS, NewOpc, 1))
2161       continue;
2162 
2163     unsigned NewR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
2164     auto At = MI->isPHI() ? B.getFirstNonPHI()
2165                           : MachineBasicBlock::iterator(MI);
2166     auto MIB = BuildMI(B, At, DL, HII.get(NewOpc), NewR)
2167                   .addReg(RS.Reg, 0, RS.Sub);
2168     if (NewOpc == Hexagon::A2_andir)
2169       MIB.addImm((1 << W) - 1);
2170     else if (NewOpc == Hexagon::S2_extractu)
2171       MIB.addImm(W).addImm(0);
2172     HBS::replaceSubWithSub(RD.Reg, RD.Sub, NewR, 0, MRI);
2173     BT.put(BitTracker::RegisterRef(NewR), RC);
2174     return true;
2175   }
2176   return false;
2177 }
2178 
2179 bool BitSimplification::genBitSplit(MachineInstr *MI,
2180       BitTracker::RegisterRef RD, const BitTracker::RegisterCell &RC,
2181       const RegisterSet &AVs) {
2182   if (!GenBitSplit)
2183     return false;
2184   if (MaxBitSplit.getNumOccurrences()) {
2185     if (CountBitSplit >= MaxBitSplit)
2186       return false;
2187   }
2188 
2189   unsigned Opc = MI->getOpcode();
2190   switch (Opc) {
2191     case Hexagon::A4_bitsplit:
2192     case Hexagon::A4_bitspliti:
2193       return false;
2194   }
2195 
2196   unsigned W = RC.width();
2197   if (W != 32)
2198     return false;
2199 
2200   auto ctlz = [] (const BitTracker::RegisterCell &C) -> unsigned {
2201     unsigned Z = C.width();
2202     while (Z > 0 && C[Z-1].is(0))
2203       --Z;
2204     return C.width() - Z;
2205   };
2206 
2207   // Count the number of leading zeros in the target RC.
2208   unsigned Z = ctlz(RC);
2209   if (Z == 0 || Z == W)
2210     return false;
2211 
2212   // A simplistic analysis: assume the source register (the one being split)
2213   // is fully unknown, and that all its bits are self-references.
2214   const BitTracker::BitValue &B0 = RC[0];
2215   if (B0.Type != BitTracker::BitValue::Ref)
2216     return false;
2217 
2218   unsigned SrcR = B0.RefI.Reg;
2219   unsigned SrcSR = 0;
2220   unsigned Pos = B0.RefI.Pos;
2221 
2222   // All the non-zero bits should be consecutive bits from the same register.
2223   for (unsigned i = 1; i < W-Z; ++i) {
2224     const BitTracker::BitValue &V = RC[i];
2225     if (V.Type != BitTracker::BitValue::Ref)
2226       return false;
2227     if (V.RefI.Reg != SrcR || V.RefI.Pos != Pos+i)
2228       return false;
2229   }
2230 
2231   // Now, find the other bitfield among AVs.
2232   for (unsigned S = AVs.find_first(); S; S = AVs.find_next(S)) {
2233     // The number of leading zeros here should be the number of trailing
2234     // non-zeros in RC.
2235     if (!BT.has(S))
2236       continue;
2237     const BitTracker::RegisterCell &SC = BT.lookup(S);
2238     if (SC.width() != W || ctlz(SC) != W-Z)
2239       continue;
2240     // The Z lower bits should now match SrcR.
2241     const BitTracker::BitValue &S0 = SC[0];
2242     if (S0.Type != BitTracker::BitValue::Ref || S0.RefI.Reg != SrcR)
2243       continue;
2244     unsigned P = S0.RefI.Pos;
2245 
2246     if (Pos <= P && (Pos + W-Z) != P)
2247       continue;
2248     if (P < Pos && (P + Z) != Pos)
2249       continue;
2250     // The starting bitfield position must be at a subregister boundary.
2251     if (std::min(P, Pos) != 0 && std::min(P, Pos) != 32)
2252       continue;
2253 
2254     unsigned I;
2255     for (I = 1; I < Z; ++I) {
2256       const BitTracker::BitValue &V = SC[I];
2257       if (V.Type != BitTracker::BitValue::Ref)
2258         break;
2259       if (V.RefI.Reg != SrcR || V.RefI.Pos != P+I)
2260         break;
2261     }
2262     if (I != Z)
2263       continue;
2264 
2265     // Generate bitsplit where S is defined.
2266     if (MaxBitSplit.getNumOccurrences())
2267       CountBitSplit++;
2268     MachineInstr *DefS = MRI.getVRegDef(S);
2269     assert(DefS != nullptr);
2270     DebugLoc DL = DefS->getDebugLoc();
2271     MachineBasicBlock &B = *DefS->getParent();
2272     auto At = DefS->isPHI() ? B.getFirstNonPHI()
2273                             : MachineBasicBlock::iterator(DefS);
2274     if (MRI.getRegClass(SrcR)->getID() == Hexagon::DoubleRegsRegClassID)
2275       SrcSR = (std::min(Pos, P) == 32) ? Hexagon::isub_hi : Hexagon::isub_lo;
2276     if (!validateReg({SrcR,SrcSR}, Hexagon::A4_bitspliti, 1))
2277       continue;
2278     unsigned ImmOp = Pos <= P ? W-Z : Z;
2279 
2280     // Find an existing bitsplit instruction if one already exists.
2281     unsigned NewR = 0;
2282     for (MachineInstr *In : NewMIs) {
2283       if (In->getOpcode() != Hexagon::A4_bitspliti)
2284         continue;
2285       MachineOperand &Op1 = In->getOperand(1);
2286       if (Op1.getReg() != SrcR || Op1.getSubReg() != SrcSR)
2287         continue;
2288       if (In->getOperand(2).getImm() != ImmOp)
2289         continue;
2290       // Check if the target register is available here.
2291       MachineOperand &Op0 = In->getOperand(0);
2292       MachineInstr *DefI = MRI.getVRegDef(Op0.getReg());
2293       assert(DefI != nullptr);
2294       if (!MDT.dominates(DefI, &*At))
2295         continue;
2296 
2297       // Found one that can be reused.
2298       assert(Op0.getSubReg() == 0);
2299       NewR = Op0.getReg();
2300       break;
2301     }
2302     if (!NewR) {
2303       NewR = MRI.createVirtualRegister(&Hexagon::DoubleRegsRegClass);
2304       auto NewBS = BuildMI(B, At, DL, HII.get(Hexagon::A4_bitspliti), NewR)
2305                       .addReg(SrcR, 0, SrcSR)
2306                       .addImm(ImmOp);
2307       NewMIs.push_back(NewBS);
2308     }
2309     if (Pos <= P) {
2310       HBS::replaceRegWithSub(RD.Reg, NewR, Hexagon::isub_lo, MRI);
2311       HBS::replaceRegWithSub(S,      NewR, Hexagon::isub_hi, MRI);
2312     } else {
2313       HBS::replaceRegWithSub(S,      NewR, Hexagon::isub_lo, MRI);
2314       HBS::replaceRegWithSub(RD.Reg, NewR, Hexagon::isub_hi, MRI);
2315     }
2316     return true;
2317   }
2318 
2319   return false;
2320 }
2321 
2322 // Check for tstbit simplification opportunity, where the bit being checked
2323 // can be tracked back to another register. For example:
2324 //   vreg2 = S2_lsr_i_r  vreg1, 5
2325 //   vreg3 = S2_tstbit_i vreg2, 0
2326 // =>
2327 //   vreg3 = S2_tstbit_i vreg1, 5
2328 bool BitSimplification::simplifyTstbit(MachineInstr *MI,
2329       BitTracker::RegisterRef RD, const BitTracker::RegisterCell &RC) {
2330   unsigned Opc = MI->getOpcode();
2331   if (Opc != Hexagon::S2_tstbit_i)
2332     return false;
2333 
2334   unsigned BN = MI->getOperand(2).getImm();
2335   BitTracker::RegisterRef RS = MI->getOperand(1);
2336   unsigned F, W;
2337   DebugLoc DL = MI->getDebugLoc();
2338   if (!BT.has(RS.Reg) || !HBS::getSubregMask(RS, F, W, MRI))
2339     return false;
2340   MachineBasicBlock &B = *MI->getParent();
2341   auto At = MI->isPHI() ? B.getFirstNonPHI()
2342                         : MachineBasicBlock::iterator(MI);
2343 
2344   const BitTracker::RegisterCell &SC = BT.lookup(RS.Reg);
2345   const BitTracker::BitValue &V = SC[F+BN];
2346   if (V.Type == BitTracker::BitValue::Ref && V.RefI.Reg != RS.Reg) {
2347     const TargetRegisterClass *TC = MRI.getRegClass(V.RefI.Reg);
2348     // Need to map V.RefI.Reg to a 32-bit register, i.e. if it is
2349     // a double register, need to use a subregister and adjust bit
2350     // number.
2351     unsigned P = std::numeric_limits<unsigned>::max();
2352     BitTracker::RegisterRef RR(V.RefI.Reg, 0);
2353     if (TC == &Hexagon::DoubleRegsRegClass) {
2354       P = V.RefI.Pos;
2355       RR.Sub = Hexagon::isub_lo;
2356       if (P >= 32) {
2357         P -= 32;
2358         RR.Sub = Hexagon::isub_hi;
2359       }
2360     } else if (TC == &Hexagon::IntRegsRegClass) {
2361       P = V.RefI.Pos;
2362     }
2363     if (P != std::numeric_limits<unsigned>::max()) {
2364       unsigned NewR = MRI.createVirtualRegister(&Hexagon::PredRegsRegClass);
2365       BuildMI(B, At, DL, HII.get(Hexagon::S2_tstbit_i), NewR)
2366           .addReg(RR.Reg, 0, RR.Sub)
2367           .addImm(P);
2368       HBS::replaceReg(RD.Reg, NewR, MRI);
2369       BT.put(NewR, RC);
2370       return true;
2371     }
2372   } else if (V.is(0) || V.is(1)) {
2373     unsigned NewR = MRI.createVirtualRegister(&Hexagon::PredRegsRegClass);
2374     unsigned NewOpc = V.is(0) ? Hexagon::PS_false : Hexagon::PS_true;
2375     BuildMI(B, At, DL, HII.get(NewOpc), NewR);
2376     HBS::replaceReg(RD.Reg, NewR, MRI);
2377     return true;
2378   }
2379 
2380   return false;
2381 }
2382 
2383 // Detect whether RD is a bitfield extract (sign- or zero-extended) of
2384 // some register from the AVs set. Create a new corresponding instruction
2385 // at the location of MI. The intent is to recognize situations where
2386 // a sequence of instructions performs an operation that is equivalent to
2387 // an extract operation, such as a shift left followed by a shift right.
2388 bool BitSimplification::simplifyExtractLow(MachineInstr *MI,
2389       BitTracker::RegisterRef RD, const BitTracker::RegisterCell &RC,
2390       const RegisterSet &AVs) {
2391   if (!GenExtract)
2392     return false;
2393   if (MaxExtract.getNumOccurrences()) {
2394     if (CountExtract >= MaxExtract)
2395       return false;
2396     CountExtract++;
2397   }
2398 
2399   unsigned W = RC.width();
2400   unsigned RW = W;
2401   unsigned Len;
2402   bool Signed;
2403 
2404   // The code is mostly class-independent, except for the part that generates
2405   // the extract instruction, and establishes the source register (in case it
2406   // needs to use a subregister).
2407   const TargetRegisterClass *FRC = HBS::getFinalVRegClass(RD, MRI);
2408   if (FRC != &Hexagon::IntRegsRegClass && FRC != &Hexagon::DoubleRegsRegClass)
2409     return false;
2410   assert(RD.Sub == 0);
2411 
2412   // Observation:
2413   // If the cell has a form of 00..0xx..x with k zeros and n remaining
2414   // bits, this could be an extractu of the n bits, but it could also be
2415   // an extractu of a longer field which happens to have 0s in the top
2416   // bit positions.
2417   // The same logic applies to sign-extended fields.
2418   //
2419   // Do not check for the extended extracts, since it would expand the
2420   // search space quite a bit. The search may be expensive as it is.
2421 
2422   const BitTracker::BitValue &TopV = RC[W-1];
2423 
2424   // Eliminate candidates that have self-referential bits, since they
2425   // cannot be extracts from other registers. Also, skip registers that
2426   // have compile-time constant values.
2427   bool IsConst = true;
2428   for (unsigned I = 0; I != W; ++I) {
2429     const BitTracker::BitValue &V = RC[I];
2430     if (V.Type == BitTracker::BitValue::Ref && V.RefI.Reg == RD.Reg)
2431       return false;
2432     IsConst = IsConst && (V.is(0) || V.is(1));
2433   }
2434   if (IsConst)
2435     return false;
2436 
2437   if (TopV.is(0) || TopV.is(1)) {
2438     bool S = TopV.is(1);
2439     for (--W; W > 0 && RC[W-1].is(S); --W)
2440       ;
2441     Len = W;
2442     Signed = S;
2443     // The sign bit must be a part of the field being extended.
2444     if (Signed)
2445       ++Len;
2446   } else {
2447     // This could still be a sign-extended extract.
2448     assert(TopV.Type == BitTracker::BitValue::Ref);
2449     if (TopV.RefI.Reg == RD.Reg || TopV.RefI.Pos == W-1)
2450       return false;
2451     for (--W; W > 0 && RC[W-1] == TopV; --W)
2452       ;
2453     // The top bits of RC are copies of TopV. One occurrence of TopV will
2454     // be a part of the field.
2455     Len = W + 1;
2456     Signed = true;
2457   }
2458 
2459   // This would be just a copy. It should be handled elsewhere.
2460   if (Len == RW)
2461     return false;
2462 
2463   DEBUG({
2464     dbgs() << __func__ << " on reg: " << PrintReg(RD.Reg, &HRI, RD.Sub)
2465            << ", MI: " << *MI;
2466     dbgs() << "Cell: " << RC << '\n';
2467     dbgs() << "Expected bitfield size: " << Len << " bits, "
2468            << (Signed ? "sign" : "zero") << "-extended\n";
2469   });
2470 
2471   bool Changed = false;
2472 
2473   for (unsigned R = AVs.find_first(); R != 0; R = AVs.find_next(R)) {
2474     if (!BT.has(R))
2475       continue;
2476     const BitTracker::RegisterCell &SC = BT.lookup(R);
2477     unsigned SW = SC.width();
2478 
2479     // The source can be longer than the destination, as long as its size is
2480     // a multiple of the size of the destination. Also, we would need to be
2481     // able to refer to the subregister in the source that would be of the
2482     // same size as the destination, but only check the sizes here.
2483     if (SW < RW || (SW % RW) != 0)
2484       continue;
2485 
2486     // The field can start at any offset in SC as long as it contains Len
2487     // bits and does not cross subregister boundary (if the source register
2488     // is longer than the destination).
2489     unsigned Off = 0;
2490     while (Off <= SW-Len) {
2491       unsigned OE = (Off+Len)/RW;
2492       if (OE != Off/RW) {
2493         // The assumption here is that if the source (R) is longer than the
2494         // destination, then the destination is a sequence of words of
2495         // size RW, and each such word in R can be accessed via a subregister.
2496         //
2497         // If the beginning and the end of the field cross the subregister
2498         // boundary, advance to the next subregister.
2499         Off = OE*RW;
2500         continue;
2501       }
2502       if (HBS::isEqual(RC, 0, SC, Off, Len))
2503         break;
2504       ++Off;
2505     }
2506 
2507     if (Off > SW-Len)
2508       continue;
2509 
2510     // Found match.
2511     unsigned ExtOpc = 0;
2512     if (Off == 0) {
2513       if (Len == 8)
2514         ExtOpc = Signed ? Hexagon::A2_sxtb : Hexagon::A2_zxtb;
2515       else if (Len == 16)
2516         ExtOpc = Signed ? Hexagon::A2_sxth : Hexagon::A2_zxth;
2517       else if (Len < 10 && !Signed)
2518         ExtOpc = Hexagon::A2_andir;
2519     }
2520     if (ExtOpc == 0) {
2521       ExtOpc =
2522           Signed ? (RW == 32 ? Hexagon::S4_extract  : Hexagon::S4_extractp)
2523                  : (RW == 32 ? Hexagon::S2_extractu : Hexagon::S2_extractup);
2524     }
2525     unsigned SR = 0;
2526     // This only recognizes isub_lo and isub_hi.
2527     if (RW != SW && RW*2 != SW)
2528       continue;
2529     if (RW != SW)
2530       SR = (Off/RW == 0) ? Hexagon::isub_lo : Hexagon::isub_hi;
2531     Off = Off % RW;
2532 
2533     if (!validateReg({R,SR}, ExtOpc, 1))
2534       continue;
2535 
2536     // Don't generate the same instruction as the one being optimized.
2537     if (MI->getOpcode() == ExtOpc) {
2538       // All possible ExtOpc's have the source in operand(1).
2539       const MachineOperand &SrcOp = MI->getOperand(1);
2540       if (SrcOp.getReg() == R)
2541         continue;
2542     }
2543 
2544     DebugLoc DL = MI->getDebugLoc();
2545     MachineBasicBlock &B = *MI->getParent();
2546     unsigned NewR = MRI.createVirtualRegister(FRC);
2547     auto At = MI->isPHI() ? B.getFirstNonPHI()
2548                           : MachineBasicBlock::iterator(MI);
2549     auto MIB = BuildMI(B, At, DL, HII.get(ExtOpc), NewR)
2550                   .addReg(R, 0, SR);
2551     switch (ExtOpc) {
2552       case Hexagon::A2_sxtb:
2553       case Hexagon::A2_zxtb:
2554       case Hexagon::A2_sxth:
2555       case Hexagon::A2_zxth:
2556         break;
2557       case Hexagon::A2_andir:
2558         MIB.addImm((1u << Len) - 1);
2559         break;
2560       case Hexagon::S4_extract:
2561       case Hexagon::S2_extractu:
2562       case Hexagon::S4_extractp:
2563       case Hexagon::S2_extractup:
2564         MIB.addImm(Len)
2565            .addImm(Off);
2566         break;
2567       default:
2568         llvm_unreachable("Unexpected opcode");
2569     }
2570 
2571     HBS::replaceReg(RD.Reg, NewR, MRI);
2572     BT.put(BitTracker::RegisterRef(NewR), RC);
2573     Changed = true;
2574     break;
2575   }
2576 
2577   return Changed;
2578 }
2579 
2580 bool BitSimplification::processBlock(MachineBasicBlock &B,
2581       const RegisterSet &AVs) {
2582   if (!BT.reached(&B))
2583     return false;
2584   bool Changed = false;
2585   RegisterSet AVB = AVs;
2586   RegisterSet Defs;
2587 
2588   for (auto I = B.begin(), E = B.end(); I != E; ++I, AVB.insert(Defs)) {
2589     MachineInstr *MI = &*I;
2590     Defs.clear();
2591     HBS::getInstrDefs(*MI, Defs);
2592 
2593     unsigned Opc = MI->getOpcode();
2594     if (Opc == TargetOpcode::COPY || Opc == TargetOpcode::REG_SEQUENCE)
2595       continue;
2596 
2597     if (MI->mayStore()) {
2598       bool T = genStoreUpperHalf(MI);
2599       T = T || genStoreImmediate(MI);
2600       Changed |= T;
2601       continue;
2602     }
2603 
2604     if (Defs.count() != 1)
2605       continue;
2606     const MachineOperand &Op0 = MI->getOperand(0);
2607     if (!Op0.isReg() || !Op0.isDef())
2608       continue;
2609     BitTracker::RegisterRef RD = Op0;
2610     if (!BT.has(RD.Reg))
2611       continue;
2612     const TargetRegisterClass *FRC = HBS::getFinalVRegClass(RD, MRI);
2613     const BitTracker::RegisterCell &RC = BT.lookup(RD.Reg);
2614 
2615     if (FRC->getID() == Hexagon::DoubleRegsRegClassID) {
2616       bool T = genPackhl(MI, RD, RC);
2617       T = T || simplifyExtractLow(MI, RD, RC, AVB);
2618       Changed |= T;
2619       continue;
2620     }
2621 
2622     if (FRC->getID() == Hexagon::IntRegsRegClassID) {
2623       bool T = genBitSplit(MI, RD, RC, AVB);
2624       T = T || simplifyExtractLow(MI, RD, RC, AVB);
2625       T = T || genExtractHalf(MI, RD, RC);
2626       T = T || genCombineHalf(MI, RD, RC);
2627       T = T || genExtractLow(MI, RD, RC);
2628       Changed |= T;
2629       continue;
2630     }
2631 
2632     if (FRC->getID() == Hexagon::PredRegsRegClassID) {
2633       bool T = simplifyTstbit(MI, RD, RC);
2634       Changed |= T;
2635       continue;
2636     }
2637   }
2638   return Changed;
2639 }
2640 
2641 bool HexagonBitSimplify::runOnMachineFunction(MachineFunction &MF) {
2642   if (skipFunction(*MF.getFunction()))
2643     return false;
2644 
2645   auto &HST = MF.getSubtarget<HexagonSubtarget>();
2646   auto &HRI = *HST.getRegisterInfo();
2647   auto &HII = *HST.getInstrInfo();
2648 
2649   MDT = &getAnalysis<MachineDominatorTree>();
2650   MachineRegisterInfo &MRI = MF.getRegInfo();
2651   bool Changed;
2652 
2653   Changed = DeadCodeElimination(MF, *MDT).run();
2654 
2655   const HexagonEvaluator HE(HRI, MRI, HII, MF);
2656   BitTracker BT(HE, MF);
2657   DEBUG(BT.trace(true));
2658   BT.run();
2659 
2660   MachineBasicBlock &Entry = MF.front();
2661 
2662   RegisterSet AIG;  // Available registers for IG.
2663   ConstGeneration ImmG(BT, HII, MRI);
2664   Changed |= visitBlock(Entry, ImmG, AIG);
2665 
2666   RegisterSet ARE;  // Available registers for RIE.
2667   RedundantInstrElimination RIE(BT, HII, HRI, MRI);
2668   bool Ried = visitBlock(Entry, RIE, ARE);
2669   if (Ried) {
2670     Changed = true;
2671     BT.run();
2672   }
2673 
2674   RegisterSet ACG;  // Available registers for CG.
2675   CopyGeneration CopyG(BT, HII, HRI, MRI);
2676   Changed |= visitBlock(Entry, CopyG, ACG);
2677 
2678   RegisterSet ACP;  // Available registers for CP.
2679   CopyPropagation CopyP(HRI, MRI);
2680   Changed |= visitBlock(Entry, CopyP, ACP);
2681 
2682   Changed = DeadCodeElimination(MF, *MDT).run() || Changed;
2683 
2684   BT.run();
2685   RegisterSet ABS;  // Available registers for BS.
2686   BitSimplification BitS(BT, *MDT, HII, HRI, MRI, MF);
2687   Changed |= visitBlock(Entry, BitS, ABS);
2688 
2689   Changed = DeadCodeElimination(MF, *MDT).run() || Changed;
2690 
2691   if (Changed) {
2692     for (auto &B : MF)
2693       for (auto &I : B)
2694         I.clearKillInfo();
2695     DeadCodeElimination(MF, *MDT).run();
2696   }
2697   return Changed;
2698 }
2699 
2700 // Recognize loops where the code at the end of the loop matches the code
2701 // before the entry of the loop, and the matching code is such that is can
2702 // be simplified. This pass relies on the bit simplification above and only
2703 // prepares code in a way that can be handled by the bit simplifcation.
2704 //
2705 // This is the motivating testcase (and explanation):
2706 //
2707 // {
2708 //   loop0(.LBB0_2, r1)      // %for.body.preheader
2709 //   r5:4 = memd(r0++#8)
2710 // }
2711 // {
2712 //   r3 = lsr(r4, #16)
2713 //   r7:6 = combine(r5, r5)
2714 // }
2715 // {
2716 //   r3 = insert(r5, #16, #16)
2717 //   r7:6 = vlsrw(r7:6, #16)
2718 // }
2719 // .LBB0_2:
2720 // {
2721 //   memh(r2+#4) = r5
2722 //   memh(r2+#6) = r6            # R6 is really R5.H
2723 // }
2724 // {
2725 //   r2 = add(r2, #8)
2726 //   memh(r2+#0) = r4
2727 //   memh(r2+#2) = r3            # R3 is really R4.H
2728 // }
2729 // {
2730 //   r5:4 = memd(r0++#8)
2731 // }
2732 // {                             # "Shuffling" code that sets up R3 and R6
2733 //   r3 = lsr(r4, #16)           # so that their halves can be stored in the
2734 //   r7:6 = combine(r5, r5)      # next iteration. This could be folded into
2735 // }                             # the stores if the code was at the beginning
2736 // {                             # of the loop iteration. Since the same code
2737 //   r3 = insert(r5, #16, #16)   # precedes the loop, it can actually be moved
2738 //   r7:6 = vlsrw(r7:6, #16)     # there.
2739 // }:endloop0
2740 //
2741 //
2742 // The outcome:
2743 //
2744 // {
2745 //   loop0(.LBB0_2, r1)
2746 //   r5:4 = memd(r0++#8)
2747 // }
2748 // .LBB0_2:
2749 // {
2750 //   memh(r2+#4) = r5
2751 //   memh(r2+#6) = r5.h
2752 // }
2753 // {
2754 //   r2 = add(r2, #8)
2755 //   memh(r2+#0) = r4
2756 //   memh(r2+#2) = r4.h
2757 // }
2758 // {
2759 //   r5:4 = memd(r0++#8)
2760 // }:endloop0
2761 
2762 namespace llvm {
2763 
2764   FunctionPass *createHexagonLoopRescheduling();
2765   void initializeHexagonLoopReschedulingPass(PassRegistry&);
2766 
2767 } // end namespace llvm
2768 
2769 namespace {
2770 
2771   class HexagonLoopRescheduling : public MachineFunctionPass {
2772   public:
2773     static char ID;
2774 
2775     HexagonLoopRescheduling() : MachineFunctionPass(ID) {
2776       initializeHexagonLoopReschedulingPass(*PassRegistry::getPassRegistry());
2777     }
2778 
2779     bool runOnMachineFunction(MachineFunction &MF) override;
2780 
2781   private:
2782     const HexagonInstrInfo *HII = nullptr;
2783     const HexagonRegisterInfo *HRI = nullptr;
2784     MachineRegisterInfo *MRI = nullptr;
2785     BitTracker *BTP = nullptr;
2786 
2787     struct LoopCand {
2788       LoopCand(MachineBasicBlock *lb, MachineBasicBlock *pb,
2789             MachineBasicBlock *eb) : LB(lb), PB(pb), EB(eb) {}
2790 
2791       MachineBasicBlock *LB, *PB, *EB;
2792     };
2793     using InstrList = std::vector<MachineInstr *>;
2794     struct InstrGroup {
2795       BitTracker::RegisterRef Inp, Out;
2796       InstrList Ins;
2797     };
2798     struct PhiInfo {
2799       PhiInfo(MachineInstr &P, MachineBasicBlock &B);
2800 
2801       unsigned DefR;
2802       BitTracker::RegisterRef LR, PR; // Loop Register, Preheader Register
2803       MachineBasicBlock *LB, *PB;     // Loop Block, Preheader Block
2804     };
2805 
2806     static unsigned getDefReg(const MachineInstr *MI);
2807     bool isConst(unsigned Reg) const;
2808     bool isBitShuffle(const MachineInstr *MI, unsigned DefR) const;
2809     bool isStoreInput(const MachineInstr *MI, unsigned DefR) const;
2810     bool isShuffleOf(unsigned OutR, unsigned InpR) const;
2811     bool isSameShuffle(unsigned OutR1, unsigned InpR1, unsigned OutR2,
2812         unsigned &InpR2) const;
2813     void moveGroup(InstrGroup &G, MachineBasicBlock &LB, MachineBasicBlock &PB,
2814         MachineBasicBlock::iterator At, unsigned OldPhiR, unsigned NewPredR);
2815     bool processLoop(LoopCand &C);
2816   };
2817 
2818 } // end anonymous namespace
2819 
2820 char HexagonLoopRescheduling::ID = 0;
2821 
2822 INITIALIZE_PASS(HexagonLoopRescheduling, "hexagon-loop-resched",
2823   "Hexagon Loop Rescheduling", false, false)
2824 
2825 HexagonLoopRescheduling::PhiInfo::PhiInfo(MachineInstr &P,
2826       MachineBasicBlock &B) {
2827   DefR = HexagonLoopRescheduling::getDefReg(&P);
2828   LB = &B;
2829   PB = nullptr;
2830   for (unsigned i = 1, n = P.getNumOperands(); i < n; i += 2) {
2831     const MachineOperand &OpB = P.getOperand(i+1);
2832     if (OpB.getMBB() == &B) {
2833       LR = P.getOperand(i);
2834       continue;
2835     }
2836     PB = OpB.getMBB();
2837     PR = P.getOperand(i);
2838   }
2839 }
2840 
2841 unsigned HexagonLoopRescheduling::getDefReg(const MachineInstr *MI) {
2842   RegisterSet Defs;
2843   HBS::getInstrDefs(*MI, Defs);
2844   if (Defs.count() != 1)
2845     return 0;
2846   return Defs.find_first();
2847 }
2848 
2849 bool HexagonLoopRescheduling::isConst(unsigned Reg) const {
2850   if (!BTP->has(Reg))
2851     return false;
2852   const BitTracker::RegisterCell &RC = BTP->lookup(Reg);
2853   for (unsigned i = 0, w = RC.width(); i < w; ++i) {
2854     const BitTracker::BitValue &V = RC[i];
2855     if (!V.is(0) && !V.is(1))
2856       return false;
2857   }
2858   return true;
2859 }
2860 
2861 bool HexagonLoopRescheduling::isBitShuffle(const MachineInstr *MI,
2862       unsigned DefR) const {
2863   unsigned Opc = MI->getOpcode();
2864   switch (Opc) {
2865     case TargetOpcode::COPY:
2866     case Hexagon::S2_lsr_i_r:
2867     case Hexagon::S2_asr_i_r:
2868     case Hexagon::S2_asl_i_r:
2869     case Hexagon::S2_lsr_i_p:
2870     case Hexagon::S2_asr_i_p:
2871     case Hexagon::S2_asl_i_p:
2872     case Hexagon::S2_insert:
2873     case Hexagon::A2_or:
2874     case Hexagon::A2_orp:
2875     case Hexagon::A2_and:
2876     case Hexagon::A2_andp:
2877     case Hexagon::A2_combinew:
2878     case Hexagon::A4_combineri:
2879     case Hexagon::A4_combineir:
2880     case Hexagon::A2_combineii:
2881     case Hexagon::A4_combineii:
2882     case Hexagon::A2_combine_ll:
2883     case Hexagon::A2_combine_lh:
2884     case Hexagon::A2_combine_hl:
2885     case Hexagon::A2_combine_hh:
2886       return true;
2887   }
2888   return false;
2889 }
2890 
2891 bool HexagonLoopRescheduling::isStoreInput(const MachineInstr *MI,
2892       unsigned InpR) const {
2893   for (unsigned i = 0, n = MI->getNumOperands(); i < n; ++i) {
2894     const MachineOperand &Op = MI->getOperand(i);
2895     if (!Op.isReg())
2896       continue;
2897     if (Op.getReg() == InpR)
2898       return i == n-1;
2899   }
2900   return false;
2901 }
2902 
2903 bool HexagonLoopRescheduling::isShuffleOf(unsigned OutR, unsigned InpR) const {
2904   if (!BTP->has(OutR) || !BTP->has(InpR))
2905     return false;
2906   const BitTracker::RegisterCell &OutC = BTP->lookup(OutR);
2907   for (unsigned i = 0, w = OutC.width(); i < w; ++i) {
2908     const BitTracker::BitValue &V = OutC[i];
2909     if (V.Type != BitTracker::BitValue::Ref)
2910       continue;
2911     if (V.RefI.Reg != InpR)
2912       return false;
2913   }
2914   return true;
2915 }
2916 
2917 bool HexagonLoopRescheduling::isSameShuffle(unsigned OutR1, unsigned InpR1,
2918       unsigned OutR2, unsigned &InpR2) const {
2919   if (!BTP->has(OutR1) || !BTP->has(InpR1) || !BTP->has(OutR2))
2920     return false;
2921   const BitTracker::RegisterCell &OutC1 = BTP->lookup(OutR1);
2922   const BitTracker::RegisterCell &OutC2 = BTP->lookup(OutR2);
2923   unsigned W = OutC1.width();
2924   unsigned MatchR = 0;
2925   if (W != OutC2.width())
2926     return false;
2927   for (unsigned i = 0; i < W; ++i) {
2928     const BitTracker::BitValue &V1 = OutC1[i], &V2 = OutC2[i];
2929     if (V1.Type != V2.Type || V1.Type == BitTracker::BitValue::One)
2930       return false;
2931     if (V1.Type != BitTracker::BitValue::Ref)
2932       continue;
2933     if (V1.RefI.Pos != V2.RefI.Pos)
2934       return false;
2935     if (V1.RefI.Reg != InpR1)
2936       return false;
2937     if (V2.RefI.Reg == 0 || V2.RefI.Reg == OutR2)
2938       return false;
2939     if (!MatchR)
2940       MatchR = V2.RefI.Reg;
2941     else if (V2.RefI.Reg != MatchR)
2942       return false;
2943   }
2944   InpR2 = MatchR;
2945   return true;
2946 }
2947 
2948 void HexagonLoopRescheduling::moveGroup(InstrGroup &G, MachineBasicBlock &LB,
2949       MachineBasicBlock &PB, MachineBasicBlock::iterator At, unsigned OldPhiR,
2950       unsigned NewPredR) {
2951   DenseMap<unsigned,unsigned> RegMap;
2952 
2953   const TargetRegisterClass *PhiRC = MRI->getRegClass(NewPredR);
2954   unsigned PhiR = MRI->createVirtualRegister(PhiRC);
2955   BuildMI(LB, At, At->getDebugLoc(), HII->get(TargetOpcode::PHI), PhiR)
2956     .addReg(NewPredR)
2957     .addMBB(&PB)
2958     .addReg(G.Inp.Reg)
2959     .addMBB(&LB);
2960   RegMap.insert(std::make_pair(G.Inp.Reg, PhiR));
2961 
2962   for (unsigned i = G.Ins.size(); i > 0; --i) {
2963     const MachineInstr *SI = G.Ins[i-1];
2964     unsigned DR = getDefReg(SI);
2965     const TargetRegisterClass *RC = MRI->getRegClass(DR);
2966     unsigned NewDR = MRI->createVirtualRegister(RC);
2967     DebugLoc DL = SI->getDebugLoc();
2968 
2969     auto MIB = BuildMI(LB, At, DL, HII->get(SI->getOpcode()), NewDR);
2970     for (unsigned j = 0, m = SI->getNumOperands(); j < m; ++j) {
2971       const MachineOperand &Op = SI->getOperand(j);
2972       if (!Op.isReg()) {
2973         MIB.add(Op);
2974         continue;
2975       }
2976       if (!Op.isUse())
2977         continue;
2978       unsigned UseR = RegMap[Op.getReg()];
2979       MIB.addReg(UseR, 0, Op.getSubReg());
2980     }
2981     RegMap.insert(std::make_pair(DR, NewDR));
2982   }
2983 
2984   HBS::replaceReg(OldPhiR, RegMap[G.Out.Reg], *MRI);
2985 }
2986 
2987 bool HexagonLoopRescheduling::processLoop(LoopCand &C) {
2988   DEBUG(dbgs() << "Processing loop in BB#" << C.LB->getNumber() << "\n");
2989   std::vector<PhiInfo> Phis;
2990   for (auto &I : *C.LB) {
2991     if (!I.isPHI())
2992       break;
2993     unsigned PR = getDefReg(&I);
2994     if (isConst(PR))
2995       continue;
2996     bool BadUse = false, GoodUse = false;
2997     for (auto UI = MRI->use_begin(PR), UE = MRI->use_end(); UI != UE; ++UI) {
2998       MachineInstr *UseI = UI->getParent();
2999       if (UseI->getParent() != C.LB) {
3000         BadUse = true;
3001         break;
3002       }
3003       if (isBitShuffle(UseI, PR) || isStoreInput(UseI, PR))
3004         GoodUse = true;
3005     }
3006     if (BadUse || !GoodUse)
3007       continue;
3008 
3009     Phis.push_back(PhiInfo(I, *C.LB));
3010   }
3011 
3012   DEBUG({
3013     dbgs() << "Phis: {";
3014     for (auto &I : Phis) {
3015       dbgs() << ' ' << PrintReg(I.DefR, HRI) << "=phi("
3016              << PrintReg(I.PR.Reg, HRI, I.PR.Sub) << ":b" << I.PB->getNumber()
3017              << ',' << PrintReg(I.LR.Reg, HRI, I.LR.Sub) << ":b"
3018              << I.LB->getNumber() << ')';
3019     }
3020     dbgs() << " }\n";
3021   });
3022 
3023   if (Phis.empty())
3024     return false;
3025 
3026   bool Changed = false;
3027   InstrList ShufIns;
3028 
3029   // Go backwards in the block: for each bit shuffling instruction, check
3030   // if that instruction could potentially be moved to the front of the loop:
3031   // the output of the loop cannot be used in a non-shuffling instruction
3032   // in this loop.
3033   for (auto I = C.LB->rbegin(), E = C.LB->rend(); I != E; ++I) {
3034     if (I->isTerminator())
3035       continue;
3036     if (I->isPHI())
3037       break;
3038 
3039     RegisterSet Defs;
3040     HBS::getInstrDefs(*I, Defs);
3041     if (Defs.count() != 1)
3042       continue;
3043     unsigned DefR = Defs.find_first();
3044     if (!TargetRegisterInfo::isVirtualRegister(DefR))
3045       continue;
3046     if (!isBitShuffle(&*I, DefR))
3047       continue;
3048 
3049     bool BadUse = false;
3050     for (auto UI = MRI->use_begin(DefR), UE = MRI->use_end(); UI != UE; ++UI) {
3051       MachineInstr *UseI = UI->getParent();
3052       if (UseI->getParent() == C.LB) {
3053         if (UseI->isPHI()) {
3054           // If the use is in a phi node in this loop, then it should be
3055           // the value corresponding to the back edge.
3056           unsigned Idx = UI.getOperandNo();
3057           if (UseI->getOperand(Idx+1).getMBB() != C.LB)
3058             BadUse = true;
3059         } else {
3060           auto F = find(ShufIns, UseI);
3061           if (F == ShufIns.end())
3062             BadUse = true;
3063         }
3064       } else {
3065         // There is a use outside of the loop, but there is no epilog block
3066         // suitable for a copy-out.
3067         if (C.EB == nullptr)
3068           BadUse = true;
3069       }
3070       if (BadUse)
3071         break;
3072     }
3073 
3074     if (BadUse)
3075       continue;
3076     ShufIns.push_back(&*I);
3077   }
3078 
3079   // Partition the list of shuffling instructions into instruction groups,
3080   // where each group has to be moved as a whole (i.e. a group is a chain of
3081   // dependent instructions). A group produces a single live output register,
3082   // which is meant to be the input of the loop phi node (although this is
3083   // not checked here yet). It also uses a single register as its input,
3084   // which is some value produced in the loop body. After moving the group
3085   // to the beginning of the loop, that input register would need to be
3086   // the loop-carried register (through a phi node) instead of the (currently
3087   // loop-carried) output register.
3088   using InstrGroupList = std::vector<InstrGroup>;
3089   InstrGroupList Groups;
3090 
3091   for (unsigned i = 0, n = ShufIns.size(); i < n; ++i) {
3092     MachineInstr *SI = ShufIns[i];
3093     if (SI == nullptr)
3094       continue;
3095 
3096     InstrGroup G;
3097     G.Ins.push_back(SI);
3098     G.Out.Reg = getDefReg(SI);
3099     RegisterSet Inputs;
3100     HBS::getInstrUses(*SI, Inputs);
3101 
3102     for (unsigned j = i+1; j < n; ++j) {
3103       MachineInstr *MI = ShufIns[j];
3104       if (MI == nullptr)
3105         continue;
3106       RegisterSet Defs;
3107       HBS::getInstrDefs(*MI, Defs);
3108       // If this instruction does not define any pending inputs, skip it.
3109       if (!Defs.intersects(Inputs))
3110         continue;
3111       // Otherwise, add it to the current group and remove the inputs that
3112       // are defined by MI.
3113       G.Ins.push_back(MI);
3114       Inputs.remove(Defs);
3115       // Then add all registers used by MI.
3116       HBS::getInstrUses(*MI, Inputs);
3117       ShufIns[j] = nullptr;
3118     }
3119 
3120     // Only add a group if it requires at most one register.
3121     if (Inputs.count() > 1)
3122       continue;
3123     auto LoopInpEq = [G] (const PhiInfo &P) -> bool {
3124       return G.Out.Reg == P.LR.Reg;
3125     };
3126     if (llvm::find_if(Phis, LoopInpEq) == Phis.end())
3127       continue;
3128 
3129     G.Inp.Reg = Inputs.find_first();
3130     Groups.push_back(G);
3131   }
3132 
3133   DEBUG({
3134     for (unsigned i = 0, n = Groups.size(); i < n; ++i) {
3135       InstrGroup &G = Groups[i];
3136       dbgs() << "Group[" << i << "] inp: "
3137              << PrintReg(G.Inp.Reg, HRI, G.Inp.Sub)
3138              << "  out: " << PrintReg(G.Out.Reg, HRI, G.Out.Sub) << "\n";
3139       for (unsigned j = 0, m = G.Ins.size(); j < m; ++j)
3140         dbgs() << "  " << *G.Ins[j];
3141     }
3142   });
3143 
3144   for (unsigned i = 0, n = Groups.size(); i < n; ++i) {
3145     InstrGroup &G = Groups[i];
3146     if (!isShuffleOf(G.Out.Reg, G.Inp.Reg))
3147       continue;
3148     auto LoopInpEq = [G] (const PhiInfo &P) -> bool {
3149       return G.Out.Reg == P.LR.Reg;
3150     };
3151     auto F = llvm::find_if(Phis, LoopInpEq);
3152     if (F == Phis.end())
3153       continue;
3154     unsigned PrehR = 0;
3155     if (!isSameShuffle(G.Out.Reg, G.Inp.Reg, F->PR.Reg, PrehR)) {
3156       const MachineInstr *DefPrehR = MRI->getVRegDef(F->PR.Reg);
3157       unsigned Opc = DefPrehR->getOpcode();
3158       if (Opc != Hexagon::A2_tfrsi && Opc != Hexagon::A2_tfrpi)
3159         continue;
3160       if (!DefPrehR->getOperand(1).isImm())
3161         continue;
3162       if (DefPrehR->getOperand(1).getImm() != 0)
3163         continue;
3164       const TargetRegisterClass *RC = MRI->getRegClass(G.Inp.Reg);
3165       if (RC != MRI->getRegClass(F->PR.Reg)) {
3166         PrehR = MRI->createVirtualRegister(RC);
3167         unsigned TfrI = (RC == &Hexagon::IntRegsRegClass) ? Hexagon::A2_tfrsi
3168                                                           : Hexagon::A2_tfrpi;
3169         auto T = C.PB->getFirstTerminator();
3170         DebugLoc DL = (T != C.PB->end()) ? T->getDebugLoc() : DebugLoc();
3171         BuildMI(*C.PB, T, DL, HII->get(TfrI), PrehR)
3172           .addImm(0);
3173       } else {
3174         PrehR = F->PR.Reg;
3175       }
3176     }
3177     // isSameShuffle could match with PrehR being of a wider class than
3178     // G.Inp.Reg, for example if G shuffles the low 32 bits of its input,
3179     // it would match for the input being a 32-bit register, and PrehR
3180     // being a 64-bit register (where the low 32 bits match). This could
3181     // be handled, but for now skip these cases.
3182     if (MRI->getRegClass(PrehR) != MRI->getRegClass(G.Inp.Reg))
3183       continue;
3184     moveGroup(G, *F->LB, *F->PB, F->LB->getFirstNonPHI(), F->DefR, PrehR);
3185     Changed = true;
3186   }
3187 
3188   return Changed;
3189 }
3190 
3191 bool HexagonLoopRescheduling::runOnMachineFunction(MachineFunction &MF) {
3192   if (skipFunction(*MF.getFunction()))
3193     return false;
3194 
3195   auto &HST = MF.getSubtarget<HexagonSubtarget>();
3196   HII = HST.getInstrInfo();
3197   HRI = HST.getRegisterInfo();
3198   MRI = &MF.getRegInfo();
3199   const HexagonEvaluator HE(*HRI, *MRI, *HII, MF);
3200   BitTracker BT(HE, MF);
3201   DEBUG(BT.trace(true));
3202   BT.run();
3203   BTP = &BT;
3204 
3205   std::vector<LoopCand> Cand;
3206 
3207   for (auto &B : MF) {
3208     if (B.pred_size() != 2 || B.succ_size() != 2)
3209       continue;
3210     MachineBasicBlock *PB = nullptr;
3211     bool IsLoop = false;
3212     for (auto PI = B.pred_begin(), PE = B.pred_end(); PI != PE; ++PI) {
3213       if (*PI != &B)
3214         PB = *PI;
3215       else
3216         IsLoop = true;
3217     }
3218     if (!IsLoop)
3219       continue;
3220 
3221     MachineBasicBlock *EB = nullptr;
3222     for (auto SI = B.succ_begin(), SE = B.succ_end(); SI != SE; ++SI) {
3223       if (*SI == &B)
3224         continue;
3225       // Set EP to the epilog block, if it has only 1 predecessor (i.e. the
3226       // edge from B to EP is non-critical.
3227       if ((*SI)->pred_size() == 1)
3228         EB = *SI;
3229       break;
3230     }
3231 
3232     Cand.push_back(LoopCand(&B, PB, EB));
3233   }
3234 
3235   bool Changed = false;
3236   for (auto &C : Cand)
3237     Changed |= processLoop(C);
3238 
3239   return Changed;
3240 }
3241 
3242 //===----------------------------------------------------------------------===//
3243 //                         Public Constructor Functions
3244 //===----------------------------------------------------------------------===//
3245 
3246 FunctionPass *llvm::createHexagonLoopRescheduling() {
3247   return new HexagonLoopRescheduling();
3248 }
3249 
3250 FunctionPass *llvm::createHexagonBitSimplify() {
3251   return new HexagonBitSimplify();
3252 }
3253