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