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