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