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