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