xref: /src/contrib/llvm-project/llvm/utils/TableGen/Common/CodeGenRegisters.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
156fe8f14SDimitry Andric //===- CodeGenRegisters.cpp - Register and RegisterClass Info -------------===//
256fe8f14SDimitry Andric //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
656fe8f14SDimitry Andric //
756fe8f14SDimitry Andric //===----------------------------------------------------------------------===//
856fe8f14SDimitry Andric //
956fe8f14SDimitry Andric // This file defines structures to encapsulate information gleaned from the
1056fe8f14SDimitry Andric // target register and register class definitions.
1156fe8f14SDimitry Andric //
1256fe8f14SDimitry Andric //===----------------------------------------------------------------------===//
1356fe8f14SDimitry Andric 
1456fe8f14SDimitry Andric #include "CodeGenRegisters.h"
15b915e9e0SDimitry Andric #include "llvm/ADT/ArrayRef.h"
16b915e9e0SDimitry Andric #include "llvm/ADT/BitVector.h"
17b915e9e0SDimitry Andric #include "llvm/ADT/DenseMap.h"
1863faed5bSDimitry Andric #include "llvm/ADT/IntEqClasses.h"
19145449b1SDimitry Andric #include "llvm/ADT/STLExtras.h"
20b915e9e0SDimitry Andric #include "llvm/ADT/SetVector.h"
21b915e9e0SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
22d8e91e46SDimitry Andric #include "llvm/ADT/SmallSet.h"
234a16efa3SDimitry Andric #include "llvm/ADT/SmallVector.h"
24b915e9e0SDimitry Andric #include "llvm/ADT/StringRef.h"
25ac9a064cSDimitry Andric #include "llvm/ADT/StringSet.h"
26b61ab53cSDimitry Andric #include "llvm/ADT/Twine.h"
27f8af5cf6SDimitry Andric #include "llvm/Support/Debug.h"
28b915e9e0SDimitry Andric #include "llvm/Support/raw_ostream.h"
294a16efa3SDimitry Andric #include "llvm/TableGen/Error.h"
30b915e9e0SDimitry Andric #include "llvm/TableGen/Record.h"
31b915e9e0SDimitry Andric #include <algorithm>
32b915e9e0SDimitry Andric #include <cassert>
33b915e9e0SDimitry Andric #include <cstdint>
34b915e9e0SDimitry Andric #include <iterator>
35b915e9e0SDimitry Andric #include <map>
36044eb2f6SDimitry Andric #include <queue>
37b915e9e0SDimitry Andric #include <set>
38b915e9e0SDimitry Andric #include <string>
39b915e9e0SDimitry Andric #include <tuple>
40b915e9e0SDimitry Andric #include <utility>
41b915e9e0SDimitry Andric #include <vector>
4256fe8f14SDimitry Andric 
4356fe8f14SDimitry Andric using namespace llvm;
4456fe8f14SDimitry Andric 
455ca98fd9SDimitry Andric #define DEBUG_TYPE "regalloc-emitter"
465ca98fd9SDimitry Andric 
4756fe8f14SDimitry Andric //===----------------------------------------------------------------------===//
4863faed5bSDimitry Andric //                             CodeGenSubRegIndex
4963faed5bSDimitry Andric //===----------------------------------------------------------------------===//
5063faed5bSDimitry Andric 
CodeGenSubRegIndex(Record * R,unsigned Enum,const CodeGenHwModes & CGH)51ac9a064cSDimitry Andric CodeGenSubRegIndex::CodeGenSubRegIndex(Record *R, unsigned Enum,
52ac9a064cSDimitry Andric                                        const CodeGenHwModes &CGH)
53eb11fae6SDimitry Andric     : TheDef(R), EnumValue(Enum), AllSuperRegsCovered(true), Artificial(true) {
54cfca06d7SDimitry Andric   Name = std::string(R->getName());
55902a7b52SDimitry Andric   if (R->getValue("Namespace"))
56cfca06d7SDimitry Andric     Namespace = std::string(R->getValueAsString("Namespace"));
57ac9a064cSDimitry Andric 
58ac9a064cSDimitry Andric   if (const RecordVal *RV = R->getValue("SubRegRanges"))
59ac9a064cSDimitry Andric     if (auto *DI = dyn_cast_or_null<DefInit>(RV->getValue()))
60ac9a064cSDimitry Andric       Range = SubRegRangeByHwMode(DI->getDef(), CGH);
61ac9a064cSDimitry Andric   if (!Range.hasDefault())
62ac9a064cSDimitry Andric     Range.insertSubRegRangeForMode(DefaultMode, SubRegRange(R));
6363faed5bSDimitry Andric }
6463faed5bSDimitry Andric 
CodeGenSubRegIndex(StringRef N,StringRef Nspace,unsigned Enum)65902a7b52SDimitry Andric CodeGenSubRegIndex::CodeGenSubRegIndex(StringRef N, StringRef Nspace,
66902a7b52SDimitry Andric                                        unsigned Enum)
67cfca06d7SDimitry Andric     : TheDef(nullptr), Name(std::string(N)), Namespace(std::string(Nspace)),
68ac9a064cSDimitry Andric       Range(SubRegRange(-1, -1)), EnumValue(Enum), AllSuperRegsCovered(true),
69cfca06d7SDimitry Andric       Artificial(true) {}
7063faed5bSDimitry Andric 
getQualifiedName() const7163faed5bSDimitry Andric std::string CodeGenSubRegIndex::getQualifiedName() const {
7263faed5bSDimitry Andric   std::string N = getNamespace();
7363faed5bSDimitry Andric   if (!N.empty())
7463faed5bSDimitry Andric     N += "::";
7563faed5bSDimitry Andric   N += getName();
7663faed5bSDimitry Andric   return N;
7763faed5bSDimitry Andric }
7863faed5bSDimitry Andric 
updateComponents(CodeGenRegBank & RegBank)7963faed5bSDimitry Andric void CodeGenSubRegIndex::updateComponents(CodeGenRegBank &RegBank) {
80902a7b52SDimitry Andric   if (!TheDef)
8163faed5bSDimitry Andric     return;
82902a7b52SDimitry Andric 
83902a7b52SDimitry Andric   std::vector<Record *> Comps = TheDef->getValueAsListOfDefs("ComposedOf");
84902a7b52SDimitry Andric   if (!Comps.empty()) {
8563faed5bSDimitry Andric     if (Comps.size() != 2)
86522600a2SDimitry Andric       PrintFatalError(TheDef->getLoc(),
87522600a2SDimitry Andric                       "ComposedOf must have exactly two entries");
8863faed5bSDimitry Andric     CodeGenSubRegIndex *A = RegBank.getSubRegIdx(Comps[0]);
8963faed5bSDimitry Andric     CodeGenSubRegIndex *B = RegBank.getSubRegIdx(Comps[1]);
90ac9a064cSDimitry Andric     CodeGenSubRegIndex *X = A->addComposite(B, this, RegBank.getHwModes());
9163faed5bSDimitry Andric     if (X)
92522600a2SDimitry Andric       PrintFatalError(TheDef->getLoc(), "Ambiguous ComposedOf entries");
9363faed5bSDimitry Andric   }
9463faed5bSDimitry Andric 
95902a7b52SDimitry Andric   std::vector<Record *> Parts =
96902a7b52SDimitry Andric       TheDef->getValueAsListOfDefs("CoveringSubRegIndices");
97902a7b52SDimitry Andric   if (!Parts.empty()) {
98902a7b52SDimitry Andric     if (Parts.size() < 2)
99522600a2SDimitry Andric       PrintFatalError(TheDef->getLoc(),
100902a7b52SDimitry Andric                       "CoveredBySubRegs must have two or more entries");
101902a7b52SDimitry Andric     SmallVector<CodeGenSubRegIndex *, 8> IdxParts;
102044eb2f6SDimitry Andric     for (Record *Part : Parts)
103044eb2f6SDimitry Andric       IdxParts.push_back(RegBank.getSubRegIdx(Part));
104044eb2f6SDimitry Andric     setConcatenationOf(IdxParts);
105902a7b52SDimitry Andric   }
106902a7b52SDimitry Andric }
107902a7b52SDimitry Andric 
computeLaneMask() const108b915e9e0SDimitry Andric LaneBitmask CodeGenSubRegIndex::computeLaneMask() const {
109522600a2SDimitry Andric   // Already computed?
110b915e9e0SDimitry Andric   if (LaneMask.any())
111522600a2SDimitry Andric     return LaneMask;
112522600a2SDimitry Andric 
113522600a2SDimitry Andric   // Recursion guard, shouldn't be required.
114b915e9e0SDimitry Andric   LaneMask = LaneBitmask::getAll();
115522600a2SDimitry Andric 
116522600a2SDimitry Andric   // The lane mask is simply the union of all sub-indices.
117b915e9e0SDimitry Andric   LaneBitmask M;
11867c32a98SDimitry Andric   for (const auto &C : Composed)
11967c32a98SDimitry Andric     M |= C.second->computeLaneMask();
120b915e9e0SDimitry Andric   assert(M.any() && "Missing lane mask, sub-register cycle?");
121522600a2SDimitry Andric   LaneMask = M;
122522600a2SDimitry Andric   return LaneMask;
12363faed5bSDimitry Andric }
12463faed5bSDimitry Andric 
setConcatenationOf(ArrayRef<CodeGenSubRegIndex * > Parts)125044eb2f6SDimitry Andric void CodeGenSubRegIndex::setConcatenationOf(
126044eb2f6SDimitry Andric     ArrayRef<CodeGenSubRegIndex *> Parts) {
127044eb2f6SDimitry Andric   if (ConcatenationOf.empty())
128044eb2f6SDimitry Andric     ConcatenationOf.assign(Parts.begin(), Parts.end());
129044eb2f6SDimitry Andric   else
130ac9a064cSDimitry Andric     assert(std::equal(Parts.begin(), Parts.end(), ConcatenationOf.begin()) &&
131ac9a064cSDimitry Andric            "parts consistent");
132044eb2f6SDimitry Andric }
133044eb2f6SDimitry Andric 
computeConcatTransitiveClosure()134044eb2f6SDimitry Andric void CodeGenSubRegIndex::computeConcatTransitiveClosure() {
135ac9a064cSDimitry Andric   for (SmallVectorImpl<CodeGenSubRegIndex *>::iterator I =
136ac9a064cSDimitry Andric            ConcatenationOf.begin();
137ac9a064cSDimitry Andric        I != ConcatenationOf.end();
138ac9a064cSDimitry Andric        /*empty*/) {
139044eb2f6SDimitry Andric     CodeGenSubRegIndex *SubIdx = *I;
140044eb2f6SDimitry Andric     SubIdx->computeConcatTransitiveClosure();
141044eb2f6SDimitry Andric #ifndef NDEBUG
142044eb2f6SDimitry Andric     for (CodeGenSubRegIndex *SRI : SubIdx->ConcatenationOf)
143044eb2f6SDimitry Andric       assert(SRI->ConcatenationOf.empty() && "No transitive closure?");
144044eb2f6SDimitry Andric #endif
145044eb2f6SDimitry Andric 
146044eb2f6SDimitry Andric     if (SubIdx->ConcatenationOf.empty()) {
147044eb2f6SDimitry Andric       ++I;
148044eb2f6SDimitry Andric     } else {
149044eb2f6SDimitry Andric       I = ConcatenationOf.erase(I);
150044eb2f6SDimitry Andric       I = ConcatenationOf.insert(I, SubIdx->ConcatenationOf.begin(),
151044eb2f6SDimitry Andric                                  SubIdx->ConcatenationOf.end());
152044eb2f6SDimitry Andric       I += SubIdx->ConcatenationOf.size();
153044eb2f6SDimitry Andric     }
154044eb2f6SDimitry Andric   }
155044eb2f6SDimitry Andric }
156044eb2f6SDimitry Andric 
15763faed5bSDimitry Andric //===----------------------------------------------------------------------===//
15856fe8f14SDimitry Andric //                              CodeGenRegister
15956fe8f14SDimitry Andric //===----------------------------------------------------------------------===//
16056fe8f14SDimitry Andric 
CodeGenRegister(Record * R,unsigned Enum)16156fe8f14SDimitry Andric CodeGenRegister::CodeGenRegister(Record *R, unsigned Enum)
162344a3780SDimitry Andric     : TheDef(R), EnumValue(Enum),
163344a3780SDimitry Andric       CostPerUse(R->getValueAsListOfInts("CostPerUse")),
16463faed5bSDimitry Andric       CoveredBySubRegs(R->getValueAsBit("CoveredBySubRegs")),
165e3b55780SDimitry Andric       HasDisjunctSubRegs(false), Constant(R->getValueAsBit("isConstant")),
166e3b55780SDimitry Andric       SubRegsComplete(false), SuperRegsComplete(false), TopoSig(~0u) {
167eb11fae6SDimitry Andric   Artificial = R->getValueAsBit("isArtificial");
168eb11fae6SDimitry Andric }
16956fe8f14SDimitry Andric 
buildObjectGraph(CodeGenRegBank & RegBank)17058b69754SDimitry Andric void CodeGenRegister::buildObjectGraph(CodeGenRegBank &RegBank) {
17158b69754SDimitry Andric   std::vector<Record *> SRIs = TheDef->getValueAsListOfDefs("SubRegIndices");
17258b69754SDimitry Andric   std::vector<Record *> SRs = TheDef->getValueAsListOfDefs("SubRegs");
17358b69754SDimitry Andric 
17458b69754SDimitry Andric   if (SRIs.size() != SRs.size())
175522600a2SDimitry Andric     PrintFatalError(TheDef->getLoc(),
17658b69754SDimitry Andric                     "SubRegs and SubRegIndices must have the same size");
17758b69754SDimitry Andric 
17858b69754SDimitry Andric   for (unsigned i = 0, e = SRIs.size(); i != e; ++i) {
17958b69754SDimitry Andric     ExplicitSubRegIndices.push_back(RegBank.getSubRegIdx(SRIs[i]));
18058b69754SDimitry Andric     ExplicitSubRegs.push_back(RegBank.getReg(SRs[i]));
18158b69754SDimitry Andric   }
18258b69754SDimitry Andric 
18358b69754SDimitry Andric   // Also compute leading super-registers. Each register has a list of
18458b69754SDimitry Andric   // covered-by-subregs super-registers where it appears as the first explicit
18558b69754SDimitry Andric   // sub-register.
18658b69754SDimitry Andric   //
18758b69754SDimitry Andric   // This is used by computeSecondarySubRegs() to find candidates.
18858b69754SDimitry Andric   if (CoveredBySubRegs && !ExplicitSubRegs.empty())
18958b69754SDimitry Andric     ExplicitSubRegs.front()->LeadingSuperRegs.push_back(this);
19058b69754SDimitry Andric 
19158b69754SDimitry Andric   // Add ad hoc alias links. This is a symmetric relationship between two
19258b69754SDimitry Andric   // registers, so build a symmetric graph by adding links in both ends.
19358b69754SDimitry Andric   std::vector<Record *> Aliases = TheDef->getValueAsListOfDefs("Aliases");
194044eb2f6SDimitry Andric   for (Record *Alias : Aliases) {
195044eb2f6SDimitry Andric     CodeGenRegister *Reg = RegBank.getReg(Alias);
19658b69754SDimitry Andric     ExplicitAliases.push_back(Reg);
19758b69754SDimitry Andric     Reg->ExplicitAliases.push_back(this);
19858b69754SDimitry Andric   }
19958b69754SDimitry Andric }
20058b69754SDimitry Andric 
getName() const201b60736ecSDimitry Andric StringRef CodeGenRegister::getName() const {
20267c32a98SDimitry Andric   assert(TheDef && "no def");
20356fe8f14SDimitry Andric   return TheDef->getName();
20456fe8f14SDimitry Andric }
20556fe8f14SDimitry Andric 
20656fe8f14SDimitry Andric namespace {
207b915e9e0SDimitry Andric 
20863faed5bSDimitry Andric // Iterate over all register units in a set of registers.
20963faed5bSDimitry Andric class RegUnitIterator {
2105a5ac124SDimitry Andric   CodeGenRegister::Vec::const_iterator RegI, RegE;
2115a5ac124SDimitry Andric   CodeGenRegister::RegUnitList::iterator UnitI, UnitE;
212145449b1SDimitry Andric   static CodeGenRegister::RegUnitList Sentinel;
21363faed5bSDimitry Andric 
21463faed5bSDimitry Andric public:
RegUnitIterator(const CodeGenRegister::Vec & Regs)215ac9a064cSDimitry Andric   RegUnitIterator(const CodeGenRegister::Vec &Regs)
216ac9a064cSDimitry Andric       : RegI(Regs.begin()), RegE(Regs.end()) {
21763faed5bSDimitry Andric 
218145449b1SDimitry Andric     if (RegI == RegE) {
219145449b1SDimitry Andric       UnitI = Sentinel.end();
220145449b1SDimitry Andric       UnitE = Sentinel.end();
221145449b1SDimitry Andric     } else {
22263faed5bSDimitry Andric       UnitI = (*RegI)->getRegUnits().begin();
22363faed5bSDimitry Andric       UnitE = (*RegI)->getRegUnits().end();
22463faed5bSDimitry Andric       advance();
22563faed5bSDimitry Andric     }
22663faed5bSDimitry Andric   }
22763faed5bSDimitry Andric 
isValid() const22863faed5bSDimitry Andric   bool isValid() const { return UnitI != UnitE; }
22963faed5bSDimitry Andric 
operator *() const230ac9a064cSDimitry Andric   unsigned operator*() const {
231ac9a064cSDimitry Andric     assert(isValid());
232ac9a064cSDimitry Andric     return *UnitI;
233ac9a064cSDimitry Andric   }
23463faed5bSDimitry Andric 
getReg() const235ac9a064cSDimitry Andric   const CodeGenRegister *getReg() const {
236ac9a064cSDimitry Andric     assert(isValid());
237ac9a064cSDimitry Andric     return *RegI;
238ac9a064cSDimitry Andric   }
23963faed5bSDimitry Andric 
24063faed5bSDimitry Andric   /// Preincrement.  Move to the next unit.
operator ++()24163faed5bSDimitry Andric   void operator++() {
24263faed5bSDimitry Andric     assert(isValid() && "Cannot advance beyond the last operand");
24363faed5bSDimitry Andric     ++UnitI;
24463faed5bSDimitry Andric     advance();
24563faed5bSDimitry Andric   }
24663faed5bSDimitry Andric 
24763faed5bSDimitry Andric protected:
advance()24863faed5bSDimitry Andric   void advance() {
24963faed5bSDimitry Andric     while (UnitI == UnitE) {
25063faed5bSDimitry Andric       if (++RegI == RegE)
25163faed5bSDimitry Andric         break;
25263faed5bSDimitry Andric       UnitI = (*RegI)->getRegUnits().begin();
25363faed5bSDimitry Andric       UnitE = (*RegI)->getRegUnits().end();
25463faed5bSDimitry Andric     }
25563faed5bSDimitry Andric   }
25656fe8f14SDimitry Andric };
257b915e9e0SDimitry Andric 
258145449b1SDimitry Andric CodeGenRegister::RegUnitList RegUnitIterator::Sentinel;
259145449b1SDimitry Andric 
260b915e9e0SDimitry Andric } // end anonymous namespace
26163faed5bSDimitry Andric 
26263faed5bSDimitry Andric // Inherit register units from subregisters.
26363faed5bSDimitry Andric // Return true if the RegUnits changed.
inheritRegUnits(CodeGenRegBank & RegBank)26463faed5bSDimitry Andric bool CodeGenRegister::inheritRegUnits(CodeGenRegBank &RegBank) {
2655a5ac124SDimitry Andric   bool changed = false;
266044eb2f6SDimitry Andric   for (const auto &SubReg : SubRegs) {
267044eb2f6SDimitry Andric     CodeGenRegister *SR = SubReg.second;
26863faed5bSDimitry Andric     // Merge the subregister's units into this register's RegUnits.
2695a5ac124SDimitry Andric     changed |= (RegUnits |= SR->RegUnits);
27063faed5bSDimitry Andric   }
2715a5ac124SDimitry Andric 
2725a5ac124SDimitry Andric   return changed;
27356fe8f14SDimitry Andric }
27456fe8f14SDimitry Andric 
27556fe8f14SDimitry Andric const CodeGenRegister::SubRegMap &
computeSubRegs(CodeGenRegBank & RegBank)27658b69754SDimitry Andric CodeGenRegister::computeSubRegs(CodeGenRegBank &RegBank) {
27756fe8f14SDimitry Andric   // Only compute this map once.
27856fe8f14SDimitry Andric   if (SubRegsComplete)
27956fe8f14SDimitry Andric     return SubRegs;
28056fe8f14SDimitry Andric   SubRegsComplete = true;
28156fe8f14SDimitry Andric 
2825a5ac124SDimitry Andric   HasDisjunctSubRegs = ExplicitSubRegs.size() > 1;
2835a5ac124SDimitry Andric 
28458b69754SDimitry Andric   // First insert the explicit subregs and make sure they are fully indexed.
28558b69754SDimitry Andric   for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
28658b69754SDimitry Andric     CodeGenRegister *SR = ExplicitSubRegs[i];
28758b69754SDimitry Andric     CodeGenSubRegIndex *Idx = ExplicitSubRegIndices[i];
288eb11fae6SDimitry Andric     if (!SR->Artificial)
289eb11fae6SDimitry Andric       Idx->Artificial = false;
290ac9a064cSDimitry Andric     if (!SubRegs.insert(std::pair(Idx, SR)).second)
291522600a2SDimitry Andric       PrintFatalError(TheDef->getLoc(), "SubRegIndex " + Idx->getName() +
292ac9a064cSDimitry Andric                                             " appears twice in Register " +
293ac9a064cSDimitry Andric                                             getName());
29458b69754SDimitry Andric     // Map explicit sub-registers first, so the names take precedence.
29558b69754SDimitry Andric     // The inherited sub-registers are mapped below.
296ac9a064cSDimitry Andric     SubReg2Idx.insert(std::pair(SR, Idx));
29756fe8f14SDimitry Andric   }
29856fe8f14SDimitry Andric 
29956fe8f14SDimitry Andric   // Keep track of inherited subregs and how they can be reached.
30063faed5bSDimitry Andric   SmallPtrSet<CodeGenRegister *, 8> Orphans;
30156fe8f14SDimitry Andric 
30263faed5bSDimitry Andric   // Clone inherited subregs and place duplicate entries in Orphans.
30356fe8f14SDimitry Andric   // Here the order is important - earlier subregs take precedence.
304044eb2f6SDimitry Andric   for (CodeGenRegister *ESR : ExplicitSubRegs) {
305044eb2f6SDimitry Andric     const SubRegMap &Map = ESR->computeSubRegs(RegBank);
306044eb2f6SDimitry Andric     HasDisjunctSubRegs |= ESR->HasDisjunctSubRegs;
307411bd29eSDimitry Andric 
308044eb2f6SDimitry Andric     for (const auto &SR : Map) {
309044eb2f6SDimitry Andric       if (!SubRegs.insert(SR).second)
310044eb2f6SDimitry Andric         Orphans.insert(SR.second);
311411bd29eSDimitry Andric     }
31256fe8f14SDimitry Andric   }
31356fe8f14SDimitry Andric 
31463faed5bSDimitry Andric   // Expand any composed subreg indices.
31563faed5bSDimitry Andric   // If dsub_2 has ComposedOf = [qsub_1, dsub_0], and this register has a
31663faed5bSDimitry Andric   // qsub_1 subreg, add a dsub_2 subreg.  Keep growing Indices and process
31763faed5bSDimitry Andric   // expanded subreg indices recursively.
31858b69754SDimitry Andric   SmallVector<CodeGenSubRegIndex *, 8> Indices = ExplicitSubRegIndices;
31963faed5bSDimitry Andric   for (unsigned i = 0; i != Indices.size(); ++i) {
32063faed5bSDimitry Andric     CodeGenSubRegIndex *Idx = Indices[i];
32163faed5bSDimitry Andric     const CodeGenSubRegIndex::CompMap &Comps = Idx->getComposites();
32263faed5bSDimitry Andric     CodeGenRegister *SR = SubRegs[Idx];
32358b69754SDimitry Andric     const SubRegMap &Map = SR->computeSubRegs(RegBank);
32463faed5bSDimitry Andric 
32563faed5bSDimitry Andric     // Look at the possible compositions of Idx.
32663faed5bSDimitry Andric     // They may not all be supported by SR.
327344a3780SDimitry Andric     for (auto Comp : Comps) {
328344a3780SDimitry Andric       SubRegMap::const_iterator SRI = Map.find(Comp.first);
32963faed5bSDimitry Andric       if (SRI == Map.end())
33063faed5bSDimitry Andric         continue; // Idx + I->first doesn't exist in SR.
33163faed5bSDimitry Andric       // Add I->second as a name for the subreg SRI->second, assuming it is
33263faed5bSDimitry Andric       // orphaned, and the name isn't already used for something else.
333344a3780SDimitry Andric       if (SubRegs.count(Comp.second) || !Orphans.erase(SRI->second))
33463faed5bSDimitry Andric         continue;
33563faed5bSDimitry Andric       // We found a new name for the orphaned sub-register.
336ac9a064cSDimitry Andric       SubRegs.insert(std::pair(Comp.second, SRI->second));
337344a3780SDimitry Andric       Indices.push_back(Comp.second);
33863faed5bSDimitry Andric     }
33963faed5bSDimitry Andric   }
34063faed5bSDimitry Andric 
34156fe8f14SDimitry Andric   // Now Orphans contains the inherited subregisters without a direct index.
34256fe8f14SDimitry Andric   // Create inferred indexes for all missing entries.
34363faed5bSDimitry Andric   // Work backwards in the Indices vector in order to compose subregs bottom-up.
34463faed5bSDimitry Andric   // Consider this subreg sequence:
34563faed5bSDimitry Andric   //
34663faed5bSDimitry Andric   //   qsub_1 -> dsub_0 -> ssub_0
34763faed5bSDimitry Andric   //
34863faed5bSDimitry Andric   // The qsub_1 -> dsub_0 composition becomes dsub_2, so the ssub_0 register
34963faed5bSDimitry Andric   // can be reached in two different ways:
35063faed5bSDimitry Andric   //
35163faed5bSDimitry Andric   //   qsub_1 -> ssub_0
35263faed5bSDimitry Andric   //   dsub_2 -> ssub_0
35363faed5bSDimitry Andric   //
35463faed5bSDimitry Andric   // We pick the latter composition because another register may have [dsub_0,
35558b69754SDimitry Andric   // dsub_1, dsub_2] subregs without necessarily having a qsub_1 subreg.  The
35663faed5bSDimitry Andric   // dsub_2 -> ssub_0 composition can be shared.
35763faed5bSDimitry Andric   while (!Indices.empty() && !Orphans.empty()) {
35863faed5bSDimitry Andric     CodeGenSubRegIndex *Idx = Indices.pop_back_val();
35963faed5bSDimitry Andric     CodeGenRegister *SR = SubRegs[Idx];
36058b69754SDimitry Andric     const SubRegMap &Map = SR->computeSubRegs(RegBank);
361044eb2f6SDimitry Andric     for (const auto &SubReg : Map)
362044eb2f6SDimitry Andric       if (Orphans.erase(SubReg.second))
363ac9a064cSDimitry Andric         SubRegs[RegBank.getCompositeSubRegIndex(Idx, SubReg.first)] =
364ac9a064cSDimitry Andric             SubReg.second;
36556fe8f14SDimitry Andric   }
36663faed5bSDimitry Andric 
36758b69754SDimitry Andric   // Compute the inverse SubReg -> Idx map.
368044eb2f6SDimitry Andric   for (const auto &SubReg : SubRegs) {
369044eb2f6SDimitry Andric     if (SubReg.second == this) {
370522600a2SDimitry Andric       ArrayRef<SMLoc> Loc;
37158b69754SDimitry Andric       if (TheDef)
37258b69754SDimitry Andric         Loc = TheDef->getLoc();
373522600a2SDimitry Andric       PrintFatalError(Loc, "Register " + getName() +
37458b69754SDimitry Andric                                " has itself as a sub-register");
37558b69754SDimitry Andric     }
376f8af5cf6SDimitry Andric 
377f8af5cf6SDimitry Andric     // Compute AllSuperRegsCovered.
378f8af5cf6SDimitry Andric     if (!CoveredBySubRegs)
379044eb2f6SDimitry Andric       SubReg.first->AllSuperRegsCovered = false;
380f8af5cf6SDimitry Andric 
38158b69754SDimitry Andric     // Ensure that every sub-register has a unique name.
38258b69754SDimitry Andric     DenseMap<const CodeGenRegister *, CodeGenSubRegIndex *>::iterator Ins =
383ac9a064cSDimitry Andric         SubReg2Idx.insert(std::pair(SubReg.second, SubReg.first)).first;
384044eb2f6SDimitry Andric     if (Ins->second == SubReg.first)
38558b69754SDimitry Andric       continue;
386044eb2f6SDimitry Andric     // Trouble: Two different names for SubReg.second.
387522600a2SDimitry Andric     ArrayRef<SMLoc> Loc;
38858b69754SDimitry Andric     if (TheDef)
38958b69754SDimitry Andric       Loc = TheDef->getLoc();
390ac9a064cSDimitry Andric     PrintFatalError(
391ac9a064cSDimitry Andric         Loc, "Sub-register can't have two names: " + SubReg.second->getName() +
392ac9a064cSDimitry Andric                  " available as " + SubReg.first->getName() + " and " +
393ac9a064cSDimitry Andric                  Ins->second->getName());
39458b69754SDimitry Andric   }
39558b69754SDimitry Andric 
39658b69754SDimitry Andric   // Derive possible names for sub-register concatenations from any explicit
39758b69754SDimitry Andric   // sub-registers. By doing this before computeSecondarySubRegs(), we ensure
39858b69754SDimitry Andric   // that getConcatSubRegIndex() won't invent any concatenated indices that the
39958b69754SDimitry Andric   // user already specified.
40058b69754SDimitry Andric   for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
40158b69754SDimitry Andric     CodeGenRegister *SR = ExplicitSubRegs[i];
402eb11fae6SDimitry Andric     if (!SR->CoveredBySubRegs || SR->ExplicitSubRegs.size() <= 1 ||
403eb11fae6SDimitry Andric         SR->Artificial)
40458b69754SDimitry Andric       continue;
40558b69754SDimitry Andric 
40658b69754SDimitry Andric     // SR is composed of multiple sub-regs. Find their names in this register.
40758b69754SDimitry Andric     SmallVector<CodeGenSubRegIndex *, 8> Parts;
408eb11fae6SDimitry Andric     for (unsigned j = 0, e = SR->ExplicitSubRegs.size(); j != e; ++j) {
409eb11fae6SDimitry Andric       CodeGenSubRegIndex &I = *SR->ExplicitSubRegIndices[j];
410eb11fae6SDimitry Andric       if (!I.Artificial)
41158b69754SDimitry Andric         Parts.push_back(getSubRegIndex(SR->ExplicitSubRegs[j]));
412eb11fae6SDimitry Andric     }
41358b69754SDimitry Andric 
41458b69754SDimitry Andric     // Offer this as an existing spelling for the concatenation of Parts.
415044eb2f6SDimitry Andric     CodeGenSubRegIndex &Idx = *ExplicitSubRegIndices[i];
416044eb2f6SDimitry Andric     Idx.setConcatenationOf(Parts);
41758b69754SDimitry Andric   }
41858b69754SDimitry Andric 
41958b69754SDimitry Andric   // Initialize RegUnitList. Because getSubRegs is called recursively, this
42058b69754SDimitry Andric   // processes the register hierarchy in postorder.
42163faed5bSDimitry Andric   //
42258b69754SDimitry Andric   // Inherit all sub-register units. It is good enough to look at the explicit
42358b69754SDimitry Andric   // sub-registers, the other registers won't contribute any more units.
42458b69754SDimitry Andric   for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
42558b69754SDimitry Andric     CodeGenRegister *SR = ExplicitSubRegs[i];
4265a5ac124SDimitry Andric     RegUnits |= SR->RegUnits;
42758b69754SDimitry Andric   }
42858b69754SDimitry Andric 
42958b69754SDimitry Andric   // Absent any ad hoc aliasing, we create one register unit per leaf register.
43058b69754SDimitry Andric   // These units correspond to the maximal cliques in the register overlap
43158b69754SDimitry Andric   // graph which is optimal.
43258b69754SDimitry Andric   //
43358b69754SDimitry Andric   // When there is ad hoc aliasing, we simply create one unit per edge in the
43458b69754SDimitry Andric   // undirected ad hoc aliasing graph. Technically, we could do better by
43558b69754SDimitry Andric   // identifying maximal cliques in the ad hoc graph, but cliques larger than 2
43658b69754SDimitry Andric   // are extremely rare anyway (I've never seen one), so we don't bother with
43758b69754SDimitry Andric   // the added complexity.
43858b69754SDimitry Andric   for (unsigned i = 0, e = ExplicitAliases.size(); i != e; ++i) {
43958b69754SDimitry Andric     CodeGenRegister *AR = ExplicitAliases[i];
44058b69754SDimitry Andric     // Only visit each edge once.
44158b69754SDimitry Andric     if (AR->SubRegsComplete)
44258b69754SDimitry Andric       continue;
44358b69754SDimitry Andric     // Create a RegUnit representing this alias edge, and add it to both
44458b69754SDimitry Andric     // registers.
44558b69754SDimitry Andric     unsigned Unit = RegBank.newRegUnit(this, AR);
4465a5ac124SDimitry Andric     RegUnits.set(Unit);
4475a5ac124SDimitry Andric     AR->RegUnits.set(Unit);
44858b69754SDimitry Andric   }
44958b69754SDimitry Andric 
45058b69754SDimitry Andric   // Finally, create units for leaf registers without ad hoc aliases. Note that
45158b69754SDimitry Andric   // a leaf register with ad hoc aliases doesn't get its own unit - it isn't
45258b69754SDimitry Andric   // necessary. This means the aliasing leaf registers can share a single unit.
45358b69754SDimitry Andric   if (RegUnits.empty())
4545a5ac124SDimitry Andric     RegUnits.set(RegBank.newRegUnit(this));
45558b69754SDimitry Andric 
45658b69754SDimitry Andric   // We have now computed the native register units. More may be adopted later
45758b69754SDimitry Andric   // for balancing purposes.
4585a5ac124SDimitry Andric   NativeRegUnits = RegUnits;
45958b69754SDimitry Andric 
46056fe8f14SDimitry Andric   return SubRegs;
46156fe8f14SDimitry Andric }
46256fe8f14SDimitry Andric 
46358b69754SDimitry Andric // In a register that is covered by its sub-registers, try to find redundant
46458b69754SDimitry Andric // sub-registers. For example:
46558b69754SDimitry Andric //
46658b69754SDimitry Andric //   QQ0 = {Q0, Q1}
46758b69754SDimitry Andric //   Q0 = {D0, D1}
46858b69754SDimitry Andric //   Q1 = {D2, D3}
46958b69754SDimitry Andric //
47058b69754SDimitry Andric // We can infer that D1_D2 is also a sub-register, even if it wasn't named in
47158b69754SDimitry Andric // the register definition.
47258b69754SDimitry Andric //
47358b69754SDimitry Andric // The explicitly specified registers form a tree. This function discovers
47458b69754SDimitry Andric // sub-register relationships that would force a DAG.
47558b69754SDimitry Andric //
computeSecondarySubRegs(CodeGenRegBank & RegBank)47658b69754SDimitry Andric void CodeGenRegister::computeSecondarySubRegs(CodeGenRegBank &RegBank) {
47758b69754SDimitry Andric   SmallVector<SubRegMap::value_type, 8> NewSubRegs;
47858b69754SDimitry Andric 
479044eb2f6SDimitry Andric   std::queue<std::pair<CodeGenSubRegIndex *, CodeGenRegister *>> SubRegQueue;
480044eb2f6SDimitry Andric   for (std::pair<CodeGenSubRegIndex *, CodeGenRegister *> P : SubRegs)
481044eb2f6SDimitry Andric     SubRegQueue.push(P);
482044eb2f6SDimitry Andric 
48358b69754SDimitry Andric   // Look at the leading super-registers of each sub-register. Those are the
48458b69754SDimitry Andric   // candidates for new sub-registers, assuming they are fully contained in
48558b69754SDimitry Andric   // this register.
486044eb2f6SDimitry Andric   while (!SubRegQueue.empty()) {
487044eb2f6SDimitry Andric     CodeGenSubRegIndex *SubRegIdx;
488044eb2f6SDimitry Andric     const CodeGenRegister *SubReg;
489044eb2f6SDimitry Andric     std::tie(SubRegIdx, SubReg) = SubRegQueue.front();
490044eb2f6SDimitry Andric     SubRegQueue.pop();
491044eb2f6SDimitry Andric 
49258b69754SDimitry Andric     const CodeGenRegister::SuperRegList &Leads = SubReg->LeadingSuperRegs;
49358b69754SDimitry Andric     for (unsigned i = 0, e = Leads.size(); i != e; ++i) {
49458b69754SDimitry Andric       CodeGenRegister *Cand = const_cast<CodeGenRegister *>(Leads[i]);
49558b69754SDimitry Andric       // Already got this sub-register?
49658b69754SDimitry Andric       if (Cand == this || getSubRegIndex(Cand))
49758b69754SDimitry Andric         continue;
49858b69754SDimitry Andric       // Check if each component of Cand is already a sub-register.
49958b69754SDimitry Andric       assert(!Cand->ExplicitSubRegs.empty() &&
50058b69754SDimitry Andric              "Super-register has no sub-registers");
501044eb2f6SDimitry Andric       if (Cand->ExplicitSubRegs.size() == 1)
502044eb2f6SDimitry Andric         continue;
503044eb2f6SDimitry Andric       SmallVector<CodeGenSubRegIndex *, 8> Parts;
504044eb2f6SDimitry Andric       // We know that the first component is (SubRegIdx,SubReg). However we
505044eb2f6SDimitry Andric       // may still need to split it into smaller subregister parts.
506044eb2f6SDimitry Andric       assert(Cand->ExplicitSubRegs[0] == SubReg && "LeadingSuperRegs correct");
507044eb2f6SDimitry Andric       assert(getSubRegIndex(SubReg) == SubRegIdx && "LeadingSuperRegs correct");
508044eb2f6SDimitry Andric       for (CodeGenRegister *SubReg : Cand->ExplicitSubRegs) {
509044eb2f6SDimitry Andric         if (CodeGenSubRegIndex *SubRegIdx = getSubRegIndex(SubReg)) {
510b60736ecSDimitry Andric           if (SubRegIdx->ConcatenationOf.empty())
511044eb2f6SDimitry Andric             Parts.push_back(SubRegIdx);
512b60736ecSDimitry Andric           else
513b60736ecSDimitry Andric             append_range(Parts, SubRegIdx->ConcatenationOf);
514044eb2f6SDimitry Andric         } else {
51558b69754SDimitry Andric           // Sub-register doesn't exist.
51658b69754SDimitry Andric           Parts.clear();
51758b69754SDimitry Andric           break;
51858b69754SDimitry Andric         }
51958b69754SDimitry Andric       }
520044eb2f6SDimitry Andric       // There is nothing to do if some Cand sub-register is not part of this
521044eb2f6SDimitry Andric       // register.
522044eb2f6SDimitry Andric       if (Parts.empty())
52358b69754SDimitry Andric         continue;
52458b69754SDimitry Andric 
52558b69754SDimitry Andric       // Each part of Cand is a sub-register of this. Make the full Cand also
52658b69754SDimitry Andric       // a sub-register with a concatenated sub-register index.
527ac9a064cSDimitry Andric       CodeGenSubRegIndex *Concat =
528ac9a064cSDimitry Andric           RegBank.getConcatSubRegIndex(Parts, RegBank.getHwModes());
529044eb2f6SDimitry Andric       std::pair<CodeGenSubRegIndex *, CodeGenRegister *> NewSubReg =
530ac9a064cSDimitry Andric           std::pair(Concat, Cand);
53158b69754SDimitry Andric 
532044eb2f6SDimitry Andric       if (!SubRegs.insert(NewSubReg).second)
53358b69754SDimitry Andric         continue;
53458b69754SDimitry Andric 
535044eb2f6SDimitry Andric       // We inserted a new subregister.
536044eb2f6SDimitry Andric       NewSubRegs.push_back(NewSubReg);
537044eb2f6SDimitry Andric       SubRegQueue.push(NewSubReg);
538ac9a064cSDimitry Andric       SubReg2Idx.insert(std::pair(Cand, Concat));
539044eb2f6SDimitry Andric     }
54058b69754SDimitry Andric   }
54158b69754SDimitry Andric 
54258b69754SDimitry Andric   // Create sub-register index composition maps for the synthesized indices.
54358b69754SDimitry Andric   for (unsigned i = 0, e = NewSubRegs.size(); i != e; ++i) {
54458b69754SDimitry Andric     CodeGenSubRegIndex *NewIdx = NewSubRegs[i].first;
54558b69754SDimitry Andric     CodeGenRegister *NewSubReg = NewSubRegs[i].second;
546344a3780SDimitry Andric     for (auto SubReg : NewSubReg->SubRegs) {
547344a3780SDimitry Andric       CodeGenSubRegIndex *SubIdx = getSubRegIndex(SubReg.second);
54858b69754SDimitry Andric       if (!SubIdx)
549522600a2SDimitry Andric         PrintFatalError(TheDef->getLoc(), "No SubRegIndex for " +
550344a3780SDimitry Andric                                               SubReg.second->getName() +
551344a3780SDimitry Andric                                               " in " + getName());
552ac9a064cSDimitry Andric       NewIdx->addComposite(SubReg.first, SubIdx, RegBank.getHwModes());
55358b69754SDimitry Andric     }
55458b69754SDimitry Andric   }
55558b69754SDimitry Andric }
55658b69754SDimitry Andric 
computeSuperRegs(CodeGenRegBank & RegBank)55758b69754SDimitry Andric void CodeGenRegister::computeSuperRegs(CodeGenRegBank &RegBank) {
55858b69754SDimitry Andric   // Only visit each register once.
55958b69754SDimitry Andric   if (SuperRegsComplete)
56058b69754SDimitry Andric     return;
56158b69754SDimitry Andric   SuperRegsComplete = true;
56258b69754SDimitry Andric 
56358b69754SDimitry Andric   // Make sure all sub-registers have been visited first, so the super-reg
56458b69754SDimitry Andric   // lists will be topologically ordered.
565344a3780SDimitry Andric   for (auto SubReg : SubRegs)
566344a3780SDimitry Andric     SubReg.second->computeSuperRegs(RegBank);
56758b69754SDimitry Andric 
56858b69754SDimitry Andric   // Now add this as a super-register on all sub-registers.
56958b69754SDimitry Andric   // Also compute the TopoSigId in post-order.
57058b69754SDimitry Andric   TopoSigId Id;
571344a3780SDimitry Andric   for (auto SubReg : SubRegs) {
57258b69754SDimitry Andric     // Topological signature computed from SubIdx, TopoId(SubReg).
57358b69754SDimitry Andric     // Loops and idempotent indices have TopoSig = ~0u.
574344a3780SDimitry Andric     Id.push_back(SubReg.first->EnumValue);
575344a3780SDimitry Andric     Id.push_back(SubReg.second->TopoSig);
57658b69754SDimitry Andric 
57758b69754SDimitry Andric     // Don't add duplicate entries.
578344a3780SDimitry Andric     if (!SubReg.second->SuperRegs.empty() &&
579344a3780SDimitry Andric         SubReg.second->SuperRegs.back() == this)
58058b69754SDimitry Andric       continue;
581344a3780SDimitry Andric     SubReg.second->SuperRegs.push_back(this);
58258b69754SDimitry Andric   }
58358b69754SDimitry Andric   TopoSig = RegBank.getTopoSig(Id);
58458b69754SDimitry Andric }
58558b69754SDimitry Andric 
addSubRegsPreOrder(SetVector<const CodeGenRegister * > & OSet,CodeGenRegBank & RegBank) const586ac9a064cSDimitry Andric void CodeGenRegister::addSubRegsPreOrder(
587ac9a064cSDimitry Andric     SetVector<const CodeGenRegister *> &OSet, CodeGenRegBank &RegBank) const {
588411bd29eSDimitry Andric   assert(SubRegsComplete && "Must precompute sub-registers");
58958b69754SDimitry Andric   for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
59058b69754SDimitry Andric     CodeGenRegister *SR = ExplicitSubRegs[i];
591411bd29eSDimitry Andric     if (OSet.insert(SR))
59263faed5bSDimitry Andric       SR->addSubRegsPreOrder(OSet, RegBank);
593411bd29eSDimitry Andric   }
59458b69754SDimitry Andric   // Add any secondary sub-registers that weren't part of the explicit tree.
595344a3780SDimitry Andric   for (auto SubReg : SubRegs)
596344a3780SDimitry Andric     OSet.insert(SubReg.second);
59758b69754SDimitry Andric }
59858b69754SDimitry Andric 
59963faed5bSDimitry Andric // Get the sum of this register's unit weights.
getWeight(const CodeGenRegBank & RegBank) const60063faed5bSDimitry Andric unsigned CodeGenRegister::getWeight(const CodeGenRegBank &RegBank) const {
60163faed5bSDimitry Andric   unsigned Weight = 0;
602344a3780SDimitry Andric   for (unsigned RegUnit : RegUnits) {
603344a3780SDimitry Andric     Weight += RegBank.getRegUnit(RegUnit).Weight;
60463faed5bSDimitry Andric   }
60563faed5bSDimitry Andric   return Weight;
60663faed5bSDimitry Andric }
60763faed5bSDimitry Andric 
608411bd29eSDimitry Andric //===----------------------------------------------------------------------===//
609411bd29eSDimitry Andric //                               RegisterTuples
610411bd29eSDimitry Andric //===----------------------------------------------------------------------===//
611411bd29eSDimitry Andric 
612411bd29eSDimitry Andric // A RegisterTuples def is used to generate pseudo-registers from lists of
613411bd29eSDimitry Andric // sub-registers. We provide a SetTheory expander class that returns the new
614411bd29eSDimitry Andric // registers.
615411bd29eSDimitry Andric namespace {
616b915e9e0SDimitry Andric 
617411bd29eSDimitry Andric struct TupleExpander : SetTheory::Expander {
618eb11fae6SDimitry Andric   // Reference to SynthDefs in the containing CodeGenRegBank, to keep track of
619eb11fae6SDimitry Andric   // the synthesized definitions for their lifetime.
620eb11fae6SDimitry Andric   std::vector<std::unique_ptr<Record>> &SynthDefs;
621eb11fae6SDimitry Andric 
622ac9a064cSDimitry Andric   // Track all synthesized tuple names in order to detect duplicate definitions.
623ac9a064cSDimitry Andric   llvm::StringSet<> TupleNames;
624ac9a064cSDimitry Andric 
TupleExpander__anone0b840950211::TupleExpander625eb11fae6SDimitry Andric   TupleExpander(std::vector<std::unique_ptr<Record>> &SynthDefs)
626eb11fae6SDimitry Andric       : SynthDefs(SynthDefs) {}
627eb11fae6SDimitry Andric 
expand__anone0b840950211::TupleExpander6285ca98fd9SDimitry Andric   void expand(SetTheory &ST, Record *Def, SetTheory::RecSet &Elts) override {
629411bd29eSDimitry Andric     std::vector<Record *> Indices = Def->getValueAsListOfDefs("SubRegIndices");
630411bd29eSDimitry Andric     unsigned Dim = Indices.size();
631411bd29eSDimitry Andric     ListInit *SubRegs = Def->getValueAsListInit("SubRegs");
63285d8b2bbSDimitry Andric     if (Dim != SubRegs->size())
633522600a2SDimitry Andric       PrintFatalError(Def->getLoc(), "SubRegIndices and SubRegs size mismatch");
634411bd29eSDimitry Andric     if (Dim < 2)
635522600a2SDimitry Andric       PrintFatalError(Def->getLoc(),
636522600a2SDimitry Andric                       "Tuples must have at least 2 sub-registers");
637411bd29eSDimitry Andric 
638411bd29eSDimitry Andric     // Evaluate the sub-register lists to be zipped.
639411bd29eSDimitry Andric     unsigned Length = ~0u;
640411bd29eSDimitry Andric     SmallVector<SetTheory::RecSet, 4> Lists(Dim);
641411bd29eSDimitry Andric     for (unsigned i = 0; i != Dim; ++i) {
642522600a2SDimitry Andric       ST.evaluate(SubRegs->getElement(i), Lists[i], Def->getLoc());
643411bd29eSDimitry Andric       Length = std::min(Length, unsigned(Lists[i].size()));
644411bd29eSDimitry Andric     }
645411bd29eSDimitry Andric 
646411bd29eSDimitry Andric     if (Length == 0)
647411bd29eSDimitry Andric       return;
648411bd29eSDimitry Andric 
649411bd29eSDimitry Andric     // Precompute some types.
650411bd29eSDimitry Andric     Record *RegisterCl = Def->getRecords().getClass("Register");
65130815c53SDimitry Andric     RecTy *RegisterRecTy = RecordRecTy::get(RegisterCl);
6521d5ae102SDimitry Andric     std::vector<StringRef> RegNames =
6531d5ae102SDimitry Andric         Def->getValueAsListOfStrings("RegAsmNames");
654411bd29eSDimitry Andric 
655411bd29eSDimitry Andric     // Zip them up.
656145449b1SDimitry Andric     RecordKeeper &RK = Def->getRecords();
657411bd29eSDimitry Andric     for (unsigned n = 0; n != Length; ++n) {
658411bd29eSDimitry Andric       std::string Name;
659411bd29eSDimitry Andric       Record *Proto = Lists[0][n];
660411bd29eSDimitry Andric       std::vector<Init *> Tuple;
661411bd29eSDimitry Andric       for (unsigned i = 0; i != Dim; ++i) {
662411bd29eSDimitry Andric         Record *Reg = Lists[i][n];
663ac9a064cSDimitry Andric         if (i)
664ac9a064cSDimitry Andric           Name += '_';
665411bd29eSDimitry Andric         Name += Reg->getName();
66630815c53SDimitry Andric         Tuple.push_back(DefInit::get(Reg));
667411bd29eSDimitry Andric       }
668411bd29eSDimitry Andric 
669344a3780SDimitry Andric       // Take the cost list of the first register in the tuple.
670344a3780SDimitry Andric       ListInit *CostList = Proto->getValueAsListInit("CostPerUse");
671344a3780SDimitry Andric       SmallVector<Init *, 2> CostPerUse;
672344a3780SDimitry Andric       CostPerUse.insert(CostPerUse.end(), CostList->begin(), CostList->end());
673344a3780SDimitry Andric 
674145449b1SDimitry Andric       StringInit *AsmName = StringInit::get(RK, "");
6751d5ae102SDimitry Andric       if (!RegNames.empty()) {
6761d5ae102SDimitry Andric         if (RegNames.size() <= n)
6771d5ae102SDimitry Andric           PrintFatalError(Def->getLoc(),
6781d5ae102SDimitry Andric                           "Register tuple definition missing name for '" +
6791d5ae102SDimitry Andric                               Name + "'.");
680145449b1SDimitry Andric         AsmName = StringInit::get(RK, RegNames[n]);
6811d5ae102SDimitry Andric       }
6821d5ae102SDimitry Andric 
683411bd29eSDimitry Andric       // Create a new Record representing the synthesized register. This record
684411bd29eSDimitry Andric       // is only for consumption by CodeGenRegister, it is not added to the
685411bd29eSDimitry Andric       // RecordKeeper.
686eb11fae6SDimitry Andric       SynthDefs.emplace_back(
6871d5ae102SDimitry Andric           std::make_unique<Record>(Name, Def->getLoc(), Def->getRecords()));
688eb11fae6SDimitry Andric       Record *NewReg = SynthDefs.back().get();
689411bd29eSDimitry Andric       Elts.insert(NewReg);
690411bd29eSDimitry Andric 
691ac9a064cSDimitry Andric       // Detect duplicates among synthesized registers.
692ac9a064cSDimitry Andric       const auto Res = TupleNames.insert(NewReg->getName());
693ac9a064cSDimitry Andric       if (!Res.second)
694ac9a064cSDimitry Andric         PrintFatalError(Def->getLoc(),
695ac9a064cSDimitry Andric                         "Register tuple redefines register '" + Name + "'.");
696ac9a064cSDimitry Andric 
697411bd29eSDimitry Andric       // Copy Proto super-classes.
69801095a5dSDimitry Andric       ArrayRef<std::pair<Record *, SMRange>> Supers = Proto->getSuperClasses();
69901095a5dSDimitry Andric       for (const auto &SuperPair : Supers)
70001095a5dSDimitry Andric         NewReg->addSuperClass(SuperPair.first, SuperPair.second);
701411bd29eSDimitry Andric 
702411bd29eSDimitry Andric       // Copy Proto fields.
703411bd29eSDimitry Andric       for (unsigned i = 0, e = Proto->getValues().size(); i != e; ++i) {
704411bd29eSDimitry Andric         RecordVal RV = Proto->getValues()[i];
705411bd29eSDimitry Andric 
70663faed5bSDimitry Andric         // Skip existing fields, like NAME.
70763faed5bSDimitry Andric         if (NewReg->getValue(RV.getNameInit()))
70863faed5bSDimitry Andric           continue;
70963faed5bSDimitry Andric 
71063faed5bSDimitry Andric         StringRef Field = RV.getName();
71163faed5bSDimitry Andric 
712411bd29eSDimitry Andric         // Replace the sub-register list with Tuple.
71363faed5bSDimitry Andric         if (Field == "SubRegs")
71430815c53SDimitry Andric           RV.setValue(ListInit::get(Tuple, RegisterRecTy));
715411bd29eSDimitry Andric 
71663faed5bSDimitry Andric         if (Field == "AsmName")
7171d5ae102SDimitry Andric           RV.setValue(AsmName);
718411bd29eSDimitry Andric 
719411bd29eSDimitry Andric         // CostPerUse is aggregated from all Tuple members.
72063faed5bSDimitry Andric         if (Field == "CostPerUse")
721344a3780SDimitry Andric           RV.setValue(ListInit::get(CostPerUse, CostList->getElementType()));
722411bd29eSDimitry Andric 
72363faed5bSDimitry Andric         // Composite registers are always covered by sub-registers.
72463faed5bSDimitry Andric         if (Field == "CoveredBySubRegs")
725145449b1SDimitry Andric           RV.setValue(BitInit::get(RK, true));
72663faed5bSDimitry Andric 
727411bd29eSDimitry Andric         // Copy fields from the RegisterTuples def.
728ac9a064cSDimitry Andric         if (Field == "SubRegIndices" || Field == "CompositeIndices") {
72963faed5bSDimitry Andric           NewReg->addValue(*Def->getValue(Field));
730411bd29eSDimitry Andric           continue;
731411bd29eSDimitry Andric         }
732411bd29eSDimitry Andric 
733411bd29eSDimitry Andric         // Some fields get their default uninitialized value.
734ac9a064cSDimitry Andric         if (Field == "DwarfNumbers" || Field == "DwarfAlias" ||
73563faed5bSDimitry Andric             Field == "Aliases") {
73663faed5bSDimitry Andric           if (const RecordVal *DefRV = RegisterCl->getValue(Field))
737411bd29eSDimitry Andric             NewReg->addValue(*DefRV);
738411bd29eSDimitry Andric           continue;
739411bd29eSDimitry Andric         }
740411bd29eSDimitry Andric 
741411bd29eSDimitry Andric         // Everything else is copied from Proto.
742411bd29eSDimitry Andric         NewReg->addValue(RV);
743411bd29eSDimitry Andric       }
744411bd29eSDimitry Andric     }
745411bd29eSDimitry Andric   }
746411bd29eSDimitry Andric };
747b915e9e0SDimitry Andric 
748b915e9e0SDimitry Andric } // end anonymous namespace
749411bd29eSDimitry Andric 
75056fe8f14SDimitry Andric //===----------------------------------------------------------------------===//
75156fe8f14SDimitry Andric //                            CodeGenRegisterClass
75256fe8f14SDimitry Andric //===----------------------------------------------------------------------===//
75356fe8f14SDimitry Andric 
sortAndUniqueRegisters(CodeGenRegister::Vec & M)7545a5ac124SDimitry Andric static void sortAndUniqueRegisters(CodeGenRegister::Vec &M) {
7551d5ae102SDimitry Andric   llvm::sort(M, deref<std::less<>>());
756ac9a064cSDimitry Andric   M.erase(llvm::unique(M, deref<std::equal_to<>>()), M.end());
7575a5ac124SDimitry Andric }
7585a5ac124SDimitry Andric 
CodeGenRegisterClass(CodeGenRegBank & RegBank,Record * R)759411bd29eSDimitry Andric CodeGenRegisterClass::CodeGenRegisterClass(CodeGenRegBank &RegBank, Record *R)
760cfca06d7SDimitry Andric     : TheDef(R), Name(std::string(R->getName())),
761c0981da4SDimitry Andric       TopoSigs(RegBank.getNumTopoSigs()), EnumValue(-1), TSFlags(0) {
762cfca06d7SDimitry Andric   GeneratePressureSet = R->getValueAsBit("GeneratePressureSet");
76356fe8f14SDimitry Andric   std::vector<Record *> TypeList = R->getValueAsListOfDefs("RegTypes");
764b60736ecSDimitry Andric   if (TypeList.empty())
765b60736ecSDimitry Andric     PrintFatalError(R->getLoc(), "RegTypes list must not be empty!");
76656fe8f14SDimitry Andric   for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
76756fe8f14SDimitry Andric     Record *Type = TypeList[i];
76856fe8f14SDimitry Andric     if (!Type->isSubClassOf("ValueType"))
769e6d15924SDimitry Andric       PrintFatalError(R->getLoc(),
770e6d15924SDimitry Andric                       "RegTypes list member '" + Type->getName() +
771522600a2SDimitry Andric                           "' does not derive from the ValueType class!");
772044eb2f6SDimitry Andric     VTs.push_back(getValueTypeByHwMode(Type, RegBank.getHwModes()));
77356fe8f14SDimitry Andric   }
77456fe8f14SDimitry Andric 
77530815c53SDimitry Andric   // Allocation order 0 is the full set. AltOrders provides others.
77630815c53SDimitry Andric   const SetTheory::RecVec *Elements = RegBank.getSets().expand(R);
77730815c53SDimitry Andric   ListInit *AltOrders = R->getValueAsListInit("AltOrders");
77885d8b2bbSDimitry Andric   Orders.resize(1 + AltOrders->size());
77930815c53SDimitry Andric 
780411bd29eSDimitry Andric   // Default allocation order always contains all registers.
781eb11fae6SDimitry Andric   Artificial = true;
78230815c53SDimitry Andric   for (unsigned i = 0, e = Elements->size(); i != e; ++i) {
78330815c53SDimitry Andric     Orders[0].push_back((*Elements)[i]);
78458b69754SDimitry Andric     const CodeGenRegister *Reg = RegBank.getReg((*Elements)[i]);
7855a5ac124SDimitry Andric     Members.push_back(Reg);
786eb11fae6SDimitry Andric     Artificial &= Reg->Artificial;
78758b69754SDimitry Andric     TopoSigs.set(Reg->getTopoSig());
78830815c53SDimitry Andric   }
7895a5ac124SDimitry Andric   sortAndUniqueRegisters(Members);
790411bd29eSDimitry Andric 
791411bd29eSDimitry Andric   // Alternative allocation orders may be subsets.
792411bd29eSDimitry Andric   SetTheory::RecSet Order;
79385d8b2bbSDimitry Andric   for (unsigned i = 0, e = AltOrders->size(); i != e; ++i) {
794522600a2SDimitry Andric     RegBank.getSets().evaluate(AltOrders->getElement(i), Order, R->getLoc());
79530815c53SDimitry Andric     Orders[1 + i].append(Order.begin(), Order.end());
796411bd29eSDimitry Andric     // Verify that all altorder members are regclass members.
797411bd29eSDimitry Andric     while (!Order.empty()) {
798411bd29eSDimitry Andric       CodeGenRegister *Reg = RegBank.getReg(Order.back());
799411bd29eSDimitry Andric       Order.pop_back();
800411bd29eSDimitry Andric       if (!contains(Reg))
801522600a2SDimitry Andric         PrintFatalError(R->getLoc(), " AltOrder register " + Reg->getName() +
802411bd29eSDimitry Andric                                          " is not a class member");
803411bd29eSDimitry Andric     }
80456fe8f14SDimitry Andric   }
80556fe8f14SDimitry Andric 
80656fe8f14SDimitry Andric   Namespace = R->getValueAsString("Namespace");
807044eb2f6SDimitry Andric 
808044eb2f6SDimitry Andric   if (const RecordVal *RV = R->getValue("RegInfos"))
809044eb2f6SDimitry Andric     if (DefInit *DI = dyn_cast_or_null<DefInit>(RV->getValue()))
810044eb2f6SDimitry Andric       RSI = RegSizeInfoByHwMode(DI->getDef(), RegBank.getHwModes());
811044eb2f6SDimitry Andric   unsigned Size = R->getValueAsInt("Size");
812044eb2f6SDimitry Andric   assert((RSI.hasDefault() || Size != 0 || VTs[0].isSimple()) &&
813044eb2f6SDimitry Andric          "Impossible to determine register size");
814044eb2f6SDimitry Andric   if (!RSI.hasDefault()) {
815044eb2f6SDimitry Andric     RegSizeInfo RI;
816ac9a064cSDimitry Andric     RI.RegSize = RI.SpillSize =
817ac9a064cSDimitry Andric         Size ? Size : VTs[0].getSimple().getSizeInBits();
818044eb2f6SDimitry Andric     RI.SpillAlignment = R->getValueAsInt("Alignment");
819344a3780SDimitry Andric     RSI.insertRegSizeForMode(DefaultMode, RI);
820044eb2f6SDimitry Andric   }
821044eb2f6SDimitry Andric 
82256fe8f14SDimitry Andric   CopyCost = R->getValueAsInt("CopyCost");
82356fe8f14SDimitry Andric   Allocatable = R->getValueAsBit("isAllocatable");
82463faed5bSDimitry Andric   AltOrderSelect = R->getValueAsString("AltOrderSelect");
8255a5ac124SDimitry Andric   int AllocationPriority = R->getValueAsInt("AllocationPriority");
826e3b55780SDimitry Andric   if (!isUInt<5>(AllocationPriority))
827e3b55780SDimitry Andric     PrintFatalError(R->getLoc(), "AllocationPriority out of range [0,31]");
8285a5ac124SDimitry Andric   this->AllocationPriority = AllocationPriority;
829c0981da4SDimitry Andric 
830e3b55780SDimitry Andric   GlobalPriority = R->getValueAsBit("GlobalPriority");
831e3b55780SDimitry Andric 
832c0981da4SDimitry Andric   BitsInit *TSF = R->getValueAsBitsInit("TSFlags");
833c0981da4SDimitry Andric   for (unsigned I = 0, E = TSF->getNumBits(); I != E; ++I) {
834c0981da4SDimitry Andric     BitInit *Bit = cast<BitInit>(TSF->getBit(I));
835c0981da4SDimitry Andric     TSFlags |= uint8_t(Bit->getValue()) << I;
836c0981da4SDimitry Andric   }
837411bd29eSDimitry Andric }
838411bd29eSDimitry Andric 
83930815c53SDimitry Andric // Create an inferred register class that was missing from the .td files.
84030815c53SDimitry Andric // Most properties will be inherited from the closest super-class after the
84130815c53SDimitry Andric // class structure has been computed.
CodeGenRegisterClass(CodeGenRegBank & RegBank,StringRef Name,Key Props)84258b69754SDimitry Andric CodeGenRegisterClass::CodeGenRegisterClass(CodeGenRegBank &RegBank,
84358b69754SDimitry Andric                                            StringRef Name, Key Props)
844cfca06d7SDimitry Andric     : Members(*Props.Members), TheDef(nullptr), Name(std::string(Name)),
845cfca06d7SDimitry Andric       TopoSigs(RegBank.getNumTopoSigs()), EnumValue(-1), RSI(Props.RSI),
846e3b55780SDimitry Andric       CopyCost(0), Allocatable(true), AllocationPriority(0),
847e3b55780SDimitry Andric       GlobalPriority(false), TSFlags(0) {
848eb11fae6SDimitry Andric   Artificial = true;
849cfca06d7SDimitry Andric   GeneratePressureSet = false;
850eb11fae6SDimitry Andric   for (const auto R : Members) {
8515a5ac124SDimitry Andric     TopoSigs.set(R->getTopoSig());
852eb11fae6SDimitry Andric     Artificial &= R->Artificial;
853eb11fae6SDimitry Andric   }
85430815c53SDimitry Andric }
85530815c53SDimitry Andric 
85630815c53SDimitry Andric // Compute inherited propertied for a synthesized register class.
inheritProperties(CodeGenRegBank & RegBank)85730815c53SDimitry Andric void CodeGenRegisterClass::inheritProperties(CodeGenRegBank &RegBank) {
85830815c53SDimitry Andric   assert(!getDef() && "Only synthesized classes can inherit properties");
85930815c53SDimitry Andric   assert(!SuperClasses.empty() && "Synthesized class without super class");
86030815c53SDimitry Andric 
86130815c53SDimitry Andric   // The last super-class is the smallest one.
86230815c53SDimitry Andric   CodeGenRegisterClass &Super = *SuperClasses.back();
86330815c53SDimitry Andric 
86430815c53SDimitry Andric   // Most properties are copied directly.
86530815c53SDimitry Andric   // Exceptions are members, size, and alignment
86630815c53SDimitry Andric   Namespace = Super.Namespace;
86730815c53SDimitry Andric   VTs = Super.VTs;
86830815c53SDimitry Andric   CopyCost = Super.CopyCost;
869344a3780SDimitry Andric   // Check for allocatable superclasses.
870344a3780SDimitry Andric   Allocatable = any_of(SuperClasses, [&](const CodeGenRegisterClass *S) {
871344a3780SDimitry Andric     return S->Allocatable;
872344a3780SDimitry Andric   });
87330815c53SDimitry Andric   AltOrderSelect = Super.AltOrderSelect;
8745a5ac124SDimitry Andric   AllocationPriority = Super.AllocationPriority;
875e3b55780SDimitry Andric   GlobalPriority = Super.GlobalPriority;
876c0981da4SDimitry Andric   TSFlags = Super.TSFlags;
877cfca06d7SDimitry Andric   GeneratePressureSet |= Super.GeneratePressureSet;
87830815c53SDimitry Andric 
87930815c53SDimitry Andric   // Copy all allocation orders, filter out foreign registers from the larger
88030815c53SDimitry Andric   // super-class.
88130815c53SDimitry Andric   Orders.resize(Super.Orders.size());
88230815c53SDimitry Andric   for (unsigned i = 0, ie = Super.Orders.size(); i != ie; ++i)
88330815c53SDimitry Andric     for (unsigned j = 0, je = Super.Orders[i].size(); j != je; ++j)
88430815c53SDimitry Andric       if (contains(RegBank.getReg(Super.Orders[i][j])))
88530815c53SDimitry Andric         Orders[i].push_back(Super.Orders[i][j]);
88630815c53SDimitry Andric }
88730815c53SDimitry Andric 
hasType(const ValueTypeByHwMode & VT) const8881f917f69SDimitry Andric bool CodeGenRegisterClass::hasType(const ValueTypeByHwMode &VT) const {
8891f917f69SDimitry Andric   if (llvm::is_contained(VTs, VT))
8901f917f69SDimitry Andric     return true;
8911f917f69SDimitry Andric 
8921f917f69SDimitry Andric   // If VT is not identical to any of this class's types, but is a simple
8931f917f69SDimitry Andric   // type, check if any of the types for this class contain it under some
8941f917f69SDimitry Andric   // mode.
8957fa27ce4SDimitry Andric   // The motivating example came from RISC-V, where (likely because of being
8961f917f69SDimitry Andric   // guarded by "64-bit" predicate), the type of X5 was {*:[i64]}, but the
8971f917f69SDimitry Andric   // type in GRC was {*:[i32], m1:[i64]}.
8981f917f69SDimitry Andric   if (VT.isSimple()) {
8991f917f69SDimitry Andric     MVT T = VT.getSimple();
9001f917f69SDimitry Andric     for (const ValueTypeByHwMode &OurVT : VTs) {
9011f917f69SDimitry Andric       if (llvm::count_if(OurVT, [T](auto &&P) { return P.second == T; }))
9021f917f69SDimitry Andric         return true;
9031f917f69SDimitry Andric     }
9041f917f69SDimitry Andric   }
9051f917f69SDimitry Andric   return false;
9061f917f69SDimitry Andric }
9071f917f69SDimitry Andric 
contains(const CodeGenRegister * Reg) const908411bd29eSDimitry Andric bool CodeGenRegisterClass::contains(const CodeGenRegister *Reg) const {
9095a5ac124SDimitry Andric   return std::binary_search(Members.begin(), Members.end(), Reg,
9101d5ae102SDimitry Andric                             deref<std::less<>>());
911411bd29eSDimitry Andric }
912411bd29eSDimitry Andric 
getWeight(const CodeGenRegBank & RegBank) const913cfca06d7SDimitry Andric unsigned CodeGenRegisterClass::getWeight(const CodeGenRegBank &RegBank) const {
914cfca06d7SDimitry Andric   if (TheDef && !TheDef->isValueUnset("Weight"))
915cfca06d7SDimitry Andric     return TheDef->getValueAsInt("Weight");
916cfca06d7SDimitry Andric 
917cfca06d7SDimitry Andric   if (Members.empty() || Artificial)
918cfca06d7SDimitry Andric     return 0;
919cfca06d7SDimitry Andric 
920cfca06d7SDimitry Andric   return (*Members.begin())->getWeight(RegBank);
921cfca06d7SDimitry Andric }
922cfca06d7SDimitry Andric 
92330815c53SDimitry Andric namespace llvm {
924b915e9e0SDimitry Andric 
operator <<(raw_ostream & OS,const CodeGenRegisterClass::Key & K)92530815c53SDimitry Andric raw_ostream &operator<<(raw_ostream &OS, const CodeGenRegisterClass::Key &K) {
926044eb2f6SDimitry Andric   OS << "{ " << K.RSI;
9275a5ac124SDimitry Andric   for (const auto R : *K.Members)
9285a5ac124SDimitry Andric     OS << ", " << R->getName();
92930815c53SDimitry Andric   return OS << " }";
93030815c53SDimitry Andric }
931b915e9e0SDimitry Andric 
932b915e9e0SDimitry Andric } // end namespace llvm
93330815c53SDimitry Andric 
93430815c53SDimitry Andric // This is a simple lexicographical order that can be used to search for sets.
93530815c53SDimitry Andric // It is not the same as the topological order provided by TopoOrderRC.
operator <(const CodeGenRegisterClass::Key & B) const936ac9a064cSDimitry Andric bool CodeGenRegisterClass::Key::operator<(
937ac9a064cSDimitry Andric     const CodeGenRegisterClass::Key &B) const {
93830815c53SDimitry Andric   assert(Members && B.Members);
939044eb2f6SDimitry Andric   return std::tie(*Members, RSI) < std::tie(*B.Members, B.RSI);
94030815c53SDimitry Andric }
94130815c53SDimitry Andric 
942411bd29eSDimitry Andric // Returns true if RC is a strict subclass.
943411bd29eSDimitry Andric // RC is a sub-class of this class if it is a valid replacement for any
944411bd29eSDimitry Andric // instruction operand where a register of this classis required. It must
945411bd29eSDimitry Andric // satisfy these conditions:
946411bd29eSDimitry Andric //
947411bd29eSDimitry Andric // 1. All RC registers are also in this.
948411bd29eSDimitry Andric // 2. The RC spill size must not be smaller than our spill size.
949411bd29eSDimitry Andric // 3. RC spill alignment must be compatible with ours.
950411bd29eSDimitry Andric //
testSubClass(const CodeGenRegisterClass * A,const CodeGenRegisterClass * B)95130815c53SDimitry Andric static bool testSubClass(const CodeGenRegisterClass *A,
95230815c53SDimitry Andric                          const CodeGenRegisterClass *B) {
953044eb2f6SDimitry Andric   return A->RSI.isSubClassOf(B->RSI) &&
95430815c53SDimitry Andric          std::includes(A->getMembers().begin(), A->getMembers().end(),
95530815c53SDimitry Andric                        B->getMembers().begin(), B->getMembers().end(),
9561d5ae102SDimitry Andric                        deref<std::less<>>());
95756fe8f14SDimitry Andric }
95856fe8f14SDimitry Andric 
95930815c53SDimitry Andric /// Sorting predicate for register classes.  This provides a topological
96030815c53SDimitry Andric /// ordering that arranges all register classes before their sub-classes.
96130815c53SDimitry Andric ///
96230815c53SDimitry Andric /// Register classes with the same registers, spill size, and alignment form a
96330815c53SDimitry Andric /// clique.  They will be ordered alphabetically.
96430815c53SDimitry Andric ///
TopoOrderRC(const CodeGenRegisterClass & PA,const CodeGenRegisterClass & PB)96567c32a98SDimitry Andric static bool TopoOrderRC(const CodeGenRegisterClass &PA,
96667c32a98SDimitry Andric                         const CodeGenRegisterClass &PB) {
96767c32a98SDimitry Andric   auto *A = &PA;
96867c32a98SDimitry Andric   auto *B = &PB;
96930815c53SDimitry Andric   if (A == B)
970b915e9e0SDimitry Andric     return false;
97130815c53SDimitry Andric 
972044eb2f6SDimitry Andric   if (A->RSI < B->RSI)
97367c32a98SDimitry Andric     return true;
974044eb2f6SDimitry Andric   if (A->RSI != B->RSI)
97567c32a98SDimitry Andric     return false;
97630815c53SDimitry Andric 
97758b69754SDimitry Andric   // Order by descending set size.  Note that the classes' allocation order may
97858b69754SDimitry Andric   // not have been computed yet.  The Members set is always vaild.
97958b69754SDimitry Andric   if (A->getMembers().size() > B->getMembers().size())
98067c32a98SDimitry Andric     return true;
98158b69754SDimitry Andric   if (A->getMembers().size() < B->getMembers().size())
98267c32a98SDimitry Andric     return false;
98358b69754SDimitry Andric 
98430815c53SDimitry Andric   // Finally order by name as a tie breaker.
98567c32a98SDimitry Andric   return StringRef(A->getName()) < B->getName();
98630815c53SDimitry Andric }
98730815c53SDimitry Andric 
getNamespaceQualification() const988b1c73532SDimitry Andric std::string CodeGenRegisterClass::getNamespaceQualification() const {
989b1c73532SDimitry Andric   return Namespace.empty() ? "" : (Namespace + "::").str();
990b1c73532SDimitry Andric }
991b1c73532SDimitry Andric 
getQualifiedName() const99230815c53SDimitry Andric std::string CodeGenRegisterClass::getQualifiedName() const {
993b1c73532SDimitry Andric   return getNamespaceQualification() + getName();
994b1c73532SDimitry Andric }
995b1c73532SDimitry Andric 
getIdName() const996b1c73532SDimitry Andric std::string CodeGenRegisterClass::getIdName() const {
997b1c73532SDimitry Andric   return getName() + "RegClassID";
998b1c73532SDimitry Andric }
999b1c73532SDimitry Andric 
getQualifiedIdName() const1000b1c73532SDimitry Andric std::string CodeGenRegisterClass::getQualifiedIdName() const {
1001b1c73532SDimitry Andric   return getNamespaceQualification() + getIdName();
100230815c53SDimitry Andric }
100330815c53SDimitry Andric 
100430815c53SDimitry Andric // Compute sub-classes of all register classes.
100530815c53SDimitry Andric // Assume the classes are ordered topologically.
computeSubClasses(CodeGenRegBank & RegBank)100630815c53SDimitry Andric void CodeGenRegisterClass::computeSubClasses(CodeGenRegBank &RegBank) {
100767c32a98SDimitry Andric   auto &RegClasses = RegBank.getRegClasses();
100830815c53SDimitry Andric 
100930815c53SDimitry Andric   // Visit backwards so sub-classes are seen first.
101067c32a98SDimitry Andric   for (auto I = RegClasses.rbegin(), E = RegClasses.rend(); I != E; ++I) {
101167c32a98SDimitry Andric     CodeGenRegisterClass &RC = *I;
101230815c53SDimitry Andric     RC.SubClasses.resize(RegClasses.size());
101330815c53SDimitry Andric     RC.SubClasses.set(RC.EnumValue);
1014eb11fae6SDimitry Andric     if (RC.Artificial)
1015eb11fae6SDimitry Andric       continue;
101630815c53SDimitry Andric 
101730815c53SDimitry Andric     // Normally, all subclasses have IDs >= rci, unless RC is part of a clique.
101867c32a98SDimitry Andric     for (auto I2 = I.base(), E2 = RegClasses.end(); I2 != E2; ++I2) {
101967c32a98SDimitry Andric       CodeGenRegisterClass &SubRC = *I2;
102067c32a98SDimitry Andric       if (RC.SubClasses.test(SubRC.EnumValue))
102130815c53SDimitry Andric         continue;
102267c32a98SDimitry Andric       if (!testSubClass(&RC, &SubRC))
102330815c53SDimitry Andric         continue;
102430815c53SDimitry Andric       // SubRC is a sub-class. Grap all its sub-classes so we won't have to
102530815c53SDimitry Andric       // check them again.
102667c32a98SDimitry Andric       RC.SubClasses |= SubRC.SubClasses;
102730815c53SDimitry Andric     }
102830815c53SDimitry Andric 
102958b69754SDimitry Andric     // Sweep up missed clique members.  They will be immediately preceding RC.
103067c32a98SDimitry Andric     for (auto I2 = std::next(I); I2 != E && testSubClass(&RC, &*I2); ++I2)
103167c32a98SDimitry Andric       RC.SubClasses.set(I2->EnumValue);
103230815c53SDimitry Andric   }
103330815c53SDimitry Andric 
103430815c53SDimitry Andric   // Compute the SuperClasses lists from the SubClasses vectors.
103567c32a98SDimitry Andric   for (auto &RC : RegClasses) {
103667c32a98SDimitry Andric     const BitVector &SC = RC.getSubClasses();
103767c32a98SDimitry Andric     auto I = RegClasses.begin();
103867c32a98SDimitry Andric     for (int s = 0, next_s = SC.find_first(); next_s != -1;
103967c32a98SDimitry Andric          next_s = SC.find_next(s)) {
104067c32a98SDimitry Andric       std::advance(I, next_s - s);
104167c32a98SDimitry Andric       s = next_s;
104267c32a98SDimitry Andric       if (&*I == &RC)
104330815c53SDimitry Andric         continue;
104467c32a98SDimitry Andric       I->SuperClasses.push_back(&RC);
104530815c53SDimitry Andric     }
104630815c53SDimitry Andric   }
104730815c53SDimitry Andric 
104830815c53SDimitry Andric   // With the class hierarchy in place, let synthesized register classes inherit
104930815c53SDimitry Andric   // properties from their closest super-class. The iteration order here can
105030815c53SDimitry Andric   // propagate properties down multiple levels.
105167c32a98SDimitry Andric   for (auto &RC : RegClasses)
105267c32a98SDimitry Andric     if (!RC.getDef())
105367c32a98SDimitry Andric       RC.inheritProperties(RegBank);
105456fe8f14SDimitry Andric }
105556fe8f14SDimitry Andric 
1056e3b55780SDimitry Andric std::optional<std::pair<CodeGenRegisterClass *, CodeGenRegisterClass *>>
getMatchingSubClassWithSubRegs(CodeGenRegBank & RegBank,const CodeGenSubRegIndex * SubIdx) const10579df3605dSDimitry Andric CodeGenRegisterClass::getMatchingSubClassWithSubRegs(
10589df3605dSDimitry Andric     CodeGenRegBank &RegBank, const CodeGenSubRegIndex *SubIdx) const {
1059b1c73532SDimitry Andric   auto WeakSizeOrder = [this](const CodeGenRegisterClass *A,
10609df3605dSDimitry Andric                               const CodeGenRegisterClass *B) {
1061cfca06d7SDimitry Andric     // If there are multiple, identical register classes, prefer the original
1062cfca06d7SDimitry Andric     // register class.
1063b60736ecSDimitry Andric     if (A == B)
1064b60736ecSDimitry Andric       return false;
1065cfca06d7SDimitry Andric     if (A->getMembers().size() == B->getMembers().size())
1066cfca06d7SDimitry Andric       return A == this;
10679df3605dSDimitry Andric     return A->getMembers().size() > B->getMembers().size();
10689df3605dSDimitry Andric   };
10699df3605dSDimitry Andric 
10709df3605dSDimitry Andric   auto &RegClasses = RegBank.getRegClasses();
10719df3605dSDimitry Andric 
10729df3605dSDimitry Andric   // Find all the subclasses of this one that fully support the sub-register
10739df3605dSDimitry Andric   // index and order them by size. BiggestSuperRC should always be first.
10749df3605dSDimitry Andric   CodeGenRegisterClass *BiggestSuperRegRC = getSubClassWithSubReg(SubIdx);
10759df3605dSDimitry Andric   if (!BiggestSuperRegRC)
1076e3b55780SDimitry Andric     return std::nullopt;
10779df3605dSDimitry Andric   BitVector SuperRegRCsBV = BiggestSuperRegRC->getSubClasses();
10789df3605dSDimitry Andric   std::vector<CodeGenRegisterClass *> SuperRegRCs;
10799df3605dSDimitry Andric   for (auto &RC : RegClasses)
10809df3605dSDimitry Andric     if (SuperRegRCsBV[RC.EnumValue])
10819df3605dSDimitry Andric       SuperRegRCs.emplace_back(&RC);
1082b1c73532SDimitry Andric   llvm::stable_sort(SuperRegRCs, WeakSizeOrder);
1083cfca06d7SDimitry Andric 
1084cfca06d7SDimitry Andric   assert(SuperRegRCs.front() == BiggestSuperRegRC &&
1085cfca06d7SDimitry Andric          "Biggest class wasn't first");
10869df3605dSDimitry Andric 
10879df3605dSDimitry Andric   // Find all the subreg classes and order them by size too.
10889df3605dSDimitry Andric   std::vector<std::pair<CodeGenRegisterClass *, BitVector>> SuperRegClasses;
10899df3605dSDimitry Andric   for (auto &RC : RegClasses) {
10909df3605dSDimitry Andric     BitVector SuperRegClassesBV(RegClasses.size());
10919df3605dSDimitry Andric     RC.getSuperRegClasses(SubIdx, SuperRegClassesBV);
10929df3605dSDimitry Andric     if (SuperRegClassesBV.any())
1093ac9a064cSDimitry Andric       SuperRegClasses.push_back(std::pair(&RC, SuperRegClassesBV));
10949df3605dSDimitry Andric   }
1095b1c73532SDimitry Andric   llvm::stable_sort(SuperRegClasses,
10969df3605dSDimitry Andric                     [&](const std::pair<CodeGenRegisterClass *, BitVector> &A,
10979df3605dSDimitry Andric                         const std::pair<CodeGenRegisterClass *, BitVector> &B) {
1098b1c73532SDimitry Andric                       return WeakSizeOrder(A.first, B.first);
10999df3605dSDimitry Andric                     });
11009df3605dSDimitry Andric 
11019df3605dSDimitry Andric   // Find the biggest subclass and subreg class such that R:subidx is in the
11029df3605dSDimitry Andric   // subreg class for all R in subclass.
11039df3605dSDimitry Andric   //
11049df3605dSDimitry Andric   // For example:
11059df3605dSDimitry Andric   // All registers in X86's GR64 have a sub_32bit subregister but no class
11069df3605dSDimitry Andric   // exists that contains all the 32-bit subregisters because GR64 contains RIP
11079df3605dSDimitry Andric   // but GR32 does not contain EIP. Instead, we constrain SuperRegRC to
11089df3605dSDimitry Andric   // GR32_with_sub_8bit (which is identical to GR32_with_sub_32bit) and then,
11099df3605dSDimitry Andric   // having excluded RIP, we are able to find a SubRegRC (GR32).
11109df3605dSDimitry Andric   CodeGenRegisterClass *ChosenSuperRegClass = nullptr;
11119df3605dSDimitry Andric   CodeGenRegisterClass *SubRegRC = nullptr;
11129df3605dSDimitry Andric   for (auto *SuperRegRC : SuperRegRCs) {
11139df3605dSDimitry Andric     for (const auto &SuperRegClassPair : SuperRegClasses) {
11149df3605dSDimitry Andric       const BitVector &SuperRegClassBV = SuperRegClassPair.second;
11159df3605dSDimitry Andric       if (SuperRegClassBV[SuperRegRC->EnumValue]) {
11169df3605dSDimitry Andric         SubRegRC = SuperRegClassPair.first;
11179df3605dSDimitry Andric         ChosenSuperRegClass = SuperRegRC;
11189df3605dSDimitry Andric 
11199df3605dSDimitry Andric         // If SubRegRC is bigger than SuperRegRC then there are members of
11209df3605dSDimitry Andric         // SubRegRC that don't have super registers via SubIdx. Keep looking to
11219df3605dSDimitry Andric         // find a better fit and fall back on this one if there isn't one.
11229df3605dSDimitry Andric         //
11239df3605dSDimitry Andric         // This is intended to prevent X86 from making odd choices such as
11249df3605dSDimitry Andric         // picking LOW32_ADDR_ACCESS_RBP instead of GR32 in the example above.
11259df3605dSDimitry Andric         // LOW32_ADDR_ACCESS_RBP is a valid choice but contains registers that
11269df3605dSDimitry Andric         // aren't subregisters of SuperRegRC whereas GR32 has a direct 1:1
11279df3605dSDimitry Andric         // mapping.
11289df3605dSDimitry Andric         if (SuperRegRC->getMembers().size() >= SubRegRC->getMembers().size())
1129ac9a064cSDimitry Andric           return std::pair(ChosenSuperRegClass, SubRegRC);
11309df3605dSDimitry Andric       }
11319df3605dSDimitry Andric     }
11329df3605dSDimitry Andric 
11339df3605dSDimitry Andric     // If we found a fit but it wasn't quite ideal because SubRegRC had excess
11349df3605dSDimitry Andric     // registers, then we're done.
11359df3605dSDimitry Andric     if (ChosenSuperRegClass)
1136ac9a064cSDimitry Andric       return std::pair(ChosenSuperRegClass, SubRegRC);
11379df3605dSDimitry Andric   }
11389df3605dSDimitry Andric 
1139e3b55780SDimitry Andric   return std::nullopt;
11409df3605dSDimitry Andric }
11419df3605dSDimitry Andric 
getSuperRegClasses(const CodeGenSubRegIndex * SubIdx,BitVector & Out) const114267c32a98SDimitry Andric void CodeGenRegisterClass::getSuperRegClasses(const CodeGenSubRegIndex *SubIdx,
114363faed5bSDimitry Andric                                               BitVector &Out) const {
114467c32a98SDimitry Andric   auto FindI = SuperRegClasses.find(SubIdx);
114563faed5bSDimitry Andric   if (FindI == SuperRegClasses.end())
114663faed5bSDimitry Andric     return;
114767c32a98SDimitry Andric   for (CodeGenRegisterClass *RC : FindI->second)
114867c32a98SDimitry Andric     Out.set(RC->EnumValue);
114963faed5bSDimitry Andric }
115063faed5bSDimitry Andric 
115163faed5bSDimitry Andric // Populate a unique sorted list of units from a register set.
buildRegUnitSet(const CodeGenRegBank & RegBank,std::vector<unsigned> & RegUnits) const1152ac9a064cSDimitry Andric void CodeGenRegisterClass::buildRegUnitSet(
1153ac9a064cSDimitry Andric     const CodeGenRegBank &RegBank, std::vector<unsigned> &RegUnits) const {
115463faed5bSDimitry Andric   std::vector<unsigned> TmpUnits;
1155eb11fae6SDimitry Andric   for (RegUnitIterator UnitI(Members); UnitI.isValid(); ++UnitI) {
1156eb11fae6SDimitry Andric     const RegUnit &RU = RegBank.getRegUnit(*UnitI);
1157eb11fae6SDimitry Andric     if (!RU.Artificial)
115863faed5bSDimitry Andric       TmpUnits.push_back(*UnitI);
1159eb11fae6SDimitry Andric   }
1160d8e91e46SDimitry Andric   llvm::sort(TmpUnits);
116163faed5bSDimitry Andric   std::unique_copy(TmpUnits.begin(), TmpUnits.end(),
116263faed5bSDimitry Andric                    std::back_inserter(RegUnits));
116363faed5bSDimitry Andric }
116463faed5bSDimitry Andric 
116556fe8f14SDimitry Andric //===----------------------------------------------------------------------===//
1166145449b1SDimitry Andric //                           CodeGenRegisterCategory
1167145449b1SDimitry Andric //===----------------------------------------------------------------------===//
1168145449b1SDimitry Andric 
CodeGenRegisterCategory(CodeGenRegBank & RegBank,Record * R)1169145449b1SDimitry Andric CodeGenRegisterCategory::CodeGenRegisterCategory(CodeGenRegBank &RegBank,
1170145449b1SDimitry Andric                                                  Record *R)
1171145449b1SDimitry Andric     : TheDef(R), Name(std::string(R->getName())) {
1172145449b1SDimitry Andric   for (Record *RegClass : R->getValueAsListOfDefs("Classes"))
1173145449b1SDimitry Andric     Classes.push_back(RegBank.getRegClass(RegClass));
1174145449b1SDimitry Andric }
1175145449b1SDimitry Andric 
1176145449b1SDimitry Andric //===----------------------------------------------------------------------===//
117756fe8f14SDimitry Andric //                               CodeGenRegBank
117856fe8f14SDimitry Andric //===----------------------------------------------------------------------===//
117956fe8f14SDimitry Andric 
CodeGenRegBank(RecordKeeper & Records,const CodeGenHwModes & Modes)1180044eb2f6SDimitry Andric CodeGenRegBank::CodeGenRegBank(RecordKeeper &Records,
1181ac9a064cSDimitry Andric                                const CodeGenHwModes &Modes)
1182ac9a064cSDimitry Andric     : CGH(Modes) {
1183411bd29eSDimitry Andric   // Configure register Sets to understand register classes and tuples.
1184411bd29eSDimitry Andric   Sets.addFieldExpander("RegisterClass", "MemberList");
118563faed5bSDimitry Andric   Sets.addFieldExpander("CalleeSavedRegs", "SaveList");
1186eb11fae6SDimitry Andric   Sets.addExpander("RegisterTuples",
11871d5ae102SDimitry Andric                    std::make_unique<TupleExpander>(SynthDefs));
1188411bd29eSDimitry Andric 
118956fe8f14SDimitry Andric   // Read in the user-defined (named) sub-register indices.
119056fe8f14SDimitry Andric   // More indices will be synthesized later.
119163faed5bSDimitry Andric   std::vector<Record *> SRIs = Records.getAllDerivedDefinitions("SubRegIndex");
1192d8e91e46SDimitry Andric   llvm::sort(SRIs, LessRecord());
119363faed5bSDimitry Andric   for (unsigned i = 0, e = SRIs.size(); i != e; ++i)
119463faed5bSDimitry Andric     getSubRegIdx(SRIs[i]);
119563faed5bSDimitry Andric   // Build composite maps from ComposedOf fields.
119667c32a98SDimitry Andric   for (auto &Idx : SubRegIndices)
119767c32a98SDimitry Andric     Idx.updateComponents(*this);
119856fe8f14SDimitry Andric 
1199b1c73532SDimitry Andric   // Read in the register and register tuple definitions.
120056fe8f14SDimitry Andric   std::vector<Record *> Regs = Records.getAllDerivedDefinitions("Register");
1201b1c73532SDimitry Andric   if (!Regs.empty() && Regs[0]->isSubClassOf("X86Reg")) {
1202b1c73532SDimitry Andric     // For X86, we need to sort Registers and RegisterTuples together to list
1203b1c73532SDimitry Andric     // new registers and register tuples at a later position. So that we can
1204b1c73532SDimitry Andric     // reduce unnecessary iterations on unsupported registers in LiveVariables.
1205b1c73532SDimitry Andric     // TODO: Remove this logic when migrate from LiveVariables to LiveIntervals
1206b1c73532SDimitry Andric     // completely.
1207b1c73532SDimitry Andric     std::vector<Record *> Tups =
1208b1c73532SDimitry Andric         Records.getAllDerivedDefinitions("RegisterTuples");
1209b1c73532SDimitry Andric     for (Record *R : Tups) {
1210b1c73532SDimitry Andric       // Expand tuples and merge the vectors
1211b1c73532SDimitry Andric       std::vector<Record *> TupRegs = *Sets.expand(R);
1212b1c73532SDimitry Andric       Regs.insert(Regs.end(), TupRegs.begin(), TupRegs.end());
1213b1c73532SDimitry Andric     }
1214b1c73532SDimitry Andric 
1215b1c73532SDimitry Andric     llvm::sort(Regs, LessRecordRegister());
1216b1c73532SDimitry Andric     // Assign the enumeration values.
1217b1c73532SDimitry Andric     for (unsigned i = 0, e = Regs.size(); i != e; ++i)
1218b1c73532SDimitry Andric       getReg(Regs[i]);
1219b1c73532SDimitry Andric   } else {
1220d8e91e46SDimitry Andric     llvm::sort(Regs, LessRecordRegister());
122156fe8f14SDimitry Andric     // Assign the enumeration values.
122256fe8f14SDimitry Andric     for (unsigned i = 0, e = Regs.size(); i != e; ++i)
1223411bd29eSDimitry Andric       getReg(Regs[i]);
1224411bd29eSDimitry Andric 
1225411bd29eSDimitry Andric     // Expand tuples and number the new registers.
1226411bd29eSDimitry Andric     std::vector<Record *> Tups =
1227411bd29eSDimitry Andric         Records.getAllDerivedDefinitions("RegisterTuples");
1228f8af5cf6SDimitry Andric 
122967c32a98SDimitry Andric     for (Record *R : Tups) {
123067c32a98SDimitry Andric       std::vector<Record *> TupRegs = *Sets.expand(R);
1231d8e91e46SDimitry Andric       llvm::sort(TupRegs, LessRecordRegister());
123267c32a98SDimitry Andric       for (Record *RC : TupRegs)
123367c32a98SDimitry Andric         getReg(RC);
1234411bd29eSDimitry Andric     }
1235b1c73532SDimitry Andric   }
1236411bd29eSDimitry Andric 
123758b69754SDimitry Andric   // Now all the registers are known. Build the object graph of explicit
123858b69754SDimitry Andric   // register-register references.
123967c32a98SDimitry Andric   for (auto &Reg : Registers)
124067c32a98SDimitry Andric     Reg.buildObjectGraph(*this);
124158b69754SDimitry Andric 
1242522600a2SDimitry Andric   // Compute register name map.
124367c32a98SDimitry Andric   for (auto &Reg : Registers)
124467c32a98SDimitry Andric     // FIXME: This could just be RegistersByName[name] = register, except that
124567c32a98SDimitry Andric     // causes some failures in MIPS - perhaps they have duplicate register name
124667c32a98SDimitry Andric     // entries? (or maybe there's a reason for it - I don't know much about this
124767c32a98SDimitry Andric     // code, just drive-by refactoring)
124867c32a98SDimitry Andric     RegistersByName.insert(
1249ac9a064cSDimitry Andric         std::pair(Reg.TheDef->getValueAsString("AsmName"), &Reg));
1250522600a2SDimitry Andric 
125158b69754SDimitry Andric   // Precompute all sub-register maps.
125258b69754SDimitry Andric   // This will create Composite entries for all inferred sub-register indices.
125367c32a98SDimitry Andric   for (auto &Reg : Registers)
125467c32a98SDimitry Andric     Reg.computeSubRegs(*this);
125558b69754SDimitry Andric 
1256044eb2f6SDimitry Andric   // Compute transitive closure of subregister index ConcatenationOf vectors
1257044eb2f6SDimitry Andric   // and initialize ConcatIdx map.
1258044eb2f6SDimitry Andric   for (CodeGenSubRegIndex &SRI : SubRegIndices) {
1259044eb2f6SDimitry Andric     SRI.computeConcatTransitiveClosure();
1260044eb2f6SDimitry Andric     if (!SRI.ConcatenationOf.empty())
1261ac9a064cSDimitry Andric       ConcatIdx.insert(
1262ac9a064cSDimitry Andric           std::pair(SmallVector<CodeGenSubRegIndex *, 8>(
1263ac9a064cSDimitry Andric                         SRI.ConcatenationOf.begin(), SRI.ConcatenationOf.end()),
1264ac9a064cSDimitry Andric                     &SRI));
1265044eb2f6SDimitry Andric   }
1266044eb2f6SDimitry Andric 
126758b69754SDimitry Andric   // Infer even more sub-registers by combining leading super-registers.
126867c32a98SDimitry Andric   for (auto &Reg : Registers)
126967c32a98SDimitry Andric     if (Reg.CoveredBySubRegs)
127067c32a98SDimitry Andric       Reg.computeSecondarySubRegs(*this);
127158b69754SDimitry Andric 
127258b69754SDimitry Andric   // After the sub-register graph is complete, compute the topologically
127358b69754SDimitry Andric   // ordered SuperRegs list.
127467c32a98SDimitry Andric   for (auto &Reg : Registers)
127567c32a98SDimitry Andric     Reg.computeSuperRegs(*this);
127630815c53SDimitry Andric 
1277eb11fae6SDimitry Andric   // For each pair of Reg:SR, if both are non-artificial, mark the
1278eb11fae6SDimitry Andric   // corresponding sub-register index as non-artificial.
1279eb11fae6SDimitry Andric   for (auto &Reg : Registers) {
1280eb11fae6SDimitry Andric     if (Reg.Artificial)
1281eb11fae6SDimitry Andric       continue;
1282eb11fae6SDimitry Andric     for (auto P : Reg.getSubRegs()) {
1283eb11fae6SDimitry Andric       const CodeGenRegister *SR = P.second;
1284eb11fae6SDimitry Andric       if (!SR->Artificial)
1285eb11fae6SDimitry Andric         P.first->Artificial = false;
1286eb11fae6SDimitry Andric     }
1287eb11fae6SDimitry Andric   }
1288eb11fae6SDimitry Andric 
128963faed5bSDimitry Andric   // Native register units are associated with a leaf register. They've all been
129063faed5bSDimitry Andric   // discovered now.
129158b69754SDimitry Andric   NumNativeRegUnits = RegUnits.size();
129263faed5bSDimitry Andric 
1293411bd29eSDimitry Andric   // Read in register class definitions.
1294411bd29eSDimitry Andric   std::vector<Record *> RCs = Records.getAllDerivedDefinitions("RegisterClass");
1295411bd29eSDimitry Andric   if (RCs.empty())
12965ca98fd9SDimitry Andric     PrintFatalError("No 'RegisterClass' subclasses defined!");
1297411bd29eSDimitry Andric 
129830815c53SDimitry Andric   // Allocate user-defined register classes.
1299eb11fae6SDimitry Andric   for (auto *R : RCs) {
1300eb11fae6SDimitry Andric     RegClasses.emplace_back(*this, R);
1301eb11fae6SDimitry Andric     CodeGenRegisterClass &RC = RegClasses.back();
1302eb11fae6SDimitry Andric     if (!RC.Artificial)
1303eb11fae6SDimitry Andric       addToMaps(&RC);
130467c32a98SDimitry Andric   }
130530815c53SDimitry Andric 
130630815c53SDimitry Andric   // Infer missing classes to create a full algebra.
130730815c53SDimitry Andric   computeInferredRegisterClasses();
130830815c53SDimitry Andric 
130930815c53SDimitry Andric   // Order register classes topologically and assign enum values.
131067c32a98SDimitry Andric   RegClasses.sort(TopoOrderRC);
131167c32a98SDimitry Andric   unsigned i = 0;
131267c32a98SDimitry Andric   for (auto &RC : RegClasses)
131367c32a98SDimitry Andric     RC.EnumValue = i++;
131430815c53SDimitry Andric   CodeGenRegisterClass::computeSubClasses(*this);
1315145449b1SDimitry Andric 
1316145449b1SDimitry Andric   // Read in the register category definitions.
1317145449b1SDimitry Andric   std::vector<Record *> RCats =
1318145449b1SDimitry Andric       Records.getAllDerivedDefinitions("RegisterCategory");
1319145449b1SDimitry Andric   for (auto *R : RCats)
1320145449b1SDimitry Andric     RegCategories.emplace_back(*this, R);
132156fe8f14SDimitry Andric }
132256fe8f14SDimitry Andric 
1323902a7b52SDimitry Andric // Create a synthetic CodeGenSubRegIndex without a corresponding Record.
createSubRegIndex(StringRef Name,StringRef Namespace)1324ac9a064cSDimitry Andric CodeGenSubRegIndex *CodeGenRegBank::createSubRegIndex(StringRef Name,
1325ac9a064cSDimitry Andric                                                       StringRef Namespace) {
132667c32a98SDimitry Andric   SubRegIndices.emplace_back(Name, Namespace, SubRegIndices.size() + 1);
132767c32a98SDimitry Andric   return &SubRegIndices.back();
1328902a7b52SDimitry Andric }
1329902a7b52SDimitry Andric 
getSubRegIdx(Record * Def)133063faed5bSDimitry Andric CodeGenSubRegIndex *CodeGenRegBank::getSubRegIdx(Record *Def) {
133163faed5bSDimitry Andric   CodeGenSubRegIndex *&Idx = Def2SubRegIdx[Def];
133263faed5bSDimitry Andric   if (Idx)
133363faed5bSDimitry Andric     return Idx;
1334ac9a064cSDimitry Andric   SubRegIndices.emplace_back(Def, SubRegIndices.size() + 1, getHwModes());
133567c32a98SDimitry Andric   Idx = &SubRegIndices.back();
133663faed5bSDimitry Andric   return Idx;
133763faed5bSDimitry Andric }
133863faed5bSDimitry Andric 
1339cfca06d7SDimitry Andric const CodeGenSubRegIndex *
findSubRegIdx(const Record * Def) const1340cfca06d7SDimitry Andric CodeGenRegBank::findSubRegIdx(const Record *Def) const {
1341b60736ecSDimitry Andric   return Def2SubRegIdx.lookup(Def);
1342cfca06d7SDimitry Andric }
1343cfca06d7SDimitry Andric 
getReg(Record * Def)134456fe8f14SDimitry Andric CodeGenRegister *CodeGenRegBank::getReg(Record *Def) {
1345411bd29eSDimitry Andric   CodeGenRegister *&Reg = Def2Reg[Def];
1346411bd29eSDimitry Andric   if (Reg)
134756fe8f14SDimitry Andric     return Reg;
134867c32a98SDimitry Andric   Registers.emplace_back(Def, Registers.size() + 1);
134967c32a98SDimitry Andric   Reg = &Registers.back();
1350411bd29eSDimitry Andric   return Reg;
1351411bd29eSDimitry Andric }
135256fe8f14SDimitry Andric 
addToMaps(CodeGenRegisterClass * RC)135330815c53SDimitry Andric void CodeGenRegBank::addToMaps(CodeGenRegisterClass *RC) {
135430815c53SDimitry Andric   if (Record *Def = RC->getDef())
1355ac9a064cSDimitry Andric     Def2RC.insert(std::pair(Def, RC));
135630815c53SDimitry Andric 
135730815c53SDimitry Andric   // Duplicate classes are rejected by insert().
135830815c53SDimitry Andric   // That's OK, we only care about the properties handled by CGRC::Key.
135930815c53SDimitry Andric   CodeGenRegisterClass::Key K(*RC);
1360ac9a064cSDimitry Andric   Key2RC.insert(std::pair(K, RC));
136130815c53SDimitry Andric }
136230815c53SDimitry Andric 
136363faed5bSDimitry Andric // Create a synthetic sub-class if it is missing.
136463faed5bSDimitry Andric CodeGenRegisterClass *
getOrCreateSubClass(const CodeGenRegisterClass * RC,const CodeGenRegister::Vec * Members,StringRef Name)136563faed5bSDimitry Andric CodeGenRegBank::getOrCreateSubClass(const CodeGenRegisterClass *RC,
13665a5ac124SDimitry Andric                                     const CodeGenRegister::Vec *Members,
136763faed5bSDimitry Andric                                     StringRef Name) {
136863faed5bSDimitry Andric   // Synthetic sub-class has the same size and alignment as RC.
1369044eb2f6SDimitry Andric   CodeGenRegisterClass::Key K(Members, RC->RSI);
137063faed5bSDimitry Andric   RCKeyMap::const_iterator FoundI = Key2RC.find(K);
137163faed5bSDimitry Andric   if (FoundI != Key2RC.end())
137263faed5bSDimitry Andric     return FoundI->second;
137363faed5bSDimitry Andric 
137463faed5bSDimitry Andric   // Sub-class doesn't exist, create a new one.
137585d8b2bbSDimitry Andric   RegClasses.emplace_back(*this, Name, K);
137667c32a98SDimitry Andric   addToMaps(&RegClasses.back());
137767c32a98SDimitry Andric   return &RegClasses.back();
137863faed5bSDimitry Andric }
137963faed5bSDimitry Andric 
getRegClass(const Record * Def) const1380cfca06d7SDimitry Andric CodeGenRegisterClass *CodeGenRegBank::getRegClass(const Record *Def) const {
1381cfca06d7SDimitry Andric   if (CodeGenRegisterClass *RC = Def2RC.lookup(Def))
1382411bd29eSDimitry Andric     return RC;
1383411bd29eSDimitry Andric 
1384522600a2SDimitry Andric   PrintFatalError(Def->getLoc(), "Not a known RegisterClass!");
138556fe8f14SDimitry Andric }
138656fe8f14SDimitry Andric 
138763faed5bSDimitry Andric CodeGenSubRegIndex *
getCompositeSubRegIndex(CodeGenSubRegIndex * A,CodeGenSubRegIndex * B)138863faed5bSDimitry Andric CodeGenRegBank::getCompositeSubRegIndex(CodeGenSubRegIndex *A,
138963faed5bSDimitry Andric                                         CodeGenSubRegIndex *B) {
139056fe8f14SDimitry Andric   // Look for an existing entry.
139163faed5bSDimitry Andric   CodeGenSubRegIndex *Comp = A->compose(B);
139263faed5bSDimitry Andric   if (Comp)
139356fe8f14SDimitry Andric     return Comp;
139456fe8f14SDimitry Andric 
139556fe8f14SDimitry Andric   // None exists, synthesize one.
139656fe8f14SDimitry Andric   std::string Name = A->getName() + "_then_" + B->getName();
1397902a7b52SDimitry Andric   Comp = createSubRegIndex(Name, A->getNamespace());
1398ac9a064cSDimitry Andric   A->addComposite(B, Comp, getHwModes());
139956fe8f14SDimitry Andric   return Comp;
140056fe8f14SDimitry Andric }
140156fe8f14SDimitry Andric 
getConcatSubRegIndex(const SmallVector<CodeGenSubRegIndex *,8> & Parts,const CodeGenHwModes & CGH)1402ac9a064cSDimitry Andric CodeGenSubRegIndex *CodeGenRegBank::getConcatSubRegIndex(
1403ac9a064cSDimitry Andric     const SmallVector<CodeGenSubRegIndex *, 8> &Parts,
1404ac9a064cSDimitry Andric     const CodeGenHwModes &CGH) {
140558b69754SDimitry Andric   assert(Parts.size() > 1 && "Need two parts to concatenate");
1406044eb2f6SDimitry Andric #ifndef NDEBUG
1407044eb2f6SDimitry Andric   for (CodeGenSubRegIndex *Idx : Parts) {
1408044eb2f6SDimitry Andric     assert(Idx->ConcatenationOf.empty() && "No transitive closure?");
1409044eb2f6SDimitry Andric   }
1410044eb2f6SDimitry Andric #endif
141158b69754SDimitry Andric 
141258b69754SDimitry Andric   // Look for an existing entry.
141358b69754SDimitry Andric   CodeGenSubRegIndex *&Idx = ConcatIdx[Parts];
141458b69754SDimitry Andric   if (Idx)
141558b69754SDimitry Andric     return Idx;
141658b69754SDimitry Andric 
141758b69754SDimitry Andric   // None exists, synthesize one.
141858b69754SDimitry Andric   std::string Name = Parts.front()->getName();
1419ac9a064cSDimitry Andric   const unsigned UnknownSize = (uint16_t)-1;
1420ac9a064cSDimitry Andric 
142158b69754SDimitry Andric   for (unsigned i = 1, e = Parts.size(); i != e; ++i) {
142258b69754SDimitry Andric     Name += '_';
142358b69754SDimitry Andric     Name += Parts[i]->getName();
1424ac9a064cSDimitry Andric   }
1425ac9a064cSDimitry Andric 
1426ac9a064cSDimitry Andric   Idx = createSubRegIndex(Name, Parts.front()->getNamespace());
1427ac9a064cSDimitry Andric   Idx->ConcatenationOf.assign(Parts.begin(), Parts.end());
1428ac9a064cSDimitry Andric 
1429ac9a064cSDimitry Andric   unsigned NumModes = CGH.getNumModeIds();
1430ac9a064cSDimitry Andric   for (unsigned M = 0; M < NumModes; ++M) {
1431ac9a064cSDimitry Andric     const CodeGenSubRegIndex *Part = Parts.front();
1432ac9a064cSDimitry Andric 
1433ac9a064cSDimitry Andric     // Determine whether all parts are contiguous.
1434ac9a064cSDimitry Andric     bool IsContinuous = true;
1435ac9a064cSDimitry Andric     const SubRegRange &FirstPartRange = Part->Range.get(M);
1436ac9a064cSDimitry Andric     unsigned Size = FirstPartRange.Size;
1437ac9a064cSDimitry Andric     unsigned LastOffset = FirstPartRange.Offset;
1438ac9a064cSDimitry Andric     unsigned LastSize = FirstPartRange.Size;
1439ac9a064cSDimitry Andric 
1440ac9a064cSDimitry Andric     for (unsigned i = 1, e = Parts.size(); i != e; ++i) {
1441ac9a064cSDimitry Andric       Part = Parts[i];
1442ac9a064cSDimitry Andric       Name += '_';
1443ac9a064cSDimitry Andric       Name += Part->getName();
1444ac9a064cSDimitry Andric 
1445ac9a064cSDimitry Andric       const SubRegRange &PartRange = Part->Range.get(M);
1446ac9a064cSDimitry Andric       if (Size == UnknownSize || PartRange.Size == UnknownSize)
1447e3b55780SDimitry Andric         Size = UnknownSize;
1448e3b55780SDimitry Andric       else
1449ac9a064cSDimitry Andric         Size += PartRange.Size;
1450ac9a064cSDimitry Andric       if (LastSize == UnknownSize ||
1451ac9a064cSDimitry Andric           PartRange.Offset != (LastOffset + LastSize))
1452ac9a064cSDimitry Andric         IsContinuous = false;
1453ac9a064cSDimitry Andric       LastOffset = PartRange.Offset;
1454ac9a064cSDimitry Andric       LastSize = PartRange.Size;
145558b69754SDimitry Andric     }
1456ac9a064cSDimitry Andric     unsigned Offset = IsContinuous ? FirstPartRange.Offset : -1;
1457ac9a064cSDimitry Andric     Idx->Range.get(M) = SubRegRange(Size, Offset);
1458ac9a064cSDimitry Andric   }
1459ac9a064cSDimitry Andric 
1460f8af5cf6SDimitry Andric   return Idx;
146158b69754SDimitry Andric }
146258b69754SDimitry Andric 
computeComposites()146356fe8f14SDimitry Andric void CodeGenRegBank::computeComposites() {
1464d8e91e46SDimitry Andric   using RegMap = std::map<const CodeGenRegister *, const CodeGenRegister *>;
1465d8e91e46SDimitry Andric 
1466d8e91e46SDimitry Andric   // Subreg -> { Reg->Reg }, where the right-hand side is the mapping from
1467d8e91e46SDimitry Andric   // register to (sub)register associated with the action of the left-hand
1468d8e91e46SDimitry Andric   // side subregister.
1469d8e91e46SDimitry Andric   std::map<const CodeGenSubRegIndex *, RegMap> SubRegAction;
1470d8e91e46SDimitry Andric   for (const CodeGenRegister &R : Registers) {
1471d8e91e46SDimitry Andric     const CodeGenRegister::SubRegMap &SM = R.getSubRegs();
1472d8e91e46SDimitry Andric     for (std::pair<const CodeGenSubRegIndex *, const CodeGenRegister *> P : SM)
1473d8e91e46SDimitry Andric       SubRegAction[P.first].insert({&R, P.second});
1474d8e91e46SDimitry Andric   }
1475d8e91e46SDimitry Andric 
1476d8e91e46SDimitry Andric   // Calculate the composition of two subregisters as compositions of their
1477d8e91e46SDimitry Andric   // associated actions.
1478d8e91e46SDimitry Andric   auto compose = [&SubRegAction](const CodeGenSubRegIndex *Sub1,
1479d8e91e46SDimitry Andric                                  const CodeGenSubRegIndex *Sub2) {
1480d8e91e46SDimitry Andric     RegMap C;
1481d8e91e46SDimitry Andric     const RegMap &Img1 = SubRegAction.at(Sub1);
1482d8e91e46SDimitry Andric     const RegMap &Img2 = SubRegAction.at(Sub2);
1483d8e91e46SDimitry Andric     for (std::pair<const CodeGenRegister *, const CodeGenRegister *> P : Img1) {
1484d8e91e46SDimitry Andric       auto F = Img2.find(P.second);
1485d8e91e46SDimitry Andric       if (F != Img2.end())
1486d8e91e46SDimitry Andric         C.insert({P.first, F->second});
1487d8e91e46SDimitry Andric     }
1488d8e91e46SDimitry Andric     return C;
1489d8e91e46SDimitry Andric   };
1490d8e91e46SDimitry Andric 
1491d8e91e46SDimitry Andric   // Check if the two maps agree on the intersection of their domains.
1492d8e91e46SDimitry Andric   auto agree = [](const RegMap &Map1, const RegMap &Map2) {
1493d8e91e46SDimitry Andric     // Technically speaking, an empty map agrees with any other map, but
1494d8e91e46SDimitry Andric     // this could flag false positives. We're interested in non-vacuous
1495d8e91e46SDimitry Andric     // agreements.
1496d8e91e46SDimitry Andric     if (Map1.empty() || Map2.empty())
1497d8e91e46SDimitry Andric       return false;
1498d8e91e46SDimitry Andric     for (std::pair<const CodeGenRegister *, const CodeGenRegister *> P : Map1) {
1499d8e91e46SDimitry Andric       auto F = Map2.find(P.first);
1500d8e91e46SDimitry Andric       if (F == Map2.end() || P.second != F->second)
1501d8e91e46SDimitry Andric         return false;
1502d8e91e46SDimitry Andric     }
1503d8e91e46SDimitry Andric     return true;
1504d8e91e46SDimitry Andric   };
1505d8e91e46SDimitry Andric 
1506ac9a064cSDimitry Andric   using CompositePair =
1507ac9a064cSDimitry Andric       std::pair<const CodeGenSubRegIndex *, const CodeGenSubRegIndex *>;
1508d8e91e46SDimitry Andric   SmallSet<CompositePair, 4> UserDefined;
1509d8e91e46SDimitry Andric   for (const CodeGenSubRegIndex &Idx : SubRegIndices)
1510d8e91e46SDimitry Andric     for (auto P : Idx.getComposites())
1511ac9a064cSDimitry Andric       UserDefined.insert(std::pair(&Idx, P.first));
1512d8e91e46SDimitry Andric 
151358b69754SDimitry Andric   // Keep track of TopoSigs visited. We only need to visit each TopoSig once,
151458b69754SDimitry Andric   // and many registers will share TopoSigs on regular architectures.
151558b69754SDimitry Andric   BitVector TopoSigs(getNumTopoSigs());
151658b69754SDimitry Andric 
151767c32a98SDimitry Andric   for (const auto &Reg1 : Registers) {
151858b69754SDimitry Andric     // Skip identical subreg structures already processed.
151967c32a98SDimitry Andric     if (TopoSigs.test(Reg1.getTopoSig()))
152058b69754SDimitry Andric       continue;
152167c32a98SDimitry Andric     TopoSigs.set(Reg1.getTopoSig());
152258b69754SDimitry Andric 
152367c32a98SDimitry Andric     const CodeGenRegister::SubRegMap &SRM1 = Reg1.getSubRegs();
1524344a3780SDimitry Andric     for (auto I1 : SRM1) {
1525344a3780SDimitry Andric       CodeGenSubRegIndex *Idx1 = I1.first;
1526344a3780SDimitry Andric       CodeGenRegister *Reg2 = I1.second;
152756fe8f14SDimitry Andric       // Ignore identity compositions.
152867c32a98SDimitry Andric       if (&Reg1 == Reg2)
152956fe8f14SDimitry Andric         continue;
1530411bd29eSDimitry Andric       const CodeGenRegister::SubRegMap &SRM2 = Reg2->getSubRegs();
153156fe8f14SDimitry Andric       // Try composing Idx1 with another SubRegIndex.
1532344a3780SDimitry Andric       for (auto I2 : SRM2) {
1533344a3780SDimitry Andric         CodeGenSubRegIndex *Idx2 = I2.first;
1534344a3780SDimitry Andric         CodeGenRegister *Reg3 = I2.second;
153556fe8f14SDimitry Andric         // Ignore identity compositions.
153656fe8f14SDimitry Andric         if (Reg2 == Reg3)
153756fe8f14SDimitry Andric           continue;
153856fe8f14SDimitry Andric         // OK Reg1:IdxPair == Reg3. Find the index with Reg:Idx == Reg3.
153967c32a98SDimitry Andric         CodeGenSubRegIndex *Idx3 = Reg1.getSubRegIndex(Reg3);
154058b69754SDimitry Andric         assert(Idx3 && "Sub-register doesn't have an index");
154158b69754SDimitry Andric 
154256fe8f14SDimitry Andric         // Conflicting composition? Emit a warning but allow it.
1543ac9a064cSDimitry Andric         if (CodeGenSubRegIndex *Prev =
1544ac9a064cSDimitry Andric                 Idx1->addComposite(Idx2, Idx3, getHwModes())) {
1545d8e91e46SDimitry Andric           // If the composition was not user-defined, always emit a warning.
1546d8e91e46SDimitry Andric           if (!UserDefined.count({Idx1, Idx2}) ||
1547d8e91e46SDimitry Andric               agree(compose(Idx1, Idx2), SubRegAction.at(Idx3)))
1548b61ab53cSDimitry Andric             PrintWarning(Twine("SubRegIndex ") + Idx1->getQualifiedName() +
1549b61ab53cSDimitry Andric                          " and " + Idx2->getQualifiedName() +
1550b61ab53cSDimitry Andric                          " compose ambiguously as " + Prev->getQualifiedName() +
155158b69754SDimitry Andric                          " or " + Idx3->getQualifiedName());
155256fe8f14SDimitry Andric         }
155356fe8f14SDimitry Andric       }
155456fe8f14SDimitry Andric     }
1555522600a2SDimitry Andric   }
1556d8e91e46SDimitry Andric }
155756fe8f14SDimitry Andric 
1558522600a2SDimitry Andric // Compute lane masks. This is similar to register units, but at the
1559522600a2SDimitry Andric // sub-register index level. Each bit in the lane mask is like a register unit
1560522600a2SDimitry Andric // class, and two lane masks will have a bit in common if two sub-register
1561522600a2SDimitry Andric // indices overlap in some register.
1562522600a2SDimitry Andric //
1563522600a2SDimitry Andric // Conservatively share a lane mask bit if two sub-register indices overlap in
1564522600a2SDimitry Andric // some registers, but not in others. That shouldn't happen a lot.
computeSubRegLaneMasks()156567c32a98SDimitry Andric void CodeGenRegBank::computeSubRegLaneMasks() {
1566522600a2SDimitry Andric   // First assign individual bits to all the leaf indices.
1567522600a2SDimitry Andric   unsigned Bit = 0;
1568f8af5cf6SDimitry Andric   // Determine mask of lanes that cover their registers.
1569b915e9e0SDimitry Andric   CoveringLanes = LaneBitmask::getAll();
157067c32a98SDimitry Andric   for (auto &Idx : SubRegIndices) {
157167c32a98SDimitry Andric     if (Idx.getComposites().empty()) {
157293c91e39SDimitry Andric       if (Bit > LaneBitmask::BitWidth) {
1573dd58ef01SDimitry Andric         PrintFatalError(
1574ac9a064cSDimitry Andric             Twine("Ran out of lanemask bits to represent subregister ") +
1575ac9a064cSDimitry Andric             Idx.getName());
1576dd58ef01SDimitry Andric       }
157793c91e39SDimitry Andric       Idx.LaneMask = LaneBitmask::getLane(Bit);
1578f8af5cf6SDimitry Andric       ++Bit;
1579522600a2SDimitry Andric     } else {
1580b915e9e0SDimitry Andric       Idx.LaneMask = LaneBitmask::getNone();
158167c32a98SDimitry Andric     }
158267c32a98SDimitry Andric   }
158367c32a98SDimitry Andric 
158467c32a98SDimitry Andric   // Compute transformation sequences for composeSubRegIndexLaneMask. The idea
158567c32a98SDimitry Andric   // here is that for each possible target subregister we look at the leafs
158667c32a98SDimitry Andric   // in the subregister graph that compose for this target and create
158767c32a98SDimitry Andric   // transformation sequences for the lanemasks. Each step in the sequence
158867c32a98SDimitry Andric   // consists of a bitmask and a bitrotate operation. As the rotation amounts
158967c32a98SDimitry Andric   // are usually the same for many subregisters we can easily combine the steps
159067c32a98SDimitry Andric   // by combining the masks.
159167c32a98SDimitry Andric   for (const auto &Idx : SubRegIndices) {
159267c32a98SDimitry Andric     const auto &Composites = Idx.getComposites();
159367c32a98SDimitry Andric     auto &LaneTransforms = Idx.CompositionLaneMaskTransform;
159401095a5dSDimitry Andric 
159501095a5dSDimitry Andric     if (Composites.empty()) {
159601095a5dSDimitry Andric       // Moving from a class with no subregisters we just had a single lane:
159701095a5dSDimitry Andric       // The subregister must be a leaf subregister and only occupies 1 bit.
159801095a5dSDimitry Andric       // Move the bit from the class without subregisters into that position.
1599044eb2f6SDimitry Andric       unsigned DstBit = Idx.LaneMask.getHighestLane();
160093c91e39SDimitry Andric       assert(Idx.LaneMask == LaneBitmask::getLane(DstBit) &&
1601b915e9e0SDimitry Andric              "Must be a leaf subregister");
160293c91e39SDimitry Andric       MaskRolPair MaskRol = {LaneBitmask::getLane(0), (uint8_t)DstBit};
160301095a5dSDimitry Andric       LaneTransforms.push_back(MaskRol);
160401095a5dSDimitry Andric     } else {
160501095a5dSDimitry Andric       // Go through all leaf subregisters and find the ones that compose with
160601095a5dSDimitry Andric       // Idx. These make out all possible valid bits in the lane mask we want to
160767c32a98SDimitry Andric       // transform. Looking only at the leafs ensure that only a single bit in
160867c32a98SDimitry Andric       // the mask is set.
160967c32a98SDimitry Andric       unsigned NextBit = 0;
161067c32a98SDimitry Andric       for (auto &Idx2 : SubRegIndices) {
161167c32a98SDimitry Andric         // Skip non-leaf subregisters.
161267c32a98SDimitry Andric         if (!Idx2.getComposites().empty())
161367c32a98SDimitry Andric           continue;
161467c32a98SDimitry Andric         // Replicate the behaviour from the lane mask generation loop above.
161567c32a98SDimitry Andric         unsigned SrcBit = NextBit;
161693c91e39SDimitry Andric         LaneBitmask SrcMask = LaneBitmask::getLane(SrcBit);
1617b915e9e0SDimitry Andric         if (NextBit < LaneBitmask::BitWidth - 1)
161867c32a98SDimitry Andric           ++NextBit;
161967c32a98SDimitry Andric         assert(Idx2.LaneMask == SrcMask);
162067c32a98SDimitry Andric 
162167c32a98SDimitry Andric         // Get the composed subregister if there is any.
162267c32a98SDimitry Andric         auto C = Composites.find(&Idx2);
162367c32a98SDimitry Andric         if (C == Composites.end())
162467c32a98SDimitry Andric           continue;
162567c32a98SDimitry Andric         const CodeGenSubRegIndex *Composite = C->second;
162667c32a98SDimitry Andric         // The Composed subreg should be a leaf subreg too
162767c32a98SDimitry Andric         assert(Composite->getComposites().empty());
162867c32a98SDimitry Andric 
162967c32a98SDimitry Andric         // Create Mask+Rotate operation and merge with existing ops if possible.
1630044eb2f6SDimitry Andric         unsigned DstBit = Composite->LaneMask.getHighestLane();
163167c32a98SDimitry Andric         int Shift = DstBit - SrcBit;
1632ac9a064cSDimitry Andric         uint8_t RotateLeft =
1633ac9a064cSDimitry Andric             Shift >= 0 ? (uint8_t)Shift : LaneBitmask::BitWidth + Shift;
163467c32a98SDimitry Andric         for (auto &I : LaneTransforms) {
163567c32a98SDimitry Andric           if (I.RotateLeft == RotateLeft) {
163667c32a98SDimitry Andric             I.Mask |= SrcMask;
1637b915e9e0SDimitry Andric             SrcMask = LaneBitmask::getNone();
163867c32a98SDimitry Andric           }
163967c32a98SDimitry Andric         }
1640b915e9e0SDimitry Andric         if (SrcMask.any()) {
164167c32a98SDimitry Andric           MaskRolPair MaskRol = {SrcMask, RotateLeft};
164267c32a98SDimitry Andric           LaneTransforms.push_back(MaskRol);
164367c32a98SDimitry Andric         }
164467c32a98SDimitry Andric       }
164501095a5dSDimitry Andric     }
164601095a5dSDimitry Andric 
164767c32a98SDimitry Andric     // Optimize if the transformation consists of one step only: Set mask to
164867c32a98SDimitry Andric     // 0xffffffff (including some irrelevant invalid bits) so that it should
164967c32a98SDimitry Andric     // merge with more entries later while compressing the table.
165067c32a98SDimitry Andric     if (LaneTransforms.size() == 1)
1651b915e9e0SDimitry Andric       LaneTransforms[0].Mask = LaneBitmask::getAll();
165267c32a98SDimitry Andric 
165367c32a98SDimitry Andric     // Further compression optimization: For invalid compositions resulting
165467c32a98SDimitry Andric     // in a sequence with 0 entries we can just pick any other. Choose
165567c32a98SDimitry Andric     // Mask 0xffffffff with Rotation 0.
165667c32a98SDimitry Andric     if (LaneTransforms.size() == 0) {
1657b915e9e0SDimitry Andric       MaskRolPair P = {LaneBitmask::getAll(), 0};
165867c32a98SDimitry Andric       LaneTransforms.push_back(P);
1659522600a2SDimitry Andric     }
1660522600a2SDimitry Andric   }
1661522600a2SDimitry Andric 
1662522600a2SDimitry Andric   // FIXME: What if ad-hoc aliasing introduces overlaps that aren't represented
1663522600a2SDimitry Andric   // by the sub-register graph? This doesn't occur in any known targets.
1664522600a2SDimitry Andric 
1665522600a2SDimitry Andric   // Inherit lanes from composites.
166667c32a98SDimitry Andric   for (const auto &Idx : SubRegIndices) {
1667b915e9e0SDimitry Andric     LaneBitmask Mask = Idx.computeLaneMask();
1668f8af5cf6SDimitry Andric     // If some super-registers without CoveredBySubRegs use this index, we can
1669f8af5cf6SDimitry Andric     // no longer assume that the lanes are covering their registers.
167067c32a98SDimitry Andric     if (!Idx.AllSuperRegsCovered)
1671f8af5cf6SDimitry Andric       CoveringLanes &= ~Mask;
1672f8af5cf6SDimitry Andric   }
167367c32a98SDimitry Andric 
167467c32a98SDimitry Andric   // Compute lane mask combinations for register classes.
167567c32a98SDimitry Andric   for (auto &RegClass : RegClasses) {
1676b915e9e0SDimitry Andric     LaneBitmask LaneMask;
167767c32a98SDimitry Andric     for (const auto &SubRegIndex : SubRegIndices) {
16785a5ac124SDimitry Andric       if (RegClass.getSubClassWithSubReg(&SubRegIndex) == nullptr)
167967c32a98SDimitry Andric         continue;
168067c32a98SDimitry Andric       LaneMask |= SubRegIndex.LaneMask;
168167c32a98SDimitry Andric     }
1682dd58ef01SDimitry Andric 
168301095a5dSDimitry Andric     // For classes without any subregisters set LaneMask to 1 instead of 0.
1684dd58ef01SDimitry Andric     // This makes it easier for client code to handle classes uniformly.
1685b915e9e0SDimitry Andric     if (LaneMask.none())
168693c91e39SDimitry Andric       LaneMask = LaneBitmask::getLane(0);
1687dd58ef01SDimitry Andric 
168867c32a98SDimitry Andric     RegClass.LaneMask = LaneMask;
168967c32a98SDimitry Andric   }
169063faed5bSDimitry Andric }
169163faed5bSDimitry Andric 
169263faed5bSDimitry Andric namespace {
1693b915e9e0SDimitry Andric 
169463faed5bSDimitry Andric // UberRegSet is a helper class for computeRegUnitWeights. Each UberRegSet is
169563faed5bSDimitry Andric // the transitive closure of the union of overlapping register
169663faed5bSDimitry Andric // classes. Together, the UberRegSets form a partition of the registers. If we
169763faed5bSDimitry Andric // consider overlapping register classes to be connected, then each UberRegSet
169863faed5bSDimitry Andric // is a set of connected components.
169963faed5bSDimitry Andric //
170063faed5bSDimitry Andric // An UberRegSet will likely be a horizontal slice of register names of
170163faed5bSDimitry Andric // the same width. Nontrivial subregisters should then be in a separate
170263faed5bSDimitry Andric // UberRegSet. But this property isn't required for valid computation of
170363faed5bSDimitry Andric // register unit weights.
170463faed5bSDimitry Andric //
170563faed5bSDimitry Andric // A Weight field caches the max per-register unit weight in each UberRegSet.
170663faed5bSDimitry Andric //
170763faed5bSDimitry Andric // A set of SingularDeterminants flags single units of some register in this set
170863faed5bSDimitry Andric // for which the unit weight equals the set weight. These units should not have
170963faed5bSDimitry Andric // their weight increased.
171063faed5bSDimitry Andric struct UberRegSet {
17115a5ac124SDimitry Andric   CodeGenRegister::Vec Regs;
1712b915e9e0SDimitry Andric   unsigned Weight = 0;
171363faed5bSDimitry Andric   CodeGenRegister::RegUnitList SingularDeterminants;
171463faed5bSDimitry Andric 
1715b915e9e0SDimitry Andric   UberRegSet() = default;
171663faed5bSDimitry Andric };
1717b915e9e0SDimitry Andric 
1718b915e9e0SDimitry Andric } // end anonymous namespace
171963faed5bSDimitry Andric 
172063faed5bSDimitry Andric // Partition registers into UberRegSets, where each set is the transitive
172163faed5bSDimitry Andric // closure of the union of overlapping register classes.
172263faed5bSDimitry Andric //
172363faed5bSDimitry Andric // UberRegSets[0] is a special non-allocatable set.
computeUberSets(std::vector<UberRegSet> & UberSets,std::vector<UberRegSet * > & RegSets,CodeGenRegBank & RegBank)172463faed5bSDimitry Andric static void computeUberSets(std::vector<UberRegSet> &UberSets,
172563faed5bSDimitry Andric                             std::vector<UberRegSet *> &RegSets,
172663faed5bSDimitry Andric                             CodeGenRegBank &RegBank) {
172767c32a98SDimitry Andric   const auto &Registers = RegBank.getRegisters();
172863faed5bSDimitry Andric 
172963faed5bSDimitry Andric   // The Register EnumValue is one greater than its index into Registers.
173067c32a98SDimitry Andric   assert(Registers.size() == Registers.back().EnumValue &&
173163faed5bSDimitry Andric          "register enum value mismatch");
173263faed5bSDimitry Andric 
173363faed5bSDimitry Andric   // For simplicitly make the SetID the same as EnumValue.
173463faed5bSDimitry Andric   IntEqClasses UberSetIDs(Registers.size() + 1);
17357fa27ce4SDimitry Andric   BitVector AllocatableRegs(Registers.size() + 1);
173667c32a98SDimitry Andric   for (auto &RegClass : RegBank.getRegClasses()) {
173767c32a98SDimitry Andric     if (!RegClass.Allocatable)
173863faed5bSDimitry Andric       continue;
173963faed5bSDimitry Andric 
17405a5ac124SDimitry Andric     const CodeGenRegister::Vec &Regs = RegClass.getMembers();
174163faed5bSDimitry Andric     if (Regs.empty())
174263faed5bSDimitry Andric       continue;
174363faed5bSDimitry Andric 
174463faed5bSDimitry Andric     unsigned USetID = UberSetIDs.findLeader((*Regs.begin())->EnumValue);
174563faed5bSDimitry Andric     assert(USetID && "register number 0 is invalid");
174663faed5bSDimitry Andric 
17477fa27ce4SDimitry Andric     AllocatableRegs.set((*Regs.begin())->EnumValue);
1748c0981da4SDimitry Andric     for (const CodeGenRegister *CGR : llvm::drop_begin(Regs)) {
17497fa27ce4SDimitry Andric       AllocatableRegs.set(CGR->EnumValue);
1750c0981da4SDimitry Andric       UberSetIDs.join(USetID, CGR->EnumValue);
175163faed5bSDimitry Andric     }
175263faed5bSDimitry Andric   }
175363faed5bSDimitry Andric   // Combine non-allocatable regs.
175467c32a98SDimitry Andric   for (const auto &Reg : Registers) {
175567c32a98SDimitry Andric     unsigned RegNum = Reg.EnumValue;
17567fa27ce4SDimitry Andric     if (AllocatableRegs.test(RegNum))
175763faed5bSDimitry Andric       continue;
175863faed5bSDimitry Andric 
175963faed5bSDimitry Andric     UberSetIDs.join(0, RegNum);
176063faed5bSDimitry Andric   }
176163faed5bSDimitry Andric   UberSetIDs.compress();
176263faed5bSDimitry Andric 
176363faed5bSDimitry Andric   // Make the first UberSet a special unallocatable set.
176463faed5bSDimitry Andric   unsigned ZeroID = UberSetIDs[0];
176563faed5bSDimitry Andric 
176663faed5bSDimitry Andric   // Insert Registers into the UberSets formed by union-find.
176763faed5bSDimitry Andric   // Do not resize after this.
176863faed5bSDimitry Andric   UberSets.resize(UberSetIDs.getNumClasses());
176967c32a98SDimitry Andric   unsigned i = 0;
177067c32a98SDimitry Andric   for (const CodeGenRegister &Reg : Registers) {
177167c32a98SDimitry Andric     unsigned USetID = UberSetIDs[Reg.EnumValue];
177263faed5bSDimitry Andric     if (!USetID)
177363faed5bSDimitry Andric       USetID = ZeroID;
177463faed5bSDimitry Andric     else if (USetID == ZeroID)
177563faed5bSDimitry Andric       USetID = 0;
177663faed5bSDimitry Andric 
177763faed5bSDimitry Andric     UberRegSet *USet = &UberSets[USetID];
17785a5ac124SDimitry Andric     USet->Regs.push_back(&Reg);
177967c32a98SDimitry Andric     RegSets[i++] = USet;
178063faed5bSDimitry Andric   }
178163faed5bSDimitry Andric }
178263faed5bSDimitry Andric 
178363faed5bSDimitry Andric // Recompute each UberSet weight after changing unit weights.
computeUberWeights(std::vector<UberRegSet> & UberSets,CodeGenRegBank & RegBank)178463faed5bSDimitry Andric static void computeUberWeights(std::vector<UberRegSet> &UberSets,
178563faed5bSDimitry Andric                                CodeGenRegBank &RegBank) {
178663faed5bSDimitry Andric   // Skip the first unallocatable set.
17875ca98fd9SDimitry Andric   for (std::vector<UberRegSet>::iterator I = std::next(UberSets.begin()),
1788ac9a064cSDimitry Andric                                          E = UberSets.end();
1789ac9a064cSDimitry Andric        I != E; ++I) {
179063faed5bSDimitry Andric 
179163faed5bSDimitry Andric     // Initialize all unit weights in this set, and remember the max units/reg.
17925ca98fd9SDimitry Andric     const CodeGenRegister *Reg = nullptr;
179363faed5bSDimitry Andric     unsigned MaxWeight = 0, Weight = 0;
179463faed5bSDimitry Andric     for (RegUnitIterator UnitI(I->Regs); UnitI.isValid(); ++UnitI) {
179563faed5bSDimitry Andric       if (Reg != UnitI.getReg()) {
179663faed5bSDimitry Andric         if (Weight > MaxWeight)
179763faed5bSDimitry Andric           MaxWeight = Weight;
179863faed5bSDimitry Andric         Reg = UnitI.getReg();
179963faed5bSDimitry Andric         Weight = 0;
180063faed5bSDimitry Andric       }
1801eb11fae6SDimitry Andric       if (!RegBank.getRegUnit(*UnitI).Artificial) {
180258b69754SDimitry Andric         unsigned UWeight = RegBank.getRegUnit(*UnitI).Weight;
180363faed5bSDimitry Andric         if (!UWeight) {
180463faed5bSDimitry Andric           UWeight = 1;
180563faed5bSDimitry Andric           RegBank.increaseRegUnitWeight(*UnitI, UWeight);
180663faed5bSDimitry Andric         }
180763faed5bSDimitry Andric         Weight += UWeight;
180863faed5bSDimitry Andric       }
1809eb11fae6SDimitry Andric     }
181063faed5bSDimitry Andric     if (Weight > MaxWeight)
181163faed5bSDimitry Andric       MaxWeight = Weight;
1812f8af5cf6SDimitry Andric     if (I->Weight != MaxWeight) {
1813eb11fae6SDimitry Andric       LLVM_DEBUG(dbgs() << "UberSet " << I - UberSets.begin() << " Weight "
1814eb11fae6SDimitry Andric                         << MaxWeight;
1815eb11fae6SDimitry Andric                  for (auto &Unit
1816eb11fae6SDimitry Andric                       : I->Regs) dbgs()
1817eb11fae6SDimitry Andric                  << " " << Unit->getName();
1818f8af5cf6SDimitry Andric                  dbgs() << "\n");
181963faed5bSDimitry Andric       // Update the set weight.
182063faed5bSDimitry Andric       I->Weight = MaxWeight;
1821f8af5cf6SDimitry Andric     }
182263faed5bSDimitry Andric 
182363faed5bSDimitry Andric     // Find singular determinants.
18245a5ac124SDimitry Andric     for (const auto R : I->Regs) {
18255a5ac124SDimitry Andric       if (R->getRegUnits().count() == 1 && R->getWeight(RegBank) == I->Weight) {
18265a5ac124SDimitry Andric         I->SingularDeterminants |= R->getRegUnits();
18275a5ac124SDimitry Andric       }
182863faed5bSDimitry Andric     }
182963faed5bSDimitry Andric   }
183063faed5bSDimitry Andric }
183163faed5bSDimitry Andric 
183263faed5bSDimitry Andric // normalizeWeight is a computeRegUnitWeights helper that adjusts the weight of
183363faed5bSDimitry Andric // a register and its subregisters so that they have the same weight as their
183463faed5bSDimitry Andric // UberSet. Self-recursion processes the subregister tree in postorder so
183563faed5bSDimitry Andric // subregisters are normalized first.
183663faed5bSDimitry Andric //
183763faed5bSDimitry Andric // Side effects:
183863faed5bSDimitry Andric // - creates new adopted register units
183963faed5bSDimitry Andric // - causes superregisters to inherit adopted units
184063faed5bSDimitry Andric // - increases the weight of "singular" units
184163faed5bSDimitry Andric // - induces recomputation of UberWeights.
normalizeWeight(CodeGenRegister * Reg,std::vector<UberRegSet> & UberSets,std::vector<UberRegSet * > & RegSets,BitVector & NormalRegs,CodeGenRegister::RegUnitList & NormalUnits,CodeGenRegBank & RegBank)184263faed5bSDimitry Andric static bool normalizeWeight(CodeGenRegister *Reg,
184363faed5bSDimitry Andric                             std::vector<UberRegSet> &UberSets,
184463faed5bSDimitry Andric                             std::vector<UberRegSet *> &RegSets,
1845eb11fae6SDimitry Andric                             BitVector &NormalRegs,
184663faed5bSDimitry Andric                             CodeGenRegister::RegUnitList &NormalUnits,
184763faed5bSDimitry Andric                             CodeGenRegBank &RegBank) {
1848eb11fae6SDimitry Andric   NormalRegs.resize(std::max(Reg->EnumValue + 1, NormalRegs.size()));
18495a5ac124SDimitry Andric   if (NormalRegs.test(Reg->EnumValue))
18505a5ac124SDimitry Andric     return false;
18515a5ac124SDimitry Andric   NormalRegs.set(Reg->EnumValue);
185258b69754SDimitry Andric 
18535a5ac124SDimitry Andric   bool Changed = false;
185463faed5bSDimitry Andric   const CodeGenRegister::SubRegMap &SRM = Reg->getSubRegs();
1855344a3780SDimitry Andric   for (auto SRI : SRM) {
1856344a3780SDimitry Andric     if (SRI.second == Reg)
185763faed5bSDimitry Andric       continue; // self-cycles happen
185863faed5bSDimitry Andric 
1859344a3780SDimitry Andric     Changed |= normalizeWeight(SRI.second, UberSets, RegSets, NormalRegs,
1860344a3780SDimitry Andric                                NormalUnits, RegBank);
186163faed5bSDimitry Andric   }
186263faed5bSDimitry Andric   // Postorder register normalization.
186363faed5bSDimitry Andric 
186463faed5bSDimitry Andric   // Inherit register units newly adopted by subregisters.
186563faed5bSDimitry Andric   if (Reg->inheritRegUnits(RegBank))
186663faed5bSDimitry Andric     computeUberWeights(UberSets, RegBank);
186763faed5bSDimitry Andric 
186863faed5bSDimitry Andric   // Check if this register is too skinny for its UberRegSet.
186963faed5bSDimitry Andric   UberRegSet *UberSet = RegSets[RegBank.getRegIndex(Reg)];
187063faed5bSDimitry Andric 
187163faed5bSDimitry Andric   unsigned RegWeight = Reg->getWeight(RegBank);
187263faed5bSDimitry Andric   if (UberSet->Weight > RegWeight) {
187363faed5bSDimitry Andric     // A register unit's weight can be adjusted only if it is the singular unit
187463faed5bSDimitry Andric     // for this register, has not been used to normalize a subregister's set,
187563faed5bSDimitry Andric     // and has not already been used to singularly determine this UberRegSet.
18765a5ac124SDimitry Andric     unsigned AdjustUnit = *Reg->getRegUnits().begin();
1877ac9a064cSDimitry Andric     if (Reg->getRegUnits().count() != 1 || NormalUnits.test(AdjustUnit) ||
1878ac9a064cSDimitry Andric         UberSet->SingularDeterminants.test(AdjustUnit)) {
187963faed5bSDimitry Andric       // We don't have an adjustable unit, so adopt a new one.
188063faed5bSDimitry Andric       AdjustUnit = RegBank.newRegUnit(UberSet->Weight - RegWeight);
188163faed5bSDimitry Andric       Reg->adoptRegUnit(AdjustUnit);
188263faed5bSDimitry Andric       // Adopting a unit does not immediately require recomputing set weights.
1883ac9a064cSDimitry Andric     } else {
188463faed5bSDimitry Andric       // Adjust the existing single unit.
1885eb11fae6SDimitry Andric       if (!RegBank.getRegUnit(AdjustUnit).Artificial)
188663faed5bSDimitry Andric         RegBank.increaseRegUnitWeight(AdjustUnit, UberSet->Weight - RegWeight);
188763faed5bSDimitry Andric       // The unit may be shared among sets and registers within this set.
188863faed5bSDimitry Andric       computeUberWeights(UberSets, RegBank);
188963faed5bSDimitry Andric     }
189063faed5bSDimitry Andric     Changed = true;
189163faed5bSDimitry Andric   }
189263faed5bSDimitry Andric 
189363faed5bSDimitry Andric   // Mark these units normalized so superregisters can't change their weights.
18945a5ac124SDimitry Andric   NormalUnits |= Reg->getRegUnits();
189563faed5bSDimitry Andric 
189663faed5bSDimitry Andric   return Changed;
189763faed5bSDimitry Andric }
189863faed5bSDimitry Andric 
189963faed5bSDimitry Andric // Compute a weight for each register unit created during getSubRegs.
190063faed5bSDimitry Andric //
190163faed5bSDimitry Andric // The goal is that two registers in the same class will have the same weight,
190263faed5bSDimitry Andric // where each register's weight is defined as sum of its units' weights.
computeRegUnitWeights()190363faed5bSDimitry Andric void CodeGenRegBank::computeRegUnitWeights() {
190463faed5bSDimitry Andric   std::vector<UberRegSet> UberSets;
190563faed5bSDimitry Andric   std::vector<UberRegSet *> RegSets(Registers.size());
190663faed5bSDimitry Andric   computeUberSets(UberSets, RegSets, *this);
190763faed5bSDimitry Andric   // UberSets and RegSets are now immutable.
190863faed5bSDimitry Andric 
190963faed5bSDimitry Andric   computeUberWeights(UberSets, *this);
191063faed5bSDimitry Andric 
191163faed5bSDimitry Andric   // Iterate over each Register, normalizing the unit weights until reaching
191263faed5bSDimitry Andric   // a fix point.
191363faed5bSDimitry Andric   unsigned NumIters = 0;
191463faed5bSDimitry Andric   for (bool Changed = true; Changed; ++NumIters) {
191563faed5bSDimitry Andric     assert(NumIters <= NumNativeRegUnits && "Runaway register unit weights");
1916145449b1SDimitry Andric     (void)NumIters;
191763faed5bSDimitry Andric     Changed = false;
191867c32a98SDimitry Andric     for (auto &Reg : Registers) {
191963faed5bSDimitry Andric       CodeGenRegister::RegUnitList NormalUnits;
1920eb11fae6SDimitry Andric       BitVector NormalRegs;
192167c32a98SDimitry Andric       Changed |= normalizeWeight(&Reg, UberSets, RegSets, NormalRegs,
192267c32a98SDimitry Andric                                  NormalUnits, *this);
192363faed5bSDimitry Andric     }
192463faed5bSDimitry Andric   }
192563faed5bSDimitry Andric }
192663faed5bSDimitry Andric 
192763faed5bSDimitry Andric // Find a set in UniqueSets with the same elements as Set.
192863faed5bSDimitry Andric // Return an iterator into UniqueSets.
192963faed5bSDimitry Andric static std::vector<RegUnitSet>::const_iterator
findRegUnitSet(const std::vector<RegUnitSet> & UniqueSets,const RegUnitSet & Set)193063faed5bSDimitry Andric findRegUnitSet(const std::vector<RegUnitSet> &UniqueSets,
193163faed5bSDimitry Andric                const RegUnitSet &Set) {
1932ac9a064cSDimitry Andric   return find_if(UniqueSets,
1933ac9a064cSDimitry Andric                  [&Set](const RegUnitSet &I) { return I.Units == Set.Units; });
193463faed5bSDimitry Andric }
193563faed5bSDimitry Andric 
193663faed5bSDimitry Andric // Return true if the RUSubSet is a subset of RUSuperSet.
isRegUnitSubSet(const std::vector<unsigned> & RUSubSet,const std::vector<unsigned> & RUSuperSet)193763faed5bSDimitry Andric static bool isRegUnitSubSet(const std::vector<unsigned> &RUSubSet,
193863faed5bSDimitry Andric                             const std::vector<unsigned> &RUSuperSet) {
1939ac9a064cSDimitry Andric   return std::includes(RUSuperSet.begin(), RUSuperSet.end(), RUSubSet.begin(),
1940ac9a064cSDimitry Andric                        RUSubSet.end());
194163faed5bSDimitry Andric }
194263faed5bSDimitry Andric 
1943f8af5cf6SDimitry Andric /// Iteratively prune unit sets. Prune subsets that are close to the superset,
1944f8af5cf6SDimitry Andric /// but with one or two registers removed. We occasionally have registers like
1945f8af5cf6SDimitry Andric /// APSR and PC thrown in with the general registers. We also see many
1946f8af5cf6SDimitry Andric /// special-purpose register subsets, such as tail-call and Thumb
1947f8af5cf6SDimitry Andric /// encodings. Generating all possible overlapping sets is combinatorial and
1948f8af5cf6SDimitry Andric /// overkill for modeling pressure. Ideally we could fix this statically in
1949f8af5cf6SDimitry Andric /// tablegen by (1) having the target define register classes that only include
1950f8af5cf6SDimitry Andric /// the allocatable registers and marking other classes as non-allocatable and
1951f8af5cf6SDimitry Andric /// (2) having a way to mark special purpose classes as "don't-care" classes for
1952f8af5cf6SDimitry Andric /// the purpose of pressure.  However, we make an attempt to handle targets that
1953f8af5cf6SDimitry Andric /// are not nicely defined by merging nearly identical register unit sets
1954f8af5cf6SDimitry Andric /// statically. This generates smaller tables. Then, dynamically, we adjust the
1955f8af5cf6SDimitry Andric /// set limit by filtering the reserved registers.
1956f8af5cf6SDimitry Andric ///
1957f8af5cf6SDimitry Andric /// Merge sets only if the units have the same weight. For example, on ARM,
1958f8af5cf6SDimitry Andric /// Q-tuples with ssub index 0 include all S regs but also include D16+. We
1959f8af5cf6SDimitry Andric /// should not expand the S set to include D regs.
pruneUnitSets()196063faed5bSDimitry Andric void CodeGenRegBank::pruneUnitSets() {
196163faed5bSDimitry Andric   assert(RegClassUnitSets.empty() && "this invalidates RegClassUnitSets");
196263faed5bSDimitry Andric 
196363faed5bSDimitry Andric   // Form an equivalence class of UnitSets with no significant difference.
196463faed5bSDimitry Andric   std::vector<unsigned> SuperSetIDs;
1965ac9a064cSDimitry Andric   for (unsigned SubIdx = 0, EndIdx = RegUnitSets.size(); SubIdx != EndIdx;
1966ac9a064cSDimitry Andric        ++SubIdx) {
196763faed5bSDimitry Andric     const RegUnitSet &SubSet = RegUnitSets[SubIdx];
196863faed5bSDimitry Andric     unsigned SuperIdx = 0;
196963faed5bSDimitry Andric     for (; SuperIdx != EndIdx; ++SuperIdx) {
197063faed5bSDimitry Andric       if (SuperIdx == SubIdx)
197163faed5bSDimitry Andric         continue;
197263faed5bSDimitry Andric 
1973f8af5cf6SDimitry Andric       unsigned UnitWeight = RegUnits[SubSet.Units[0]].Weight;
197463faed5bSDimitry Andric       const RegUnitSet &SuperSet = RegUnitSets[SuperIdx];
1975ac9a064cSDimitry Andric       if (isRegUnitSubSet(SubSet.Units, SuperSet.Units) &&
1976ac9a064cSDimitry Andric           (SubSet.Units.size() + 3 > SuperSet.Units.size()) &&
1977ac9a064cSDimitry Andric           UnitWeight == RegUnits[SuperSet.Units[0]].Weight &&
1978ac9a064cSDimitry Andric           UnitWeight == RegUnits[SuperSet.Units.back()].Weight) {
1979eb11fae6SDimitry Andric         LLVM_DEBUG(dbgs() << "UnitSet " << SubIdx << " subsumed by " << SuperIdx
1980f8af5cf6SDimitry Andric                           << "\n");
1981dd58ef01SDimitry Andric         // We can pick any of the set names for the merged set. Go for the
1982dd58ef01SDimitry Andric         // shortest one to avoid picking the name of one of the classes that are
1983dd58ef01SDimitry Andric         // artificially created by tablegen. So "FPR128_lo" instead of
1984dd58ef01SDimitry Andric         // "QQQQ_with_qsub3_in_FPR128_lo".
1985dd58ef01SDimitry Andric         if (RegUnitSets[SubIdx].Name.size() < RegUnitSets[SuperIdx].Name.size())
1986dd58ef01SDimitry Andric           RegUnitSets[SuperIdx].Name = RegUnitSets[SubIdx].Name;
198763faed5bSDimitry Andric         break;
198863faed5bSDimitry Andric       }
198963faed5bSDimitry Andric     }
199063faed5bSDimitry Andric     if (SuperIdx == EndIdx)
199163faed5bSDimitry Andric       SuperSetIDs.push_back(SubIdx);
199263faed5bSDimitry Andric   }
199363faed5bSDimitry Andric   // Populate PrunedUnitSets with each equivalence class's superset.
1994ac9a064cSDimitry Andric   std::vector<RegUnitSet> PrunedUnitSets;
1995ac9a064cSDimitry Andric   PrunedUnitSets.reserve(SuperSetIDs.size());
199663faed5bSDimitry Andric   for (unsigned i = 0, e = SuperSetIDs.size(); i != e; ++i) {
199763faed5bSDimitry Andric     unsigned SuperIdx = SuperSetIDs[i];
1998ac9a064cSDimitry Andric     PrunedUnitSets.emplace_back(RegUnitSets[SuperIdx].Name);
1999ac9a064cSDimitry Andric     PrunedUnitSets.back().Units = std::move(RegUnitSets[SuperIdx].Units);
200063faed5bSDimitry Andric   }
2001ac9a064cSDimitry Andric   RegUnitSets = std::move(PrunedUnitSets);
200263faed5bSDimitry Andric }
200363faed5bSDimitry Andric 
200463faed5bSDimitry Andric // Create a RegUnitSet for each RegClass that contains all units in the class
200563faed5bSDimitry Andric // including adopted units that are necessary to model register pressure. Then
200663faed5bSDimitry Andric // iteratively compute RegUnitSets such that the union of any two overlapping
200763faed5bSDimitry Andric // RegUnitSets is repreresented.
200863faed5bSDimitry Andric //
200963faed5bSDimitry Andric // RegisterInfoEmitter will map each RegClass to its RegUnitClass and any
201063faed5bSDimitry Andric // RegUnitSet that is a superset of that RegUnitClass.
computeRegUnitSets()201163faed5bSDimitry Andric void CodeGenRegBank::computeRegUnitSets() {
2012f8af5cf6SDimitry Andric   assert(RegUnitSets.empty() && "dirty RegUnitSets");
201363faed5bSDimitry Andric 
201463faed5bSDimitry Andric   // Compute a unique RegUnitSet for each RegClass.
201567c32a98SDimitry Andric   auto &RegClasses = getRegClasses();
201667c32a98SDimitry Andric   for (auto &RC : RegClasses) {
2017cfca06d7SDimitry Andric     if (!RC.Allocatable || RC.Artificial || !RC.GeneratePressureSet)
201863faed5bSDimitry Andric       continue;
201963faed5bSDimitry Andric 
202063faed5bSDimitry Andric     // Compute a sorted list of units in this class.
2021ac9a064cSDimitry Andric     RegUnitSet RUSet(RC.getName());
2022ac9a064cSDimitry Andric     RC.buildRegUnitSet(*this, RUSet.Units);
202363faed5bSDimitry Andric 
202463faed5bSDimitry Andric     // Find an existing RegUnitSet.
2025ac9a064cSDimitry Andric     if (findRegUnitSet(RegUnitSets, RUSet) == RegUnitSets.end())
2026ac9a064cSDimitry Andric       RegUnitSets.push_back(std::move(RUSet));
202763faed5bSDimitry Andric   }
202863faed5bSDimitry Andric 
2029c0981da4SDimitry Andric   if (RegUnitSets.empty())
2030c0981da4SDimitry Andric     PrintFatalError("RegUnitSets cannot be empty!");
2031c0981da4SDimitry Andric 
2032eb11fae6SDimitry Andric   LLVM_DEBUG(dbgs() << "\nBefore pruning:\n"; for (unsigned USIdx = 0,
2033eb11fae6SDimitry Andric                                                    USEnd = RegUnitSets.size();
2034f8af5cf6SDimitry Andric                                                    USIdx < USEnd; ++USIdx) {
2035eb11fae6SDimitry Andric     dbgs() << "UnitSet " << USIdx << " " << RegUnitSets[USIdx].Name << ":";
203667c32a98SDimitry Andric     for (auto &U : RegUnitSets[USIdx].Units)
203771d5a254SDimitry Andric       printRegUnitName(U);
2038f8af5cf6SDimitry Andric     dbgs() << "\n";
2039f8af5cf6SDimitry Andric   });
2040f8af5cf6SDimitry Andric 
204163faed5bSDimitry Andric   // Iteratively prune unit sets.
204263faed5bSDimitry Andric   pruneUnitSets();
204363faed5bSDimitry Andric 
2044eb11fae6SDimitry Andric   LLVM_DEBUG(dbgs() << "\nBefore union:\n"; for (unsigned USIdx = 0,
2045eb11fae6SDimitry Andric                                                  USEnd = RegUnitSets.size();
2046f8af5cf6SDimitry Andric                                                  USIdx < USEnd; ++USIdx) {
2047eb11fae6SDimitry Andric     dbgs() << "UnitSet " << USIdx << " " << RegUnitSets[USIdx].Name << ":";
204867c32a98SDimitry Andric     for (auto &U : RegUnitSets[USIdx].Units)
204971d5a254SDimitry Andric       printRegUnitName(U);
2050f8af5cf6SDimitry Andric     dbgs() << "\n";
2051eb11fae6SDimitry Andric   } dbgs() << "\nUnion sets:\n");
2052f8af5cf6SDimitry Andric 
205363faed5bSDimitry Andric   // Iterate over all unit sets, including new ones added by this loop.
205463faed5bSDimitry Andric   unsigned NumRegUnitSubSets = RegUnitSets.size();
205563faed5bSDimitry Andric   for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx) {
205663faed5bSDimitry Andric     // In theory, this is combinatorial. In practice, it needs to be bounded
205763faed5bSDimitry Andric     // by a small number of sets for regpressure to be efficient.
205863faed5bSDimitry Andric     // If the assert is hit, we need to implement pruning.
205963faed5bSDimitry Andric     assert(Idx < (2 * NumRegUnitSubSets) && "runaway unit set inference");
206063faed5bSDimitry Andric 
206163faed5bSDimitry Andric     // Compare new sets with all original classes.
206263faed5bSDimitry Andric     for (unsigned SearchIdx = (Idx >= NumRegUnitSubSets) ? 0 : Idx + 1;
206363faed5bSDimitry Andric          SearchIdx != EndIdx; ++SearchIdx) {
2064ac9a064cSDimitry Andric       std::vector<unsigned> Intersection;
2065ac9a064cSDimitry Andric       std::set_intersection(
2066ac9a064cSDimitry Andric           RegUnitSets[Idx].Units.begin(), RegUnitSets[Idx].Units.end(),
206763faed5bSDimitry Andric           RegUnitSets[SearchIdx].Units.begin(),
2068ac9a064cSDimitry Andric           RegUnitSets[SearchIdx].Units.end(), std::back_inserter(Intersection));
206963faed5bSDimitry Andric       if (Intersection.empty())
207063faed5bSDimitry Andric         continue;
207163faed5bSDimitry Andric 
2072ac9a064cSDimitry Andric       RegUnitSet RUSet(RegUnitSets[Idx].Name + "_with_" +
2073ac9a064cSDimitry Andric                        RegUnitSets[SearchIdx].Name);
207463faed5bSDimitry Andric       std::set_union(RegUnitSets[Idx].Units.begin(),
207563faed5bSDimitry Andric                      RegUnitSets[Idx].Units.end(),
207663faed5bSDimitry Andric                      RegUnitSets[SearchIdx].Units.begin(),
207763faed5bSDimitry Andric                      RegUnitSets[SearchIdx].Units.end(),
2078ac9a064cSDimitry Andric                      std::inserter(RUSet.Units, RUSet.Units.begin()));
207963faed5bSDimitry Andric 
208063faed5bSDimitry Andric       // Find an existing RegUnitSet, or add the union to the unique sets.
2081ac9a064cSDimitry Andric       if (findRegUnitSet(RegUnitSets, RUSet) == RegUnitSets.end()) {
2082ac9a064cSDimitry Andric         LLVM_DEBUG(dbgs() << "UnitSet " << RegUnitSets.size() << " "
2083ac9a064cSDimitry Andric                           << RUSet.Name << ":";
2084eb11fae6SDimitry Andric                    for (auto &U
2085ac9a064cSDimitry Andric                         : RUSet.Units) printRegUnitName(U);
2086f8af5cf6SDimitry Andric                    dbgs() << "\n";);
2087ac9a064cSDimitry Andric         RegUnitSets.push_back(std::move(RUSet));
2088f8af5cf6SDimitry Andric       }
208963faed5bSDimitry Andric     }
209063faed5bSDimitry Andric   }
209163faed5bSDimitry Andric 
209263faed5bSDimitry Andric   // Iteratively prune unit sets after inferring supersets.
209363faed5bSDimitry Andric   pruneUnitSets();
209463faed5bSDimitry Andric 
2095eb11fae6SDimitry Andric   LLVM_DEBUG(
2096eb11fae6SDimitry Andric       dbgs() << "\n"; for (unsigned USIdx = 0, USEnd = RegUnitSets.size();
2097f8af5cf6SDimitry Andric                            USIdx < USEnd; ++USIdx) {
2098eb11fae6SDimitry Andric         dbgs() << "UnitSet " << USIdx << " " << RegUnitSets[USIdx].Name << ":";
209967c32a98SDimitry Andric         for (auto &U : RegUnitSets[USIdx].Units)
210071d5a254SDimitry Andric           printRegUnitName(U);
2101f8af5cf6SDimitry Andric         dbgs() << "\n";
2102f8af5cf6SDimitry Andric       });
2103f8af5cf6SDimitry Andric 
210463faed5bSDimitry Andric   // For each register class, list the UnitSets that are supersets.
210567c32a98SDimitry Andric   RegClassUnitSets.resize(RegClasses.size());
210667c32a98SDimitry Andric   int RCIdx = -1;
210767c32a98SDimitry Andric   for (auto &RC : RegClasses) {
210867c32a98SDimitry Andric     ++RCIdx;
210967c32a98SDimitry Andric     if (!RC.Allocatable)
211063faed5bSDimitry Andric       continue;
211163faed5bSDimitry Andric 
211263faed5bSDimitry Andric     // Recompute the sorted list of units in this class.
2113f8af5cf6SDimitry Andric     std::vector<unsigned> RCRegUnits;
2114eb11fae6SDimitry Andric     RC.buildRegUnitSet(*this, RCRegUnits);
211563faed5bSDimitry Andric 
211663faed5bSDimitry Andric     // Don't increase pressure for unallocatable regclasses.
2117f8af5cf6SDimitry Andric     if (RCRegUnits.empty())
211863faed5bSDimitry Andric       continue;
211963faed5bSDimitry Andric 
2120eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << "RC " << RC.getName() << " Units:\n";
2121eb11fae6SDimitry Andric                for (auto U
2122eb11fae6SDimitry Andric                     : RCRegUnits) printRegUnitName(U);
2123f8af5cf6SDimitry Andric                dbgs() << "\n  UnitSetIDs:");
2124f8af5cf6SDimitry Andric 
212563faed5bSDimitry Andric     // Find all supersets.
2126ac9a064cSDimitry Andric     for (unsigned USIdx = 0, USEnd = RegUnitSets.size(); USIdx != USEnd;
2127ac9a064cSDimitry Andric          ++USIdx) {
2128f8af5cf6SDimitry Andric       if (isRegUnitSubSet(RCRegUnits, RegUnitSets[USIdx].Units)) {
2129eb11fae6SDimitry Andric         LLVM_DEBUG(dbgs() << " " << USIdx);
213063faed5bSDimitry Andric         RegClassUnitSets[RCIdx].push_back(USIdx);
213163faed5bSDimitry Andric       }
2132f8af5cf6SDimitry Andric     }
2133eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << "\n");
2134c0981da4SDimitry Andric     assert((!RegClassUnitSets[RCIdx].empty() || !RC.GeneratePressureSet) &&
2135c0981da4SDimitry Andric            "missing unit set for regclass");
213656fe8f14SDimitry Andric   }
21374a16efa3SDimitry Andric 
21384a16efa3SDimitry Andric   // For each register unit, ensure that we have the list of UnitSets that
21394a16efa3SDimitry Andric   // contain the unit. Normally, this matches an existing list of UnitSets for a
21404a16efa3SDimitry Andric   // register class. If not, we create a new entry in RegClassUnitSets as a
21414a16efa3SDimitry Andric   // "fake" register class.
2142ac9a064cSDimitry Andric   for (unsigned UnitIdx = 0, UnitEnd = NumNativeRegUnits; UnitIdx < UnitEnd;
2143ac9a064cSDimitry Andric        ++UnitIdx) {
21444a16efa3SDimitry Andric     std::vector<unsigned> RUSets;
21454a16efa3SDimitry Andric     for (unsigned i = 0, e = RegUnitSets.size(); i != e; ++i) {
2146ac9a064cSDimitry Andric       if (is_contained(RegUnitSets[i].Units, UnitIdx))
21474a16efa3SDimitry Andric         RUSets.push_back(i);
21484a16efa3SDimitry Andric     }
21494a16efa3SDimitry Andric     unsigned RCUnitSetsIdx = 0;
2150ac9a064cSDimitry Andric     for (unsigned e = RegClassUnitSets.size(); RCUnitSetsIdx != e;
2151ac9a064cSDimitry Andric          ++RCUnitSetsIdx) {
21524a16efa3SDimitry Andric       if (RegClassUnitSets[RCUnitSetsIdx] == RUSets) {
21534a16efa3SDimitry Andric         break;
21544a16efa3SDimitry Andric       }
21554a16efa3SDimitry Andric     }
21564a16efa3SDimitry Andric     RegUnits[UnitIdx].RegClassUnitSetsIdx = RCUnitSetsIdx;
21574a16efa3SDimitry Andric     if (RCUnitSetsIdx == RegClassUnitSets.size()) {
21584a16efa3SDimitry Andric       // Create a new list of UnitSets as a "fake" register class.
2159ac9a064cSDimitry Andric       RegClassUnitSets.push_back(std::move(RUSets));
21604a16efa3SDimitry Andric     }
21614a16efa3SDimitry Andric   }
216256fe8f14SDimitry Andric }
216356fe8f14SDimitry Andric 
computeRegUnitLaneMasks()216467c32a98SDimitry Andric void CodeGenRegBank::computeRegUnitLaneMasks() {
216567c32a98SDimitry Andric   for (auto &Register : Registers) {
216667c32a98SDimitry Andric     // Create an initial lane mask for all register units.
216767c32a98SDimitry Andric     const auto &RegUnits = Register.getRegUnits();
2168b1c73532SDimitry Andric     CodeGenRegister::RegUnitLaneMaskList RegUnitLaneMasks(
2169b1c73532SDimitry Andric         RegUnits.count(), LaneBitmask::getAll());
217067c32a98SDimitry Andric     // Iterate through SubRegisters.
217167c32a98SDimitry Andric     typedef CodeGenRegister::SubRegMap SubRegMap;
217267c32a98SDimitry Andric     const SubRegMap &SubRegs = Register.getSubRegs();
2173344a3780SDimitry Andric     for (auto S : SubRegs) {
2174344a3780SDimitry Andric       CodeGenRegister *SubReg = S.second;
217567c32a98SDimitry Andric       // Ignore non-leaf subregisters, their lane masks are fully covered by
217667c32a98SDimitry Andric       // the leaf subregisters anyway.
2177b915e9e0SDimitry Andric       if (!SubReg->getSubRegs().empty())
217867c32a98SDimitry Andric         continue;
2179344a3780SDimitry Andric       CodeGenSubRegIndex *SubRegIndex = S.first;
2180344a3780SDimitry Andric       const CodeGenRegister *SubRegister = S.second;
2181b915e9e0SDimitry Andric       LaneBitmask LaneMask = SubRegIndex->LaneMask;
218267c32a98SDimitry Andric       // Distribute LaneMask to Register Units touched.
21835a5ac124SDimitry Andric       for (unsigned SUI : SubRegister->getRegUnits()) {
218467c32a98SDimitry Andric         bool Found = false;
21855a5ac124SDimitry Andric         unsigned u = 0;
21865a5ac124SDimitry Andric         for (unsigned RU : RegUnits) {
21875a5ac124SDimitry Andric           if (SUI == RU) {
2188b1c73532SDimitry Andric             RegUnitLaneMasks[u] &= LaneMask;
218967c32a98SDimitry Andric             assert(!Found);
219067c32a98SDimitry Andric             Found = true;
219167c32a98SDimitry Andric           }
21925a5ac124SDimitry Andric           ++u;
219367c32a98SDimitry Andric         }
21945a5ac124SDimitry Andric         (void)Found;
219567c32a98SDimitry Andric         assert(Found);
219667c32a98SDimitry Andric       }
219767c32a98SDimitry Andric     }
219867c32a98SDimitry Andric     Register.setRegUnitLaneMasks(RegUnitLaneMasks);
219967c32a98SDimitry Andric   }
220067c32a98SDimitry Andric }
220167c32a98SDimitry Andric 
computeDerivedInfo()220256fe8f14SDimitry Andric void CodeGenRegBank::computeDerivedInfo() {
220356fe8f14SDimitry Andric   computeComposites();
220467c32a98SDimitry Andric   computeSubRegLaneMasks();
220563faed5bSDimitry Andric 
220663faed5bSDimitry Andric   // Compute a weight for each register unit created during getSubRegs.
220763faed5bSDimitry Andric   // This may create adopted register units (with unit # >= NumNativeRegUnits).
220863faed5bSDimitry Andric   computeRegUnitWeights();
220963faed5bSDimitry Andric 
221063faed5bSDimitry Andric   // Compute a unique set of RegUnitSets. One for each RegClass and inferred
221163faed5bSDimitry Andric   // supersets for the union of overlapping sets.
221263faed5bSDimitry Andric   computeRegUnitSets();
2213f8af5cf6SDimitry Andric 
221467c32a98SDimitry Andric   computeRegUnitLaneMasks();
221567c32a98SDimitry Andric 
221601095a5dSDimitry Andric   // Compute register class HasDisjunctSubRegs/CoveredBySubRegs flag.
22175a5ac124SDimitry Andric   for (CodeGenRegisterClass &RC : RegClasses) {
22185a5ac124SDimitry Andric     RC.HasDisjunctSubRegs = false;
221901095a5dSDimitry Andric     RC.CoveredBySubRegs = true;
222001095a5dSDimitry Andric     for (const CodeGenRegister *Reg : RC.getMembers()) {
22215a5ac124SDimitry Andric       RC.HasDisjunctSubRegs |= Reg->HasDisjunctSubRegs;
222201095a5dSDimitry Andric       RC.CoveredBySubRegs &= Reg->CoveredBySubRegs;
222301095a5dSDimitry Andric     }
22245a5ac124SDimitry Andric   }
22255a5ac124SDimitry Andric 
2226f8af5cf6SDimitry Andric   // Get the weight of each set.
2227f8af5cf6SDimitry Andric   for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx)
2228f8af5cf6SDimitry Andric     RegUnitSets[Idx].Weight = getRegUnitSetWeight(RegUnitSets[Idx].Units);
2229f8af5cf6SDimitry Andric 
2230f8af5cf6SDimitry Andric   // Find the order of each set.
2231f8af5cf6SDimitry Andric   RegUnitSetOrder.reserve(RegUnitSets.size());
2232f8af5cf6SDimitry Andric   for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx)
2233f8af5cf6SDimitry Andric     RegUnitSetOrder.push_back(Idx);
2234f8af5cf6SDimitry Andric 
2235e6d15924SDimitry Andric   llvm::stable_sort(RegUnitSetOrder, [this](unsigned ID1, unsigned ID2) {
22365ca98fd9SDimitry Andric     return getRegPressureSet(ID1).Units.size() <
22375ca98fd9SDimitry Andric            getRegPressureSet(ID2).Units.size();
22385ca98fd9SDimitry Andric   });
2239f8af5cf6SDimitry Andric   for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx) {
2240f8af5cf6SDimitry Andric     RegUnitSets[RegUnitSetOrder[Idx]].Order = Idx;
2241f8af5cf6SDimitry Andric   }
224256fe8f14SDimitry Andric }
224356fe8f14SDimitry Andric 
224430815c53SDimitry Andric //
224563faed5bSDimitry Andric // Synthesize missing register class intersections.
224663faed5bSDimitry Andric //
224763faed5bSDimitry Andric // Make sure that sub-classes of RC exists such that getCommonSubClass(RC, X)
224863faed5bSDimitry Andric // returns a maximal register class for all X.
224963faed5bSDimitry Andric //
inferCommonSubClass(CodeGenRegisterClass * RC)225063faed5bSDimitry Andric void CodeGenRegBank::inferCommonSubClass(CodeGenRegisterClass *RC) {
225167c32a98SDimitry Andric   assert(!RegClasses.empty());
225267c32a98SDimitry Andric   // Stash the iterator to the last element so that this loop doesn't visit
225367c32a98SDimitry Andric   // elements added by the getOrCreateSubClass call within it.
225467c32a98SDimitry Andric   for (auto I = RegClasses.begin(), E = std::prev(RegClasses.end());
225567c32a98SDimitry Andric        I != std::next(E); ++I) {
225663faed5bSDimitry Andric     CodeGenRegisterClass *RC1 = RC;
225767c32a98SDimitry Andric     CodeGenRegisterClass *RC2 = &*I;
225863faed5bSDimitry Andric     if (RC1 == RC2)
225963faed5bSDimitry Andric       continue;
226030815c53SDimitry Andric 
226163faed5bSDimitry Andric     // Compute the set intersection of RC1 and RC2.
22625a5ac124SDimitry Andric     const CodeGenRegister::Vec &Memb1 = RC1->getMembers();
22635a5ac124SDimitry Andric     const CodeGenRegister::Vec &Memb2 = RC2->getMembers();
22645a5ac124SDimitry Andric     CodeGenRegister::Vec Intersection;
22651d5ae102SDimitry Andric     std::set_intersection(Memb1.begin(), Memb1.end(), Memb2.begin(),
22661d5ae102SDimitry Andric                           Memb2.end(),
22671d5ae102SDimitry Andric                           std::inserter(Intersection, Intersection.begin()),
22681d5ae102SDimitry Andric                           deref<std::less<>>());
226930815c53SDimitry Andric 
227063faed5bSDimitry Andric     // Skip disjoint class pairs.
227163faed5bSDimitry Andric     if (Intersection.empty())
227263faed5bSDimitry Andric       continue;
227363faed5bSDimitry Andric 
227463faed5bSDimitry Andric     // If RC1 and RC2 have different spill sizes or alignments, use the
2275044eb2f6SDimitry Andric     // stricter one for sub-classing.  If they are equal, prefer RC1.
2276044eb2f6SDimitry Andric     if (RC2->RSI.hasStricterSpillThan(RC1->RSI))
227763faed5bSDimitry Andric       std::swap(RC1, RC2);
227863faed5bSDimitry Andric 
227963faed5bSDimitry Andric     getOrCreateSubClass(RC1, &Intersection,
228063faed5bSDimitry Andric                         RC1->getName() + "_and_" + RC2->getName());
228163faed5bSDimitry Andric   }
228263faed5bSDimitry Andric }
228363faed5bSDimitry Andric 
228463faed5bSDimitry Andric //
228563faed5bSDimitry Andric // Synthesize missing sub-classes for getSubClassWithSubReg().
228663faed5bSDimitry Andric //
228763faed5bSDimitry Andric // Make sure that the set of registers in RC with a given SubIdx sub-register
228863faed5bSDimitry Andric // form a register class.  Update RC->SubClassWithSubReg.
228963faed5bSDimitry Andric //
inferSubClassWithSubReg(CodeGenRegisterClass * RC)229063faed5bSDimitry Andric void CodeGenRegBank::inferSubClassWithSubReg(CodeGenRegisterClass *RC) {
229163faed5bSDimitry Andric   // Map SubRegIndex to set of registers in RC supporting that SubRegIndex.
22925a5ac124SDimitry Andric   typedef std::map<const CodeGenSubRegIndex *, CodeGenRegister::Vec,
22931d5ae102SDimitry Andric                    deref<std::less<>>>
22941d5ae102SDimitry Andric       SubReg2SetMap;
229530815c53SDimitry Andric 
229630815c53SDimitry Andric   // Compute the set of registers supporting each SubRegIndex.
229730815c53SDimitry Andric   SubReg2SetMap SRSets;
22985a5ac124SDimitry Andric   for (const auto R : RC->getMembers()) {
2299eb11fae6SDimitry Andric     if (R->Artificial)
2300eb11fae6SDimitry Andric       continue;
23015a5ac124SDimitry Andric     const CodeGenRegister::SubRegMap &SRM = R->getSubRegs();
2302344a3780SDimitry Andric     for (auto I : SRM) {
2303344a3780SDimitry Andric       if (!I.first->Artificial)
2304344a3780SDimitry Andric         SRSets[I.first].push_back(R);
230530815c53SDimitry Andric     }
2306eb11fae6SDimitry Andric   }
230730815c53SDimitry Andric 
23085a5ac124SDimitry Andric   for (auto I : SRSets)
23095a5ac124SDimitry Andric     sortAndUniqueRegisters(I.second);
23105a5ac124SDimitry Andric 
231130815c53SDimitry Andric   // Find matching classes for all SRSets entries.  Iterate in SubRegIndex
231230815c53SDimitry Andric   // numerical order to visit synthetic indices last.
231367c32a98SDimitry Andric   for (const auto &SubIdx : SubRegIndices) {
2314eb11fae6SDimitry Andric     if (SubIdx.Artificial)
2315eb11fae6SDimitry Andric       continue;
231667c32a98SDimitry Andric     SubReg2SetMap::const_iterator I = SRSets.find(&SubIdx);
231730815c53SDimitry Andric     // Unsupported SubRegIndex. Skip it.
231830815c53SDimitry Andric     if (I == SRSets.end())
231930815c53SDimitry Andric       continue;
232030815c53SDimitry Andric     // In most cases, all RC registers support the SubRegIndex.
232163faed5bSDimitry Andric     if (I->second.size() == RC->getMembers().size()) {
232267c32a98SDimitry Andric       RC->setSubClassWithSubReg(&SubIdx, RC);
232330815c53SDimitry Andric       continue;
232430815c53SDimitry Andric     }
232530815c53SDimitry Andric     // This is a real subset.  See if we have a matching class.
2326ac9a064cSDimitry Andric     CodeGenRegisterClass *SubRC = getOrCreateSubClass(
2327ac9a064cSDimitry Andric         RC, &I->second, RC->getName() + "_with_" + I->first->getName());
232867c32a98SDimitry Andric     RC->setSubClassWithSubReg(&SubIdx, SubRC);
232963faed5bSDimitry Andric   }
233030815c53SDimitry Andric }
233130815c53SDimitry Andric 
233263faed5bSDimitry Andric //
233363faed5bSDimitry Andric // Synthesize missing sub-classes of RC for getMatchingSuperRegClass().
233463faed5bSDimitry Andric //
233563faed5bSDimitry Andric // Create sub-classes of RC such that getMatchingSuperRegClass(RC, SubIdx, X)
233663faed5bSDimitry Andric // has a maximal result for any SubIdx and any X >= FirstSubRegRC.
233763faed5bSDimitry Andric //
233863faed5bSDimitry Andric 
inferMatchingSuperRegClass(CodeGenRegisterClass * RC,std::list<CodeGenRegisterClass>::iterator FirstSubRegRC)2339ac9a064cSDimitry Andric void CodeGenRegBank::inferMatchingSuperRegClass(
2340ac9a064cSDimitry Andric     CodeGenRegisterClass *RC,
234167c32a98SDimitry Andric     std::list<CodeGenRegisterClass>::iterator FirstSubRegRC) {
2342b1c73532SDimitry Andric   DenseMap<const CodeGenRegister *, std::vector<const CodeGenRegister *>>
2343b1c73532SDimitry Andric       SubToSuperRegs;
234458b69754SDimitry Andric   BitVector TopoSigs(getNumTopoSigs());
234563faed5bSDimitry Andric 
234663faed5bSDimitry Andric   // Iterate in SubRegIndex numerical order to visit synthetic indices last.
234767c32a98SDimitry Andric   for (auto &SubIdx : SubRegIndices) {
234863faed5bSDimitry Andric     // Skip indexes that aren't fully supported by RC's registers. This was
234963faed5bSDimitry Andric     // computed by inferSubClassWithSubReg() above which should have been
235063faed5bSDimitry Andric     // called first.
235167c32a98SDimitry Andric     if (RC->getSubClassWithSubReg(&SubIdx) != RC)
235263faed5bSDimitry Andric       continue;
235363faed5bSDimitry Andric 
235463faed5bSDimitry Andric     // Build list of (Super, Sub) pairs for this SubIdx.
2355b1c73532SDimitry Andric     SubToSuperRegs.clear();
235658b69754SDimitry Andric     TopoSigs.reset();
23575a5ac124SDimitry Andric     for (const auto Super : RC->getMembers()) {
235867c32a98SDimitry Andric       const CodeGenRegister *Sub = Super->getSubRegs().find(&SubIdx)->second;
235963faed5bSDimitry Andric       assert(Sub && "Missing sub-register");
2360b1c73532SDimitry Andric       SubToSuperRegs[Sub].push_back(Super);
236158b69754SDimitry Andric       TopoSigs.set(Sub->getTopoSig());
236263faed5bSDimitry Andric     }
236363faed5bSDimitry Andric 
236463faed5bSDimitry Andric     // Iterate over sub-register class candidates.  Ignore classes created by
236563faed5bSDimitry Andric     // this loop. They will never be useful.
236667c32a98SDimitry Andric     // Store an iterator to the last element (not end) so that this loop doesn't
236767c32a98SDimitry Andric     // visit newly inserted elements.
236867c32a98SDimitry Andric     assert(!RegClasses.empty());
236967c32a98SDimitry Andric     for (auto I = FirstSubRegRC, E = std::prev(RegClasses.end());
237067c32a98SDimitry Andric          I != std::next(E); ++I) {
237167c32a98SDimitry Andric       CodeGenRegisterClass &SubRC = *I;
2372eb11fae6SDimitry Andric       if (SubRC.Artificial)
2373eb11fae6SDimitry Andric         continue;
237458b69754SDimitry Andric       // Topological shortcut: SubRC members have the wrong shape.
237567c32a98SDimitry Andric       if (!TopoSigs.anyCommon(SubRC.getTopoSigs()))
237658b69754SDimitry Andric         continue;
237763faed5bSDimitry Andric       // Compute the subset of RC that maps into SubRC.
23785a5ac124SDimitry Andric       CodeGenRegister::Vec SubSetVec;
2379b1c73532SDimitry Andric       for (const CodeGenRegister *R : SubRC.getMembers()) {
2380b1c73532SDimitry Andric         auto It = SubToSuperRegs.find(R);
2381b1c73532SDimitry Andric         if (It != SubToSuperRegs.end()) {
2382b1c73532SDimitry Andric           const std::vector<const CodeGenRegister *> &SuperRegs = It->second;
2383b1c73532SDimitry Andric           SubSetVec.insert(SubSetVec.end(), SuperRegs.begin(), SuperRegs.end());
2384b1c73532SDimitry Andric         }
2385b1c73532SDimitry Andric       }
23865a5ac124SDimitry Andric 
23875a5ac124SDimitry Andric       if (SubSetVec.empty())
238863faed5bSDimitry Andric         continue;
23895a5ac124SDimitry Andric 
239063faed5bSDimitry Andric       // RC injects completely into SubRC.
23915a5ac124SDimitry Andric       sortAndUniqueRegisters(SubSetVec);
2392b1c73532SDimitry Andric       if (SubSetVec.size() == RC->getMembers().size()) {
239367c32a98SDimitry Andric         SubRC.addSuperRegClass(&SubIdx, RC);
239463faed5bSDimitry Andric         continue;
239563faed5bSDimitry Andric       }
23965a5ac124SDimitry Andric 
239763faed5bSDimitry Andric       // Only a subset of RC maps into SubRC. Make sure it is represented by a
239863faed5bSDimitry Andric       // class.
2399ac9a064cSDimitry Andric       getOrCreateSubClass(RC, &SubSetVec,
2400ac9a064cSDimitry Andric                           RC->getName() + "_with_" + SubIdx.getName() + "_in_" +
240167c32a98SDimitry Andric                               SubRC.getName());
240263faed5bSDimitry Andric     }
240363faed5bSDimitry Andric   }
240463faed5bSDimitry Andric }
240563faed5bSDimitry Andric 
240663faed5bSDimitry Andric //
240763faed5bSDimitry Andric // Infer missing register classes.
240863faed5bSDimitry Andric //
computeInferredRegisterClasses()240963faed5bSDimitry Andric void CodeGenRegBank::computeInferredRegisterClasses() {
241067c32a98SDimitry Andric   assert(!RegClasses.empty());
241163faed5bSDimitry Andric   // When this function is called, the register classes have not been sorted
241263faed5bSDimitry Andric   // and assigned EnumValues yet.  That means getSubClasses(),
241363faed5bSDimitry Andric   // getSuperClasses(), and hasSubClass() functions are defunct.
241467c32a98SDimitry Andric 
241567c32a98SDimitry Andric   // Use one-before-the-end so it doesn't move forward when new elements are
241667c32a98SDimitry Andric   // added.
241767c32a98SDimitry Andric   auto FirstNewRC = std::prev(RegClasses.end());
241863faed5bSDimitry Andric 
241963faed5bSDimitry Andric   // Visit all register classes, including the ones being added by the loop.
242067c32a98SDimitry Andric   // Watch out for iterator invalidation here.
242167c32a98SDimitry Andric   for (auto I = RegClasses.begin(), E = RegClasses.end(); I != E; ++I) {
242267c32a98SDimitry Andric     CodeGenRegisterClass *RC = &*I;
2423eb11fae6SDimitry Andric     if (RC->Artificial)
2424eb11fae6SDimitry Andric       continue;
242563faed5bSDimitry Andric 
242663faed5bSDimitry Andric     // Synthesize answers for getSubClassWithSubReg().
242763faed5bSDimitry Andric     inferSubClassWithSubReg(RC);
242863faed5bSDimitry Andric 
242963faed5bSDimitry Andric     // Synthesize answers for getCommonSubClass().
243063faed5bSDimitry Andric     inferCommonSubClass(RC);
243163faed5bSDimitry Andric 
243263faed5bSDimitry Andric     // Synthesize answers for getMatchingSuperRegClass().
243363faed5bSDimitry Andric     inferMatchingSuperRegClass(RC);
243463faed5bSDimitry Andric 
243563faed5bSDimitry Andric     // New register classes are created while this loop is running, and we need
243663faed5bSDimitry Andric     // to visit all of them.  I  particular, inferMatchingSuperRegClass needs
243763faed5bSDimitry Andric     // to match old super-register classes with sub-register classes created
243863faed5bSDimitry Andric     // after inferMatchingSuperRegClass was called.  At this point,
243963faed5bSDimitry Andric     // inferMatchingSuperRegClass has checked SuperRC = [0..rci] with SubRC =
244063faed5bSDimitry Andric     // [0..FirstNewRC).  We need to cover SubRC = [FirstNewRC..rci].
244167c32a98SDimitry Andric     if (I == FirstNewRC) {
244267c32a98SDimitry Andric       auto NextNewRC = std::prev(RegClasses.end());
244367c32a98SDimitry Andric       for (auto I2 = RegClasses.begin(), E2 = std::next(FirstNewRC); I2 != E2;
244467c32a98SDimitry Andric            ++I2)
244567c32a98SDimitry Andric         inferMatchingSuperRegClass(&*I2, E2);
244663faed5bSDimitry Andric       FirstNewRC = NextNewRC;
244730815c53SDimitry Andric     }
244830815c53SDimitry Andric   }
244930815c53SDimitry Andric }
245030815c53SDimitry Andric 
2451411bd29eSDimitry Andric /// getRegisterClassForRegister - Find the register class that contains the
2452411bd29eSDimitry Andric /// specified physical register.  If the register is not in a register class,
2453411bd29eSDimitry Andric /// return null. If the register is in multiple classes, and the classes have a
2454411bd29eSDimitry Andric /// superset-subset relationship and the same set of types, return the
2455411bd29eSDimitry Andric /// superclass.  Otherwise return null.
getRegClassForRegister(Record * R)2456ac9a064cSDimitry Andric const CodeGenRegisterClass *CodeGenRegBank::getRegClassForRegister(Record *R) {
2457411bd29eSDimitry Andric   const CodeGenRegister *Reg = getReg(R);
24585ca98fd9SDimitry Andric   const CodeGenRegisterClass *FoundRC = nullptr;
245967c32a98SDimitry Andric   for (const auto &RC : getRegClasses()) {
2460411bd29eSDimitry Andric     if (!RC.contains(Reg))
2461411bd29eSDimitry Andric       continue;
2462411bd29eSDimitry Andric 
2463411bd29eSDimitry Andric     // If this is the first class that contains the register,
2464411bd29eSDimitry Andric     // make a note of it and go on to the next class.
2465411bd29eSDimitry Andric     if (!FoundRC) {
2466411bd29eSDimitry Andric       FoundRC = &RC;
2467411bd29eSDimitry Andric       continue;
2468411bd29eSDimitry Andric     }
2469411bd29eSDimitry Andric 
2470411bd29eSDimitry Andric     // If a register's classes have different types, return null.
2471411bd29eSDimitry Andric     if (RC.getValueTypes() != FoundRC->getValueTypes())
24725ca98fd9SDimitry Andric       return nullptr;
2473411bd29eSDimitry Andric 
2474411bd29eSDimitry Andric     // Check to see if the previously found class that contains
2475411bd29eSDimitry Andric     // the register is a subclass of the current class. If so,
2476411bd29eSDimitry Andric     // prefer the superclass.
2477411bd29eSDimitry Andric     if (RC.hasSubClass(FoundRC)) {
2478411bd29eSDimitry Andric       FoundRC = &RC;
2479411bd29eSDimitry Andric       continue;
2480411bd29eSDimitry Andric     }
2481411bd29eSDimitry Andric 
2482411bd29eSDimitry Andric     // Check to see if the previously found class that contains
2483411bd29eSDimitry Andric     // the register is a superclass of the current class. If so,
2484411bd29eSDimitry Andric     // prefer the superclass.
2485411bd29eSDimitry Andric     if (FoundRC->hasSubClass(&RC))
2486411bd29eSDimitry Andric       continue;
2487411bd29eSDimitry Andric 
2488411bd29eSDimitry Andric     // Multiple classes, and neither is a superclass of the other.
2489411bd29eSDimitry Andric     // Return null.
24905ca98fd9SDimitry Andric     return nullptr;
2491411bd29eSDimitry Andric   }
2492411bd29eSDimitry Andric   return FoundRC;
2493411bd29eSDimitry Andric }
249463faed5bSDimitry Andric 
24951d5ae102SDimitry Andric const CodeGenRegisterClass *
getMinimalPhysRegClass(Record * RegRecord,ValueTypeByHwMode * VT)24961d5ae102SDimitry Andric CodeGenRegBank::getMinimalPhysRegClass(Record *RegRecord,
24971d5ae102SDimitry Andric                                        ValueTypeByHwMode *VT) {
24981d5ae102SDimitry Andric   const CodeGenRegister *Reg = getReg(RegRecord);
24991d5ae102SDimitry Andric   const CodeGenRegisterClass *BestRC = nullptr;
25001d5ae102SDimitry Andric   for (const auto &RC : getRegClasses()) {
2501ac9a064cSDimitry Andric     if ((!VT || RC.hasType(*VT)) && RC.contains(Reg) &&
2502ac9a064cSDimitry Andric         (!BestRC || BestRC->hasSubClass(&RC)))
25031d5ae102SDimitry Andric       BestRC = &RC;
25041d5ae102SDimitry Andric   }
25051d5ae102SDimitry Andric 
25061d5ae102SDimitry Andric   assert(BestRC && "Couldn't find the register class");
25071d5ae102SDimitry Andric   return BestRC;
25081d5ae102SDimitry Andric }
25091d5ae102SDimitry Andric 
computeCoveredRegisters(ArrayRef<Record * > Regs)251063faed5bSDimitry Andric BitVector CodeGenRegBank::computeCoveredRegisters(ArrayRef<Record *> Regs) {
251163faed5bSDimitry Andric   SetVector<const CodeGenRegister *> Set;
251263faed5bSDimitry Andric 
251363faed5bSDimitry Andric   // First add Regs with all sub-registers.
251463faed5bSDimitry Andric   for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
251563faed5bSDimitry Andric     CodeGenRegister *Reg = getReg(Regs[i]);
251663faed5bSDimitry Andric     if (Set.insert(Reg))
251763faed5bSDimitry Andric       // Reg is new, add all sub-registers.
251863faed5bSDimitry Andric       // The pre-ordering is not important here.
251963faed5bSDimitry Andric       Reg->addSubRegsPreOrder(Set, *this);
252063faed5bSDimitry Andric   }
252163faed5bSDimitry Andric 
252263faed5bSDimitry Andric   // Second, find all super-registers that are completely covered by the set.
252363faed5bSDimitry Andric   for (unsigned i = 0; i != Set.size(); ++i) {
252463faed5bSDimitry Andric     const CodeGenRegister::SuperRegList &SR = Set[i]->getSuperRegs();
252563faed5bSDimitry Andric     for (unsigned j = 0, e = SR.size(); j != e; ++j) {
252663faed5bSDimitry Andric       const CodeGenRegister *Super = SR[j];
252763faed5bSDimitry Andric       if (!Super->CoveredBySubRegs || Set.count(Super))
252863faed5bSDimitry Andric         continue;
252963faed5bSDimitry Andric       // This new super-register is covered by its sub-registers.
253063faed5bSDimitry Andric       bool AllSubsInSet = true;
253163faed5bSDimitry Andric       const CodeGenRegister::SubRegMap &SRM = Super->getSubRegs();
2532344a3780SDimitry Andric       for (auto I : SRM)
2533344a3780SDimitry Andric         if (!Set.count(I.second)) {
253463faed5bSDimitry Andric           AllSubsInSet = false;
253563faed5bSDimitry Andric           break;
253663faed5bSDimitry Andric         }
253763faed5bSDimitry Andric       // All sub-registers in Set, add Super as well.
253863faed5bSDimitry Andric       // We will visit Super later to recheck its super-registers.
253963faed5bSDimitry Andric       if (AllSubsInSet)
254063faed5bSDimitry Andric         Set.insert(Super);
254163faed5bSDimitry Andric     }
254263faed5bSDimitry Andric   }
254363faed5bSDimitry Andric 
254463faed5bSDimitry Andric   // Convert to BitVector.
254563faed5bSDimitry Andric   BitVector BV(Registers.size() + 1);
254663faed5bSDimitry Andric   for (unsigned i = 0, e = Set.size(); i != e; ++i)
254763faed5bSDimitry Andric     BV.set(Set[i]->EnumValue);
254863faed5bSDimitry Andric   return BV;
254963faed5bSDimitry Andric }
255071d5a254SDimitry Andric 
printRegUnitName(unsigned Unit) const255171d5a254SDimitry Andric void CodeGenRegBank::printRegUnitName(unsigned Unit) const {
255271d5a254SDimitry Andric   if (Unit < NumNativeRegUnits)
255371d5a254SDimitry Andric     dbgs() << ' ' << RegUnits[Unit].Roots[0]->getName();
255471d5a254SDimitry Andric   else
255571d5a254SDimitry Andric     dbgs() << " #" << Unit;
255671d5a254SDimitry Andric }
2557