xref: /freebsd/contrib/llvm-project/llvm/lib/Target/Hexagon/HexagonGenInsert.cpp (revision e64bea71c21eb42e97aa615188ba91f6cce0d36d)
1 //===- HexagonGenInsert.cpp -----------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "BitTracker.h"
10 #include "Hexagon.h"
11 #include "HexagonBitTracker.h"
12 #include "HexagonInstrInfo.h"
13 #include "HexagonRegisterInfo.h"
14 #include "HexagonSubtarget.h"
15 #include "llvm/ADT/BitVector.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/GraphTraits.h"
18 #include "llvm/ADT/PostOrderIterator.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SmallSet.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/CodeGen/MachineBasicBlock.h"
24 #include "llvm/CodeGen/MachineDominators.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineFunctionPass.h"
27 #include "llvm/CodeGen/MachineInstr.h"
28 #include "llvm/CodeGen/MachineInstrBuilder.h"
29 #include "llvm/CodeGen/MachineOperand.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/CodeGen/TargetRegisterInfo.h"
32 #include "llvm/IR/DebugLoc.h"
33 #include "llvm/InitializePasses.h"
34 #include "llvm/Pass.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/Timer.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include <algorithm>
41 #include <cassert>
42 #include <cstdint>
43 #include <iterator>
44 #include <utility>
45 #include <vector>
46 
47 #define DEBUG_TYPE "hexinsert"
48 
49 using namespace llvm;
50 
51 static cl::opt<unsigned>
52     VRegIndexCutoff("insert-vreg-cutoff", cl::init(~0U), cl::Hidden,
53                     cl::desc("Vreg# cutoff for insert generation."));
54 // The distance cutoff is selected based on the precheckin-perf results:
55 // cutoffs 20, 25, 35, and 40 are worse than 30.
56 static cl::opt<unsigned>
57     VRegDistCutoff("insert-dist-cutoff", cl::init(30U), cl::Hidden,
58                    cl::desc("Vreg distance cutoff for insert "
59                             "generation."));
60 
61 // Limit the container sizes for extreme cases where we run out of memory.
62 static cl::opt<unsigned>
63     MaxORLSize("insert-max-orl", cl::init(4096), cl::Hidden,
64                cl::desc("Maximum size of OrderedRegisterList"));
65 static cl::opt<unsigned> MaxIFMSize("insert-max-ifmap", cl::init(1024),
66                                     cl::Hidden,
67                                     cl::desc("Maximum size of IFMap"));
68 
69 static cl::opt<bool> OptTiming("insert-timing", cl::Hidden,
70                                cl::desc("Enable timing of insert generation"));
71 static cl::opt<bool>
72     OptTimingDetail("insert-timing-detail", cl::Hidden,
73                     cl::desc("Enable detailed timing of insert "
74                              "generation"));
75 
76 static cl::opt<bool> OptSelectAll0("insert-all0", cl::init(false), cl::Hidden);
77 static cl::opt<bool> OptSelectHas0("insert-has0", cl::init(false), cl::Hidden);
78 // Whether to construct constant values via "insert". Could eliminate constant
79 // extenders, but often not practical.
80 static cl::opt<bool> OptConst("insert-const", cl::init(false), cl::Hidden);
81 
82 // The preprocessor gets confused when the DEBUG macro is passed larger
83 // chunks of code. Use this function to detect debugging.
isDebug()84 inline static bool isDebug() {
85 #ifndef NDEBUG
86   return DebugFlag && isCurrentDebugType(DEBUG_TYPE);
87 #else
88   return false;
89 #endif
90 }
91 
92 namespace {
93 
94   // Set of virtual registers, based on BitVector.
95   struct RegisterSet : private BitVector {
96     RegisterSet() = default;
RegisterSet__anon7f002ed80111::RegisterSet97     explicit RegisterSet(unsigned s, bool t = false) : BitVector(s, t) {}
98     RegisterSet(const RegisterSet &RS) = default;
99     RegisterSet &operator=(const RegisterSet &RS) = default;
100 
101     using BitVector::clear;
102 
find_first__anon7f002ed80111::RegisterSet103     unsigned find_first() const {
104       int First = BitVector::find_first();
105       if (First < 0)
106         return 0;
107       return x2v(First);
108     }
109 
find_next__anon7f002ed80111::RegisterSet110     unsigned find_next(unsigned Prev) const {
111       int Next = BitVector::find_next(v2x(Prev));
112       if (Next < 0)
113         return 0;
114       return x2v(Next);
115     }
116 
insert__anon7f002ed80111::RegisterSet117     RegisterSet &insert(unsigned R) {
118       unsigned Idx = v2x(R);
119       ensure(Idx);
120       return static_cast<RegisterSet&>(BitVector::set(Idx));
121     }
remove__anon7f002ed80111::RegisterSet122     RegisterSet &remove(unsigned R) {
123       unsigned Idx = v2x(R);
124       if (Idx >= size())
125         return *this;
126       return static_cast<RegisterSet&>(BitVector::reset(Idx));
127     }
128 
insert__anon7f002ed80111::RegisterSet129     RegisterSet &insert(const RegisterSet &Rs) {
130       return static_cast<RegisterSet&>(BitVector::operator|=(Rs));
131     }
remove__anon7f002ed80111::RegisterSet132     RegisterSet &remove(const RegisterSet &Rs) {
133       return static_cast<RegisterSet&>(BitVector::reset(Rs));
134     }
135 
operator []__anon7f002ed80111::RegisterSet136     reference operator[](unsigned R) {
137       unsigned Idx = v2x(R);
138       ensure(Idx);
139       return BitVector::operator[](Idx);
140     }
operator []__anon7f002ed80111::RegisterSet141     bool operator[](unsigned R) const {
142       unsigned Idx = v2x(R);
143       assert(Idx < size());
144       return BitVector::operator[](Idx);
145     }
has__anon7f002ed80111::RegisterSet146     bool has(unsigned R) const {
147       unsigned Idx = v2x(R);
148       if (Idx >= size())
149         return false;
150       return BitVector::test(Idx);
151     }
152 
empty__anon7f002ed80111::RegisterSet153     bool empty() const {
154       return !BitVector::any();
155     }
includes__anon7f002ed80111::RegisterSet156     bool includes(const RegisterSet &Rs) const {
157       // A.BitVector::test(B)  <=>  A-B != {}
158       return !Rs.BitVector::test(*this);
159     }
intersects__anon7f002ed80111::RegisterSet160     bool intersects(const RegisterSet &Rs) const {
161       return BitVector::anyCommon(Rs);
162     }
163 
164   private:
ensure__anon7f002ed80111::RegisterSet165     void ensure(unsigned Idx) {
166       if (size() <= Idx)
167         resize(std::max(Idx+1, 32U));
168     }
169 
v2x__anon7f002ed80111::RegisterSet170     static inline unsigned v2x(unsigned v) {
171       return Register(v).virtRegIndex();
172     }
173 
x2v__anon7f002ed80111::RegisterSet174     static inline unsigned x2v(unsigned x) {
175       return Register::index2VirtReg(x);
176     }
177   };
178 
179   struct PrintRegSet {
PrintRegSet__anon7f002ed80111::PrintRegSet180     PrintRegSet(const RegisterSet &S, const TargetRegisterInfo *RI)
181       : RS(S), TRI(RI) {}
182 
183     friend raw_ostream &operator<< (raw_ostream &OS,
184           const PrintRegSet &P);
185 
186   private:
187     const RegisterSet &RS;
188     const TargetRegisterInfo *TRI;
189   };
190 
operator <<(raw_ostream & OS,const PrintRegSet & P)191   raw_ostream &operator<< (raw_ostream &OS, const PrintRegSet &P) {
192     OS << '{';
193     for (unsigned R = P.RS.find_first(); R; R = P.RS.find_next(R))
194       OS << ' ' << printReg(R, P.TRI);
195     OS << " }";
196     return OS;
197   }
198 
199   // A convenience class to associate unsigned numbers (such as virtual
200   // registers) with unsigned numbers.
201   struct UnsignedMap : public DenseMap<unsigned,unsigned> {
202     UnsignedMap() = default;
203 
204   private:
205     using BaseType = DenseMap<unsigned, unsigned>;
206   };
207 
208   // A utility to establish an ordering between virtual registers:
209   // VRegA < VRegB  <=>  RegisterOrdering[VRegA] < RegisterOrdering[VRegB]
210   // This is meant as a cache for the ordering of virtual registers defined
211   // by a potentially expensive comparison function, or obtained by a proce-
212   // dure that should not be repeated each time two registers are compared.
213   struct RegisterOrdering : public UnsignedMap {
214     RegisterOrdering() = default;
215 
operator []__anon7f002ed80111::RegisterOrdering216     unsigned operator[](unsigned VR) const {
217       const_iterator F = find(VR);
218       assert(F != end());
219       return F->second;
220     }
221 
222     // Add operator(), so that objects of this class can be used as
223     // comparators in std::sort et al.
operator ()__anon7f002ed80111::RegisterOrdering224     bool operator() (unsigned VR1, unsigned VR2) const {
225       return operator[](VR1) < operator[](VR2);
226     }
227   };
228 
229   // Ordering of bit values. This class does not have operator[], but
230   // is supplies a comparison operator() for use in std:: algorithms.
231   // The order is as follows:
232   // - 0 < 1 < ref
233   // - ref1 < ref2, if ord(ref1.Reg) < ord(ref2.Reg),
234   //   or ord(ref1.Reg) == ord(ref2.Reg), and ref1.Pos < ref2.Pos.
235   struct BitValueOrdering {
BitValueOrdering__anon7f002ed80111::BitValueOrdering236     BitValueOrdering(const RegisterOrdering &RB) : BaseOrd(RB) {}
237 
238     bool operator() (const BitTracker::BitValue &V1,
239           const BitTracker::BitValue &V2) const;
240 
241     const RegisterOrdering &BaseOrd;
242   };
243 
244 } // end anonymous namespace
245 
operator ()(const BitTracker::BitValue & V1,const BitTracker::BitValue & V2) const246 bool BitValueOrdering::operator() (const BitTracker::BitValue &V1,
247       const BitTracker::BitValue &V2) const {
248   if (V1 == V2)
249     return false;
250   // V1==0 => true, V2==0 => false
251   if (V1.is(0) || V2.is(0))
252     return V1.is(0);
253   // Neither of V1,V2 is 0, and V1!=V2.
254   // V2==1 => false, V1==1 => true
255   if (V2.is(1) || V1.is(1))
256     return !V2.is(1);
257   // Both V1,V2 are refs.
258   unsigned Ind1 = BaseOrd[V1.RefI.Reg], Ind2 = BaseOrd[V2.RefI.Reg];
259   if (Ind1 != Ind2)
260     return Ind1 < Ind2;
261   // If V1.Pos==V2.Pos
262   assert(V1.RefI.Pos != V2.RefI.Pos && "Bit values should be different");
263   return V1.RefI.Pos < V2.RefI.Pos;
264 }
265 
266 namespace {
267 
268   // Cache for the BitTracker's cell map. Map lookup has a logarithmic
269   // complexity, this class will memoize the lookup results to reduce
270   // the access time for repeated lookups of the same cell.
271   struct CellMapShadow {
CellMapShadow__anon7f002ed80211::CellMapShadow272     CellMapShadow(const BitTracker &T) : BT(T) {}
273 
lookup__anon7f002ed80211::CellMapShadow274     const BitTracker::RegisterCell &lookup(unsigned VR) {
275       unsigned RInd = Register(VR).virtRegIndex();
276       // Grow the vector to at least 32 elements.
277       if (RInd >= CVect.size())
278         CVect.resize(std::max(RInd+16, 32U), nullptr);
279       const BitTracker::RegisterCell *CP = CVect[RInd];
280       if (CP == nullptr)
281         CP = CVect[RInd] = &BT.lookup(VR);
282       return *CP;
283     }
284 
285     const BitTracker &BT;
286 
287   private:
288     using CellVectType = std::vector<const BitTracker::RegisterCell *>;
289 
290     CellVectType CVect;
291   };
292 
293   // Comparator class for lexicographic ordering of virtual registers
294   // according to the corresponding BitTracker::RegisterCell objects.
295   struct RegisterCellLexCompare {
RegisterCellLexCompare__anon7f002ed80211::RegisterCellLexCompare296     RegisterCellLexCompare(const BitValueOrdering &BO, CellMapShadow &M)
297       : BitOrd(BO), CM(M) {}
298 
299     bool operator() (unsigned VR1, unsigned VR2) const;
300 
301   private:
302     const BitValueOrdering &BitOrd;
303     CellMapShadow &CM;
304   };
305 
306   // Comparator class for lexicographic ordering of virtual registers
307   // according to the specified bits of the corresponding BitTracker::
308   // RegisterCell objects.
309   // Specifically, this class will be used to compare bit B of a register
310   // cell for a selected virtual register R with bit N of any register
311   // other than R.
312   struct RegisterCellBitCompareSel {
RegisterCellBitCompareSel__anon7f002ed80211::RegisterCellBitCompareSel313     RegisterCellBitCompareSel(unsigned R, unsigned B, unsigned N,
314           const BitValueOrdering &BO, CellMapShadow &M)
315       : SelR(R), SelB(B), BitN(N), BitOrd(BO), CM(M) {}
316 
317     bool operator() (unsigned VR1, unsigned VR2) const;
318 
319   private:
320     const unsigned SelR, SelB;
321     const unsigned BitN;
322     const BitValueOrdering &BitOrd;
323     CellMapShadow &CM;
324   };
325 
326 } // end anonymous namespace
327 
operator ()(unsigned VR1,unsigned VR2) const328 bool RegisterCellLexCompare::operator() (unsigned VR1, unsigned VR2) const {
329   // Ordering of registers, made up from two given orderings:
330   // - the ordering of the register numbers, and
331   // - the ordering of register cells.
332   // Def. R1 < R2 if:
333   // - cell(R1) < cell(R2), or
334   // - cell(R1) == cell(R2), and index(R1) < index(R2).
335   //
336   // For register cells, the ordering is lexicographic, with index 0 being
337   // the most significant.
338   if (VR1 == VR2)
339     return false;
340 
341   const BitTracker::RegisterCell &RC1 = CM.lookup(VR1), &RC2 = CM.lookup(VR2);
342   uint16_t W1 = RC1.width(), W2 = RC2.width();
343   for (uint16_t i = 0, w = std::min(W1, W2); i < w; ++i) {
344     const BitTracker::BitValue &V1 = RC1[i], &V2 = RC2[i];
345     if (V1 != V2)
346       return BitOrd(V1, V2);
347   }
348   // Cells are equal up until the common length.
349   if (W1 != W2)
350     return W1 < W2;
351 
352   return BitOrd.BaseOrd[VR1] < BitOrd.BaseOrd[VR2];
353 }
354 
operator ()(unsigned VR1,unsigned VR2) const355 bool RegisterCellBitCompareSel::operator() (unsigned VR1, unsigned VR2) const {
356   if (VR1 == VR2)
357     return false;
358   const BitTracker::RegisterCell &RC1 = CM.lookup(VR1);
359   const BitTracker::RegisterCell &RC2 = CM.lookup(VR2);
360   uint16_t W1 = RC1.width(), W2 = RC2.width();
361   uint16_t Bit1 = (VR1 == SelR) ? SelB : BitN;
362   uint16_t Bit2 = (VR2 == SelR) ? SelB : BitN;
363   // If Bit1 exceeds the width of VR1, then:
364   // - return false, if at the same time Bit2 exceeds VR2, or
365   // - return true, otherwise.
366   // (I.e. "a bit value that does not exist is less than any bit value
367   // that does exist".)
368   if (W1 <= Bit1)
369     return Bit2 < W2;
370   // If Bit1 is within VR1, but Bit2 is not within VR2, return false.
371   if (W2 <= Bit2)
372     return false;
373 
374   const BitTracker::BitValue &V1 = RC1[Bit1], V2 = RC2[Bit2];
375   if (V1 != V2)
376     return BitOrd(V1, V2);
377   return false;
378 }
379 
380 namespace {
381 
382   class OrderedRegisterList {
383     using ListType = std::vector<unsigned>;
384     const unsigned MaxSize;
385 
386   public:
OrderedRegisterList(const RegisterOrdering & RO)387     OrderedRegisterList(const RegisterOrdering &RO)
388       : MaxSize(MaxORLSize), Ord(RO) {}
389 
390     void insert(unsigned VR);
391     void remove(unsigned VR);
392 
operator [](unsigned Idx) const393     unsigned operator[](unsigned Idx) const {
394       assert(Idx < Seq.size());
395       return Seq[Idx];
396     }
397 
size() const398     unsigned size() const {
399       return Seq.size();
400     }
401 
402     using iterator = ListType::iterator;
403     using const_iterator = ListType::const_iterator;
404 
begin()405     iterator begin() { return Seq.begin(); }
end()406     iterator end() { return Seq.end(); }
begin() const407     const_iterator begin() const { return Seq.begin(); }
end() const408     const_iterator end() const { return Seq.end(); }
409 
410     // Convenience function to convert an iterator to the corresponding index.
idx(iterator It) const411     unsigned idx(iterator It) const { return It-begin(); }
412 
413   private:
414     ListType Seq;
415     const RegisterOrdering &Ord;
416   };
417 
418   struct PrintORL {
PrintORL__anon7f002ed80311::PrintORL419     PrintORL(const OrderedRegisterList &L, const TargetRegisterInfo *RI)
420       : RL(L), TRI(RI) {}
421 
422     friend raw_ostream &operator<< (raw_ostream &OS, const PrintORL &P);
423 
424   private:
425     const OrderedRegisterList &RL;
426     const TargetRegisterInfo *TRI;
427   };
428 
operator <<(raw_ostream & OS,const PrintORL & P)429   raw_ostream &operator<< (raw_ostream &OS, const PrintORL &P) {
430     OS << '(';
431     OrderedRegisterList::const_iterator B = P.RL.begin(), E = P.RL.end();
432     for (OrderedRegisterList::const_iterator I = B; I != E; ++I) {
433       if (I != B)
434         OS << ", ";
435       OS << printReg(*I, P.TRI);
436     }
437     OS << ')';
438     return OS;
439   }
440 
441 } // end anonymous namespace
442 
insert(unsigned VR)443 void OrderedRegisterList::insert(unsigned VR) {
444   iterator L = llvm::lower_bound(Seq, VR, Ord);
445   if (L == Seq.end())
446     Seq.push_back(VR);
447   else
448     Seq.insert(L, VR);
449 
450   unsigned S = Seq.size();
451   if (S > MaxSize)
452     Seq.resize(MaxSize);
453   assert(Seq.size() <= MaxSize);
454 }
455 
remove(unsigned VR)456 void OrderedRegisterList::remove(unsigned VR) {
457   iterator L = llvm::lower_bound(Seq, VR, Ord);
458   if (L != Seq.end())
459     Seq.erase(L);
460 }
461 
462 namespace {
463 
464   // A record of the insert form. The fields correspond to the operands
465   // of the "insert" instruction:
466   // ... = insert(SrcR, InsR, #Wdh, #Off)
467   struct IFRecord {
IFRecord__anon7f002ed80411::IFRecord468     IFRecord(unsigned SR = 0, unsigned IR = 0, uint16_t W = 0, uint16_t O = 0)
469       : SrcR(SR), InsR(IR), Wdh(W), Off(O) {}
470 
471     unsigned SrcR, InsR;
472     uint16_t Wdh, Off;
473   };
474 
475   struct PrintIFR {
PrintIFR__anon7f002ed80411::PrintIFR476     PrintIFR(const IFRecord &R, const TargetRegisterInfo *RI)
477       : IFR(R), TRI(RI) {}
478 
479   private:
480     friend raw_ostream &operator<< (raw_ostream &OS, const PrintIFR &P);
481 
482     const IFRecord &IFR;
483     const TargetRegisterInfo *TRI;
484   };
485 
operator <<(raw_ostream & OS,const PrintIFR & P)486   raw_ostream &operator<< (raw_ostream &OS, const PrintIFR &P) {
487     unsigned SrcR = P.IFR.SrcR, InsR = P.IFR.InsR;
488     OS << '(' << printReg(SrcR, P.TRI) << ',' << printReg(InsR, P.TRI)
489        << ",#" << P.IFR.Wdh << ",#" << P.IFR.Off << ')';
490     return OS;
491   }
492 
493   using IFRecordWithRegSet = std::pair<IFRecord, RegisterSet>;
494 
495 } // end anonymous namespace
496 
497 namespace {
498 
499   class HexagonGenInsert : public MachineFunctionPass {
500   public:
501     static char ID;
502 
HexagonGenInsert()503     HexagonGenInsert() : MachineFunctionPass(ID) {}
504 
getPassName() const505     StringRef getPassName() const override {
506       return "Hexagon generate \"insert\" instructions";
507     }
508 
getAnalysisUsage(AnalysisUsage & AU) const509     void getAnalysisUsage(AnalysisUsage &AU) const override {
510       AU.addRequired<MachineDominatorTreeWrapperPass>();
511       AU.addPreserved<MachineDominatorTreeWrapperPass>();
512       MachineFunctionPass::getAnalysisUsage(AU);
513     }
514 
515     bool runOnMachineFunction(MachineFunction &MF) override;
516 
517   private:
518     using PairMapType = DenseMap<std::pair<unsigned, unsigned>, unsigned>;
519 
520     void buildOrderingMF(RegisterOrdering &RO) const;
521     void buildOrderingBT(RegisterOrdering &RB, RegisterOrdering &RO) const;
522     bool isIntClass(const TargetRegisterClass *RC) const;
523     bool isConstant(unsigned VR) const;
524     bool isSmallConstant(unsigned VR) const;
525     bool isValidInsertForm(unsigned DstR, unsigned SrcR, unsigned InsR,
526           uint16_t L, uint16_t S) const;
527     bool findSelfReference(unsigned VR) const;
528     bool findNonSelfReference(unsigned VR) const;
529     void getInstrDefs(const MachineInstr *MI, RegisterSet &Defs) const;
530     void getInstrUses(const MachineInstr *MI, RegisterSet &Uses) const;
531     unsigned distance(const MachineBasicBlock *FromB,
532           const MachineBasicBlock *ToB, const UnsignedMap &RPO,
533           PairMapType &M) const;
534     unsigned distance(MachineBasicBlock::const_iterator FromI,
535           MachineBasicBlock::const_iterator ToI, const UnsignedMap &RPO,
536           PairMapType &M) const;
537     bool findRecordInsertForms(unsigned VR, OrderedRegisterList &AVs);
538     void collectInBlock(MachineBasicBlock *B, OrderedRegisterList &AVs);
539     void findRemovableRegisters(unsigned VR, IFRecord IF,
540           RegisterSet &RMs) const;
541     void computeRemovableRegisters();
542 
543     void pruneEmptyLists();
544     void pruneCoveredSets(unsigned VR);
545     void pruneUsesTooFar(unsigned VR, const UnsignedMap &RPO, PairMapType &M);
546     void pruneRegCopies(unsigned VR);
547     void pruneCandidates();
548     void selectCandidates();
549     bool generateInserts();
550 
551     bool removeDeadCode(MachineDomTreeNode *N);
552 
553     // IFRecord coupled with a set of potentially removable registers:
554     using IFListType = std::vector<IFRecordWithRegSet>;
555     using IFMapType = DenseMap<unsigned, IFListType>; // vreg -> IFListType
556 
557     void dump_map() const;
558 
559     const HexagonInstrInfo *HII = nullptr;
560     const HexagonRegisterInfo *HRI = nullptr;
561 
562     MachineFunction *MFN;
563     MachineRegisterInfo *MRI;
564     MachineDominatorTree *MDT;
565     CellMapShadow *CMS;
566 
567     RegisterOrdering BaseOrd;
568     RegisterOrdering CellOrd;
569     IFMapType IFMap;
570   };
571 
572 } // end anonymous namespace
573 
574 char HexagonGenInsert::ID = 0;
575 
dump_map() const576 void HexagonGenInsert::dump_map() const {
577   for (const auto &I : IFMap) {
578     dbgs() << "  " << printReg(I.first, HRI) << ":\n";
579     const IFListType &LL = I.second;
580     for (const auto &J : LL)
581       dbgs() << "    " << PrintIFR(J.first, HRI) << ", "
582              << PrintRegSet(J.second, HRI) << '\n';
583   }
584 }
585 
buildOrderingMF(RegisterOrdering & RO) const586 void HexagonGenInsert::buildOrderingMF(RegisterOrdering &RO) const {
587   unsigned Index = 0;
588 
589   for (const MachineBasicBlock &B : *MFN) {
590     if (!CMS->BT.reached(&B))
591       continue;
592 
593     for (const MachineInstr &MI : B) {
594       for (const MachineOperand &MO : MI.operands()) {
595         if (MO.isReg() && MO.isDef()) {
596           Register R = MO.getReg();
597           assert(MO.getSubReg() == 0 && "Unexpected subregister in definition");
598           if (R.isVirtual())
599             RO.insert(std::make_pair(R, Index++));
600         }
601       }
602     }
603   }
604   // Since some virtual registers may have had their def and uses eliminated,
605   // they are no longer referenced in the code, and so they will not appear
606   // in the map.
607 }
608 
buildOrderingBT(RegisterOrdering & RB,RegisterOrdering & RO) const609 void HexagonGenInsert::buildOrderingBT(RegisterOrdering &RB,
610       RegisterOrdering &RO) const {
611   // Create a vector of all virtual registers (collect them from the base
612   // ordering RB), and then sort it using the RegisterCell comparator.
613   BitValueOrdering BVO(RB);
614   RegisterCellLexCompare LexCmp(BVO, *CMS);
615 
616   using SortableVectorType = std::vector<unsigned>;
617 
618   SortableVectorType VRs;
619   for (auto &I : RB)
620     VRs.push_back(I.first);
621   llvm::sort(VRs, LexCmp);
622   // Transfer the results to the outgoing register ordering.
623   for (unsigned i = 0, n = VRs.size(); i < n; ++i)
624     RO.insert(std::make_pair(VRs[i], i));
625 }
626 
isIntClass(const TargetRegisterClass * RC) const627 inline bool HexagonGenInsert::isIntClass(const TargetRegisterClass *RC) const {
628   return RC == &Hexagon::IntRegsRegClass || RC == &Hexagon::DoubleRegsRegClass;
629 }
630 
isConstant(unsigned VR) const631 bool HexagonGenInsert::isConstant(unsigned VR) const {
632   const BitTracker::RegisterCell &RC = CMS->lookup(VR);
633   uint16_t W = RC.width();
634   for (uint16_t i = 0; i < W; ++i) {
635     const BitTracker::BitValue &BV = RC[i];
636     if (BV.is(0) || BV.is(1))
637       continue;
638     return false;
639   }
640   return true;
641 }
642 
isSmallConstant(unsigned VR) const643 bool HexagonGenInsert::isSmallConstant(unsigned VR) const {
644   const BitTracker::RegisterCell &RC = CMS->lookup(VR);
645   uint16_t W = RC.width();
646   if (W > 64)
647     return false;
648   uint64_t V = 0, B = 1;
649   for (uint16_t i = 0; i < W; ++i) {
650     const BitTracker::BitValue &BV = RC[i];
651     if (BV.is(1))
652       V |= B;
653     else if (!BV.is(0))
654       return false;
655     B <<= 1;
656   }
657 
658   // For 32-bit registers, consider: Rd = #s16.
659   if (W == 32)
660     return isInt<16>(V);
661 
662   // For 64-bit registers, it's Rdd = #s8 or Rdd = combine(#s8,#s8)
663   return isInt<8>(Lo_32(V)) && isInt<8>(Hi_32(V));
664 }
665 
isValidInsertForm(unsigned DstR,unsigned SrcR,unsigned InsR,uint16_t L,uint16_t S) const666 bool HexagonGenInsert::isValidInsertForm(unsigned DstR, unsigned SrcR,
667       unsigned InsR, uint16_t L, uint16_t S) const {
668   const TargetRegisterClass *DstRC = MRI->getRegClass(DstR);
669   const TargetRegisterClass *SrcRC = MRI->getRegClass(SrcR);
670   const TargetRegisterClass *InsRC = MRI->getRegClass(InsR);
671   // Only integet (32-/64-bit) register classes.
672   if (!isIntClass(DstRC) || !isIntClass(SrcRC) || !isIntClass(InsRC))
673     return false;
674   // The "source" register must be of the same class as DstR.
675   if (DstRC != SrcRC)
676     return false;
677   if (DstRC == InsRC)
678     return true;
679   // A 64-bit register can only be generated from other 64-bit registers.
680   if (DstRC == &Hexagon::DoubleRegsRegClass)
681     return false;
682   // Otherwise, the L and S cannot span 32-bit word boundary.
683   if (S < 32 && S+L > 32)
684     return false;
685   return true;
686 }
687 
findSelfReference(unsigned VR) const688 bool HexagonGenInsert::findSelfReference(unsigned VR) const {
689   const BitTracker::RegisterCell &RC = CMS->lookup(VR);
690   for (uint16_t i = 0, w = RC.width(); i < w; ++i) {
691     const BitTracker::BitValue &V = RC[i];
692     if (V.Type == BitTracker::BitValue::Ref && V.RefI.Reg == VR)
693       return true;
694   }
695   return false;
696 }
697 
findNonSelfReference(unsigned VR) const698 bool HexagonGenInsert::findNonSelfReference(unsigned VR) const {
699   BitTracker::RegisterCell RC = CMS->lookup(VR);
700   for (uint16_t i = 0, w = RC.width(); i < w; ++i) {
701     const BitTracker::BitValue &V = RC[i];
702     if (V.Type == BitTracker::BitValue::Ref && V.RefI.Reg != VR)
703       return true;
704   }
705   return false;
706 }
707 
getInstrDefs(const MachineInstr * MI,RegisterSet & Defs) const708 void HexagonGenInsert::getInstrDefs(const MachineInstr *MI,
709       RegisterSet &Defs) const {
710   for (const MachineOperand &MO : MI->operands()) {
711     if (!MO.isReg() || !MO.isDef())
712       continue;
713     Register R = MO.getReg();
714     if (!R.isVirtual())
715       continue;
716     Defs.insert(R);
717   }
718 }
719 
getInstrUses(const MachineInstr * MI,RegisterSet & Uses) const720 void HexagonGenInsert::getInstrUses(const MachineInstr *MI,
721       RegisterSet &Uses) const {
722   for (const MachineOperand &MO : MI->operands()) {
723     if (!MO.isReg() || !MO.isUse())
724       continue;
725     Register R = MO.getReg();
726     if (!R.isVirtual())
727       continue;
728     Uses.insert(R);
729   }
730 }
731 
distance(const MachineBasicBlock * FromB,const MachineBasicBlock * ToB,const UnsignedMap & RPO,PairMapType & M) const732 unsigned HexagonGenInsert::distance(const MachineBasicBlock *FromB,
733       const MachineBasicBlock *ToB, const UnsignedMap &RPO,
734       PairMapType &M) const {
735   // Forward distance from the end of a block to the beginning of it does
736   // not make sense. This function should not be called with FromB == ToB.
737   assert(FromB != ToB);
738 
739   unsigned FromN = FromB->getNumber(), ToN = ToB->getNumber();
740   // If we have already computed it, return the cached result.
741   PairMapType::iterator F = M.find(std::make_pair(FromN, ToN));
742   if (F != M.end())
743     return F->second;
744   unsigned ToRPO = RPO.lookup(ToN);
745 
746   unsigned MaxD = 0;
747 
748   for (const MachineBasicBlock *PB : ToB->predecessors()) {
749     // Skip back edges. Also, if FromB is a predecessor of ToB, the distance
750     // along that path will be 0, and we don't need to do any calculations
751     // on it.
752     if (PB == FromB || RPO.lookup(PB->getNumber()) >= ToRPO)
753       continue;
754     unsigned D = PB->size() + distance(FromB, PB, RPO, M);
755     if (D > MaxD)
756       MaxD = D;
757   }
758 
759   // Memoize the result for later lookup.
760   M.insert(std::make_pair(std::make_pair(FromN, ToN), MaxD));
761   return MaxD;
762 }
763 
distance(MachineBasicBlock::const_iterator FromI,MachineBasicBlock::const_iterator ToI,const UnsignedMap & RPO,PairMapType & M) const764 unsigned HexagonGenInsert::distance(MachineBasicBlock::const_iterator FromI,
765       MachineBasicBlock::const_iterator ToI, const UnsignedMap &RPO,
766       PairMapType &M) const {
767   const MachineBasicBlock *FB = FromI->getParent(), *TB = ToI->getParent();
768   if (FB == TB)
769     return std::distance(FromI, ToI);
770   unsigned D1 = std::distance(TB->begin(), ToI);
771   unsigned D2 = distance(FB, TB, RPO, M);
772   unsigned D3 = std::distance(FromI, FB->end());
773   return D1+D2+D3;
774 }
775 
findRecordInsertForms(unsigned VR,OrderedRegisterList & AVs)776 bool HexagonGenInsert::findRecordInsertForms(unsigned VR,
777       OrderedRegisterList &AVs) {
778   if (isDebug()) {
779     dbgs() << __func__ << ": " << printReg(VR, HRI)
780            << "  AVs: " << PrintORL(AVs, HRI) << "\n";
781   }
782   if (AVs.size() == 0)
783     return false;
784 
785   using iterator = OrderedRegisterList::iterator;
786 
787   BitValueOrdering BVO(BaseOrd);
788   const BitTracker::RegisterCell &RC = CMS->lookup(VR);
789   uint16_t W = RC.width();
790 
791   using RSRecord = std::pair<unsigned, uint16_t>; // (reg,shift)
792   using RSListType = std::vector<RSRecord>;
793   // Have a map, with key being the matching prefix length, and the value
794   // being the list of pairs (R,S), where R's prefix matches VR at S.
795   // (DenseMap<uint16_t,RSListType> fails to instantiate.)
796   using LRSMapType = DenseMap<unsigned, RSListType>;
797   LRSMapType LM;
798 
799   // Conceptually, rotate the cell RC right (i.e. towards the LSB) by S,
800   // and find matching prefixes from AVs with the rotated RC. Such a prefix
801   // would match a string of bits (of length L) in RC starting at S.
802   for (uint16_t S = 0; S < W; ++S) {
803     iterator B = AVs.begin(), E = AVs.end();
804     // The registers in AVs are ordered according to the lexical order of
805     // the corresponding register cells. This means that the range of regis-
806     // ters in AVs that match a prefix of length L+1 will be contained in
807     // the range that matches a prefix of length L. This means that we can
808     // keep narrowing the search space as the prefix length goes up. This
809     // helps reduce the overall complexity of the search.
810     uint16_t L;
811     for (L = 0; L < W-S; ++L) {
812       // Compare against VR's bits starting at S, which emulates rotation
813       // of VR by S.
814       RegisterCellBitCompareSel RCB(VR, S+L, L, BVO, *CMS);
815       iterator NewB = std::lower_bound(B, E, VR, RCB);
816       iterator NewE = std::upper_bound(NewB, E, VR, RCB);
817       // For the registers that are eliminated from the next range, L is
818       // the longest prefix matching VR at position S (their prefixes
819       // differ from VR at S+L). If L>0, record this information for later
820       // use.
821       if (L > 0) {
822         for (iterator I = B; I != NewB; ++I)
823           LM[L].push_back(std::make_pair(*I, S));
824         for (iterator I = NewE; I != E; ++I)
825           LM[L].push_back(std::make_pair(*I, S));
826       }
827       B = NewB, E = NewE;
828       if (B == E)
829         break;
830     }
831     // Record the final register range. If this range is non-empty, then
832     // L=W-S.
833     assert(B == E || L == W-S);
834     if (B != E) {
835       for (iterator I = B; I != E; ++I)
836         LM[L].push_back(std::make_pair(*I, S));
837       // If B!=E, then we found a range of registers whose prefixes cover the
838       // rest of VR from position S. There is no need to further advance S.
839       break;
840     }
841   }
842 
843   if (isDebug()) {
844     dbgs() << "Prefixes matching register " << printReg(VR, HRI) << "\n";
845     for (const auto &I : LM) {
846       dbgs() << "  L=" << I.first << ':';
847       const RSListType &LL = I.second;
848       for (const auto &J : LL)
849         dbgs() << " (" << printReg(J.first, HRI) << ",@" << J.second << ')';
850       dbgs() << '\n';
851     }
852   }
853 
854   bool Recorded = false;
855 
856   for (unsigned SrcR : AVs) {
857     int FDi = -1, LDi = -1;   // First/last different bit.
858     const BitTracker::RegisterCell &AC = CMS->lookup(SrcR);
859     uint16_t AW = AC.width();
860     for (uint16_t i = 0, w = std::min(W, AW); i < w; ++i) {
861       if (RC[i] == AC[i])
862         continue;
863       if (FDi == -1)
864         FDi = i;
865       LDi = i;
866     }
867     if (FDi == -1)
868       continue;  // TODO (future): Record identical registers.
869     // Look for a register whose prefix could patch the range [FD..LD]
870     // where VR and SrcR differ.
871     uint16_t FD = FDi, LD = LDi;  // Switch to unsigned type.
872     uint16_t MinL = LD-FD+1;
873     for (uint16_t L = MinL; L < W; ++L) {
874       LRSMapType::iterator F = LM.find(L);
875       if (F == LM.end())
876         continue;
877       RSListType &LL = F->second;
878       for (const auto &I : LL) {
879         uint16_t S = I.second;
880         // MinL is the minimum length of the prefix. Any length above MinL
881         // allows some flexibility as to where the prefix can start:
882         // given the extra length EL=L-MinL, the prefix must start between
883         // max(0,FD-EL) and FD.
884         if (S > FD)   // Starts too late.
885           continue;
886         uint16_t EL = L-MinL;
887         uint16_t LowS = (EL < FD) ? FD-EL : 0;
888         if (S < LowS) // Starts too early.
889           continue;
890         unsigned InsR = I.first;
891         if (!isValidInsertForm(VR, SrcR, InsR, L, S))
892           continue;
893         if (isDebug()) {
894           dbgs() << printReg(VR, HRI) << " = insert(" << printReg(SrcR, HRI)
895                  << ',' << printReg(InsR, HRI) << ",#" << L << ",#"
896                  << S << ")\n";
897         }
898         IFRecordWithRegSet RR(IFRecord(SrcR, InsR, L, S), RegisterSet());
899         IFMap[VR].push_back(RR);
900         Recorded = true;
901       }
902     }
903   }
904 
905   return Recorded;
906 }
907 
collectInBlock(MachineBasicBlock * B,OrderedRegisterList & AVs)908 void HexagonGenInsert::collectInBlock(MachineBasicBlock *B,
909       OrderedRegisterList &AVs) {
910   if (isDebug())
911     dbgs() << "visiting block " << printMBBReference(*B) << "\n";
912 
913   // First, check if this block is reachable at all. If not, the bit tracker
914   // will not have any information about registers in it.
915   if (!CMS->BT.reached(B))
916     return;
917 
918   bool DoConst = OptConst;
919   // Keep a separate set of registers defined in this block, so that we
920   // can remove them from the list of available registers once all DT
921   // successors have been processed.
922   RegisterSet BlockDefs, InsDefs;
923   for (MachineInstr &MI : *B) {
924     // Stop if the map size is too large.
925     if (IFMap.size() >= MaxIFMSize)
926       break;
927 
928     InsDefs.clear();
929     getInstrDefs(&MI, InsDefs);
930     // Leave those alone. They are more transparent than "insert".
931     bool Skip = MI.isCopy() || MI.isRegSequence();
932 
933     if (!Skip) {
934       // Visit all defined registers, and attempt to find the corresponding
935       // "insert" representations.
936       for (unsigned VR = InsDefs.find_first(); VR; VR = InsDefs.find_next(VR)) {
937         // Do not collect registers that are known to be compile-time cons-
938         // tants, unless requested.
939         if (!DoConst && isConstant(VR))
940           continue;
941         // If VR's cell contains a reference to VR, then VR cannot be defined
942         // via "insert". If VR is a constant that can be generated in a single
943         // instruction (without constant extenders), generating it via insert
944         // makes no sense.
945         if (findSelfReference(VR) || isSmallConstant(VR))
946           continue;
947 
948         findRecordInsertForms(VR, AVs);
949         // Stop if the map size is too large.
950         if (IFMap.size() >= MaxIFMSize)
951           break;
952       }
953     }
954 
955     // Insert the defined registers into the list of available registers
956     // after they have been processed.
957     for (unsigned VR = InsDefs.find_first(); VR; VR = InsDefs.find_next(VR))
958       AVs.insert(VR);
959     BlockDefs.insert(InsDefs);
960   }
961 
962   for (auto *DTN : children<MachineDomTreeNode*>(MDT->getNode(B))) {
963     MachineBasicBlock *SB = DTN->getBlock();
964     collectInBlock(SB, AVs);
965   }
966 
967   for (unsigned VR = BlockDefs.find_first(); VR; VR = BlockDefs.find_next(VR))
968     AVs.remove(VR);
969 }
970 
findRemovableRegisters(unsigned VR,IFRecord IF,RegisterSet & RMs) const971 void HexagonGenInsert::findRemovableRegisters(unsigned VR, IFRecord IF,
972       RegisterSet &RMs) const {
973   // For a given register VR and a insert form, find the registers that are
974   // used by the current definition of VR, and which would no longer be
975   // needed for it after the definition of VR is replaced with the insert
976   // form. These are the registers that could potentially become dead.
977   RegisterSet Regs[2];
978 
979   unsigned S = 0;  // Register set selector.
980   Regs[S].insert(VR);
981 
982   while (!Regs[S].empty()) {
983     // Breadth-first search.
984     unsigned OtherS = 1-S;
985     Regs[OtherS].clear();
986     for (unsigned R = Regs[S].find_first(); R; R = Regs[S].find_next(R)) {
987       Regs[S].remove(R);
988       if (R == IF.SrcR || R == IF.InsR)
989         continue;
990       // Check if a given register has bits that are references to any other
991       // registers. This is to detect situations where the instruction that
992       // defines register R takes register Q as an operand, but R itself does
993       // not contain any bits from Q. Loads are examples of how this could
994       // happen:
995       //   R = load Q
996       // In this case (assuming we do not have any knowledge about the loaded
997       // value), we must not treat R as a "conveyance" of the bits from Q.
998       // (The information in BT about R's bits would have them as constants,
999       // in case of zero-extending loads, or refs to R.)
1000       if (!findNonSelfReference(R))
1001         continue;
1002       RMs.insert(R);
1003       const MachineInstr *DefI = MRI->getVRegDef(R);
1004       assert(DefI);
1005       // Do not iterate past PHI nodes to avoid infinite loops. This can
1006       // make the final set a bit less accurate, but the removable register
1007       // sets are an approximation anyway.
1008       if (DefI->isPHI())
1009         continue;
1010       getInstrUses(DefI, Regs[OtherS]);
1011     }
1012     S = OtherS;
1013   }
1014   // The register VR is added to the list as a side-effect of the algorithm,
1015   // but it is not "potentially removable". A potentially removable register
1016   // is one that may become unused (dead) after conversion to the insert form
1017   // IF, and obviously VR (or its replacement) will not become dead by apply-
1018   // ing IF.
1019   RMs.remove(VR);
1020 }
1021 
computeRemovableRegisters()1022 void HexagonGenInsert::computeRemovableRegisters() {
1023   for (auto &I : IFMap) {
1024     IFListType &LL = I.second;
1025     for (auto &J : LL)
1026       findRemovableRegisters(I.first, J.first, J.second);
1027   }
1028 }
1029 
pruneEmptyLists()1030 void HexagonGenInsert::pruneEmptyLists() {
1031   // Remove all entries from the map, where the register has no insert forms
1032   // associated with it.
1033   using IterListType = SmallVector<IFMapType::iterator, 16>;
1034   IterListType Prune;
1035   for (IFMapType::iterator I = IFMap.begin(), E = IFMap.end(); I != E; ++I) {
1036     if (I->second.empty())
1037       Prune.push_back(I);
1038   }
1039   for (const auto &It : Prune)
1040     IFMap.erase(It);
1041 }
1042 
pruneCoveredSets(unsigned VR)1043 void HexagonGenInsert::pruneCoveredSets(unsigned VR) {
1044   IFMapType::iterator F = IFMap.find(VR);
1045   assert(F != IFMap.end());
1046   IFListType &LL = F->second;
1047 
1048   // First, examine the IF candidates for register VR whose removable-regis-
1049   // ter sets are empty. This means that a given candidate will not help eli-
1050   // minate any registers, but since "insert" is not a constant-extendable
1051   // instruction, using such a candidate may reduce code size if the defini-
1052   // tion of VR is constant-extended.
1053   // If there exists a candidate with a non-empty set, the ones with empty
1054   // sets will not be used and can be removed.
1055   MachineInstr *DefVR = MRI->getVRegDef(VR);
1056   bool DefEx = HII->isConstExtended(*DefVR);
1057   bool HasNE = false;
1058   for (const auto &I : LL) {
1059     if (I.second.empty())
1060       continue;
1061     HasNE = true;
1062     break;
1063   }
1064   if (!DefEx || HasNE) {
1065     // The definition of VR is not constant-extended, or there is a candidate
1066     // with a non-empty set. Remove all candidates with empty sets.
1067     auto IsEmpty = [] (const IFRecordWithRegSet &IR) -> bool {
1068       return IR.second.empty();
1069     };
1070     llvm::erase_if(LL, IsEmpty);
1071   } else {
1072     // The definition of VR is constant-extended, and all candidates have
1073     // empty removable-register sets. Pick the maximum candidate, and remove
1074     // all others. The "maximum" does not have any special meaning here, it
1075     // is only so that the candidate that will remain on the list is selec-
1076     // ted deterministically.
1077     IFRecord MaxIF = LL[0].first;
1078     for (unsigned i = 1, n = LL.size(); i < n; ++i) {
1079       // If LL[MaxI] < LL[i], then MaxI = i.
1080       const IFRecord &IF = LL[i].first;
1081       unsigned M0 = BaseOrd[MaxIF.SrcR], M1 = BaseOrd[MaxIF.InsR];
1082       unsigned R0 = BaseOrd[IF.SrcR], R1 = BaseOrd[IF.InsR];
1083       if (M0 > R0)
1084         continue;
1085       if (M0 == R0) {
1086         if (M1 > R1)
1087           continue;
1088         if (M1 == R1) {
1089           if (MaxIF.Wdh > IF.Wdh)
1090             continue;
1091           if (MaxIF.Wdh == IF.Wdh && MaxIF.Off >= IF.Off)
1092             continue;
1093         }
1094       }
1095       // MaxIF < IF.
1096       MaxIF = IF;
1097     }
1098     // Remove everything except the maximum candidate. All register sets
1099     // are empty, so no need to preserve anything.
1100     LL.clear();
1101     LL.push_back(std::make_pair(MaxIF, RegisterSet()));
1102   }
1103 
1104   // Now, remove those whose sets of potentially removable registers are
1105   // contained in another IF candidate for VR. For example, given these
1106   // candidates for %45,
1107   //   %45:
1108   //     (%44,%41,#9,#8), { %42 }
1109   //     (%43,%41,#9,#8), { %42 %44 }
1110   // remove the first one, since it is contained in the second one.
1111   for (unsigned i = 0, n = LL.size(); i < n; ) {
1112     const RegisterSet &RMi = LL[i].second;
1113     unsigned j = 0;
1114     while (j < n) {
1115       if (j != i && LL[j].second.includes(RMi))
1116         break;
1117       j++;
1118     }
1119     if (j == n) {   // RMi not contained in anything else.
1120       i++;
1121       continue;
1122     }
1123     LL.erase(LL.begin()+i);
1124     n = LL.size();
1125   }
1126 }
1127 
pruneUsesTooFar(unsigned VR,const UnsignedMap & RPO,PairMapType & M)1128 void HexagonGenInsert::pruneUsesTooFar(unsigned VR, const UnsignedMap &RPO,
1129       PairMapType &M) {
1130   IFMapType::iterator F = IFMap.find(VR);
1131   assert(F != IFMap.end());
1132   IFListType &LL = F->second;
1133   unsigned Cutoff = VRegDistCutoff;
1134   const MachineInstr *DefV = MRI->getVRegDef(VR);
1135 
1136   for (unsigned i = LL.size(); i > 0; --i) {
1137     unsigned SR = LL[i-1].first.SrcR, IR = LL[i-1].first.InsR;
1138     const MachineInstr *DefS = MRI->getVRegDef(SR);
1139     const MachineInstr *DefI = MRI->getVRegDef(IR);
1140     unsigned DSV = distance(DefS, DefV, RPO, M);
1141     if (DSV < Cutoff) {
1142       unsigned DIV = distance(DefI, DefV, RPO, M);
1143       if (DIV < Cutoff)
1144         continue;
1145     }
1146     LL.erase(LL.begin()+(i-1));
1147   }
1148 }
1149 
pruneRegCopies(unsigned VR)1150 void HexagonGenInsert::pruneRegCopies(unsigned VR) {
1151   IFMapType::iterator F = IFMap.find(VR);
1152   assert(F != IFMap.end());
1153   IFListType &LL = F->second;
1154 
1155   auto IsCopy = [] (const IFRecordWithRegSet &IR) -> bool {
1156     return IR.first.Wdh == 32 && (IR.first.Off == 0 || IR.first.Off == 32);
1157   };
1158   llvm::erase_if(LL, IsCopy);
1159 }
1160 
pruneCandidates()1161 void HexagonGenInsert::pruneCandidates() {
1162   // Remove candidates that are not beneficial, regardless of the final
1163   // selection method.
1164   // First, remove candidates whose potentially removable set is a subset
1165   // of another candidate's set.
1166   for (const auto &I : IFMap)
1167     pruneCoveredSets(I.first);
1168 
1169   UnsignedMap RPO;
1170 
1171   using RPOTType = ReversePostOrderTraversal<const MachineFunction *>;
1172 
1173   RPOTType RPOT(MFN);
1174   unsigned RPON = 0;
1175   for (const auto &I : RPOT)
1176     RPO[I->getNumber()] = RPON++;
1177 
1178   PairMapType Memo; // Memoization map for distance calculation.
1179   // Remove candidates that would use registers defined too far away.
1180   for (const auto &I : IFMap)
1181     pruneUsesTooFar(I.first, RPO, Memo);
1182 
1183   pruneEmptyLists();
1184 
1185   for (const auto &I : IFMap)
1186     pruneRegCopies(I.first);
1187 }
1188 
1189 namespace {
1190 
1191   // Class for comparing IF candidates for registers that have multiple of
1192   // them. The smaller the candidate, according to this ordering, the better.
1193   // First, compare the number of zeros in the associated potentially remova-
1194   // ble register sets. "Zero" indicates that the register is very likely to
1195   // become dead after this transformation.
1196   // Second, compare "averages", i.e. use-count per size. The lower wins.
1197   // After that, it does not really matter which one is smaller. Resolve
1198   // the tie in some deterministic way.
1199   struct IFOrdering {
IFOrdering__anon7f002ed80811::IFOrdering1200     IFOrdering(const UnsignedMap &UC, const RegisterOrdering &BO)
1201       : UseC(UC), BaseOrd(BO) {}
1202 
1203     bool operator() (const IFRecordWithRegSet &A,
1204                      const IFRecordWithRegSet &B) const;
1205 
1206   private:
1207     void stats(const RegisterSet &Rs, unsigned &Size, unsigned &Zero,
1208           unsigned &Sum) const;
1209 
1210     const UnsignedMap &UseC;
1211     const RegisterOrdering &BaseOrd;
1212   };
1213 
1214 } // end anonymous namespace
1215 
operator ()(const IFRecordWithRegSet & A,const IFRecordWithRegSet & B) const1216 bool IFOrdering::operator() (const IFRecordWithRegSet &A,
1217       const IFRecordWithRegSet &B) const {
1218   unsigned SizeA = 0, ZeroA = 0, SumA = 0;
1219   unsigned SizeB = 0, ZeroB = 0, SumB = 0;
1220   stats(A.second, SizeA, ZeroA, SumA);
1221   stats(B.second, SizeB, ZeroB, SumB);
1222 
1223   // We will pick the minimum element. The more zeros, the better.
1224   if (ZeroA != ZeroB)
1225     return ZeroA > ZeroB;
1226   // Compare SumA/SizeA with SumB/SizeB, lower is better.
1227   uint64_t AvgA = SumA*SizeB, AvgB = SumB*SizeA;
1228   if (AvgA != AvgB)
1229     return AvgA < AvgB;
1230 
1231   // The sets compare identical so far. Resort to comparing the IF records.
1232   // The actual values don't matter, this is only for determinism.
1233   unsigned OSA = BaseOrd[A.first.SrcR], OSB = BaseOrd[B.first.SrcR];
1234   if (OSA != OSB)
1235     return OSA < OSB;
1236   unsigned OIA = BaseOrd[A.first.InsR], OIB = BaseOrd[B.first.InsR];
1237   if (OIA != OIB)
1238     return OIA < OIB;
1239   if (A.first.Wdh != B.first.Wdh)
1240     return A.first.Wdh < B.first.Wdh;
1241   return A.first.Off < B.first.Off;
1242 }
1243 
stats(const RegisterSet & Rs,unsigned & Size,unsigned & Zero,unsigned & Sum) const1244 void IFOrdering::stats(const RegisterSet &Rs, unsigned &Size, unsigned &Zero,
1245       unsigned &Sum) const {
1246   for (unsigned R = Rs.find_first(); R; R = Rs.find_next(R)) {
1247     UnsignedMap::const_iterator F = UseC.find(R);
1248     assert(F != UseC.end());
1249     unsigned UC = F->second;
1250     if (UC == 0)
1251       Zero++;
1252     Sum += UC;
1253     Size++;
1254   }
1255 }
1256 
selectCandidates()1257 void HexagonGenInsert::selectCandidates() {
1258   // Some registers may have multiple valid candidates. Pick the best one
1259   // (or decide not to use any).
1260 
1261   // Compute the "removability" measure of R:
1262   // For each potentially removable register R, record the number of regis-
1263   // ters with IF candidates, where R appears in at least one set.
1264   RegisterSet AllRMs;
1265   UnsignedMap UseC, RemC;
1266   IFMapType::iterator End = IFMap.end();
1267 
1268   for (IFMapType::iterator I = IFMap.begin(); I != End; ++I) {
1269     const IFListType &LL = I->second;
1270     RegisterSet TT;
1271     for (const auto &J : LL)
1272       TT.insert(J.second);
1273     for (unsigned R = TT.find_first(); R; R = TT.find_next(R))
1274       RemC[R]++;
1275     AllRMs.insert(TT);
1276   }
1277 
1278   for (unsigned R = AllRMs.find_first(); R; R = AllRMs.find_next(R)) {
1279     using use_iterator = MachineRegisterInfo::use_nodbg_iterator;
1280     using InstrSet = SmallSet<const MachineInstr *, 16>;
1281 
1282     InstrSet UIs;
1283     // Count as the number of instructions in which R is used, not the
1284     // number of operands.
1285     use_iterator E = MRI->use_nodbg_end();
1286     for (use_iterator I = MRI->use_nodbg_begin(R); I != E; ++I)
1287       UIs.insert(I->getParent());
1288     unsigned C = UIs.size();
1289     // Calculate a measure, which is the number of instructions using R,
1290     // minus the "removability" count computed earlier.
1291     unsigned D = RemC[R];
1292     UseC[R] = (C > D) ? C-D : 0;  // doz
1293   }
1294 
1295   bool SelectAll0 = OptSelectAll0, SelectHas0 = OptSelectHas0;
1296   if (!SelectAll0 && !SelectHas0)
1297     SelectAll0 = true;
1298 
1299   // The smaller the number UseC for a given register R, the "less used"
1300   // R is aside from the opportunities for removal offered by generating
1301   // "insert" instructions.
1302   // Iterate over the IF map, and for those registers that have multiple
1303   // candidates, pick the minimum one according to IFOrdering.
1304   IFOrdering IFO(UseC, BaseOrd);
1305   for (IFMapType::iterator I = IFMap.begin(); I != End; ++I) {
1306     IFListType &LL = I->second;
1307     if (LL.empty())
1308       continue;
1309     // Get the minimum element, remember it and clear the list. If the
1310     // element found is adequate, we will put it back on the list, other-
1311     // wise the list will remain empty, and the entry for this register
1312     // will be removed (i.e. this register will not be replaced by insert).
1313     IFListType::iterator MinI = llvm::min_element(LL, IFO);
1314     assert(MinI != LL.end());
1315     IFRecordWithRegSet M = *MinI;
1316     LL.clear();
1317 
1318     // We want to make sure that this replacement will have a chance to be
1319     // beneficial, and that means that we want to have indication that some
1320     // register will be removed. The most likely registers to be eliminated
1321     // are the use operands in the definition of I->first. Accept/reject a
1322     // candidate based on how many of its uses it can potentially eliminate.
1323 
1324     RegisterSet Us;
1325     const MachineInstr *DefI = MRI->getVRegDef(I->first);
1326     getInstrUses(DefI, Us);
1327     bool Accept = false;
1328 
1329     if (SelectAll0) {
1330       bool All0 = true;
1331       for (unsigned R = Us.find_first(); R; R = Us.find_next(R)) {
1332         if (UseC[R] == 0)
1333           continue;
1334         All0 = false;
1335         break;
1336       }
1337       Accept = All0;
1338     } else if (SelectHas0) {
1339       bool Has0 = false;
1340       for (unsigned R = Us.find_first(); R; R = Us.find_next(R)) {
1341         if (UseC[R] != 0)
1342           continue;
1343         Has0 = true;
1344         break;
1345       }
1346       Accept = Has0;
1347     }
1348     if (Accept)
1349       LL.push_back(M);
1350   }
1351 
1352   // Remove candidates that add uses of removable registers, unless the
1353   // removable registers are among replacement candidates.
1354   // Recompute the removable registers, since some candidates may have
1355   // been eliminated.
1356   AllRMs.clear();
1357   for (IFMapType::iterator I = IFMap.begin(); I != End; ++I) {
1358     const IFListType &LL = I->second;
1359     if (!LL.empty())
1360       AllRMs.insert(LL[0].second);
1361   }
1362   for (IFMapType::iterator I = IFMap.begin(); I != End; ++I) {
1363     IFListType &LL = I->second;
1364     if (LL.empty())
1365       continue;
1366     unsigned SR = LL[0].first.SrcR, IR = LL[0].first.InsR;
1367     if (AllRMs[SR] || AllRMs[IR])
1368       LL.clear();
1369   }
1370 
1371   pruneEmptyLists();
1372 }
1373 
generateInserts()1374 bool HexagonGenInsert::generateInserts() {
1375   // Create a new register for each one from IFMap, and store them in the
1376   // map.
1377   UnsignedMap RegMap;
1378   for (auto &I : IFMap) {
1379     unsigned VR = I.first;
1380     const TargetRegisterClass *RC = MRI->getRegClass(VR);
1381     Register NewVR = MRI->createVirtualRegister(RC);
1382     RegMap[VR] = NewVR;
1383   }
1384 
1385   // We can generate the "insert" instructions using potentially stale re-
1386   // gisters: SrcR and InsR for a given VR may be among other registers that
1387   // are also replaced. This is fine, we will do the mass "rauw" a bit later.
1388   for (auto &I : IFMap) {
1389     MachineInstr *MI = MRI->getVRegDef(I.first);
1390     MachineBasicBlock &B = *MI->getParent();
1391     DebugLoc DL = MI->getDebugLoc();
1392     unsigned NewR = RegMap[I.first];
1393     bool R32 = MRI->getRegClass(NewR) == &Hexagon::IntRegsRegClass;
1394     const MCInstrDesc &D = R32 ? HII->get(Hexagon::S2_insert)
1395                                : HII->get(Hexagon::S2_insertp);
1396     IFRecord IF = I.second[0].first;
1397     unsigned Wdh = IF.Wdh, Off = IF.Off;
1398     unsigned InsS = 0;
1399     if (R32 && MRI->getRegClass(IF.InsR) == &Hexagon::DoubleRegsRegClass) {
1400       InsS = Hexagon::isub_lo;
1401       if (Off >= 32) {
1402         InsS = Hexagon::isub_hi;
1403         Off -= 32;
1404       }
1405     }
1406     // Advance to the proper location for inserting instructions. This could
1407     // be B.end().
1408     MachineBasicBlock::iterator At = MI;
1409     if (MI->isPHI())
1410       At = B.getFirstNonPHI();
1411 
1412     BuildMI(B, At, DL, D, NewR)
1413       .addReg(IF.SrcR)
1414       .addReg(IF.InsR, 0, InsS)
1415       .addImm(Wdh)
1416       .addImm(Off);
1417 
1418     MRI->clearKillFlags(IF.SrcR);
1419     MRI->clearKillFlags(IF.InsR);
1420   }
1421 
1422   for (const auto &I : IFMap) {
1423     MachineInstr *DefI = MRI->getVRegDef(I.first);
1424     MRI->replaceRegWith(I.first, RegMap[I.first]);
1425     DefI->eraseFromParent();
1426   }
1427 
1428   return true;
1429 }
1430 
removeDeadCode(MachineDomTreeNode * N)1431 bool HexagonGenInsert::removeDeadCode(MachineDomTreeNode *N) {
1432   bool Changed = false;
1433 
1434   for (auto *DTN : children<MachineDomTreeNode*>(N))
1435     Changed |= removeDeadCode(DTN);
1436 
1437   MachineBasicBlock *B = N->getBlock();
1438   std::vector<MachineInstr*> Instrs;
1439   for (MachineInstr &MI : llvm::reverse(*B))
1440     Instrs.push_back(&MI);
1441 
1442   for (MachineInstr *MI : Instrs) {
1443     unsigned Opc = MI->getOpcode();
1444     // Do not touch lifetime markers. This is why the target-independent DCE
1445     // cannot be used.
1446     if (Opc == TargetOpcode::LIFETIME_START ||
1447         Opc == TargetOpcode::LIFETIME_END)
1448       continue;
1449     bool Store = false;
1450     if (MI->isInlineAsm() || !MI->isSafeToMove(Store))
1451       continue;
1452 
1453     bool AllDead = true;
1454     SmallVector<unsigned,2> Regs;
1455     for (const MachineOperand &MO : MI->operands()) {
1456       if (!MO.isReg() || !MO.isDef())
1457         continue;
1458       Register R = MO.getReg();
1459       if (!R.isVirtual() || !MRI->use_nodbg_empty(R)) {
1460         AllDead = false;
1461         break;
1462       }
1463       Regs.push_back(R);
1464     }
1465     if (!AllDead)
1466       continue;
1467 
1468     B->erase(MI);
1469     for (unsigned Reg : Regs)
1470       MRI->markUsesInDebugValueAsUndef(Reg);
1471     Changed = true;
1472   }
1473 
1474   return Changed;
1475 }
1476 
runOnMachineFunction(MachineFunction & MF)1477 bool HexagonGenInsert::runOnMachineFunction(MachineFunction &MF) {
1478   if (skipFunction(MF.getFunction()))
1479     return false;
1480 
1481   bool Timing = OptTiming, TimingDetail = Timing && OptTimingDetail;
1482   bool Changed = false;
1483 
1484   // Verify: one, but not both.
1485   assert(!OptSelectAll0 || !OptSelectHas0);
1486 
1487   IFMap.clear();
1488   BaseOrd.clear();
1489   CellOrd.clear();
1490 
1491   const auto &ST = MF.getSubtarget<HexagonSubtarget>();
1492   HII = ST.getInstrInfo();
1493   HRI = ST.getRegisterInfo();
1494   MFN = &MF;
1495   MRI = &MF.getRegInfo();
1496   MDT = &getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
1497 
1498   // Clean up before any further processing, so that dead code does not
1499   // get used in a newly generated "insert" instruction. Have a custom
1500   // version of DCE that preserves lifetime markers. Without it, merging
1501   // of stack objects can fail to recognize and merge disjoint objects
1502   // leading to unnecessary stack growth.
1503   Changed = removeDeadCode(MDT->getRootNode());
1504 
1505   const HexagonEvaluator HE(*HRI, *MRI, *HII, MF);
1506   BitTracker BTLoc(HE, MF);
1507   BTLoc.trace(isDebug());
1508   BTLoc.run();
1509   CellMapShadow MS(BTLoc);
1510   CMS = &MS;
1511 
1512   buildOrderingMF(BaseOrd);
1513   buildOrderingBT(BaseOrd, CellOrd);
1514 
1515   if (isDebug()) {
1516     dbgs() << "Cell ordering:\n";
1517     for (const auto &I : CellOrd) {
1518       unsigned VR = I.first, Pos = I.second;
1519       dbgs() << printReg(VR, HRI) << " -> " << Pos << "\n";
1520     }
1521   }
1522 
1523   // Collect candidates for conversion into the insert forms.
1524   MachineBasicBlock *RootB = MDT->getRoot();
1525   OrderedRegisterList AvailR(CellOrd);
1526 
1527   const char *const TGName = "hexinsert";
1528   const char *const TGDesc = "Generate Insert Instructions";
1529 
1530   {
1531     NamedRegionTimer _T("collection", "collection", TGName, TGDesc,
1532                         TimingDetail);
1533     collectInBlock(RootB, AvailR);
1534     // Complete the information gathered in IFMap.
1535     computeRemovableRegisters();
1536   }
1537 
1538   if (isDebug()) {
1539     dbgs() << "Candidates after collection:\n";
1540     dump_map();
1541   }
1542 
1543   if (IFMap.empty())
1544     return Changed;
1545 
1546   {
1547     NamedRegionTimer _T("pruning", "pruning", TGName, TGDesc, TimingDetail);
1548     pruneCandidates();
1549   }
1550 
1551   if (isDebug()) {
1552     dbgs() << "Candidates after pruning:\n";
1553     dump_map();
1554   }
1555 
1556   if (IFMap.empty())
1557     return Changed;
1558 
1559   {
1560     NamedRegionTimer _T("selection", "selection", TGName, TGDesc, TimingDetail);
1561     selectCandidates();
1562   }
1563 
1564   if (isDebug()) {
1565     dbgs() << "Candidates after selection:\n";
1566     dump_map();
1567   }
1568 
1569   // Filter out vregs beyond the cutoff.
1570   if (VRegIndexCutoff.getPosition()) {
1571     unsigned Cutoff = VRegIndexCutoff;
1572 
1573     using IterListType = SmallVector<IFMapType::iterator, 16>;
1574 
1575     IterListType Out;
1576     for (IFMapType::iterator I = IFMap.begin(), E = IFMap.end(); I != E; ++I) {
1577       unsigned Idx = Register(I->first).virtRegIndex();
1578       if (Idx >= Cutoff)
1579         Out.push_back(I);
1580     }
1581     for (const auto &It : Out)
1582       IFMap.erase(It);
1583   }
1584   if (IFMap.empty())
1585     return Changed;
1586 
1587   {
1588     NamedRegionTimer _T("generation", "generation", TGName, TGDesc,
1589                         TimingDetail);
1590     generateInserts();
1591   }
1592 
1593   return true;
1594 }
1595 
createHexagonGenInsert()1596 FunctionPass *llvm::createHexagonGenInsert() {
1597   return new HexagonGenInsert();
1598 }
1599 
1600 //===----------------------------------------------------------------------===//
1601 //                         Public Constructor Functions
1602 //===----------------------------------------------------------------------===//
1603 
1604 INITIALIZE_PASS_BEGIN(HexagonGenInsert, "hexinsert",
1605   "Hexagon generate \"insert\" instructions", false, false)
1606 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTreeWrapperPass)
1607 INITIALIZE_PASS_END(HexagonGenInsert, "hexinsert",
1608   "Hexagon generate \"insert\" instructions", false, false)
1609