1 //===--- HexagonBitSimplify.cpp -------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "HexagonBitTracker.h"
11 #include "HexagonTargetMachine.h"
12 #include "llvm/ADT/BitVector.h"
13 #include "llvm/ADT/DenseMap.h"
14 #include "llvm/ADT/STLExtras.h"
15 #include "llvm/ADT/SmallVector.h"
16 #include "llvm/ADT/StringRef.h"
17 #include "llvm/CodeGen/MachineBasicBlock.h"
18 #include "llvm/CodeGen/MachineDominators.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineFunctionPass.h"
21 #include "llvm/CodeGen/MachineInstr.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/MachineOperand.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/Passes.h"
26 #include "llvm/IR/DebugLoc.h"
27 #include "llvm/MC/MCInstrDesc.h"
28 #include "llvm/Pass.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Compiler.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetRegisterInfo.h"
43 #define DEBUG_TYPE "hexbit"
47 static cl::opt<bool> PreserveTiedOps("hexbit-keep-tied", cl::Hidden,
48 cl::init(true), cl::desc("Preserve subregisters in tied operands"));
49 static cl::opt<bool> GenExtract("hexbit-extract", cl::Hidden,
50 cl::init(true), cl::desc("Generate extract instructions"));
51 static cl::opt<bool> GenBitSplit("hexbit-bitsplit", cl::Hidden,
52 cl::init(true), cl::desc("Generate bitsplit instructions"));
54 static cl::opt<unsigned> MaxExtract("hexbit-max-extract", cl::Hidden,
56 static unsigned CountExtract = 0;
57 static cl::opt<unsigned> MaxBitSplit("hexbit-max-bitsplit", cl::Hidden,
59 static unsigned CountBitSplit = 0;
63 void initializeHexagonBitSimplifyPass(PassRegistry& Registry);
64 FunctionPass *createHexagonBitSimplify();
66 } // end namespace llvm
70 // Set of virtual registers, based on BitVector.
71 struct RegisterSet : private BitVector {
72 RegisterSet() = default;
73 explicit RegisterSet(unsigned s, bool t = false) : BitVector(s, t) {}
74 RegisterSet(const RegisterSet &RS) = default;
76 using BitVector::clear;
77 using BitVector::count;
79 unsigned find_first() const {
80 int First = BitVector::find_first();
86 unsigned find_next(unsigned Prev) const {
87 int Next = BitVector::find_next(v2x(Prev));
93 RegisterSet &insert(unsigned R) {
94 unsigned Idx = v2x(R);
96 return static_cast<RegisterSet&>(BitVector::set(Idx));
98 RegisterSet &remove(unsigned R) {
99 unsigned Idx = v2x(R);
102 return static_cast<RegisterSet&>(BitVector::reset(Idx));
105 RegisterSet &insert(const RegisterSet &Rs) {
106 return static_cast<RegisterSet&>(BitVector::operator|=(Rs));
108 RegisterSet &remove(const RegisterSet &Rs) {
109 return static_cast<RegisterSet&>(BitVector::reset(Rs));
112 reference operator[](unsigned R) {
113 unsigned Idx = v2x(R);
115 return BitVector::operator[](Idx);
117 bool operator[](unsigned R) const {
118 unsigned Idx = v2x(R);
119 assert(Idx < size());
120 return BitVector::operator[](Idx);
122 bool has(unsigned R) const {
123 unsigned Idx = v2x(R);
126 return BitVector::test(Idx);
130 return !BitVector::any();
132 bool includes(const RegisterSet &Rs) const {
133 // A.BitVector::test(B) <=> A-B != {}
134 return !Rs.BitVector::test(*this);
136 bool intersects(const RegisterSet &Rs) const {
137 return BitVector::anyCommon(Rs);
141 void ensure(unsigned Idx) {
143 resize(std::max(Idx+1, 32U));
146 static inline unsigned v2x(unsigned v) {
147 return TargetRegisterInfo::virtReg2Index(v);
150 static inline unsigned x2v(unsigned x) {
151 return TargetRegisterInfo::index2VirtReg(x);
156 PrintRegSet(const RegisterSet &S, const TargetRegisterInfo *RI)
159 friend raw_ostream &operator<< (raw_ostream &OS,
160 const PrintRegSet &P);
163 const RegisterSet &RS;
164 const TargetRegisterInfo *TRI;
167 raw_ostream &operator<< (raw_ostream &OS, const PrintRegSet &P)
168 LLVM_ATTRIBUTE_UNUSED;
169 raw_ostream &operator<< (raw_ostream &OS, const PrintRegSet &P) {
171 for (unsigned R = P.RS.find_first(); R; R = P.RS.find_next(R))
172 OS << ' ' << PrintReg(R, P.TRI);
177 class Transformation;
179 class HexagonBitSimplify : public MachineFunctionPass {
183 HexagonBitSimplify() : MachineFunctionPass(ID), MDT(nullptr) {
184 initializeHexagonBitSimplifyPass(*PassRegistry::getPassRegistry());
187 StringRef getPassName() const override {
188 return "Hexagon bit simplification";
191 void getAnalysisUsage(AnalysisUsage &AU) const override {
192 AU.addRequired<MachineDominatorTree>();
193 AU.addPreserved<MachineDominatorTree>();
194 MachineFunctionPass::getAnalysisUsage(AU);
197 bool runOnMachineFunction(MachineFunction &MF) override;
199 static void getInstrDefs(const MachineInstr &MI, RegisterSet &Defs);
200 static void getInstrUses(const MachineInstr &MI, RegisterSet &Uses);
201 static bool isEqual(const BitTracker::RegisterCell &RC1, uint16_t B1,
202 const BitTracker::RegisterCell &RC2, uint16_t B2, uint16_t W);
203 static bool isZero(const BitTracker::RegisterCell &RC, uint16_t B,
205 static bool getConst(const BitTracker::RegisterCell &RC, uint16_t B,
206 uint16_t W, uint64_t &U);
207 static bool replaceReg(unsigned OldR, unsigned NewR,
208 MachineRegisterInfo &MRI);
209 static bool getSubregMask(const BitTracker::RegisterRef &RR,
210 unsigned &Begin, unsigned &Width, MachineRegisterInfo &MRI);
211 static bool replaceRegWithSub(unsigned OldR, unsigned NewR,
212 unsigned NewSR, MachineRegisterInfo &MRI);
213 static bool replaceSubWithSub(unsigned OldR, unsigned OldSR,
214 unsigned NewR, unsigned NewSR, MachineRegisterInfo &MRI);
215 static bool parseRegSequence(const MachineInstr &I,
216 BitTracker::RegisterRef &SL, BitTracker::RegisterRef &SH,
217 const MachineRegisterInfo &MRI);
219 static bool getUsedBitsInStore(unsigned Opc, BitVector &Bits,
221 static bool getUsedBits(unsigned Opc, unsigned OpN, BitVector &Bits,
222 uint16_t Begin, const HexagonInstrInfo &HII);
224 static const TargetRegisterClass *getFinalVRegClass(
225 const BitTracker::RegisterRef &RR, MachineRegisterInfo &MRI);
226 static bool isTransparentCopy(const BitTracker::RegisterRef &RD,
227 const BitTracker::RegisterRef &RS, MachineRegisterInfo &MRI);
230 MachineDominatorTree *MDT;
232 bool visitBlock(MachineBasicBlock &B, Transformation &T, RegisterSet &AVs);
233 static bool hasTiedUse(unsigned Reg, MachineRegisterInfo &MRI,
234 unsigned NewSub = Hexagon::NoSubRegister);
237 char HexagonBitSimplify::ID = 0;
238 typedef HexagonBitSimplify HBS;
240 // The purpose of this class is to provide a common facility to traverse
241 // the function top-down or bottom-up via the dominator tree, and keep
242 // track of the available registers.
243 class Transformation {
247 Transformation(bool TD) : TopDown(TD) {}
248 virtual ~Transformation() = default;
250 virtual bool processBlock(MachineBasicBlock &B, const RegisterSet &AVs) = 0;
253 } // end anonymous namespace
255 INITIALIZE_PASS_BEGIN(HexagonBitSimplify, "hexbit",
256 "Hexagon bit simplification", false, false)
257 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
258 INITIALIZE_PASS_END(HexagonBitSimplify, "hexbit",
259 "Hexagon bit simplification", false, false)
261 bool HexagonBitSimplify::visitBlock(MachineBasicBlock &B, Transformation &T,
263 bool Changed = false;
266 Changed = T.processBlock(B, AVs);
270 getInstrDefs(I, Defs);
271 RegisterSet NewAVs = AVs;
274 for (auto *DTN : children<MachineDomTreeNode*>(MDT->getNode(&B)))
275 Changed |= visitBlock(*(DTN->getBlock()), T, NewAVs);
278 Changed |= T.processBlock(B, AVs);
284 // Utility functions:
286 void HexagonBitSimplify::getInstrDefs(const MachineInstr &MI,
288 for (auto &Op : MI.operands()) {
289 if (!Op.isReg() || !Op.isDef())
291 unsigned R = Op.getReg();
292 if (!TargetRegisterInfo::isVirtualRegister(R))
298 void HexagonBitSimplify::getInstrUses(const MachineInstr &MI,
300 for (auto &Op : MI.operands()) {
301 if (!Op.isReg() || !Op.isUse())
303 unsigned R = Op.getReg();
304 if (!TargetRegisterInfo::isVirtualRegister(R))
310 // Check if all the bits in range [B, E) in both cells are equal.
311 bool HexagonBitSimplify::isEqual(const BitTracker::RegisterCell &RC1,
312 uint16_t B1, const BitTracker::RegisterCell &RC2, uint16_t B2,
314 for (uint16_t i = 0; i < W; ++i) {
315 // If RC1[i] is "bottom", it cannot be proven equal to RC2[i].
316 if (RC1[B1+i].Type == BitTracker::BitValue::Ref && RC1[B1+i].RefI.Reg == 0)
319 if (RC2[B2+i].Type == BitTracker::BitValue::Ref && RC2[B2+i].RefI.Reg == 0)
321 if (RC1[B1+i] != RC2[B2+i])
327 bool HexagonBitSimplify::isZero(const BitTracker::RegisterCell &RC,
328 uint16_t B, uint16_t W) {
329 assert(B < RC.width() && B+W <= RC.width());
330 for (uint16_t i = B; i < B+W; ++i)
336 bool HexagonBitSimplify::getConst(const BitTracker::RegisterCell &RC,
337 uint16_t B, uint16_t W, uint64_t &U) {
338 assert(B < RC.width() && B+W <= RC.width());
340 for (uint16_t i = B+W; i > B; --i) {
341 const BitTracker::BitValue &BV = RC[i-1];
352 bool HexagonBitSimplify::replaceReg(unsigned OldR, unsigned NewR,
353 MachineRegisterInfo &MRI) {
354 if (!TargetRegisterInfo::isVirtualRegister(OldR) ||
355 !TargetRegisterInfo::isVirtualRegister(NewR))
357 auto Begin = MRI.use_begin(OldR), End = MRI.use_end();
359 for (auto I = Begin; I != End; I = NextI) {
360 NextI = std::next(I);
366 bool HexagonBitSimplify::replaceRegWithSub(unsigned OldR, unsigned NewR,
367 unsigned NewSR, MachineRegisterInfo &MRI) {
368 if (!TargetRegisterInfo::isVirtualRegister(OldR) ||
369 !TargetRegisterInfo::isVirtualRegister(NewR))
371 if (hasTiedUse(OldR, MRI, NewSR))
373 auto Begin = MRI.use_begin(OldR), End = MRI.use_end();
375 for (auto I = Begin; I != End; I = NextI) {
376 NextI = std::next(I);
383 bool HexagonBitSimplify::replaceSubWithSub(unsigned OldR, unsigned OldSR,
384 unsigned NewR, unsigned NewSR, MachineRegisterInfo &MRI) {
385 if (!TargetRegisterInfo::isVirtualRegister(OldR) ||
386 !TargetRegisterInfo::isVirtualRegister(NewR))
388 if (OldSR != NewSR && hasTiedUse(OldR, MRI, NewSR))
390 auto Begin = MRI.use_begin(OldR), End = MRI.use_end();
392 for (auto I = Begin; I != End; I = NextI) {
393 NextI = std::next(I);
394 if (I->getSubReg() != OldSR)
402 // For a register ref (pair Reg:Sub), set Begin to the position of the LSB
403 // of Sub in Reg, and set Width to the size of Sub in bits. Return true,
404 // if this succeeded, otherwise return false.
405 bool HexagonBitSimplify::getSubregMask(const BitTracker::RegisterRef &RR,
406 unsigned &Begin, unsigned &Width, MachineRegisterInfo &MRI) {
407 const TargetRegisterClass *RC = MRI.getRegClass(RR.Reg);
410 Width = MRI.getTargetRegisterInfo()->getRegSizeInBits(*RC);
416 switch (RC->getID()) {
417 case Hexagon::DoubleRegsRegClassID:
418 case Hexagon::VecDblRegsRegClassID:
419 case Hexagon::VecDblRegs128BRegClassID:
420 Width = MRI.getTargetRegisterInfo()->getRegSizeInBits(*RC) / 2;
421 if (RR.Sub == Hexagon::isub_hi || RR.Sub == Hexagon::vsub_hi)
431 // For a REG_SEQUENCE, set SL to the low subregister and SH to the high
433 bool HexagonBitSimplify::parseRegSequence(const MachineInstr &I,
434 BitTracker::RegisterRef &SL, BitTracker::RegisterRef &SH,
435 const MachineRegisterInfo &MRI) {
436 assert(I.getOpcode() == TargetOpcode::REG_SEQUENCE);
437 unsigned Sub1 = I.getOperand(2).getImm(), Sub2 = I.getOperand(4).getImm();
438 auto *DstRC = MRI.getRegClass(I.getOperand(0).getReg());
439 auto &HRI = static_cast<const HexagonRegisterInfo&>(
440 *MRI.getTargetRegisterInfo());
441 unsigned SubLo = HRI.getHexagonSubRegIndex(DstRC, Hexagon::ps_sub_lo);
442 unsigned SubHi = HRI.getHexagonSubRegIndex(DstRC, Hexagon::ps_sub_hi);
443 assert((Sub1 == SubLo && Sub2 == SubHi) || (Sub1 == SubHi && Sub2 == SubLo));
444 if (Sub1 == SubLo && Sub2 == SubHi) {
445 SL = I.getOperand(1);
446 SH = I.getOperand(3);
449 if (Sub1 == SubHi && Sub2 == SubLo) {
450 SH = I.getOperand(1);
451 SL = I.getOperand(3);
457 // All stores (except 64-bit stores) take a 32-bit register as the source
458 // of the value to be stored. If the instruction stores into a location
459 // that is shorter than 32 bits, some bits of the source register are not
460 // used. For each store instruction, calculate the set of used bits in
461 // the source register, and set appropriate bits in Bits. Return true if
462 // the bits are calculated, false otherwise.
463 bool HexagonBitSimplify::getUsedBitsInStore(unsigned Opc, BitVector &Bits,
465 using namespace Hexagon;
469 case S2_storerb_io: // memb(Rs32+#s11:0)=Rt32
470 case S2_storerbnew_io: // memb(Rs32+#s11:0)=Nt8.new
471 case S2_pstorerbt_io: // if (Pv4) memb(Rs32+#u6:0)=Rt32
472 case S2_pstorerbf_io: // if (!Pv4) memb(Rs32+#u6:0)=Rt32
473 case S4_pstorerbtnew_io: // if (Pv4.new) memb(Rs32+#u6:0)=Rt32
474 case S4_pstorerbfnew_io: // if (!Pv4.new) memb(Rs32+#u6:0)=Rt32
475 case S2_pstorerbnewt_io: // if (Pv4) memb(Rs32+#u6:0)=Nt8.new
476 case S2_pstorerbnewf_io: // if (!Pv4) memb(Rs32+#u6:0)=Nt8.new
477 case S4_pstorerbnewtnew_io: // if (Pv4.new) memb(Rs32+#u6:0)=Nt8.new
478 case S4_pstorerbnewfnew_io: // if (!Pv4.new) memb(Rs32+#u6:0)=Nt8.new
479 case S2_storerb_pi: // memb(Rx32++#s4:0)=Rt32
480 case S2_storerbnew_pi: // memb(Rx32++#s4:0)=Nt8.new
481 case S2_pstorerbt_pi: // if (Pv4) memb(Rx32++#s4:0)=Rt32
482 case S2_pstorerbf_pi: // if (!Pv4) memb(Rx32++#s4:0)=Rt32
483 case S2_pstorerbtnew_pi: // if (Pv4.new) memb(Rx32++#s4:0)=Rt32
484 case S2_pstorerbfnew_pi: // if (!Pv4.new) memb(Rx32++#s4:0)=Rt32
485 case S2_pstorerbnewt_pi: // if (Pv4) memb(Rx32++#s4:0)=Nt8.new
486 case S2_pstorerbnewf_pi: // if (!Pv4) memb(Rx32++#s4:0)=Nt8.new
487 case S2_pstorerbnewtnew_pi: // if (Pv4.new) memb(Rx32++#s4:0)=Nt8.new
488 case S2_pstorerbnewfnew_pi: // if (!Pv4.new) memb(Rx32++#s4:0)=Nt8.new
489 case S4_storerb_ap: // memb(Re32=#U6)=Rt32
490 case S4_storerbnew_ap: // memb(Re32=#U6)=Nt8.new
491 case S2_storerb_pr: // memb(Rx32++Mu2)=Rt32
492 case S2_storerbnew_pr: // memb(Rx32++Mu2)=Nt8.new
493 case S4_storerb_ur: // memb(Ru32<<#u2+#U6)=Rt32
494 case S4_storerbnew_ur: // memb(Ru32<<#u2+#U6)=Nt8.new
495 case S2_storerb_pbr: // memb(Rx32++Mu2:brev)=Rt32
496 case S2_storerbnew_pbr: // memb(Rx32++Mu2:brev)=Nt8.new
497 case S2_storerb_pci: // memb(Rx32++#s4:0:circ(Mu2))=Rt32
498 case S2_storerbnew_pci: // memb(Rx32++#s4:0:circ(Mu2))=Nt8.new
499 case S2_storerb_pcr: // memb(Rx32++I:circ(Mu2))=Rt32
500 case S2_storerbnew_pcr: // memb(Rx32++I:circ(Mu2))=Nt8.new
501 case S4_storerb_rr: // memb(Rs32+Ru32<<#u2)=Rt32
502 case S4_storerbnew_rr: // memb(Rs32+Ru32<<#u2)=Nt8.new
503 case S4_pstorerbt_rr: // if (Pv4) memb(Rs32+Ru32<<#u2)=Rt32
504 case S4_pstorerbf_rr: // if (!Pv4) memb(Rs32+Ru32<<#u2)=Rt32
505 case S4_pstorerbtnew_rr: // if (Pv4.new) memb(Rs32+Ru32<<#u2)=Rt32
506 case S4_pstorerbfnew_rr: // if (!Pv4.new) memb(Rs32+Ru32<<#u2)=Rt32
507 case S4_pstorerbnewt_rr: // if (Pv4) memb(Rs32+Ru32<<#u2)=Nt8.new
508 case S4_pstorerbnewf_rr: // if (!Pv4) memb(Rs32+Ru32<<#u2)=Nt8.new
509 case S4_pstorerbnewtnew_rr: // if (Pv4.new) memb(Rs32+Ru32<<#u2)=Nt8.new
510 case S4_pstorerbnewfnew_rr: // if (!Pv4.new) memb(Rs32+Ru32<<#u2)=Nt8.new
511 case S2_storerbgp: // memb(gp+#u16:0)=Rt32
512 case S2_storerbnewgp: // memb(gp+#u16:0)=Nt8.new
513 case S4_pstorerbt_abs: // if (Pv4) memb(#u6)=Rt32
514 case S4_pstorerbf_abs: // if (!Pv4) memb(#u6)=Rt32
515 case S4_pstorerbtnew_abs: // if (Pv4.new) memb(#u6)=Rt32
516 case S4_pstorerbfnew_abs: // if (!Pv4.new) memb(#u6)=Rt32
517 case S4_pstorerbnewt_abs: // if (Pv4) memb(#u6)=Nt8.new
518 case S4_pstorerbnewf_abs: // if (!Pv4) memb(#u6)=Nt8.new
519 case S4_pstorerbnewtnew_abs: // if (Pv4.new) memb(#u6)=Nt8.new
520 case S4_pstorerbnewfnew_abs: // if (!Pv4.new) memb(#u6)=Nt8.new
521 Bits.set(Begin, Begin+8);
525 case S2_storerh_io: // memh(Rs32+#s11:1)=Rt32
526 case S2_storerhnew_io: // memh(Rs32+#s11:1)=Nt8.new
527 case S2_pstorerht_io: // if (Pv4) memh(Rs32+#u6:1)=Rt32
528 case S2_pstorerhf_io: // if (!Pv4) memh(Rs32+#u6:1)=Rt32
529 case S4_pstorerhtnew_io: // if (Pv4.new) memh(Rs32+#u6:1)=Rt32
530 case S4_pstorerhfnew_io: // if (!Pv4.new) memh(Rs32+#u6:1)=Rt32
531 case S2_pstorerhnewt_io: // if (Pv4) memh(Rs32+#u6:1)=Nt8.new
532 case S2_pstorerhnewf_io: // if (!Pv4) memh(Rs32+#u6:1)=Nt8.new
533 case S4_pstorerhnewtnew_io: // if (Pv4.new) memh(Rs32+#u6:1)=Nt8.new
534 case S4_pstorerhnewfnew_io: // if (!Pv4.new) memh(Rs32+#u6:1)=Nt8.new
535 case S2_storerh_pi: // memh(Rx32++#s4:1)=Rt32
536 case S2_storerhnew_pi: // memh(Rx32++#s4:1)=Nt8.new
537 case S2_pstorerht_pi: // if (Pv4) memh(Rx32++#s4:1)=Rt32
538 case S2_pstorerhf_pi: // if (!Pv4) memh(Rx32++#s4:1)=Rt32
539 case S2_pstorerhtnew_pi: // if (Pv4.new) memh(Rx32++#s4:1)=Rt32
540 case S2_pstorerhfnew_pi: // if (!Pv4.new) memh(Rx32++#s4:1)=Rt32
541 case S2_pstorerhnewt_pi: // if (Pv4) memh(Rx32++#s4:1)=Nt8.new
542 case S2_pstorerhnewf_pi: // if (!Pv4) memh(Rx32++#s4:1)=Nt8.new
543 case S2_pstorerhnewtnew_pi: // if (Pv4.new) memh(Rx32++#s4:1)=Nt8.new
544 case S2_pstorerhnewfnew_pi: // if (!Pv4.new) memh(Rx32++#s4:1)=Nt8.new
545 case S4_storerh_ap: // memh(Re32=#U6)=Rt32
546 case S4_storerhnew_ap: // memh(Re32=#U6)=Nt8.new
547 case S2_storerh_pr: // memh(Rx32++Mu2)=Rt32
548 case S2_storerhnew_pr: // memh(Rx32++Mu2)=Nt8.new
549 case S4_storerh_ur: // memh(Ru32<<#u2+#U6)=Rt32
550 case S4_storerhnew_ur: // memh(Ru32<<#u2+#U6)=Nt8.new
551 case S2_storerh_pbr: // memh(Rx32++Mu2:brev)=Rt32
552 case S2_storerhnew_pbr: // memh(Rx32++Mu2:brev)=Nt8.new
553 case S2_storerh_pci: // memh(Rx32++#s4:1:circ(Mu2))=Rt32
554 case S2_storerhnew_pci: // memh(Rx32++#s4:1:circ(Mu2))=Nt8.new
555 case S2_storerh_pcr: // memh(Rx32++I:circ(Mu2))=Rt32
556 case S2_storerhnew_pcr: // memh(Rx32++I:circ(Mu2))=Nt8.new
557 case S4_storerh_rr: // memh(Rs32+Ru32<<#u2)=Rt32
558 case S4_pstorerht_rr: // if (Pv4) memh(Rs32+Ru32<<#u2)=Rt32
559 case S4_pstorerhf_rr: // if (!Pv4) memh(Rs32+Ru32<<#u2)=Rt32
560 case S4_pstorerhtnew_rr: // if (Pv4.new) memh(Rs32+Ru32<<#u2)=Rt32
561 case S4_pstorerhfnew_rr: // if (!Pv4.new) memh(Rs32+Ru32<<#u2)=Rt32
562 case S4_storerhnew_rr: // memh(Rs32+Ru32<<#u2)=Nt8.new
563 case S4_pstorerhnewt_rr: // if (Pv4) memh(Rs32+Ru32<<#u2)=Nt8.new
564 case S4_pstorerhnewf_rr: // if (!Pv4) memh(Rs32+Ru32<<#u2)=Nt8.new
565 case S4_pstorerhnewtnew_rr: // if (Pv4.new) memh(Rs32+Ru32<<#u2)=Nt8.new
566 case S4_pstorerhnewfnew_rr: // if (!Pv4.new) memh(Rs32+Ru32<<#u2)=Nt8.new
567 case S2_storerhgp: // memh(gp+#u16:1)=Rt32
568 case S2_storerhnewgp: // memh(gp+#u16:1)=Nt8.new
569 case S4_pstorerht_abs: // if (Pv4) memh(#u6)=Rt32
570 case S4_pstorerhf_abs: // if (!Pv4) memh(#u6)=Rt32
571 case S4_pstorerhtnew_abs: // if (Pv4.new) memh(#u6)=Rt32
572 case S4_pstorerhfnew_abs: // if (!Pv4.new) memh(#u6)=Rt32
573 case S4_pstorerhnewt_abs: // if (Pv4) memh(#u6)=Nt8.new
574 case S4_pstorerhnewf_abs: // if (!Pv4) memh(#u6)=Nt8.new
575 case S4_pstorerhnewtnew_abs: // if (Pv4.new) memh(#u6)=Nt8.new
576 case S4_pstorerhnewfnew_abs: // if (!Pv4.new) memh(#u6)=Nt8.new
577 Bits.set(Begin, Begin+16);
581 case S2_storerf_io: // memh(Rs32+#s11:1)=Rt.H32
582 case S2_pstorerft_io: // if (Pv4) memh(Rs32+#u6:1)=Rt.H32
583 case S2_pstorerff_io: // if (!Pv4) memh(Rs32+#u6:1)=Rt.H32
584 case S4_pstorerftnew_io: // if (Pv4.new) memh(Rs32+#u6:1)=Rt.H32
585 case S4_pstorerffnew_io: // if (!Pv4.new) memh(Rs32+#u6:1)=Rt.H32
586 case S2_storerf_pi: // memh(Rx32++#s4:1)=Rt.H32
587 case S2_pstorerft_pi: // if (Pv4) memh(Rx32++#s4:1)=Rt.H32
588 case S2_pstorerff_pi: // if (!Pv4) memh(Rx32++#s4:1)=Rt.H32
589 case S2_pstorerftnew_pi: // if (Pv4.new) memh(Rx32++#s4:1)=Rt.H32
590 case S2_pstorerffnew_pi: // if (!Pv4.new) memh(Rx32++#s4:1)=Rt.H32
591 case S4_storerf_ap: // memh(Re32=#U6)=Rt.H32
592 case S2_storerf_pr: // memh(Rx32++Mu2)=Rt.H32
593 case S4_storerf_ur: // memh(Ru32<<#u2+#U6)=Rt.H32
594 case S2_storerf_pbr: // memh(Rx32++Mu2:brev)=Rt.H32
595 case S2_storerf_pci: // memh(Rx32++#s4:1:circ(Mu2))=Rt.H32
596 case S2_storerf_pcr: // memh(Rx32++I:circ(Mu2))=Rt.H32
597 case S4_storerf_rr: // memh(Rs32+Ru32<<#u2)=Rt.H32
598 case S4_pstorerft_rr: // if (Pv4) memh(Rs32+Ru32<<#u2)=Rt.H32
599 case S4_pstorerff_rr: // if (!Pv4) memh(Rs32+Ru32<<#u2)=Rt.H32
600 case S4_pstorerftnew_rr: // if (Pv4.new) memh(Rs32+Ru32<<#u2)=Rt.H32
601 case S4_pstorerffnew_rr: // if (!Pv4.new) memh(Rs32+Ru32<<#u2)=Rt.H32
602 case S2_storerfgp: // memh(gp+#u16:1)=Rt.H32
603 case S4_pstorerft_abs: // if (Pv4) memh(#u6)=Rt.H32
604 case S4_pstorerff_abs: // if (!Pv4) memh(#u6)=Rt.H32
605 case S4_pstorerftnew_abs: // if (Pv4.new) memh(#u6)=Rt.H32
606 case S4_pstorerffnew_abs: // if (!Pv4.new) memh(#u6)=Rt.H32
607 Bits.set(Begin+16, Begin+32);
614 // For an instruction with opcode Opc, calculate the set of bits that it
615 // uses in a register in operand OpN. This only calculates the set of used
616 // bits for cases where it does not depend on any operands (as is the case
617 // in shifts, for example). For concrete instructions from a program, the
618 // operand may be a subregister of a larger register, while Bits would
619 // correspond to the larger register in its entirety. Because of that,
620 // the parameter Begin can be used to indicate which bit of Bits should be
621 // considered the LSB of of the operand.
622 bool HexagonBitSimplify::getUsedBits(unsigned Opc, unsigned OpN,
623 BitVector &Bits, uint16_t Begin, const HexagonInstrInfo &HII) {
624 using namespace Hexagon;
626 const MCInstrDesc &D = HII.get(Opc);
628 if (OpN == D.getNumOperands()-1)
629 return getUsedBitsInStore(Opc, Bits, Begin);
634 // One register source. Used bits: R1[0-7].
641 Bits.set(Begin, Begin+8);
646 // One register source. Used bits: R1[0-15].
654 Bits.set(Begin, Begin+16);
659 // One register source. Used bits: R1[16-31].
662 Bits.set(Begin+16, Begin+32);
667 // Two register sources. Used bits: R1[0-7], R2[0-7].
672 Bits.set(Begin, Begin+8);
677 // Two register sources. Used bits: R1[0-15], R2[0-15].
682 case A2_addh_h16_sat_ll:
684 case A2_addh_l16_sat_ll:
687 case A2_subh_h16_sat_ll:
689 case A2_subh_l16_sat_ll:
690 case M2_mpy_acc_ll_s0:
691 case M2_mpy_acc_ll_s1:
692 case M2_mpy_acc_sat_ll_s0:
693 case M2_mpy_acc_sat_ll_s1:
696 case M2_mpy_nac_ll_s0:
697 case M2_mpy_nac_ll_s1:
698 case M2_mpy_nac_sat_ll_s0:
699 case M2_mpy_nac_sat_ll_s1:
700 case M2_mpy_rnd_ll_s0:
701 case M2_mpy_rnd_ll_s1:
702 case M2_mpy_sat_ll_s0:
703 case M2_mpy_sat_ll_s1:
704 case M2_mpy_sat_rnd_ll_s0:
705 case M2_mpy_sat_rnd_ll_s1:
706 case M2_mpyd_acc_ll_s0:
707 case M2_mpyd_acc_ll_s1:
710 case M2_mpyd_nac_ll_s0:
711 case M2_mpyd_nac_ll_s1:
712 case M2_mpyd_rnd_ll_s0:
713 case M2_mpyd_rnd_ll_s1:
714 case M2_mpyu_acc_ll_s0:
715 case M2_mpyu_acc_ll_s1:
718 case M2_mpyu_nac_ll_s0:
719 case M2_mpyu_nac_ll_s1:
720 case M2_mpyud_acc_ll_s0:
721 case M2_mpyud_acc_ll_s1:
724 case M2_mpyud_nac_ll_s0:
725 case M2_mpyud_nac_ll_s1:
726 if (OpN == 1 || OpN == 2) {
727 Bits.set(Begin, Begin+16);
732 // Two register sources. Used bits: R1[0-15], R2[16-31].
734 case A2_addh_h16_sat_lh:
737 case A2_subh_h16_sat_lh:
738 case M2_mpy_acc_lh_s0:
739 case M2_mpy_acc_lh_s1:
740 case M2_mpy_acc_sat_lh_s0:
741 case M2_mpy_acc_sat_lh_s1:
744 case M2_mpy_nac_lh_s0:
745 case M2_mpy_nac_lh_s1:
746 case M2_mpy_nac_sat_lh_s0:
747 case M2_mpy_nac_sat_lh_s1:
748 case M2_mpy_rnd_lh_s0:
749 case M2_mpy_rnd_lh_s1:
750 case M2_mpy_sat_lh_s0:
751 case M2_mpy_sat_lh_s1:
752 case M2_mpy_sat_rnd_lh_s0:
753 case M2_mpy_sat_rnd_lh_s1:
754 case M2_mpyd_acc_lh_s0:
755 case M2_mpyd_acc_lh_s1:
758 case M2_mpyd_nac_lh_s0:
759 case M2_mpyd_nac_lh_s1:
760 case M2_mpyd_rnd_lh_s0:
761 case M2_mpyd_rnd_lh_s1:
762 case M2_mpyu_acc_lh_s0:
763 case M2_mpyu_acc_lh_s1:
766 case M2_mpyu_nac_lh_s0:
767 case M2_mpyu_nac_lh_s1:
768 case M2_mpyud_acc_lh_s0:
769 case M2_mpyud_acc_lh_s1:
772 case M2_mpyud_nac_lh_s0:
773 case M2_mpyud_nac_lh_s1:
774 // These four are actually LH.
776 case A2_addh_l16_sat_hl:
778 case A2_subh_l16_sat_hl:
780 Bits.set(Begin, Begin+16);
784 Bits.set(Begin+16, Begin+32);
789 // Two register sources, used bits: R1[16-31], R2[0-15].
791 case A2_addh_h16_sat_hl:
794 case A2_subh_h16_sat_hl:
795 case M2_mpy_acc_hl_s0:
796 case M2_mpy_acc_hl_s1:
797 case M2_mpy_acc_sat_hl_s0:
798 case M2_mpy_acc_sat_hl_s1:
801 case M2_mpy_nac_hl_s0:
802 case M2_mpy_nac_hl_s1:
803 case M2_mpy_nac_sat_hl_s0:
804 case M2_mpy_nac_sat_hl_s1:
805 case M2_mpy_rnd_hl_s0:
806 case M2_mpy_rnd_hl_s1:
807 case M2_mpy_sat_hl_s0:
808 case M2_mpy_sat_hl_s1:
809 case M2_mpy_sat_rnd_hl_s0:
810 case M2_mpy_sat_rnd_hl_s1:
811 case M2_mpyd_acc_hl_s0:
812 case M2_mpyd_acc_hl_s1:
815 case M2_mpyd_nac_hl_s0:
816 case M2_mpyd_nac_hl_s1:
817 case M2_mpyd_rnd_hl_s0:
818 case M2_mpyd_rnd_hl_s1:
819 case M2_mpyu_acc_hl_s0:
820 case M2_mpyu_acc_hl_s1:
823 case M2_mpyu_nac_hl_s0:
824 case M2_mpyu_nac_hl_s1:
825 case M2_mpyud_acc_hl_s0:
826 case M2_mpyud_acc_hl_s1:
829 case M2_mpyud_nac_hl_s0:
830 case M2_mpyud_nac_hl_s1:
832 Bits.set(Begin+16, Begin+32);
836 Bits.set(Begin, Begin+16);
841 // Two register sources, used bits: R1[16-31], R2[16-31].
843 case A2_addh_h16_sat_hh:
846 case A2_subh_h16_sat_hh:
847 case M2_mpy_acc_hh_s0:
848 case M2_mpy_acc_hh_s1:
849 case M2_mpy_acc_sat_hh_s0:
850 case M2_mpy_acc_sat_hh_s1:
853 case M2_mpy_nac_hh_s0:
854 case M2_mpy_nac_hh_s1:
855 case M2_mpy_nac_sat_hh_s0:
856 case M2_mpy_nac_sat_hh_s1:
857 case M2_mpy_rnd_hh_s0:
858 case M2_mpy_rnd_hh_s1:
859 case M2_mpy_sat_hh_s0:
860 case M2_mpy_sat_hh_s1:
861 case M2_mpy_sat_rnd_hh_s0:
862 case M2_mpy_sat_rnd_hh_s1:
863 case M2_mpyd_acc_hh_s0:
864 case M2_mpyd_acc_hh_s1:
867 case M2_mpyd_nac_hh_s0:
868 case M2_mpyd_nac_hh_s1:
869 case M2_mpyd_rnd_hh_s0:
870 case M2_mpyd_rnd_hh_s1:
871 case M2_mpyu_acc_hh_s0:
872 case M2_mpyu_acc_hh_s1:
875 case M2_mpyu_nac_hh_s0:
876 case M2_mpyu_nac_hh_s1:
877 case M2_mpyud_acc_hh_s0:
878 case M2_mpyud_acc_hh_s1:
881 case M2_mpyud_nac_hh_s0:
882 case M2_mpyud_nac_hh_s1:
883 if (OpN == 1 || OpN == 2) {
884 Bits.set(Begin+16, Begin+32);
893 // Calculate the register class that matches Reg:Sub. For example, if
894 // vreg1 is a double register, then vreg1:isub_hi would match the "int"
896 const TargetRegisterClass *HexagonBitSimplify::getFinalVRegClass(
897 const BitTracker::RegisterRef &RR, MachineRegisterInfo &MRI) {
898 if (!TargetRegisterInfo::isVirtualRegister(RR.Reg))
900 auto *RC = MRI.getRegClass(RR.Reg);
903 auto &HRI = static_cast<const HexagonRegisterInfo&>(
904 *MRI.getTargetRegisterInfo());
906 auto VerifySR = [&HRI] (const TargetRegisterClass *RC, unsigned Sub) -> void {
908 assert(Sub == HRI.getHexagonSubRegIndex(RC, Hexagon::ps_sub_lo) ||
909 Sub == HRI.getHexagonSubRegIndex(RC, Hexagon::ps_sub_hi));
912 switch (RC->getID()) {
913 case Hexagon::DoubleRegsRegClassID:
914 VerifySR(RC, RR.Sub);
915 return &Hexagon::IntRegsRegClass;
916 case Hexagon::VecDblRegsRegClassID:
917 VerifySR(RC, RR.Sub);
918 return &Hexagon::VectorRegsRegClass;
919 case Hexagon::VecDblRegs128BRegClassID:
920 VerifySR(RC, RR.Sub);
921 return &Hexagon::VectorRegs128BRegClass;
926 // Check if RD could be replaced with RS at any possible use of RD.
927 // For example a predicate register cannot be replaced with a integer
928 // register, but a 64-bit register with a subregister can be replaced
929 // with a 32-bit register.
930 bool HexagonBitSimplify::isTransparentCopy(const BitTracker::RegisterRef &RD,
931 const BitTracker::RegisterRef &RS, MachineRegisterInfo &MRI) {
932 if (!TargetRegisterInfo::isVirtualRegister(RD.Reg) ||
933 !TargetRegisterInfo::isVirtualRegister(RS.Reg))
935 // Return false if one (or both) classes are nullptr.
936 auto *DRC = getFinalVRegClass(RD, MRI);
940 return DRC == getFinalVRegClass(RS, MRI);
943 bool HexagonBitSimplify::hasTiedUse(unsigned Reg, MachineRegisterInfo &MRI,
945 if (!PreserveTiedOps)
947 return llvm::any_of(MRI.use_operands(Reg),
948 [NewSub] (const MachineOperand &Op) -> bool {
949 return Op.getSubReg() != NewSub && Op.isTied();
955 class DeadCodeElimination {
957 DeadCodeElimination(MachineFunction &mf, MachineDominatorTree &mdt)
958 : MF(mf), HII(*MF.getSubtarget<HexagonSubtarget>().getInstrInfo()),
959 MDT(mdt), MRI(mf.getRegInfo()) {}
962 return runOnNode(MDT.getRootNode());
966 bool isDead(unsigned R) const;
967 bool runOnNode(MachineDomTreeNode *N);
970 const HexagonInstrInfo &HII;
971 MachineDominatorTree &MDT;
972 MachineRegisterInfo &MRI;
975 } // end anonymous namespace
977 bool DeadCodeElimination::isDead(unsigned R) const {
978 for (auto I = MRI.use_begin(R), E = MRI.use_end(); I != E; ++I) {
979 MachineInstr *UseI = I->getParent();
980 if (UseI->isDebugValue())
983 assert(!UseI->getOperand(0).getSubReg());
984 unsigned DR = UseI->getOperand(0).getReg();
993 bool DeadCodeElimination::runOnNode(MachineDomTreeNode *N) {
994 bool Changed = false;
996 for (auto *DTN : children<MachineDomTreeNode*>(N))
997 Changed |= runOnNode(DTN);
999 MachineBasicBlock *B = N->getBlock();
1000 std::vector<MachineInstr*> Instrs;
1001 for (auto I = B->rbegin(), E = B->rend(); I != E; ++I)
1002 Instrs.push_back(&*I);
1004 for (auto MI : Instrs) {
1005 unsigned Opc = MI->getOpcode();
1006 // Do not touch lifetime markers. This is why the target-independent DCE
1008 if (Opc == TargetOpcode::LIFETIME_START ||
1009 Opc == TargetOpcode::LIFETIME_END)
1012 if (MI->isInlineAsm())
1014 // Delete PHIs if possible.
1015 if (!MI->isPHI() && !MI->isSafeToMove(nullptr, Store))
1018 bool AllDead = true;
1019 SmallVector<unsigned,2> Regs;
1020 for (auto &Op : MI->operands()) {
1021 if (!Op.isReg() || !Op.isDef())
1023 unsigned R = Op.getReg();
1024 if (!TargetRegisterInfo::isVirtualRegister(R) || !isDead(R)) {
1034 for (unsigned i = 0, n = Regs.size(); i != n; ++i)
1035 MRI.markUsesInDebugValueAsUndef(Regs[i]);
1044 // Eliminate redundant instructions
1046 // This transformation will identify instructions where the output register
1047 // is the same as one of its input registers. This only works on instructions
1048 // that define a single register (unlike post-increment loads, for example).
1049 // The equality check is actually more detailed: the code calculates which
1050 // bits of the output are used, and only compares these bits with the input
1052 // If the output matches an input, the instruction is replaced with COPY.
1053 // The copies will be removed by another transformation.
1054 class RedundantInstrElimination : public Transformation {
1056 RedundantInstrElimination(BitTracker &bt, const HexagonInstrInfo &hii,
1057 const HexagonRegisterInfo &hri, MachineRegisterInfo &mri)
1058 : Transformation(true), HII(hii), HRI(hri), MRI(mri), BT(bt) {}
1060 bool processBlock(MachineBasicBlock &B, const RegisterSet &AVs) override;
1063 bool isLossyShiftLeft(const MachineInstr &MI, unsigned OpN,
1064 unsigned &LostB, unsigned &LostE);
1065 bool isLossyShiftRight(const MachineInstr &MI, unsigned OpN,
1066 unsigned &LostB, unsigned &LostE);
1067 bool computeUsedBits(unsigned Reg, BitVector &Bits);
1068 bool computeUsedBits(const MachineInstr &MI, unsigned OpN, BitVector &Bits,
1070 bool usedBitsEqual(BitTracker::RegisterRef RD, BitTracker::RegisterRef RS);
1072 const HexagonInstrInfo &HII;
1073 const HexagonRegisterInfo &HRI;
1074 MachineRegisterInfo &MRI;
1078 } // end anonymous namespace
1080 // Check if the instruction is a lossy shift left, where the input being
1081 // shifted is the operand OpN of MI. If true, [LostB, LostE) is the range
1082 // of bit indices that are lost.
1083 bool RedundantInstrElimination::isLossyShiftLeft(const MachineInstr &MI,
1084 unsigned OpN, unsigned &LostB, unsigned &LostE) {
1085 using namespace Hexagon;
1087 unsigned Opc = MI.getOpcode();
1088 unsigned ImN, RegN, Width;
1095 case S2_asl_i_p_acc:
1096 case S2_asl_i_p_and:
1097 case S2_asl_i_p_nac:
1099 case S2_asl_i_p_xacc:
1109 case S2_addasl_rrri:
1110 case S4_andi_asl_ri:
1112 case S4_addi_asl_ri:
1113 case S4_subi_asl_ri:
1114 case S2_asl_i_r_acc:
1115 case S2_asl_i_r_and:
1116 case S2_asl_i_r_nac:
1118 case S2_asl_i_r_sat:
1119 case S2_asl_i_r_xacc:
1131 assert(MI.getOperand(ImN).isImm());
1132 unsigned S = MI.getOperand(ImN).getImm();
1140 // Check if the instruction is a lossy shift right, where the input being
1141 // shifted is the operand OpN of MI. If true, [LostB, LostE) is the range
1142 // of bit indices that are lost.
1143 bool RedundantInstrElimination::isLossyShiftRight(const MachineInstr &MI,
1144 unsigned OpN, unsigned &LostB, unsigned &LostE) {
1145 using namespace Hexagon;
1147 unsigned Opc = MI.getOpcode();
1155 case S2_asr_i_p_acc:
1156 case S2_asr_i_p_and:
1157 case S2_asr_i_p_nac:
1159 case S2_lsr_i_p_acc:
1160 case S2_lsr_i_p_and:
1161 case S2_lsr_i_p_nac:
1163 case S2_lsr_i_p_xacc:
1172 case S4_andi_lsr_ri:
1174 case S4_addi_lsr_ri:
1175 case S4_subi_lsr_ri:
1176 case S2_asr_i_r_acc:
1177 case S2_asr_i_r_and:
1178 case S2_asr_i_r_nac:
1180 case S2_lsr_i_r_acc:
1181 case S2_lsr_i_r_and:
1182 case S2_lsr_i_r_nac:
1184 case S2_lsr_i_r_xacc:
1196 assert(MI.getOperand(ImN).isImm());
1197 unsigned S = MI.getOperand(ImN).getImm();
1203 // Calculate the bit vector that corresponds to the used bits of register Reg.
1204 // The vector Bits has the same size, as the size of Reg in bits. If the cal-
1205 // culation fails (i.e. the used bits are unknown), it returns false. Other-
1206 // wise, it returns true and sets the corresponding bits in Bits.
1207 bool RedundantInstrElimination::computeUsedBits(unsigned Reg, BitVector &Bits) {
1208 BitVector Used(Bits.size());
1209 RegisterSet Visited;
1210 std::vector<unsigned> Pending;
1211 Pending.push_back(Reg);
1213 for (unsigned i = 0; i < Pending.size(); ++i) {
1214 unsigned R = Pending[i];
1218 for (auto I = MRI.use_begin(R), E = MRI.use_end(); I != E; ++I) {
1219 BitTracker::RegisterRef UR = *I;
1221 if (!HBS::getSubregMask(UR, B, W, MRI))
1223 MachineInstr &UseI = *I->getParent();
1224 if (UseI.isPHI() || UseI.isCopy()) {
1225 unsigned DefR = UseI.getOperand(0).getReg();
1226 if (!TargetRegisterInfo::isVirtualRegister(DefR))
1228 Pending.push_back(DefR);
1230 if (!computeUsedBits(UseI, I.getOperandNo(), Used, B))
1239 // Calculate the bits used by instruction MI in a register in operand OpN.
1240 // Return true/false if the calculation succeeds/fails. If is succeeds, set
1241 // used bits in Bits. This function does not reset any bits in Bits, so
1242 // subsequent calls over different instructions will result in the union
1243 // of the used bits in all these instructions.
1244 // The register in question may be used with a sub-register, whereas Bits
1245 // holds the bits for the entire register. To keep track of that, the
1246 // argument Begin indicates where in Bits is the lowest-significant bit
1247 // of the register used in operand OpN. For example, in instruction:
1248 // vreg1 = S2_lsr_i_r vreg2:isub_hi, 10
1249 // the operand 1 is a 32-bit register, which happens to be a subregister
1250 // of the 64-bit register vreg2, and that subregister starts at position 32.
1251 // In this case Begin=32, since Bits[32] would be the lowest-significant bit
1252 // of vreg2:isub_hi.
1253 bool RedundantInstrElimination::computeUsedBits(const MachineInstr &MI,
1254 unsigned OpN, BitVector &Bits, uint16_t Begin) {
1255 unsigned Opc = MI.getOpcode();
1256 BitVector T(Bits.size());
1257 bool GotBits = HBS::getUsedBits(Opc, OpN, T, Begin, HII);
1258 // Even if we don't have bits yet, we could still provide some information
1259 // if the instruction is a lossy shift: the lost bits will be marked as
1262 if (isLossyShiftLeft(MI, OpN, LB, LE) || isLossyShiftRight(MI, OpN, LB, LE)) {
1263 assert(MI.getOperand(OpN).isReg());
1264 BitTracker::RegisterRef RR = MI.getOperand(OpN);
1265 const TargetRegisterClass *RC = HBS::getFinalVRegClass(RR, MRI);
1266 uint16_t Width = HRI.getRegSizeInBits(*RC);
1269 T.set(Begin, Begin+Width);
1270 assert(LB <= LE && LB < Width && LE <= Width);
1271 T.reset(Begin+LB, Begin+LE);
1279 // Calculates the used bits in RD ("defined register"), and checks if these
1280 // bits in RS ("used register") and RD are identical.
1281 bool RedundantInstrElimination::usedBitsEqual(BitTracker::RegisterRef RD,
1282 BitTracker::RegisterRef RS) {
1283 const BitTracker::RegisterCell &DC = BT.lookup(RD.Reg);
1284 const BitTracker::RegisterCell &SC = BT.lookup(RS.Reg);
1287 if (!HBS::getSubregMask(RD, DB, DW, MRI))
1290 if (!HBS::getSubregMask(RS, SB, SW, MRI))
1295 BitVector Used(DC.width());
1296 if (!computeUsedBits(RD.Reg, Used))
1299 for (unsigned i = 0; i != DW; ++i)
1300 if (Used[i+DB] && DC[DB+i] != SC[SB+i])
1305 bool RedundantInstrElimination::processBlock(MachineBasicBlock &B,
1306 const RegisterSet&) {
1307 if (!BT.reached(&B))
1309 bool Changed = false;
1311 for (auto I = B.begin(), E = B.end(), NextI = I; I != E; ++I) {
1312 NextI = std::next(I);
1313 MachineInstr *MI = &*I;
1315 if (MI->getOpcode() == TargetOpcode::COPY)
1317 if (MI->hasUnmodeledSideEffects() || MI->isInlineAsm())
1319 unsigned NumD = MI->getDesc().getNumDefs();
1323 BitTracker::RegisterRef RD = MI->getOperand(0);
1324 if (!BT.has(RD.Reg))
1326 const BitTracker::RegisterCell &DC = BT.lookup(RD.Reg);
1327 auto At = MI->isPHI() ? B.getFirstNonPHI()
1328 : MachineBasicBlock::iterator(MI);
1330 // Find a source operand that is equal to the result.
1331 for (auto &Op : MI->uses()) {
1334 BitTracker::RegisterRef RS = Op;
1335 if (!BT.has(RS.Reg))
1337 if (!HBS::isTransparentCopy(RD, RS, MRI))
1341 if (!HBS::getSubregMask(RS, BN, BW, MRI))
1344 const BitTracker::RegisterCell &SC = BT.lookup(RS.Reg);
1345 if (!usedBitsEqual(RD, RS) && !HBS::isEqual(DC, 0, SC, BN, BW))
1348 // If found, replace the instruction with a COPY.
1349 const DebugLoc &DL = MI->getDebugLoc();
1350 const TargetRegisterClass *FRC = HBS::getFinalVRegClass(RD, MRI);
1351 unsigned NewR = MRI.createVirtualRegister(FRC);
1352 MachineInstr *CopyI =
1353 BuildMI(B, At, DL, HII.get(TargetOpcode::COPY), NewR)
1354 .addReg(RS.Reg, 0, RS.Sub);
1355 HBS::replaceSubWithSub(RD.Reg, RD.Sub, NewR, 0, MRI);
1356 // This pass can create copies between registers that don't have the
1357 // exact same values. Updating the tracker has to involve updating
1358 // all dependent cells. Example:
1359 // vreg1 = inst vreg2 ; vreg1 != vreg2, but used bits are equal
1361 // vreg3 = copy vreg2 ; <- inserted
1362 // ... = vreg3 ; <- replaced from vreg2
1363 // Indirectly, we can create a "copy" between vreg1 and vreg2 even
1364 // though their exact values do not match.
1376 // Recognize instructions that produce constant values known at compile-time.
1377 // Replace them with register definitions that load these constants directly.
1378 class ConstGeneration : public Transformation {
1380 ConstGeneration(BitTracker &bt, const HexagonInstrInfo &hii,
1381 MachineRegisterInfo &mri)
1382 : Transformation(true), HII(hii), MRI(mri), BT(bt) {}
1384 bool processBlock(MachineBasicBlock &B, const RegisterSet &AVs) override;
1385 static bool isTfrConst(const MachineInstr &MI);
1388 unsigned genTfrConst(const TargetRegisterClass *RC, int64_t C,
1389 MachineBasicBlock &B, MachineBasicBlock::iterator At, DebugLoc &DL);
1391 const HexagonInstrInfo &HII;
1392 MachineRegisterInfo &MRI;
1396 } // end anonymous namespace
1398 bool ConstGeneration::isTfrConst(const MachineInstr &MI) {
1399 unsigned Opc = MI.getOpcode();
1401 case Hexagon::A2_combineii:
1402 case Hexagon::A4_combineii:
1403 case Hexagon::A2_tfrsi:
1404 case Hexagon::A2_tfrpi:
1405 case Hexagon::PS_true:
1406 case Hexagon::PS_false:
1407 case Hexagon::CONST32:
1408 case Hexagon::CONST64:
1414 // Generate a transfer-immediate instruction that is appropriate for the
1415 // register class and the actual value being transferred.
1416 unsigned ConstGeneration::genTfrConst(const TargetRegisterClass *RC, int64_t C,
1417 MachineBasicBlock &B, MachineBasicBlock::iterator At, DebugLoc &DL) {
1418 unsigned Reg = MRI.createVirtualRegister(RC);
1419 if (RC == &Hexagon::IntRegsRegClass) {
1420 BuildMI(B, At, DL, HII.get(Hexagon::A2_tfrsi), Reg)
1421 .addImm(int32_t(C));
1425 if (RC == &Hexagon::DoubleRegsRegClass) {
1427 BuildMI(B, At, DL, HII.get(Hexagon::A2_tfrpi), Reg)
1432 unsigned Lo = Lo_32(C), Hi = Hi_32(C);
1433 if (isInt<8>(Lo) || isInt<8>(Hi)) {
1434 unsigned Opc = isInt<8>(Lo) ? Hexagon::A2_combineii
1435 : Hexagon::A4_combineii;
1436 BuildMI(B, At, DL, HII.get(Opc), Reg)
1437 .addImm(int32_t(Hi))
1438 .addImm(int32_t(Lo));
1442 BuildMI(B, At, DL, HII.get(Hexagon::CONST64), Reg)
1447 if (RC == &Hexagon::PredRegsRegClass) {
1450 Opc = Hexagon::PS_false;
1451 else if ((C & 0xFF) == 0xFF)
1452 Opc = Hexagon::PS_true;
1455 BuildMI(B, At, DL, HII.get(Opc), Reg);
1462 bool ConstGeneration::processBlock(MachineBasicBlock &B, const RegisterSet&) {
1463 if (!BT.reached(&B))
1465 bool Changed = false;
1468 for (auto I = B.begin(), E = B.end(); I != E; ++I) {
1472 HBS::getInstrDefs(*I, Defs);
1473 if (Defs.count() != 1)
1475 unsigned DR = Defs.find_first();
1476 if (!TargetRegisterInfo::isVirtualRegister(DR))
1479 const BitTracker::RegisterCell &DRC = BT.lookup(DR);
1480 if (HBS::getConst(DRC, 0, DRC.width(), U)) {
1482 DebugLoc DL = I->getDebugLoc();
1483 auto At = I->isPHI() ? B.getFirstNonPHI() : I;
1484 unsigned ImmReg = genTfrConst(MRI.getRegClass(DR), C, B, At, DL);
1486 HBS::replaceReg(DR, ImmReg, MRI);
1487 BT.put(ImmReg, DRC);
1497 // Identify pairs of available registers which hold identical values.
1498 // In such cases, only one of them needs to be calculated, the other one
1499 // will be defined as a copy of the first.
1500 class CopyGeneration : public Transformation {
1502 CopyGeneration(BitTracker &bt, const HexagonInstrInfo &hii,
1503 const HexagonRegisterInfo &hri, MachineRegisterInfo &mri)
1504 : Transformation(true), HII(hii), HRI(hri), MRI(mri), BT(bt) {}
1506 bool processBlock(MachineBasicBlock &B, const RegisterSet &AVs) override;
1509 bool findMatch(const BitTracker::RegisterRef &Inp,
1510 BitTracker::RegisterRef &Out, const RegisterSet &AVs);
1512 const HexagonInstrInfo &HII;
1513 const HexagonRegisterInfo &HRI;
1514 MachineRegisterInfo &MRI;
1516 RegisterSet Forbidden;
1519 // Eliminate register copies RD = RS, by replacing the uses of RD with
1521 class CopyPropagation : public Transformation {
1523 CopyPropagation(const HexagonRegisterInfo &hri, MachineRegisterInfo &mri)
1524 : Transformation(false), HRI(hri), MRI(mri) {}
1526 bool processBlock(MachineBasicBlock &B, const RegisterSet &AVs) override;
1528 static bool isCopyReg(unsigned Opc, bool NoConv);
1531 bool propagateRegCopy(MachineInstr &MI);
1533 const HexagonRegisterInfo &HRI;
1534 MachineRegisterInfo &MRI;
1537 } // end anonymous namespace
1539 /// Check if there is a register in AVs that is identical to Inp. If so,
1540 /// set Out to the found register. The output may be a pair Reg:Sub.
1541 bool CopyGeneration::findMatch(const BitTracker::RegisterRef &Inp,
1542 BitTracker::RegisterRef &Out, const RegisterSet &AVs) {
1543 if (!BT.has(Inp.Reg))
1545 const BitTracker::RegisterCell &InpRC = BT.lookup(Inp.Reg);
1546 auto *FRC = HBS::getFinalVRegClass(Inp, MRI);
1548 if (!HBS::getSubregMask(Inp, B, W, MRI))
1551 for (unsigned R = AVs.find_first(); R; R = AVs.find_next(R)) {
1552 if (!BT.has(R) || Forbidden[R])
1554 const BitTracker::RegisterCell &RC = BT.lookup(R);
1555 unsigned RW = RC.width();
1557 if (FRC != MRI.getRegClass(R))
1559 if (!HBS::isTransparentCopy(R, Inp, MRI))
1561 if (!HBS::isEqual(InpRC, B, RC, 0, W))
1567 // Check if there is a super-register, whose part (with a subregister)
1568 // is equal to the input.
1569 // Only do double registers for now.
1572 if (MRI.getRegClass(R) != &Hexagon::DoubleRegsRegClass)
1575 if (HBS::isEqual(InpRC, B, RC, 0, W))
1576 Out.Sub = Hexagon::isub_lo;
1577 else if (HBS::isEqual(InpRC, B, RC, W, W))
1578 Out.Sub = Hexagon::isub_hi;
1582 if (HBS::isTransparentCopy(Out, Inp, MRI))
1588 bool CopyGeneration::processBlock(MachineBasicBlock &B,
1589 const RegisterSet &AVs) {
1590 if (!BT.reached(&B))
1592 RegisterSet AVB(AVs);
1593 bool Changed = false;
1596 for (auto I = B.begin(), E = B.end(), NextI = I; I != E;
1597 ++I, AVB.insert(Defs)) {
1598 NextI = std::next(I);
1600 HBS::getInstrDefs(*I, Defs);
1602 unsigned Opc = I->getOpcode();
1603 if (CopyPropagation::isCopyReg(Opc, false) ||
1604 ConstGeneration::isTfrConst(*I))
1607 DebugLoc DL = I->getDebugLoc();
1608 auto At = I->isPHI() ? B.getFirstNonPHI() : I;
1610 for (unsigned R = Defs.find_first(); R; R = Defs.find_next(R)) {
1611 BitTracker::RegisterRef MR;
1612 auto *FRC = HBS::getFinalVRegClass(R, MRI);
1614 if (findMatch(R, MR, AVB)) {
1615 unsigned NewR = MRI.createVirtualRegister(FRC);
1616 BuildMI(B, At, DL, HII.get(TargetOpcode::COPY), NewR)
1617 .addReg(MR.Reg, 0, MR.Sub);
1618 BT.put(BitTracker::RegisterRef(NewR), BT.get(MR));
1619 HBS::replaceReg(R, NewR, MRI);
1620 Forbidden.insert(R);
1624 if (FRC == &Hexagon::DoubleRegsRegClass ||
1625 FRC == &Hexagon::VecDblRegsRegClass ||
1626 FRC == &Hexagon::VecDblRegs128BRegClass) {
1627 // Try to generate REG_SEQUENCE.
1628 unsigned SubLo = HRI.getHexagonSubRegIndex(FRC, Hexagon::ps_sub_lo);
1629 unsigned SubHi = HRI.getHexagonSubRegIndex(FRC, Hexagon::ps_sub_hi);
1630 BitTracker::RegisterRef TL = { R, SubLo };
1631 BitTracker::RegisterRef TH = { R, SubHi };
1632 BitTracker::RegisterRef ML, MH;
1633 if (findMatch(TL, ML, AVB) && findMatch(TH, MH, AVB)) {
1634 auto *FRC = HBS::getFinalVRegClass(R, MRI);
1635 unsigned NewR = MRI.createVirtualRegister(FRC);
1636 BuildMI(B, At, DL, HII.get(TargetOpcode::REG_SEQUENCE), NewR)
1637 .addReg(ML.Reg, 0, ML.Sub)
1639 .addReg(MH.Reg, 0, MH.Sub)
1641 BT.put(BitTracker::RegisterRef(NewR), BT.get(R));
1642 HBS::replaceReg(R, NewR, MRI);
1643 Forbidden.insert(R);
1652 bool CopyPropagation::isCopyReg(unsigned Opc, bool NoConv) {
1654 case TargetOpcode::COPY:
1655 case TargetOpcode::REG_SEQUENCE:
1656 case Hexagon::A4_combineir:
1657 case Hexagon::A4_combineri:
1659 case Hexagon::A2_tfr:
1660 case Hexagon::A2_tfrp:
1661 case Hexagon::A2_combinew:
1662 case Hexagon::V6_vcombine:
1663 case Hexagon::V6_vcombine_128B:
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);
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))
1685 Changed = HBS::replaceRegWithSub(RD.Reg, RS.Reg, RS.Sub, MRI);
1687 Changed = HBS::replaceReg(RD.Reg, RS.Reg, MRI);
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);
1701 case Hexagon::A2_combinew:
1702 case Hexagon::V6_vcombine:
1703 case Hexagon::V6_vcombine_128B: {
1704 const TargetRegisterClass *RC = MRI.getRegClass(RD.Reg);
1705 unsigned SubLo = HRI.getHexagonSubRegIndex(RC, Hexagon::ps_sub_lo);
1706 unsigned SubHi = HRI.getHexagonSubRegIndex(RC, Hexagon::ps_sub_hi);
1707 BitTracker::RegisterRef RH = MI.getOperand(1), RL = MI.getOperand(2);
1708 Changed = HBS::replaceSubWithSub(RD.Reg, SubLo, RL.Reg, RL.Sub, MRI);
1709 Changed |= HBS::replaceSubWithSub(RD.Reg, SubHi, RH.Reg, RH.Sub, MRI);
1712 case Hexagon::A4_combineir:
1713 case Hexagon::A4_combineri: {
1714 unsigned SrcX = (Opc == Hexagon::A4_combineir) ? 2 : 1;
1715 unsigned Sub = (Opc == Hexagon::A4_combineir) ? Hexagon::isub_lo
1717 BitTracker::RegisterRef RS = MI.getOperand(SrcX);
1718 Changed = HBS::replaceSubWithSub(RD.Reg, Sub, RS.Reg, RS.Sub, MRI);
1725 bool CopyPropagation::processBlock(MachineBasicBlock &B, const RegisterSet&) {
1726 std::vector<MachineInstr*> Instrs;
1727 for (auto I = B.rbegin(), E = B.rend(); I != E; ++I)
1728 Instrs.push_back(&*I);
1730 bool Changed = false;
1731 for (auto I : Instrs) {
1732 unsigned Opc = I->getOpcode();
1733 if (!CopyPropagation::isCopyReg(Opc, true))
1735 Changed |= propagateRegCopy(*I);
1743 // Recognize patterns that can be simplified and replace them with the
1745 // This is by no means complete
1746 class BitSimplification : public Transformation {
1748 BitSimplification(BitTracker &bt, const MachineDominatorTree &mdt,
1749 const HexagonInstrInfo &hii, const HexagonRegisterInfo &hri,
1750 MachineRegisterInfo &mri, MachineFunction &mf)
1751 : Transformation(true), MDT(mdt), HII(hii), HRI(hri), MRI(mri),
1754 bool processBlock(MachineBasicBlock &B, const RegisterSet &AVs) override;
1757 struct RegHalf : public BitTracker::RegisterRef {
1758 bool Low; // Low/High halfword.
1761 bool matchHalf(unsigned SelfR, const BitTracker::RegisterCell &RC,
1762 unsigned B, RegHalf &RH);
1763 bool validateReg(BitTracker::RegisterRef R, unsigned Opc, unsigned OpNum);
1765 bool matchPackhl(unsigned SelfR, const BitTracker::RegisterCell &RC,
1766 BitTracker::RegisterRef &Rs, BitTracker::RegisterRef &Rt);
1767 unsigned getCombineOpcode(bool HLow, bool LLow);
1769 bool genStoreUpperHalf(MachineInstr *MI);
1770 bool genStoreImmediate(MachineInstr *MI);
1771 bool genPackhl(MachineInstr *MI, BitTracker::RegisterRef RD,
1772 const BitTracker::RegisterCell &RC);
1773 bool genExtractHalf(MachineInstr *MI, BitTracker::RegisterRef RD,
1774 const BitTracker::RegisterCell &RC);
1775 bool genCombineHalf(MachineInstr *MI, BitTracker::RegisterRef RD,
1776 const BitTracker::RegisterCell &RC);
1777 bool genExtractLow(MachineInstr *MI, BitTracker::RegisterRef RD,
1778 const BitTracker::RegisterCell &RC);
1779 bool genBitSplit(MachineInstr *MI, BitTracker::RegisterRef RD,
1780 const BitTracker::RegisterCell &RC, const RegisterSet &AVs);
1781 bool simplifyTstbit(MachineInstr *MI, BitTracker::RegisterRef RD,
1782 const BitTracker::RegisterCell &RC);
1783 bool simplifyExtractLow(MachineInstr *MI, BitTracker::RegisterRef RD,
1784 const BitTracker::RegisterCell &RC, const RegisterSet &AVs);
1786 // Cache of created instructions to avoid creating duplicates.
1787 // XXX Currently only used by genBitSplit.
1788 std::vector<MachineInstr*> NewMIs;
1790 const MachineDominatorTree &MDT;
1791 const HexagonInstrInfo &HII;
1792 const HexagonRegisterInfo &HRI;
1793 MachineRegisterInfo &MRI;
1794 MachineFunction &MF;
1798 } // end anonymous namespace
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.
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]... }.
1814 while (I < B+16 && RC[I].num())
1819 unsigned Reg = RC[I].RefI.Reg;
1820 unsigned P = RC[I].RefI.Pos; // The RefI.Pos will be advanced by I-B.
1823 unsigned Pos = P - (I-B);
1825 if (Reg == 0 || Reg == SelfR) // Don't match "self".
1827 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1832 const BitTracker::RegisterCell &SC = BT.lookup(Reg);
1833 if (Pos+16 > SC.width())
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)
1841 if (RV.RefI.Pos != i+Pos)
1845 if (RC[i+B] != SC[i+Pos])
1852 Sub = Hexagon::isub_lo;
1856 Sub = Hexagon::isub_lo;
1860 Sub = Hexagon::isub_hi;
1864 Sub = Hexagon::isub_hi;
1874 // If the subregister is not valid with the register, set it to 0.
1875 if (!HBS::getFinalVRegClass(RH, MRI))
1881 bool BitSimplification::validateReg(BitTracker::RegisterRef R, unsigned Opc,
1883 auto *OpRC = HII.getRegClass(HII.get(Opc), OpNum, &HRI, MF);
1884 auto *RRC = HBS::getFinalVRegClass(R, MRI);
1885 return OpRC->hasSubClassEq(RRC);
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;
1895 if (!matchHalf(SelfR, RC, 0, L2) || !matchHalf(SelfR, RC, 16, L1))
1897 if (!matchHalf(SelfR, RC, 32, H2) || !matchHalf(SelfR, RC, 48, H1))
1900 // Rs = H1.L1, Rt = H2.L2
1901 if (H1.Reg != L1.Reg || H1.Sub != L1.Sub || H1.Low || !L1.Low)
1903 if (H2.Reg != L2.Reg || H2.Sub != L2.Sub || H2.Low || !L2.Low)
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;
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)
1926 MachineOperand &ValOp = MI->getOperand(2);
1927 BitTracker::RegisterRef RS = ValOp;
1928 if (!BT.has(RS.Reg))
1930 const BitTracker::RegisterCell &RC = BT.lookup(RS.Reg);
1932 if (!matchHalf(0, RC, 0, H))
1936 MI->setDesc(HII.get(Hexagon::S2_storerf_io));
1937 ValOp.setReg(H.Reg);
1938 ValOp.setSubReg(H.Sub);
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();
1948 case Hexagon::S2_storeri_io:
1951 case Hexagon::S2_storerh_io:
1954 case Hexagon::S2_storerb_io:
1960 // Avoid stores to frame-indices (due to an unknown offset).
1961 if (!MI->getOperand(0).isReg())
1963 MachineOperand &OffOp = MI->getOperand(1);
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)))
1972 BitTracker::RegisterRef RS = MI->getOperand(2);
1973 if (!BT.has(RS.Reg))
1975 const BitTracker::RegisterCell &RC = BT.lookup(RS.Reg);
1977 if (!HBS::getConst(RC, 0, RC.width(), U))
1980 // Only consider 8-bit values to avoid constant-extenders.
1983 case Hexagon::S2_storerb_io:
1986 case Hexagon::S2_storerh_io:
1989 case Hexagon::S2_storeri_io:
1996 MI->RemoveOperand(2);
1998 case Hexagon::S2_storerb_io:
1999 MI->setDesc(HII.get(Hexagon::S4_storeirb_io));
2001 case Hexagon::S2_storerh_io:
2002 MI->setDesc(HII.get(Hexagon::S4_storeirh_io));
2004 case Hexagon::S2_storeri_io:
2005 MI->setDesc(HII.get(Hexagon::S4_storeiri_io));
2008 MI->addOperand(MachineOperand::CreateImm(V));
2012 // If MI is equivalent o S2_packhl, generate the S2_packhl. MI could be the
2013 // last instruction in a sequence that results in something equivalent to
2014 // the pack-halfwords. The intent is to cause the entire sequence to become
2016 bool BitSimplification::genPackhl(MachineInstr *MI,
2017 BitTracker::RegisterRef RD, const BitTracker::RegisterCell &RC) {
2018 unsigned Opc = MI->getOpcode();
2019 if (Opc == Hexagon::S2_packhl)
2021 BitTracker::RegisterRef Rs, Rt;
2022 if (!matchPackhl(RD.Reg, RC, Rs, Rt))
2024 if (!validateReg(Rs, Hexagon::S2_packhl, 1) ||
2025 !validateReg(Rt, Hexagon::S2_packhl, 2))
2028 MachineBasicBlock &B = *MI->getParent();
2029 unsigned NewR = MRI.createVirtualRegister(&Hexagon::DoubleRegsRegClass);
2030 DebugLoc DL = MI->getDebugLoc();
2031 auto At = MI->isPHI() ? B.getFirstNonPHI()
2032 : MachineBasicBlock::iterator(MI);
2033 BuildMI(B, At, DL, HII.get(Hexagon::S2_packhl), NewR)
2034 .addReg(Rs.Reg, 0, Rs.Sub)
2035 .addReg(Rt.Reg, 0, Rt.Sub);
2036 HBS::replaceSubWithSub(RD.Reg, RD.Sub, NewR, 0, MRI);
2037 BT.put(BitTracker::RegisterRef(NewR), RC);
2041 // If MI produces halfword of the input in the low half of the output,
2042 // replace it with zero-extend or extractu.
2043 bool BitSimplification::genExtractHalf(MachineInstr *MI,
2044 BitTracker::RegisterRef RD, const BitTracker::RegisterCell &RC) {
2046 // Check for halfword in low 16 bits, zeros elsewhere.
2047 if (!matchHalf(RD.Reg, RC, 0, L) || !HBS::isZero(RC, 16, 16))
2050 unsigned Opc = MI->getOpcode();
2051 MachineBasicBlock &B = *MI->getParent();
2052 DebugLoc DL = MI->getDebugLoc();
2054 // Prefer zxth, since zxth can go in any slot, while extractu only in
2057 auto At = MI->isPHI() ? B.getFirstNonPHI()
2058 : MachineBasicBlock::iterator(MI);
2059 if (L.Low && Opc != Hexagon::A2_zxth) {
2060 if (validateReg(L, Hexagon::A2_zxth, 1)) {
2061 NewR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
2062 BuildMI(B, At, DL, HII.get(Hexagon::A2_zxth), NewR)
2063 .addReg(L.Reg, 0, L.Sub);
2065 } else if (!L.Low && Opc != Hexagon::S2_lsr_i_r) {
2066 if (validateReg(L, Hexagon::S2_lsr_i_r, 1)) {
2067 NewR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
2068 BuildMI(B, MI, DL, HII.get(Hexagon::S2_lsr_i_r), NewR)
2069 .addReg(L.Reg, 0, L.Sub)
2075 HBS::replaceSubWithSub(RD.Reg, RD.Sub, NewR, 0, MRI);
2076 BT.put(BitTracker::RegisterRef(NewR), RC);
2080 // If MI is equivalent to a combine(.L/.H, .L/.H) replace with with the
2082 bool BitSimplification::genCombineHalf(MachineInstr *MI,
2083 BitTracker::RegisterRef RD, const BitTracker::RegisterCell &RC) {
2085 // Check for combine h/l
2086 if (!matchHalf(RD.Reg, RC, 0, L) || !matchHalf(RD.Reg, RC, 16, H))
2088 // Do nothing if this is just a reg copy.
2089 if (L.Reg == H.Reg && L.Sub == H.Sub && !H.Low && L.Low)
2092 unsigned Opc = MI->getOpcode();
2093 unsigned COpc = getCombineOpcode(H.Low, L.Low);
2096 if (!validateReg(H, COpc, 1) || !validateReg(L, COpc, 2))
2099 MachineBasicBlock &B = *MI->getParent();
2100 DebugLoc DL = MI->getDebugLoc();
2101 unsigned NewR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
2102 auto At = MI->isPHI() ? B.getFirstNonPHI()
2103 : MachineBasicBlock::iterator(MI);
2104 BuildMI(B, At, DL, HII.get(COpc), NewR)
2105 .addReg(H.Reg, 0, H.Sub)
2106 .addReg(L.Reg, 0, L.Sub);
2107 HBS::replaceSubWithSub(RD.Reg, RD.Sub, NewR, 0, MRI);
2108 BT.put(BitTracker::RegisterRef(NewR), RC);
2112 // If MI resets high bits of a register and keeps the lower ones, replace it
2113 // with zero-extend byte/half, and-immediate, or extractu, as appropriate.
2114 bool BitSimplification::genExtractLow(MachineInstr *MI,
2115 BitTracker::RegisterRef RD, const BitTracker::RegisterCell &RC) {
2116 unsigned Opc = MI->getOpcode();
2118 case Hexagon::A2_zxtb:
2119 case Hexagon::A2_zxth:
2120 case Hexagon::S2_extractu:
2123 if (Opc == Hexagon::A2_andir && MI->getOperand(2).isImm()) {
2124 int32_t Imm = MI->getOperand(2).getImm();
2129 if (MI->hasUnmodeledSideEffects() || MI->isInlineAsm())
2131 unsigned W = RC.width();
2132 while (W > 0 && RC[W-1].is(0))
2134 if (W == 0 || W == RC.width())
2136 unsigned NewOpc = (W == 8) ? Hexagon::A2_zxtb
2137 : (W == 16) ? Hexagon::A2_zxth
2138 : (W < 10) ? Hexagon::A2_andir
2139 : Hexagon::S2_extractu;
2140 MachineBasicBlock &B = *MI->getParent();
2141 DebugLoc DL = MI->getDebugLoc();
2143 for (auto &Op : MI->uses()) {
2146 BitTracker::RegisterRef RS = Op;
2147 if (!BT.has(RS.Reg))
2149 const BitTracker::RegisterCell &SC = BT.lookup(RS.Reg);
2151 if (!HBS::getSubregMask(RS, BN, BW, MRI))
2153 if (BW < W || !HBS::isEqual(RC, 0, SC, BN, W))
2155 if (!validateReg(RS, NewOpc, 1))
2158 unsigned NewR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
2159 auto At = MI->isPHI() ? B.getFirstNonPHI()
2160 : MachineBasicBlock::iterator(MI);
2161 auto MIB = BuildMI(B, At, DL, HII.get(NewOpc), NewR)
2162 .addReg(RS.Reg, 0, RS.Sub);
2163 if (NewOpc == Hexagon::A2_andir)
2164 MIB.addImm((1 << W) - 1);
2165 else if (NewOpc == Hexagon::S2_extractu)
2166 MIB.addImm(W).addImm(0);
2167 HBS::replaceSubWithSub(RD.Reg, RD.Sub, NewR, 0, MRI);
2168 BT.put(BitTracker::RegisterRef(NewR), RC);
2174 bool BitSimplification::genBitSplit(MachineInstr *MI,
2175 BitTracker::RegisterRef RD, const BitTracker::RegisterCell &RC,
2176 const RegisterSet &AVs) {
2179 if (MaxBitSplit.getNumOccurrences()) {
2180 if (CountBitSplit >= MaxBitSplit)
2184 unsigned Opc = MI->getOpcode();
2186 case Hexagon::A4_bitsplit:
2187 case Hexagon::A4_bitspliti:
2191 unsigned W = RC.width();
2195 auto ctlz = [] (const BitTracker::RegisterCell &C) -> unsigned {
2196 unsigned Z = C.width();
2197 while (Z > 0 && C[Z-1].is(0))
2199 return C.width() - Z;
2202 // Count the number of leading zeros in the target RC.
2203 unsigned Z = ctlz(RC);
2204 if (Z == 0 || Z == W)
2207 // A simplistic analysis: assume the source register (the one being split)
2208 // is fully unknown, and that all its bits are self-references.
2209 const BitTracker::BitValue &B0 = RC[0];
2210 if (B0.Type != BitTracker::BitValue::Ref)
2213 unsigned SrcR = B0.RefI.Reg;
2215 unsigned Pos = B0.RefI.Pos;
2217 // All the non-zero bits should be consecutive bits from the same register.
2218 for (unsigned i = 1; i < W-Z; ++i) {
2219 const BitTracker::BitValue &V = RC[i];
2220 if (V.Type != BitTracker::BitValue::Ref)
2222 if (V.RefI.Reg != SrcR || V.RefI.Pos != Pos+i)
2226 // Now, find the other bitfield among AVs.
2227 for (unsigned S = AVs.find_first(); S; S = AVs.find_next(S)) {
2228 // The number of leading zeros here should be the number of trailing
2232 const BitTracker::RegisterCell &SC = BT.lookup(S);
2233 if (SC.width() != W || ctlz(SC) != W-Z)
2235 // The Z lower bits should now match SrcR.
2236 const BitTracker::BitValue &S0 = SC[0];
2237 if (S0.Type != BitTracker::BitValue::Ref || S0.RefI.Reg != SrcR)
2239 unsigned P = S0.RefI.Pos;
2241 if (Pos <= P && (Pos + W-Z) != P)
2243 if (P < Pos && (P + Z) != Pos)
2245 // The starting bitfield position must be at a subregister boundary.
2246 if (std::min(P, Pos) != 0 && std::min(P, Pos) != 32)
2250 for (I = 1; I < Z; ++I) {
2251 const BitTracker::BitValue &V = SC[I];
2252 if (V.Type != BitTracker::BitValue::Ref)
2254 if (V.RefI.Reg != SrcR || V.RefI.Pos != P+I)
2260 // Generate bitsplit where S is defined.
2261 if (MaxBitSplit.getNumOccurrences())
2263 MachineInstr *DefS = MRI.getVRegDef(S);
2264 assert(DefS != nullptr);
2265 DebugLoc DL = DefS->getDebugLoc();
2266 MachineBasicBlock &B = *DefS->getParent();
2267 auto At = DefS->isPHI() ? B.getFirstNonPHI()
2268 : MachineBasicBlock::iterator(DefS);
2269 if (MRI.getRegClass(SrcR)->getID() == Hexagon::DoubleRegsRegClassID)
2270 SrcSR = (std::min(Pos, P) == 32) ? Hexagon::isub_hi : Hexagon::isub_lo;
2271 if (!validateReg({SrcR,SrcSR}, Hexagon::A4_bitspliti, 1))
2273 unsigned ImmOp = Pos <= P ? W-Z : Z;
2275 // Find an existing bitsplit instruction if one already exists.
2277 for (MachineInstr *In : NewMIs) {
2278 if (In->getOpcode() != Hexagon::A4_bitspliti)
2280 MachineOperand &Op1 = In->getOperand(1);
2281 if (Op1.getReg() != SrcR || Op1.getSubReg() != SrcSR)
2283 if (In->getOperand(2).getImm() != ImmOp)
2285 // Check if the target register is available here.
2286 MachineOperand &Op0 = In->getOperand(0);
2287 MachineInstr *DefI = MRI.getVRegDef(Op0.getReg());
2288 assert(DefI != nullptr);
2289 if (!MDT.dominates(DefI, &*At))
2292 // Found one that can be reused.
2293 assert(Op0.getSubReg() == 0);
2294 NewR = Op0.getReg();
2298 NewR = MRI.createVirtualRegister(&Hexagon::DoubleRegsRegClass);
2299 auto NewBS = BuildMI(B, At, DL, HII.get(Hexagon::A4_bitspliti), NewR)
2300 .addReg(SrcR, 0, SrcSR)
2302 NewMIs.push_back(NewBS);
2305 HBS::replaceRegWithSub(RD.Reg, NewR, Hexagon::isub_lo, MRI);
2306 HBS::replaceRegWithSub(S, NewR, Hexagon::isub_hi, MRI);
2308 HBS::replaceRegWithSub(S, NewR, Hexagon::isub_lo, MRI);
2309 HBS::replaceRegWithSub(RD.Reg, NewR, Hexagon::isub_hi, MRI);
2317 // Check for tstbit simplification opportunity, where the bit being checked
2318 // can be tracked back to another register. For example:
2319 // vreg2 = S2_lsr_i_r vreg1, 5
2320 // vreg3 = S2_tstbit_i vreg2, 0
2322 // vreg3 = S2_tstbit_i vreg1, 5
2323 bool BitSimplification::simplifyTstbit(MachineInstr *MI,
2324 BitTracker::RegisterRef RD, const BitTracker::RegisterCell &RC) {
2325 unsigned Opc = MI->getOpcode();
2326 if (Opc != Hexagon::S2_tstbit_i)
2329 unsigned BN = MI->getOperand(2).getImm();
2330 BitTracker::RegisterRef RS = MI->getOperand(1);
2332 DebugLoc DL = MI->getDebugLoc();
2333 if (!BT.has(RS.Reg) || !HBS::getSubregMask(RS, F, W, MRI))
2335 MachineBasicBlock &B = *MI->getParent();
2336 auto At = MI->isPHI() ? B.getFirstNonPHI()
2337 : MachineBasicBlock::iterator(MI);
2339 const BitTracker::RegisterCell &SC = BT.lookup(RS.Reg);
2340 const BitTracker::BitValue &V = SC[F+BN];
2341 if (V.Type == BitTracker::BitValue::Ref && V.RefI.Reg != RS.Reg) {
2342 const TargetRegisterClass *TC = MRI.getRegClass(V.RefI.Reg);
2343 // Need to map V.RefI.Reg to a 32-bit register, i.e. if it is
2344 // a double register, need to use a subregister and adjust bit
2346 unsigned P = std::numeric_limits<unsigned>::max();
2347 BitTracker::RegisterRef RR(V.RefI.Reg, 0);
2348 if (TC == &Hexagon::DoubleRegsRegClass) {
2350 RR.Sub = Hexagon::isub_lo;
2353 RR.Sub = Hexagon::isub_hi;
2355 } else if (TC == &Hexagon::IntRegsRegClass) {
2358 if (P != std::numeric_limits<unsigned>::max()) {
2359 unsigned NewR = MRI.createVirtualRegister(&Hexagon::PredRegsRegClass);
2360 BuildMI(B, At, DL, HII.get(Hexagon::S2_tstbit_i), NewR)
2361 .addReg(RR.Reg, 0, RR.Sub)
2363 HBS::replaceReg(RD.Reg, NewR, MRI);
2367 } else if (V.is(0) || V.is(1)) {
2368 unsigned NewR = MRI.createVirtualRegister(&Hexagon::PredRegsRegClass);
2369 unsigned NewOpc = V.is(0) ? Hexagon::PS_false : Hexagon::PS_true;
2370 BuildMI(B, At, DL, HII.get(NewOpc), NewR);
2371 HBS::replaceReg(RD.Reg, NewR, MRI);
2378 // Detect whether RD is a bitfield extract (sign- or zero-extended) of
2379 // some register from the AVs set. Create a new corresponding instruction
2380 // at the location of MI. The intent is to recognize situations where
2381 // a sequence of instructions performs an operation that is equivalent to
2382 // an extract operation, such as a shift left followed by a shift right.
2383 bool BitSimplification::simplifyExtractLow(MachineInstr *MI,
2384 BitTracker::RegisterRef RD, const BitTracker::RegisterCell &RC,
2385 const RegisterSet &AVs) {
2388 if (MaxExtract.getNumOccurrences()) {
2389 if (CountExtract >= MaxExtract)
2394 unsigned W = RC.width();
2399 // The code is mostly class-independent, except for the part that generates
2400 // the extract instruction, and establishes the source register (in case it
2401 // needs to use a subregister).
2402 const TargetRegisterClass *FRC = HBS::getFinalVRegClass(RD, MRI);
2403 if (FRC != &Hexagon::IntRegsRegClass && FRC != &Hexagon::DoubleRegsRegClass)
2405 assert(RD.Sub == 0);
2408 // If the cell has a form of 00..0xx..x with k zeros and n remaining
2409 // bits, this could be an extractu of the n bits, but it could also be
2410 // an extractu of a longer field which happens to have 0s in the top
2412 // The same logic applies to sign-extended fields.
2414 // Do not check for the extended extracts, since it would expand the
2415 // search space quite a bit. The search may be expensive as it is.
2417 const BitTracker::BitValue &TopV = RC[W-1];
2419 // Eliminate candidates that have self-referential bits, since they
2420 // cannot be extracts from other registers. Also, skip registers that
2421 // have compile-time constant values.
2422 bool IsConst = true;
2423 for (unsigned I = 0; I != W; ++I) {
2424 const BitTracker::BitValue &V = RC[I];
2425 if (V.Type == BitTracker::BitValue::Ref && V.RefI.Reg == RD.Reg)
2427 IsConst = IsConst && (V.is(0) || V.is(1));
2432 if (TopV.is(0) || TopV.is(1)) {
2433 bool S = TopV.is(1);
2434 for (--W; W > 0 && RC[W-1].is(S); --W)
2438 // The sign bit must be a part of the field being extended.
2442 // This could still be a sign-extended extract.
2443 assert(TopV.Type == BitTracker::BitValue::Ref);
2444 if (TopV.RefI.Reg == RD.Reg || TopV.RefI.Pos == W-1)
2446 for (--W; W > 0 && RC[W-1] == TopV; --W)
2448 // The top bits of RC are copies of TopV. One occurrence of TopV will
2449 // be a part of the field.
2454 // This would be just a copy. It should be handled elsewhere.
2459 dbgs() << __func__ << " on reg: " << PrintReg(RD.Reg, &HRI, RD.Sub)
2461 dbgs() << "Cell: " << RC << '\n';
2462 dbgs() << "Expected bitfield size: " << Len << " bits, "
2463 << (Signed ? "sign" : "zero") << "-extended\n";
2466 bool Changed = false;
2468 for (unsigned R = AVs.find_first(); R != 0; R = AVs.find_next(R)) {
2471 const BitTracker::RegisterCell &SC = BT.lookup(R);
2472 unsigned SW = SC.width();
2474 // The source can be longer than the destination, as long as its size is
2475 // a multiple of the size of the destination. Also, we would need to be
2476 // able to refer to the subregister in the source that would be of the
2477 // same size as the destination, but only check the sizes here.
2478 if (SW < RW || (SW % RW) != 0)
2481 // The field can start at any offset in SC as long as it contains Len
2482 // bits and does not cross subregister boundary (if the source register
2483 // is longer than the destination).
2485 while (Off <= SW-Len) {
2486 unsigned OE = (Off+Len)/RW;
2488 // The assumption here is that if the source (R) is longer than the
2489 // destination, then the destination is a sequence of words of
2490 // size RW, and each such word in R can be accessed via a subregister.
2492 // If the beginning and the end of the field cross the subregister
2493 // boundary, advance to the next subregister.
2497 if (HBS::isEqual(RC, 0, SC, Off, Len))
2506 unsigned ExtOpc = 0;
2509 ExtOpc = Signed ? Hexagon::A2_sxtb : Hexagon::A2_zxtb;
2511 ExtOpc = Signed ? Hexagon::A2_sxth : Hexagon::A2_zxth;
2512 else if (Len < 10 && !Signed)
2513 ExtOpc = Hexagon::A2_andir;
2517 Signed ? (RW == 32 ? Hexagon::S4_extract : Hexagon::S4_extractp)
2518 : (RW == 32 ? Hexagon::S2_extractu : Hexagon::S2_extractup);
2521 // This only recognizes isub_lo and isub_hi.
2522 if (RW != SW && RW*2 != SW)
2525 SR = (Off/RW == 0) ? Hexagon::isub_lo : Hexagon::isub_hi;
2528 if (!validateReg({R,SR}, ExtOpc, 1))
2531 // Don't generate the same instruction as the one being optimized.
2532 if (MI->getOpcode() == ExtOpc) {
2533 // All possible ExtOpc's have the source in operand(1).
2534 const MachineOperand &SrcOp = MI->getOperand(1);
2535 if (SrcOp.getReg() == R)
2539 DebugLoc DL = MI->getDebugLoc();
2540 MachineBasicBlock &B = *MI->getParent();
2541 unsigned NewR = MRI.createVirtualRegister(FRC);
2542 auto At = MI->isPHI() ? B.getFirstNonPHI()
2543 : MachineBasicBlock::iterator(MI);
2544 auto MIB = BuildMI(B, At, DL, HII.get(ExtOpc), NewR)
2547 case Hexagon::A2_sxtb:
2548 case Hexagon::A2_zxtb:
2549 case Hexagon::A2_sxth:
2550 case Hexagon::A2_zxth:
2552 case Hexagon::A2_andir:
2553 MIB.addImm((1u << Len) - 1);
2555 case Hexagon::S4_extract:
2556 case Hexagon::S2_extractu:
2557 case Hexagon::S4_extractp:
2558 case Hexagon::S2_extractup:
2563 llvm_unreachable("Unexpected opcode");
2566 HBS::replaceReg(RD.Reg, NewR, MRI);
2567 BT.put(BitTracker::RegisterRef(NewR), RC);
2575 bool BitSimplification::processBlock(MachineBasicBlock &B,
2576 const RegisterSet &AVs) {
2577 if (!BT.reached(&B))
2579 bool Changed = false;
2580 RegisterSet AVB = AVs;
2583 for (auto I = B.begin(), E = B.end(); I != E; ++I, AVB.insert(Defs)) {
2584 MachineInstr *MI = &*I;
2586 HBS::getInstrDefs(*MI, Defs);
2588 unsigned Opc = MI->getOpcode();
2589 if (Opc == TargetOpcode::COPY || Opc == TargetOpcode::REG_SEQUENCE)
2592 if (MI->mayStore()) {
2593 bool T = genStoreUpperHalf(MI);
2594 T = T || genStoreImmediate(MI);
2599 if (Defs.count() != 1)
2601 const MachineOperand &Op0 = MI->getOperand(0);
2602 if (!Op0.isReg() || !Op0.isDef())
2604 BitTracker::RegisterRef RD = Op0;
2605 if (!BT.has(RD.Reg))
2607 const TargetRegisterClass *FRC = HBS::getFinalVRegClass(RD, MRI);
2608 const BitTracker::RegisterCell &RC = BT.lookup(RD.Reg);
2610 if (FRC->getID() == Hexagon::DoubleRegsRegClassID) {
2611 bool T = genPackhl(MI, RD, RC);
2612 T = T || simplifyExtractLow(MI, RD, RC, AVB);
2617 if (FRC->getID() == Hexagon::IntRegsRegClassID) {
2618 bool T = genBitSplit(MI, RD, RC, AVB);
2619 T = T || simplifyExtractLow(MI, RD, RC, AVB);
2620 T = T || genExtractHalf(MI, RD, RC);
2621 T = T || genCombineHalf(MI, RD, RC);
2622 T = T || genExtractLow(MI, RD, RC);
2627 if (FRC->getID() == Hexagon::PredRegsRegClassID) {
2628 bool T = simplifyTstbit(MI, RD, RC);
2636 bool HexagonBitSimplify::runOnMachineFunction(MachineFunction &MF) {
2637 if (skipFunction(*MF.getFunction()))
2640 auto &HST = MF.getSubtarget<HexagonSubtarget>();
2641 auto &HRI = *HST.getRegisterInfo();
2642 auto &HII = *HST.getInstrInfo();
2644 MDT = &getAnalysis<MachineDominatorTree>();
2645 MachineRegisterInfo &MRI = MF.getRegInfo();
2648 Changed = DeadCodeElimination(MF, *MDT).run();
2650 const HexagonEvaluator HE(HRI, MRI, HII, MF);
2651 BitTracker BT(HE, MF);
2652 DEBUG(BT.trace(true));
2655 MachineBasicBlock &Entry = MF.front();
2657 RegisterSet AIG; // Available registers for IG.
2658 ConstGeneration ImmG(BT, HII, MRI);
2659 Changed |= visitBlock(Entry, ImmG, AIG);
2661 RegisterSet ARE; // Available registers for RIE.
2662 RedundantInstrElimination RIE(BT, HII, HRI, MRI);
2663 bool Ried = visitBlock(Entry, RIE, ARE);
2669 RegisterSet ACG; // Available registers for CG.
2670 CopyGeneration CopyG(BT, HII, HRI, MRI);
2671 Changed |= visitBlock(Entry, CopyG, ACG);
2673 RegisterSet ACP; // Available registers for CP.
2674 CopyPropagation CopyP(HRI, MRI);
2675 Changed |= visitBlock(Entry, CopyP, ACP);
2677 Changed = DeadCodeElimination(MF, *MDT).run() || Changed;
2680 RegisterSet ABS; // Available registers for BS.
2681 BitSimplification BitS(BT, *MDT, HII, HRI, MRI, MF);
2682 Changed |= visitBlock(Entry, BitS, ABS);
2684 Changed = DeadCodeElimination(MF, *MDT).run() || Changed;
2690 DeadCodeElimination(MF, *MDT).run();
2695 // Recognize loops where the code at the end of the loop matches the code
2696 // before the entry of the loop, and the matching code is such that is can
2697 // be simplified. This pass relies on the bit simplification above and only
2698 // prepares code in a way that can be handled by the bit simplifcation.
2700 // This is the motivating testcase (and explanation):
2703 // loop0(.LBB0_2, r1) // %for.body.preheader
2704 // r5:4 = memd(r0++#8)
2707 // r3 = lsr(r4, #16)
2708 // r7:6 = combine(r5, r5)
2711 // r3 = insert(r5, #16, #16)
2712 // r7:6 = vlsrw(r7:6, #16)
2717 // memh(r2+#6) = r6 # R6 is really R5.H
2722 // memh(r2+#2) = r3 # R3 is really R4.H
2725 // r5:4 = memd(r0++#8)
2727 // { # "Shuffling" code that sets up R3 and R6
2728 // r3 = lsr(r4, #16) # so that their halves can be stored in the
2729 // r7:6 = combine(r5, r5) # next iteration. This could be folded into
2730 // } # the stores if the code was at the beginning
2731 // { # of the loop iteration. Since the same code
2732 // r3 = insert(r5, #16, #16) # precedes the loop, it can actually be moved
2733 // r7:6 = vlsrw(r7:6, #16) # there.
2740 // loop0(.LBB0_2, r1)
2741 // r5:4 = memd(r0++#8)
2746 // memh(r2+#6) = r5.h
2751 // memh(r2+#2) = r4.h
2754 // r5:4 = memd(r0++#8)
2759 FunctionPass *createHexagonLoopRescheduling();
2760 void initializeHexagonLoopReschedulingPass(PassRegistry&);
2762 } // end namespace llvm
2766 class HexagonLoopRescheduling : public MachineFunctionPass {
2770 HexagonLoopRescheduling() : MachineFunctionPass(ID),
2771 HII(nullptr), HRI(nullptr), MRI(nullptr), BTP(nullptr) {
2772 initializeHexagonLoopReschedulingPass(*PassRegistry::getPassRegistry());
2775 bool runOnMachineFunction(MachineFunction &MF) override;
2778 const HexagonInstrInfo *HII;
2779 const HexagonRegisterInfo *HRI;
2780 MachineRegisterInfo *MRI;
2784 LoopCand(MachineBasicBlock *lb, MachineBasicBlock *pb,
2785 MachineBasicBlock *eb) : LB(lb), PB(pb), EB(eb) {}
2786 MachineBasicBlock *LB, *PB, *EB;
2788 typedef std::vector<MachineInstr*> InstrList;
2790 BitTracker::RegisterRef Inp, Out;
2794 PhiInfo(MachineInstr &P, MachineBasicBlock &B);
2796 BitTracker::RegisterRef LR, PR; // Loop Register, Preheader Register
2797 MachineBasicBlock *LB, *PB; // Loop Block, Preheader Block
2800 static unsigned getDefReg(const MachineInstr *MI);
2801 bool isConst(unsigned Reg) const;
2802 bool isBitShuffle(const MachineInstr *MI, unsigned DefR) const;
2803 bool isStoreInput(const MachineInstr *MI, unsigned DefR) const;
2804 bool isShuffleOf(unsigned OutR, unsigned InpR) const;
2805 bool isSameShuffle(unsigned OutR1, unsigned InpR1, unsigned OutR2,
2806 unsigned &InpR2) const;
2807 void moveGroup(InstrGroup &G, MachineBasicBlock &LB, MachineBasicBlock &PB,
2808 MachineBasicBlock::iterator At, unsigned OldPhiR, unsigned NewPredR);
2809 bool processLoop(LoopCand &C);
2812 } // end anonymous namespace
2814 char HexagonLoopRescheduling::ID = 0;
2816 INITIALIZE_PASS(HexagonLoopRescheduling, "hexagon-loop-resched",
2817 "Hexagon Loop Rescheduling", false, false)
2819 HexagonLoopRescheduling::PhiInfo::PhiInfo(MachineInstr &P,
2820 MachineBasicBlock &B) {
2821 DefR = HexagonLoopRescheduling::getDefReg(&P);
2824 for (unsigned i = 1, n = P.getNumOperands(); i < n; i += 2) {
2825 const MachineOperand &OpB = P.getOperand(i+1);
2826 if (OpB.getMBB() == &B) {
2827 LR = P.getOperand(i);
2831 PR = P.getOperand(i);
2835 unsigned HexagonLoopRescheduling::getDefReg(const MachineInstr *MI) {
2837 HBS::getInstrDefs(*MI, Defs);
2838 if (Defs.count() != 1)
2840 return Defs.find_first();
2843 bool HexagonLoopRescheduling::isConst(unsigned Reg) const {
2846 const BitTracker::RegisterCell &RC = BTP->lookup(Reg);
2847 for (unsigned i = 0, w = RC.width(); i < w; ++i) {
2848 const BitTracker::BitValue &V = RC[i];
2849 if (!V.is(0) && !V.is(1))
2855 bool HexagonLoopRescheduling::isBitShuffle(const MachineInstr *MI,
2856 unsigned DefR) const {
2857 unsigned Opc = MI->getOpcode();
2859 case TargetOpcode::COPY:
2860 case Hexagon::S2_lsr_i_r:
2861 case Hexagon::S2_asr_i_r:
2862 case Hexagon::S2_asl_i_r:
2863 case Hexagon::S2_lsr_i_p:
2864 case Hexagon::S2_asr_i_p:
2865 case Hexagon::S2_asl_i_p:
2866 case Hexagon::S2_insert:
2867 case Hexagon::A2_or:
2868 case Hexagon::A2_orp:
2869 case Hexagon::A2_and:
2870 case Hexagon::A2_andp:
2871 case Hexagon::A2_combinew:
2872 case Hexagon::A4_combineri:
2873 case Hexagon::A4_combineir:
2874 case Hexagon::A2_combineii:
2875 case Hexagon::A4_combineii:
2876 case Hexagon::A2_combine_ll:
2877 case Hexagon::A2_combine_lh:
2878 case Hexagon::A2_combine_hl:
2879 case Hexagon::A2_combine_hh:
2885 bool HexagonLoopRescheduling::isStoreInput(const MachineInstr *MI,
2886 unsigned InpR) const {
2887 for (unsigned i = 0, n = MI->getNumOperands(); i < n; ++i) {
2888 const MachineOperand &Op = MI->getOperand(i);
2891 if (Op.getReg() == InpR)
2897 bool HexagonLoopRescheduling::isShuffleOf(unsigned OutR, unsigned InpR) const {
2898 if (!BTP->has(OutR) || !BTP->has(InpR))
2900 const BitTracker::RegisterCell &OutC = BTP->lookup(OutR);
2901 for (unsigned i = 0, w = OutC.width(); i < w; ++i) {
2902 const BitTracker::BitValue &V = OutC[i];
2903 if (V.Type != BitTracker::BitValue::Ref)
2905 if (V.RefI.Reg != InpR)
2911 bool HexagonLoopRescheduling::isSameShuffle(unsigned OutR1, unsigned InpR1,
2912 unsigned OutR2, unsigned &InpR2) const {
2913 if (!BTP->has(OutR1) || !BTP->has(InpR1) || !BTP->has(OutR2))
2915 const BitTracker::RegisterCell &OutC1 = BTP->lookup(OutR1);
2916 const BitTracker::RegisterCell &OutC2 = BTP->lookup(OutR2);
2917 unsigned W = OutC1.width();
2918 unsigned MatchR = 0;
2919 if (W != OutC2.width())
2921 for (unsigned i = 0; i < W; ++i) {
2922 const BitTracker::BitValue &V1 = OutC1[i], &V2 = OutC2[i];
2923 if (V1.Type != V2.Type || V1.Type == BitTracker::BitValue::One)
2925 if (V1.Type != BitTracker::BitValue::Ref)
2927 if (V1.RefI.Pos != V2.RefI.Pos)
2929 if (V1.RefI.Reg != InpR1)
2931 if (V2.RefI.Reg == 0 || V2.RefI.Reg == OutR2)
2934 MatchR = V2.RefI.Reg;
2935 else if (V2.RefI.Reg != MatchR)
2942 void HexagonLoopRescheduling::moveGroup(InstrGroup &G, MachineBasicBlock &LB,
2943 MachineBasicBlock &PB, MachineBasicBlock::iterator At, unsigned OldPhiR,
2944 unsigned NewPredR) {
2945 DenseMap<unsigned,unsigned> RegMap;
2947 const TargetRegisterClass *PhiRC = MRI->getRegClass(NewPredR);
2948 unsigned PhiR = MRI->createVirtualRegister(PhiRC);
2949 BuildMI(LB, At, At->getDebugLoc(), HII->get(TargetOpcode::PHI), PhiR)
2954 RegMap.insert(std::make_pair(G.Inp.Reg, PhiR));
2956 for (unsigned i = G.Ins.size(); i > 0; --i) {
2957 const MachineInstr *SI = G.Ins[i-1];
2958 unsigned DR = getDefReg(SI);
2959 const TargetRegisterClass *RC = MRI->getRegClass(DR);
2960 unsigned NewDR = MRI->createVirtualRegister(RC);
2961 DebugLoc DL = SI->getDebugLoc();
2963 auto MIB = BuildMI(LB, At, DL, HII->get(SI->getOpcode()), NewDR);
2964 for (unsigned j = 0, m = SI->getNumOperands(); j < m; ++j) {
2965 const MachineOperand &Op = SI->getOperand(j);
2972 unsigned UseR = RegMap[Op.getReg()];
2973 MIB.addReg(UseR, 0, Op.getSubReg());
2975 RegMap.insert(std::make_pair(DR, NewDR));
2978 HBS::replaceReg(OldPhiR, RegMap[G.Out.Reg], *MRI);
2981 bool HexagonLoopRescheduling::processLoop(LoopCand &C) {
2982 DEBUG(dbgs() << "Processing loop in BB#" << C.LB->getNumber() << "\n");
2983 std::vector<PhiInfo> Phis;
2984 for (auto &I : *C.LB) {
2987 unsigned PR = getDefReg(&I);
2990 bool BadUse = false, GoodUse = false;
2991 for (auto UI = MRI->use_begin(PR), UE = MRI->use_end(); UI != UE; ++UI) {
2992 MachineInstr *UseI = UI->getParent();
2993 if (UseI->getParent() != C.LB) {
2997 if (isBitShuffle(UseI, PR) || isStoreInput(UseI, PR))
3000 if (BadUse || !GoodUse)
3003 Phis.push_back(PhiInfo(I, *C.LB));
3007 dbgs() << "Phis: {";
3008 for (auto &I : Phis) {
3009 dbgs() << ' ' << PrintReg(I.DefR, HRI) << "=phi("
3010 << PrintReg(I.PR.Reg, HRI, I.PR.Sub) << ":b" << I.PB->getNumber()
3011 << ',' << PrintReg(I.LR.Reg, HRI, I.LR.Sub) << ":b"
3012 << I.LB->getNumber() << ')';
3020 bool Changed = false;
3023 // Go backwards in the block: for each bit shuffling instruction, check
3024 // if that instruction could potentially be moved to the front of the loop:
3025 // the output of the loop cannot be used in a non-shuffling instruction
3027 for (auto I = C.LB->rbegin(), E = C.LB->rend(); I != E; ++I) {
3028 if (I->isTerminator())
3034 HBS::getInstrDefs(*I, Defs);
3035 if (Defs.count() != 1)
3037 unsigned DefR = Defs.find_first();
3038 if (!TargetRegisterInfo::isVirtualRegister(DefR))
3040 if (!isBitShuffle(&*I, DefR))
3043 bool BadUse = false;
3044 for (auto UI = MRI->use_begin(DefR), UE = MRI->use_end(); UI != UE; ++UI) {
3045 MachineInstr *UseI = UI->getParent();
3046 if (UseI->getParent() == C.LB) {
3047 if (UseI->isPHI()) {
3048 // If the use is in a phi node in this loop, then it should be
3049 // the value corresponding to the back edge.
3050 unsigned Idx = UI.getOperandNo();
3051 if (UseI->getOperand(Idx+1).getMBB() != C.LB)
3054 auto F = find(ShufIns, UseI);
3055 if (F == ShufIns.end())
3059 // There is a use outside of the loop, but there is no epilog block
3060 // suitable for a copy-out.
3061 if (C.EB == nullptr)
3070 ShufIns.push_back(&*I);
3073 // Partition the list of shuffling instructions into instruction groups,
3074 // where each group has to be moved as a whole (i.e. a group is a chain of
3075 // dependent instructions). A group produces a single live output register,
3076 // which is meant to be the input of the loop phi node (although this is
3077 // not checked here yet). It also uses a single register as its input,
3078 // which is some value produced in the loop body. After moving the group
3079 // to the beginning of the loop, that input register would need to be
3080 // the loop-carried register (through a phi node) instead of the (currently
3081 // loop-carried) output register.
3082 typedef std::vector<InstrGroup> InstrGroupList;
3083 InstrGroupList Groups;
3085 for (unsigned i = 0, n = ShufIns.size(); i < n; ++i) {
3086 MachineInstr *SI = ShufIns[i];
3091 G.Ins.push_back(SI);
3092 G.Out.Reg = getDefReg(SI);
3094 HBS::getInstrUses(*SI, Inputs);
3096 for (unsigned j = i+1; j < n; ++j) {
3097 MachineInstr *MI = ShufIns[j];
3101 HBS::getInstrDefs(*MI, Defs);
3102 // If this instruction does not define any pending inputs, skip it.
3103 if (!Defs.intersects(Inputs))
3105 // Otherwise, add it to the current group and remove the inputs that
3106 // are defined by MI.
3107 G.Ins.push_back(MI);
3108 Inputs.remove(Defs);
3109 // Then add all registers used by MI.
3110 HBS::getInstrUses(*MI, Inputs);
3111 ShufIns[j] = nullptr;
3114 // Only add a group if it requires at most one register.
3115 if (Inputs.count() > 1)
3117 auto LoopInpEq = [G] (const PhiInfo &P) -> bool {
3118 return G.Out.Reg == P.LR.Reg;
3120 if (llvm::find_if(Phis, LoopInpEq) == Phis.end())
3123 G.Inp.Reg = Inputs.find_first();
3124 Groups.push_back(G);
3128 for (unsigned i = 0, n = Groups.size(); i < n; ++i) {
3129 InstrGroup &G = Groups[i];
3130 dbgs() << "Group[" << i << "] inp: "
3131 << PrintReg(G.Inp.Reg, HRI, G.Inp.Sub)
3132 << " out: " << PrintReg(G.Out.Reg, HRI, G.Out.Sub) << "\n";
3133 for (unsigned j = 0, m = G.Ins.size(); j < m; ++j)
3134 dbgs() << " " << *G.Ins[j];
3138 for (unsigned i = 0, n = Groups.size(); i < n; ++i) {
3139 InstrGroup &G = Groups[i];
3140 if (!isShuffleOf(G.Out.Reg, G.Inp.Reg))
3142 auto LoopInpEq = [G] (const PhiInfo &P) -> bool {
3143 return G.Out.Reg == P.LR.Reg;
3145 auto F = llvm::find_if(Phis, LoopInpEq);
3146 if (F == Phis.end())
3149 if (!isSameShuffle(G.Out.Reg, G.Inp.Reg, F->PR.Reg, PrehR)) {
3150 const MachineInstr *DefPrehR = MRI->getVRegDef(F->PR.Reg);
3151 unsigned Opc = DefPrehR->getOpcode();
3152 if (Opc != Hexagon::A2_tfrsi && Opc != Hexagon::A2_tfrpi)
3154 if (!DefPrehR->getOperand(1).isImm())
3156 if (DefPrehR->getOperand(1).getImm() != 0)
3158 const TargetRegisterClass *RC = MRI->getRegClass(G.Inp.Reg);
3159 if (RC != MRI->getRegClass(F->PR.Reg)) {
3160 PrehR = MRI->createVirtualRegister(RC);
3161 unsigned TfrI = (RC == &Hexagon::IntRegsRegClass) ? Hexagon::A2_tfrsi
3162 : Hexagon::A2_tfrpi;
3163 auto T = C.PB->getFirstTerminator();
3164 DebugLoc DL = (T != C.PB->end()) ? T->getDebugLoc() : DebugLoc();
3165 BuildMI(*C.PB, T, DL, HII->get(TfrI), PrehR)
3171 // isSameShuffle could match with PrehR being of a wider class than
3172 // G.Inp.Reg, for example if G shuffles the low 32 bits of its input,
3173 // it would match for the input being a 32-bit register, and PrehR
3174 // being a 64-bit register (where the low 32 bits match). This could
3175 // be handled, but for now skip these cases.
3176 if (MRI->getRegClass(PrehR) != MRI->getRegClass(G.Inp.Reg))
3178 moveGroup(G, *F->LB, *F->PB, F->LB->getFirstNonPHI(), F->DefR, PrehR);
3185 bool HexagonLoopRescheduling::runOnMachineFunction(MachineFunction &MF) {
3186 if (skipFunction(*MF.getFunction()))
3189 auto &HST = MF.getSubtarget<HexagonSubtarget>();
3190 HII = HST.getInstrInfo();
3191 HRI = HST.getRegisterInfo();
3192 MRI = &MF.getRegInfo();
3193 const HexagonEvaluator HE(*HRI, *MRI, *HII, MF);
3194 BitTracker BT(HE, MF);
3195 DEBUG(BT.trace(true));
3199 std::vector<LoopCand> Cand;
3201 for (auto &B : MF) {
3202 if (B.pred_size() != 2 || B.succ_size() != 2)
3204 MachineBasicBlock *PB = nullptr;
3205 bool IsLoop = false;
3206 for (auto PI = B.pred_begin(), PE = B.pred_end(); PI != PE; ++PI) {
3215 MachineBasicBlock *EB = nullptr;
3216 for (auto SI = B.succ_begin(), SE = B.succ_end(); SI != SE; ++SI) {
3219 // Set EP to the epilog block, if it has only 1 predecessor (i.e. the
3220 // edge from B to EP is non-critical.
3221 if ((*SI)->pred_size() == 1)
3226 Cand.push_back(LoopCand(&B, PB, EB));
3229 bool Changed = false;
3230 for (auto &C : Cand)
3231 Changed |= processLoop(C);
3236 //===----------------------------------------------------------------------===//
3237 // Public Constructor Functions
3238 //===----------------------------------------------------------------------===//
3240 FunctionPass *llvm::createHexagonLoopRescheduling() {
3241 return new HexagonLoopRescheduling();
3244 FunctionPass *llvm::createHexagonBitSimplify() {
3245 return new HexagonBitSimplify();