1bd5abe19SDimitry Andric //===- CodeGenRegisters.cpp - Register and RegisterClass Info -------------===//
2bd5abe19SDimitry Andric //
3bd5abe19SDimitry Andric //                     The LLVM Compiler Infrastructure
4bd5abe19SDimitry Andric //
5bd5abe19SDimitry Andric // This file is distributed under the University of Illinois Open Source
6bd5abe19SDimitry Andric // License. See LICENSE.TXT for details.
7bd5abe19SDimitry Andric //
8bd5abe19SDimitry Andric //===----------------------------------------------------------------------===//
9bd5abe19SDimitry Andric //
10bd5abe19SDimitry Andric // This file defines structures to encapsulate information gleaned from the
11bd5abe19SDimitry Andric // target register and register class definitions.
12bd5abe19SDimitry Andric //
13bd5abe19SDimitry Andric //===----------------------------------------------------------------------===//
14bd5abe19SDimitry Andric 
15bd5abe19SDimitry Andric #include "CodeGenRegisters.h"
16bd5abe19SDimitry Andric #include "CodeGenTarget.h"
17d88c1a5aSDimitry Andric #include "llvm/ADT/ArrayRef.h"
18d88c1a5aSDimitry Andric #include "llvm/ADT/BitVector.h"
19d88c1a5aSDimitry Andric #include "llvm/ADT/DenseMap.h"
20dff0c46cSDimitry Andric #include "llvm/ADT/IntEqClasses.h"
21d88c1a5aSDimitry Andric #include "llvm/ADT/SetVector.h"
22d88c1a5aSDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
23*b5893f02SDimitry Andric #include "llvm/ADT/SmallSet.h"
24139f7f9bSDimitry Andric #include "llvm/ADT/SmallVector.h"
25d88c1a5aSDimitry Andric #include "llvm/ADT/STLExtras.h"
26bd5abe19SDimitry Andric #include "llvm/ADT/StringExtras.h"
27d88c1a5aSDimitry Andric #include "llvm/ADT/StringRef.h"
28cb4dff85SDimitry Andric #include "llvm/ADT/Twine.h"
29f785676fSDimitry Andric #include "llvm/Support/Debug.h"
30d88c1a5aSDimitry Andric #include "llvm/Support/MathExtras.h"
31d88c1a5aSDimitry Andric #include "llvm/Support/raw_ostream.h"
32139f7f9bSDimitry Andric #include "llvm/TableGen/Error.h"
33d88c1a5aSDimitry Andric #include "llvm/TableGen/Record.h"
34d88c1a5aSDimitry Andric #include <algorithm>
35d88c1a5aSDimitry Andric #include <cassert>
36d88c1a5aSDimitry Andric #include <cstdint>
37d88c1a5aSDimitry Andric #include <iterator>
38d88c1a5aSDimitry Andric #include <map>
392cab237bSDimitry Andric #include <queue>
40d88c1a5aSDimitry Andric #include <set>
41d88c1a5aSDimitry Andric #include <string>
42d88c1a5aSDimitry Andric #include <tuple>
43d88c1a5aSDimitry Andric #include <utility>
44d88c1a5aSDimitry Andric #include <vector>
45bd5abe19SDimitry Andric 
46bd5abe19SDimitry Andric using namespace llvm;
47bd5abe19SDimitry Andric 
4891bc56edSDimitry Andric #define DEBUG_TYPE "regalloc-emitter"
4991bc56edSDimitry Andric 
50bd5abe19SDimitry Andric //===----------------------------------------------------------------------===//
51dff0c46cSDimitry Andric //                             CodeGenSubRegIndex
52dff0c46cSDimitry Andric //===----------------------------------------------------------------------===//
53dff0c46cSDimitry Andric 
CodeGenSubRegIndex(Record * R,unsigned Enum)54dff0c46cSDimitry Andric CodeGenSubRegIndex::CodeGenSubRegIndex(Record *R, unsigned Enum)
554ba319b5SDimitry Andric   : TheDef(R), EnumValue(Enum), AllSuperRegsCovered(true), Artificial(true) {
567ae0e2c9SDimitry Andric   Name = R->getName();
577ae0e2c9SDimitry Andric   if (R->getValue("Namespace"))
587ae0e2c9SDimitry Andric     Namespace = R->getValueAsString("Namespace");
59f785676fSDimitry Andric   Size = R->getValueAsInt("Size");
60f785676fSDimitry Andric   Offset = R->getValueAsInt("Offset");
61dff0c46cSDimitry Andric }
62dff0c46cSDimitry Andric 
CodeGenSubRegIndex(StringRef N,StringRef Nspace,unsigned Enum)637ae0e2c9SDimitry Andric CodeGenSubRegIndex::CodeGenSubRegIndex(StringRef N, StringRef Nspace,
647ae0e2c9SDimitry Andric                                        unsigned Enum)
6591bc56edSDimitry Andric   : TheDef(nullptr), Name(N), Namespace(Nspace), Size(-1), Offset(-1),
664ba319b5SDimitry Andric     EnumValue(Enum), AllSuperRegsCovered(true), Artificial(true) {
67dff0c46cSDimitry Andric }
68dff0c46cSDimitry Andric 
getQualifiedName() const69dff0c46cSDimitry Andric std::string CodeGenSubRegIndex::getQualifiedName() const {
70dff0c46cSDimitry Andric   std::string N = getNamespace();
71dff0c46cSDimitry Andric   if (!N.empty())
72dff0c46cSDimitry Andric     N += "::";
73dff0c46cSDimitry Andric   N += getName();
74dff0c46cSDimitry Andric   return N;
75dff0c46cSDimitry Andric }
76dff0c46cSDimitry Andric 
updateComponents(CodeGenRegBank & RegBank)77dff0c46cSDimitry Andric void CodeGenSubRegIndex::updateComponents(CodeGenRegBank &RegBank) {
787ae0e2c9SDimitry Andric   if (!TheDef)
79dff0c46cSDimitry Andric     return;
807ae0e2c9SDimitry Andric 
817ae0e2c9SDimitry Andric   std::vector<Record*> Comps = TheDef->getValueAsListOfDefs("ComposedOf");
827ae0e2c9SDimitry Andric   if (!Comps.empty()) {
83dff0c46cSDimitry Andric     if (Comps.size() != 2)
843861d79fSDimitry Andric       PrintFatalError(TheDef->getLoc(),
853861d79fSDimitry Andric                       "ComposedOf must have exactly two entries");
86dff0c46cSDimitry Andric     CodeGenSubRegIndex *A = RegBank.getSubRegIdx(Comps[0]);
87dff0c46cSDimitry Andric     CodeGenSubRegIndex *B = RegBank.getSubRegIdx(Comps[1]);
88dff0c46cSDimitry Andric     CodeGenSubRegIndex *X = A->addComposite(B, this);
89dff0c46cSDimitry Andric     if (X)
903861d79fSDimitry Andric       PrintFatalError(TheDef->getLoc(), "Ambiguous ComposedOf entries");
91dff0c46cSDimitry Andric   }
92dff0c46cSDimitry Andric 
937ae0e2c9SDimitry Andric   std::vector<Record*> Parts =
947ae0e2c9SDimitry Andric     TheDef->getValueAsListOfDefs("CoveringSubRegIndices");
957ae0e2c9SDimitry Andric   if (!Parts.empty()) {
967ae0e2c9SDimitry Andric     if (Parts.size() < 2)
973861d79fSDimitry Andric       PrintFatalError(TheDef->getLoc(),
987ae0e2c9SDimitry Andric                       "CoveredBySubRegs must have two or more entries");
997ae0e2c9SDimitry Andric     SmallVector<CodeGenSubRegIndex*, 8> IdxParts;
1002cab237bSDimitry Andric     for (Record *Part : Parts)
1012cab237bSDimitry Andric       IdxParts.push_back(RegBank.getSubRegIdx(Part));
1022cab237bSDimitry Andric     setConcatenationOf(IdxParts);
1037ae0e2c9SDimitry Andric   }
1047ae0e2c9SDimitry Andric }
1057ae0e2c9SDimitry Andric 
computeLaneMask() const106d88c1a5aSDimitry Andric LaneBitmask CodeGenSubRegIndex::computeLaneMask() const {
1073861d79fSDimitry Andric   // Already computed?
108d88c1a5aSDimitry Andric   if (LaneMask.any())
1093861d79fSDimitry Andric     return LaneMask;
1103861d79fSDimitry Andric 
1113861d79fSDimitry Andric   // Recursion guard, shouldn't be required.
112d88c1a5aSDimitry Andric   LaneMask = LaneBitmask::getAll();
1133861d79fSDimitry Andric 
1143861d79fSDimitry Andric   // The lane mask is simply the union of all sub-indices.
115d88c1a5aSDimitry Andric   LaneBitmask M;
11639d628a0SDimitry Andric   for (const auto &C : Composed)
11739d628a0SDimitry Andric     M |= C.second->computeLaneMask();
118d88c1a5aSDimitry Andric   assert(M.any() && "Missing lane mask, sub-register cycle?");
1193861d79fSDimitry Andric   LaneMask = M;
1203861d79fSDimitry Andric   return LaneMask;
121dff0c46cSDimitry Andric }
122dff0c46cSDimitry Andric 
setConcatenationOf(ArrayRef<CodeGenSubRegIndex * > Parts)1232cab237bSDimitry Andric void CodeGenSubRegIndex::setConcatenationOf(
1242cab237bSDimitry Andric     ArrayRef<CodeGenSubRegIndex*> Parts) {
1252cab237bSDimitry Andric   if (ConcatenationOf.empty())
1262cab237bSDimitry Andric     ConcatenationOf.assign(Parts.begin(), Parts.end());
1272cab237bSDimitry Andric   else
1282cab237bSDimitry Andric     assert(std::equal(Parts.begin(), Parts.end(),
1292cab237bSDimitry Andric                       ConcatenationOf.begin()) && "parts consistent");
1302cab237bSDimitry Andric }
1312cab237bSDimitry Andric 
computeConcatTransitiveClosure()1322cab237bSDimitry Andric void CodeGenSubRegIndex::computeConcatTransitiveClosure() {
1332cab237bSDimitry Andric   for (SmallVectorImpl<CodeGenSubRegIndex*>::iterator
1342cab237bSDimitry Andric        I = ConcatenationOf.begin(); I != ConcatenationOf.end(); /*empty*/) {
1352cab237bSDimitry Andric     CodeGenSubRegIndex *SubIdx = *I;
1362cab237bSDimitry Andric     SubIdx->computeConcatTransitiveClosure();
1372cab237bSDimitry Andric #ifndef NDEBUG
1382cab237bSDimitry Andric     for (CodeGenSubRegIndex *SRI : SubIdx->ConcatenationOf)
1392cab237bSDimitry Andric       assert(SRI->ConcatenationOf.empty() && "No transitive closure?");
1402cab237bSDimitry Andric #endif
1412cab237bSDimitry Andric 
1422cab237bSDimitry Andric     if (SubIdx->ConcatenationOf.empty()) {
1432cab237bSDimitry Andric       ++I;
1442cab237bSDimitry Andric     } else {
1452cab237bSDimitry Andric       I = ConcatenationOf.erase(I);
1462cab237bSDimitry Andric       I = ConcatenationOf.insert(I, SubIdx->ConcatenationOf.begin(),
1472cab237bSDimitry Andric                                  SubIdx->ConcatenationOf.end());
1482cab237bSDimitry Andric       I += SubIdx->ConcatenationOf.size();
1492cab237bSDimitry Andric     }
1502cab237bSDimitry Andric   }
1512cab237bSDimitry Andric }
1522cab237bSDimitry Andric 
153dff0c46cSDimitry Andric //===----------------------------------------------------------------------===//
154bd5abe19SDimitry Andric //                              CodeGenRegister
155bd5abe19SDimitry Andric //===----------------------------------------------------------------------===//
156bd5abe19SDimitry Andric 
CodeGenRegister(Record * R,unsigned Enum)157bd5abe19SDimitry Andric CodeGenRegister::CodeGenRegister(Record *R, unsigned Enum)
158bd5abe19SDimitry Andric   : TheDef(R),
159bd5abe19SDimitry Andric     EnumValue(Enum),
160bd5abe19SDimitry Andric     CostPerUse(R->getValueAsInt("CostPerUse")),
161dff0c46cSDimitry Andric     CoveredBySubRegs(R->getValueAsBit("CoveredBySubRegs")),
162ff0cc061SDimitry Andric     HasDisjunctSubRegs(false),
1637ae0e2c9SDimitry Andric     SubRegsComplete(false),
1647ae0e2c9SDimitry Andric     SuperRegsComplete(false),
1654ba319b5SDimitry Andric     TopoSig(~0u) {
1664ba319b5SDimitry Andric   Artificial = R->getValueAsBit("isArtificial");
1674ba319b5SDimitry Andric }
168bd5abe19SDimitry Andric 
buildObjectGraph(CodeGenRegBank & RegBank)1697ae0e2c9SDimitry Andric void CodeGenRegister::buildObjectGraph(CodeGenRegBank &RegBank) {
1707ae0e2c9SDimitry Andric   std::vector<Record*> SRIs = TheDef->getValueAsListOfDefs("SubRegIndices");
1717ae0e2c9SDimitry Andric   std::vector<Record*> SRs = TheDef->getValueAsListOfDefs("SubRegs");
1727ae0e2c9SDimitry Andric 
1737ae0e2c9SDimitry Andric   if (SRIs.size() != SRs.size())
1743861d79fSDimitry Andric     PrintFatalError(TheDef->getLoc(),
1757ae0e2c9SDimitry Andric                     "SubRegs and SubRegIndices must have the same size");
1767ae0e2c9SDimitry Andric 
1777ae0e2c9SDimitry Andric   for (unsigned i = 0, e = SRIs.size(); i != e; ++i) {
1787ae0e2c9SDimitry Andric     ExplicitSubRegIndices.push_back(RegBank.getSubRegIdx(SRIs[i]));
1797ae0e2c9SDimitry Andric     ExplicitSubRegs.push_back(RegBank.getReg(SRs[i]));
1807ae0e2c9SDimitry Andric   }
1817ae0e2c9SDimitry Andric 
1827ae0e2c9SDimitry Andric   // Also compute leading super-registers. Each register has a list of
1837ae0e2c9SDimitry Andric   // covered-by-subregs super-registers where it appears as the first explicit
1847ae0e2c9SDimitry Andric   // sub-register.
1857ae0e2c9SDimitry Andric   //
1867ae0e2c9SDimitry Andric   // This is used by computeSecondarySubRegs() to find candidates.
1877ae0e2c9SDimitry Andric   if (CoveredBySubRegs && !ExplicitSubRegs.empty())
1887ae0e2c9SDimitry Andric     ExplicitSubRegs.front()->LeadingSuperRegs.push_back(this);
1897ae0e2c9SDimitry Andric 
1907ae0e2c9SDimitry Andric   // Add ad hoc alias links. This is a symmetric relationship between two
1917ae0e2c9SDimitry Andric   // registers, so build a symmetric graph by adding links in both ends.
1927ae0e2c9SDimitry Andric   std::vector<Record*> Aliases = TheDef->getValueAsListOfDefs("Aliases");
1932cab237bSDimitry Andric   for (Record *Alias : Aliases) {
1942cab237bSDimitry Andric     CodeGenRegister *Reg = RegBank.getReg(Alias);
1957ae0e2c9SDimitry Andric     ExplicitAliases.push_back(Reg);
1967ae0e2c9SDimitry Andric     Reg->ExplicitAliases.push_back(this);
1977ae0e2c9SDimitry Andric   }
1987ae0e2c9SDimitry Andric }
1997ae0e2c9SDimitry Andric 
getName() const200d88c1a5aSDimitry Andric const StringRef CodeGenRegister::getName() const {
20139d628a0SDimitry Andric   assert(TheDef && "no def");
202bd5abe19SDimitry Andric   return TheDef->getName();
203bd5abe19SDimitry Andric }
204bd5abe19SDimitry Andric 
205bd5abe19SDimitry Andric namespace {
206d88c1a5aSDimitry Andric 
207dff0c46cSDimitry Andric // Iterate over all register units in a set of registers.
208dff0c46cSDimitry Andric class RegUnitIterator {
209ff0cc061SDimitry Andric   CodeGenRegister::Vec::const_iterator RegI, RegE;
210ff0cc061SDimitry Andric   CodeGenRegister::RegUnitList::iterator UnitI, UnitE;
211dff0c46cSDimitry Andric 
212dff0c46cSDimitry Andric public:
RegUnitIterator(const CodeGenRegister::Vec & Regs)213ff0cc061SDimitry Andric   RegUnitIterator(const CodeGenRegister::Vec &Regs):
214d88c1a5aSDimitry Andric     RegI(Regs.begin()), RegE(Regs.end()) {
215dff0c46cSDimitry Andric 
216dff0c46cSDimitry Andric     if (RegI != RegE) {
217dff0c46cSDimitry Andric       UnitI = (*RegI)->getRegUnits().begin();
218dff0c46cSDimitry Andric       UnitE = (*RegI)->getRegUnits().end();
219dff0c46cSDimitry Andric       advance();
220dff0c46cSDimitry Andric     }
221dff0c46cSDimitry Andric   }
222dff0c46cSDimitry Andric 
isValid() const223dff0c46cSDimitry Andric   bool isValid() const { return UnitI != UnitE; }
224dff0c46cSDimitry Andric 
operator *() const2257ae0e2c9SDimitry Andric   unsigned operator* () const { assert(isValid()); return *UnitI; }
226dff0c46cSDimitry Andric 
getReg() const227dff0c46cSDimitry Andric   const CodeGenRegister *getReg() const { assert(isValid()); return *RegI; }
228dff0c46cSDimitry Andric 
229dff0c46cSDimitry Andric   /// Preincrement.  Move to the next unit.
operator ++()230dff0c46cSDimitry Andric   void operator++() {
231dff0c46cSDimitry Andric     assert(isValid() && "Cannot advance beyond the last operand");
232dff0c46cSDimitry Andric     ++UnitI;
233dff0c46cSDimitry Andric     advance();
234dff0c46cSDimitry Andric   }
235dff0c46cSDimitry Andric 
236dff0c46cSDimitry Andric protected:
advance()237dff0c46cSDimitry Andric   void advance() {
238dff0c46cSDimitry Andric     while (UnitI == UnitE) {
239dff0c46cSDimitry Andric       if (++RegI == RegE)
240dff0c46cSDimitry Andric         break;
241dff0c46cSDimitry Andric       UnitI = (*RegI)->getRegUnits().begin();
242dff0c46cSDimitry Andric       UnitE = (*RegI)->getRegUnits().end();
243dff0c46cSDimitry Andric     }
244dff0c46cSDimitry Andric   }
245bd5abe19SDimitry Andric };
246d88c1a5aSDimitry Andric 
247d88c1a5aSDimitry Andric } // end anonymous namespace
248dff0c46cSDimitry Andric 
249dff0c46cSDimitry Andric // Return true of this unit appears in RegUnits.
hasRegUnit(CodeGenRegister::RegUnitList & RegUnits,unsigned Unit)250dff0c46cSDimitry Andric static bool hasRegUnit(CodeGenRegister::RegUnitList &RegUnits, unsigned Unit) {
251ff0cc061SDimitry Andric   return RegUnits.test(Unit);
252dff0c46cSDimitry Andric }
253dff0c46cSDimitry Andric 
254dff0c46cSDimitry Andric // Inherit register units from subregisters.
255dff0c46cSDimitry Andric // Return true if the RegUnits changed.
inheritRegUnits(CodeGenRegBank & RegBank)256dff0c46cSDimitry Andric bool CodeGenRegister::inheritRegUnits(CodeGenRegBank &RegBank) {
257ff0cc061SDimitry Andric   bool changed = false;
2582cab237bSDimitry Andric   for (const auto &SubReg : SubRegs) {
2592cab237bSDimitry Andric     CodeGenRegister *SR = SubReg.second;
260dff0c46cSDimitry Andric     // Merge the subregister's units into this register's RegUnits.
261ff0cc061SDimitry Andric     changed |= (RegUnits |= SR->RegUnits);
262dff0c46cSDimitry Andric   }
263ff0cc061SDimitry Andric 
264ff0cc061SDimitry Andric   return changed;
265bd5abe19SDimitry Andric }
266bd5abe19SDimitry Andric 
267bd5abe19SDimitry Andric const CodeGenRegister::SubRegMap &
computeSubRegs(CodeGenRegBank & RegBank)2687ae0e2c9SDimitry Andric CodeGenRegister::computeSubRegs(CodeGenRegBank &RegBank) {
269bd5abe19SDimitry Andric   // Only compute this map once.
270bd5abe19SDimitry Andric   if (SubRegsComplete)
271bd5abe19SDimitry Andric     return SubRegs;
272bd5abe19SDimitry Andric   SubRegsComplete = true;
273bd5abe19SDimitry Andric 
274ff0cc061SDimitry Andric   HasDisjunctSubRegs = ExplicitSubRegs.size() > 1;
275ff0cc061SDimitry Andric 
2767ae0e2c9SDimitry Andric   // First insert the explicit subregs and make sure they are fully indexed.
2777ae0e2c9SDimitry Andric   for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
2787ae0e2c9SDimitry Andric     CodeGenRegister *SR = ExplicitSubRegs[i];
2797ae0e2c9SDimitry Andric     CodeGenSubRegIndex *Idx = ExplicitSubRegIndices[i];
2804ba319b5SDimitry Andric     if (!SR->Artificial)
2814ba319b5SDimitry Andric       Idx->Artificial = false;
282dff0c46cSDimitry Andric     if (!SubRegs.insert(std::make_pair(Idx, SR)).second)
2833861d79fSDimitry Andric       PrintFatalError(TheDef->getLoc(), "SubRegIndex " + Idx->getName() +
284bd5abe19SDimitry Andric                       " appears twice in Register " + getName());
2857ae0e2c9SDimitry Andric     // Map explicit sub-registers first, so the names take precedence.
2867ae0e2c9SDimitry Andric     // The inherited sub-registers are mapped below.
2877ae0e2c9SDimitry Andric     SubReg2Idx.insert(std::make_pair(SR, Idx));
288bd5abe19SDimitry Andric   }
289bd5abe19SDimitry Andric 
290bd5abe19SDimitry Andric   // Keep track of inherited subregs and how they can be reached.
291dff0c46cSDimitry Andric   SmallPtrSet<CodeGenRegister*, 8> Orphans;
292bd5abe19SDimitry Andric 
293dff0c46cSDimitry Andric   // Clone inherited subregs and place duplicate entries in Orphans.
294bd5abe19SDimitry Andric   // Here the order is important - earlier subregs take precedence.
2952cab237bSDimitry Andric   for (CodeGenRegister *ESR : ExplicitSubRegs) {
2962cab237bSDimitry Andric     const SubRegMap &Map = ESR->computeSubRegs(RegBank);
2972cab237bSDimitry Andric     HasDisjunctSubRegs |= ESR->HasDisjunctSubRegs;
29817a519f9SDimitry Andric 
2992cab237bSDimitry Andric     for (const auto &SR : Map) {
3002cab237bSDimitry Andric       if (!SubRegs.insert(SR).second)
3012cab237bSDimitry Andric         Orphans.insert(SR.second);
30217a519f9SDimitry Andric     }
303bd5abe19SDimitry Andric   }
304bd5abe19SDimitry Andric 
305dff0c46cSDimitry Andric   // Expand any composed subreg indices.
306dff0c46cSDimitry Andric   // If dsub_2 has ComposedOf = [qsub_1, dsub_0], and this register has a
307dff0c46cSDimitry Andric   // qsub_1 subreg, add a dsub_2 subreg.  Keep growing Indices and process
308dff0c46cSDimitry Andric   // expanded subreg indices recursively.
3097ae0e2c9SDimitry Andric   SmallVector<CodeGenSubRegIndex*, 8> Indices = ExplicitSubRegIndices;
310dff0c46cSDimitry Andric   for (unsigned i = 0; i != Indices.size(); ++i) {
311dff0c46cSDimitry Andric     CodeGenSubRegIndex *Idx = Indices[i];
312dff0c46cSDimitry Andric     const CodeGenSubRegIndex::CompMap &Comps = Idx->getComposites();
313dff0c46cSDimitry Andric     CodeGenRegister *SR = SubRegs[Idx];
3147ae0e2c9SDimitry Andric     const SubRegMap &Map = SR->computeSubRegs(RegBank);
315dff0c46cSDimitry Andric 
316dff0c46cSDimitry Andric     // Look at the possible compositions of Idx.
317dff0c46cSDimitry Andric     // They may not all be supported by SR.
318dff0c46cSDimitry Andric     for (CodeGenSubRegIndex::CompMap::const_iterator I = Comps.begin(),
319dff0c46cSDimitry Andric            E = Comps.end(); I != E; ++I) {
320dff0c46cSDimitry Andric       SubRegMap::const_iterator SRI = Map.find(I->first);
321dff0c46cSDimitry Andric       if (SRI == Map.end())
322dff0c46cSDimitry Andric         continue; // Idx + I->first doesn't exist in SR.
323dff0c46cSDimitry Andric       // Add I->second as a name for the subreg SRI->second, assuming it is
324dff0c46cSDimitry Andric       // orphaned, and the name isn't already used for something else.
325dff0c46cSDimitry Andric       if (SubRegs.count(I->second) || !Orphans.erase(SRI->second))
326dff0c46cSDimitry Andric         continue;
327dff0c46cSDimitry Andric       // We found a new name for the orphaned sub-register.
328dff0c46cSDimitry Andric       SubRegs.insert(std::make_pair(I->second, SRI->second));
329dff0c46cSDimitry Andric       Indices.push_back(I->second);
330dff0c46cSDimitry Andric     }
331dff0c46cSDimitry Andric   }
332dff0c46cSDimitry Andric 
333bd5abe19SDimitry Andric   // Now Orphans contains the inherited subregisters without a direct index.
334bd5abe19SDimitry Andric   // Create inferred indexes for all missing entries.
335dff0c46cSDimitry Andric   // Work backwards in the Indices vector in order to compose subregs bottom-up.
336dff0c46cSDimitry Andric   // Consider this subreg sequence:
337dff0c46cSDimitry Andric   //
338dff0c46cSDimitry Andric   //   qsub_1 -> dsub_0 -> ssub_0
339dff0c46cSDimitry Andric   //
340dff0c46cSDimitry Andric   // The qsub_1 -> dsub_0 composition becomes dsub_2, so the ssub_0 register
341dff0c46cSDimitry Andric   // can be reached in two different ways:
342dff0c46cSDimitry Andric   //
343dff0c46cSDimitry Andric   //   qsub_1 -> ssub_0
344dff0c46cSDimitry Andric   //   dsub_2 -> ssub_0
345dff0c46cSDimitry Andric   //
346dff0c46cSDimitry Andric   // We pick the latter composition because another register may have [dsub_0,
3477ae0e2c9SDimitry Andric   // dsub_1, dsub_2] subregs without necessarily having a qsub_1 subreg.  The
348dff0c46cSDimitry Andric   // dsub_2 -> ssub_0 composition can be shared.
349dff0c46cSDimitry Andric   while (!Indices.empty() && !Orphans.empty()) {
350dff0c46cSDimitry Andric     CodeGenSubRegIndex *Idx = Indices.pop_back_val();
351dff0c46cSDimitry Andric     CodeGenRegister *SR = SubRegs[Idx];
3527ae0e2c9SDimitry Andric     const SubRegMap &Map = SR->computeSubRegs(RegBank);
3532cab237bSDimitry Andric     for (const auto &SubReg : Map)
3542cab237bSDimitry Andric       if (Orphans.erase(SubReg.second))
3552cab237bSDimitry Andric         SubRegs[RegBank.getCompositeSubRegIndex(Idx, SubReg.first)] = SubReg.second;
356bd5abe19SDimitry Andric   }
357dff0c46cSDimitry Andric 
3587ae0e2c9SDimitry Andric   // Compute the inverse SubReg -> Idx map.
3592cab237bSDimitry Andric   for (const auto &SubReg : SubRegs) {
3602cab237bSDimitry Andric     if (SubReg.second == this) {
3613861d79fSDimitry Andric       ArrayRef<SMLoc> Loc;
3627ae0e2c9SDimitry Andric       if (TheDef)
3637ae0e2c9SDimitry Andric         Loc = TheDef->getLoc();
3643861d79fSDimitry Andric       PrintFatalError(Loc, "Register " + getName() +
3657ae0e2c9SDimitry Andric                       " has itself as a sub-register");
3667ae0e2c9SDimitry Andric     }
367f785676fSDimitry Andric 
368f785676fSDimitry Andric     // Compute AllSuperRegsCovered.
369f785676fSDimitry Andric     if (!CoveredBySubRegs)
3702cab237bSDimitry Andric       SubReg.first->AllSuperRegsCovered = false;
371f785676fSDimitry Andric 
3727ae0e2c9SDimitry Andric     // Ensure that every sub-register has a unique name.
3737ae0e2c9SDimitry Andric     DenseMap<const CodeGenRegister*, CodeGenSubRegIndex*>::iterator Ins =
3742cab237bSDimitry Andric       SubReg2Idx.insert(std::make_pair(SubReg.second, SubReg.first)).first;
3752cab237bSDimitry Andric     if (Ins->second == SubReg.first)
3767ae0e2c9SDimitry Andric       continue;
3772cab237bSDimitry Andric     // Trouble: Two different names for SubReg.second.
3783861d79fSDimitry Andric     ArrayRef<SMLoc> Loc;
3797ae0e2c9SDimitry Andric     if (TheDef)
3807ae0e2c9SDimitry Andric       Loc = TheDef->getLoc();
3813861d79fSDimitry Andric     PrintFatalError(Loc, "Sub-register can't have two names: " +
3822cab237bSDimitry Andric                   SubReg.second->getName() + " available as " +
3832cab237bSDimitry Andric                   SubReg.first->getName() + " and " + Ins->second->getName());
3847ae0e2c9SDimitry Andric   }
3857ae0e2c9SDimitry Andric 
3867ae0e2c9SDimitry Andric   // Derive possible names for sub-register concatenations from any explicit
3877ae0e2c9SDimitry Andric   // sub-registers. By doing this before computeSecondarySubRegs(), we ensure
3887ae0e2c9SDimitry Andric   // that getConcatSubRegIndex() won't invent any concatenated indices that the
3897ae0e2c9SDimitry Andric   // user already specified.
3907ae0e2c9SDimitry Andric   for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
3917ae0e2c9SDimitry Andric     CodeGenRegister *SR = ExplicitSubRegs[i];
3924ba319b5SDimitry Andric     if (!SR->CoveredBySubRegs || SR->ExplicitSubRegs.size() <= 1 ||
3934ba319b5SDimitry Andric         SR->Artificial)
3947ae0e2c9SDimitry Andric       continue;
3957ae0e2c9SDimitry Andric 
3967ae0e2c9SDimitry Andric     // SR is composed of multiple sub-regs. Find their names in this register.
3977ae0e2c9SDimitry Andric     SmallVector<CodeGenSubRegIndex*, 8> Parts;
3984ba319b5SDimitry Andric     for (unsigned j = 0, e = SR->ExplicitSubRegs.size(); j != e; ++j) {
3994ba319b5SDimitry Andric       CodeGenSubRegIndex &I = *SR->ExplicitSubRegIndices[j];
4004ba319b5SDimitry Andric       if (!I.Artificial)
4017ae0e2c9SDimitry Andric         Parts.push_back(getSubRegIndex(SR->ExplicitSubRegs[j]));
4024ba319b5SDimitry Andric     }
4037ae0e2c9SDimitry Andric 
4047ae0e2c9SDimitry Andric     // Offer this as an existing spelling for the concatenation of Parts.
4052cab237bSDimitry Andric     CodeGenSubRegIndex &Idx = *ExplicitSubRegIndices[i];
4062cab237bSDimitry Andric     Idx.setConcatenationOf(Parts);
4077ae0e2c9SDimitry Andric   }
4087ae0e2c9SDimitry Andric 
4097ae0e2c9SDimitry Andric   // Initialize RegUnitList. Because getSubRegs is called recursively, this
4107ae0e2c9SDimitry Andric   // processes the register hierarchy in postorder.
411dff0c46cSDimitry Andric   //
4127ae0e2c9SDimitry Andric   // Inherit all sub-register units. It is good enough to look at the explicit
4137ae0e2c9SDimitry Andric   // sub-registers, the other registers won't contribute any more units.
4147ae0e2c9SDimitry Andric   for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
4157ae0e2c9SDimitry Andric     CodeGenRegister *SR = ExplicitSubRegs[i];
416ff0cc061SDimitry Andric     RegUnits |= SR->RegUnits;
4177ae0e2c9SDimitry Andric   }
4187ae0e2c9SDimitry Andric 
4197ae0e2c9SDimitry Andric   // Absent any ad hoc aliasing, we create one register unit per leaf register.
4207ae0e2c9SDimitry Andric   // These units correspond to the maximal cliques in the register overlap
4217ae0e2c9SDimitry Andric   // graph which is optimal.
4227ae0e2c9SDimitry Andric   //
4237ae0e2c9SDimitry Andric   // When there is ad hoc aliasing, we simply create one unit per edge in the
4247ae0e2c9SDimitry Andric   // undirected ad hoc aliasing graph. Technically, we could do better by
4257ae0e2c9SDimitry Andric   // identifying maximal cliques in the ad hoc graph, but cliques larger than 2
4267ae0e2c9SDimitry Andric   // are extremely rare anyway (I've never seen one), so we don't bother with
4277ae0e2c9SDimitry Andric   // the added complexity.
4287ae0e2c9SDimitry Andric   for (unsigned i = 0, e = ExplicitAliases.size(); i != e; ++i) {
4297ae0e2c9SDimitry Andric     CodeGenRegister *AR = ExplicitAliases[i];
4307ae0e2c9SDimitry Andric     // Only visit each edge once.
4317ae0e2c9SDimitry Andric     if (AR->SubRegsComplete)
4327ae0e2c9SDimitry Andric       continue;
4337ae0e2c9SDimitry Andric     // Create a RegUnit representing this alias edge, and add it to both
4347ae0e2c9SDimitry Andric     // registers.
4357ae0e2c9SDimitry Andric     unsigned Unit = RegBank.newRegUnit(this, AR);
436ff0cc061SDimitry Andric     RegUnits.set(Unit);
437ff0cc061SDimitry Andric     AR->RegUnits.set(Unit);
4387ae0e2c9SDimitry Andric   }
4397ae0e2c9SDimitry Andric 
4407ae0e2c9SDimitry Andric   // Finally, create units for leaf registers without ad hoc aliases. Note that
4417ae0e2c9SDimitry Andric   // a leaf register with ad hoc aliases doesn't get its own unit - it isn't
4427ae0e2c9SDimitry Andric   // necessary. This means the aliasing leaf registers can share a single unit.
4437ae0e2c9SDimitry Andric   if (RegUnits.empty())
444ff0cc061SDimitry Andric     RegUnits.set(RegBank.newRegUnit(this));
4457ae0e2c9SDimitry Andric 
4467ae0e2c9SDimitry Andric   // We have now computed the native register units. More may be adopted later
4477ae0e2c9SDimitry Andric   // for balancing purposes.
448ff0cc061SDimitry Andric   NativeRegUnits = RegUnits;
4497ae0e2c9SDimitry Andric 
450bd5abe19SDimitry Andric   return SubRegs;
451bd5abe19SDimitry Andric }
452bd5abe19SDimitry Andric 
4537ae0e2c9SDimitry Andric // In a register that is covered by its sub-registers, try to find redundant
4547ae0e2c9SDimitry Andric // sub-registers. For example:
4557ae0e2c9SDimitry Andric //
4567ae0e2c9SDimitry Andric //   QQ0 = {Q0, Q1}
4577ae0e2c9SDimitry Andric //   Q0 = {D0, D1}
4587ae0e2c9SDimitry Andric //   Q1 = {D2, D3}
4597ae0e2c9SDimitry Andric //
4607ae0e2c9SDimitry Andric // We can infer that D1_D2 is also a sub-register, even if it wasn't named in
4617ae0e2c9SDimitry Andric // the register definition.
4627ae0e2c9SDimitry Andric //
4637ae0e2c9SDimitry Andric // The explicitly specified registers form a tree. This function discovers
4647ae0e2c9SDimitry Andric // sub-register relationships that would force a DAG.
4657ae0e2c9SDimitry Andric //
computeSecondarySubRegs(CodeGenRegBank & RegBank)4667ae0e2c9SDimitry Andric void CodeGenRegister::computeSecondarySubRegs(CodeGenRegBank &RegBank) {
4677ae0e2c9SDimitry Andric   SmallVector<SubRegMap::value_type, 8> NewSubRegs;
4687ae0e2c9SDimitry Andric 
4692cab237bSDimitry Andric   std::queue<std::pair<CodeGenSubRegIndex*,CodeGenRegister*>> SubRegQueue;
4702cab237bSDimitry Andric   for (std::pair<CodeGenSubRegIndex*,CodeGenRegister*> P : SubRegs)
4712cab237bSDimitry Andric     SubRegQueue.push(P);
4722cab237bSDimitry Andric 
4737ae0e2c9SDimitry Andric   // Look at the leading super-registers of each sub-register. Those are the
4747ae0e2c9SDimitry Andric   // candidates for new sub-registers, assuming they are fully contained in
4757ae0e2c9SDimitry Andric   // this register.
4762cab237bSDimitry Andric   while (!SubRegQueue.empty()) {
4772cab237bSDimitry Andric     CodeGenSubRegIndex *SubRegIdx;
4782cab237bSDimitry Andric     const CodeGenRegister *SubReg;
4792cab237bSDimitry Andric     std::tie(SubRegIdx, SubReg) = SubRegQueue.front();
4802cab237bSDimitry Andric     SubRegQueue.pop();
4812cab237bSDimitry Andric 
4827ae0e2c9SDimitry Andric     const CodeGenRegister::SuperRegList &Leads = SubReg->LeadingSuperRegs;
4837ae0e2c9SDimitry Andric     for (unsigned i = 0, e = Leads.size(); i != e; ++i) {
4847ae0e2c9SDimitry Andric       CodeGenRegister *Cand = const_cast<CodeGenRegister*>(Leads[i]);
4857ae0e2c9SDimitry Andric       // Already got this sub-register?
4867ae0e2c9SDimitry Andric       if (Cand == this || getSubRegIndex(Cand))
4877ae0e2c9SDimitry Andric         continue;
4887ae0e2c9SDimitry Andric       // Check if each component of Cand is already a sub-register.
4897ae0e2c9SDimitry Andric       assert(!Cand->ExplicitSubRegs.empty() &&
4907ae0e2c9SDimitry Andric              "Super-register has no sub-registers");
4912cab237bSDimitry Andric       if (Cand->ExplicitSubRegs.size() == 1)
4922cab237bSDimitry Andric         continue;
4932cab237bSDimitry Andric       SmallVector<CodeGenSubRegIndex*, 8> Parts;
4942cab237bSDimitry Andric       // We know that the first component is (SubRegIdx,SubReg). However we
4952cab237bSDimitry Andric       // may still need to split it into smaller subregister parts.
4962cab237bSDimitry Andric       assert(Cand->ExplicitSubRegs[0] == SubReg && "LeadingSuperRegs correct");
4972cab237bSDimitry Andric       assert(getSubRegIndex(SubReg) == SubRegIdx && "LeadingSuperRegs correct");
4982cab237bSDimitry Andric       for (CodeGenRegister *SubReg : Cand->ExplicitSubRegs) {
4992cab237bSDimitry Andric         if (CodeGenSubRegIndex *SubRegIdx = getSubRegIndex(SubReg)) {
5002cab237bSDimitry Andric           if (SubRegIdx->ConcatenationOf.empty()) {
5012cab237bSDimitry Andric             Parts.push_back(SubRegIdx);
5022cab237bSDimitry Andric           } else
5032cab237bSDimitry Andric             for (CodeGenSubRegIndex *SubIdx : SubRegIdx->ConcatenationOf)
5042cab237bSDimitry Andric               Parts.push_back(SubIdx);
5052cab237bSDimitry Andric         } else {
5067ae0e2c9SDimitry Andric           // Sub-register doesn't exist.
5077ae0e2c9SDimitry Andric           Parts.clear();
5087ae0e2c9SDimitry Andric           break;
5097ae0e2c9SDimitry Andric         }
5107ae0e2c9SDimitry Andric       }
5112cab237bSDimitry Andric       // There is nothing to do if some Cand sub-register is not part of this
5122cab237bSDimitry Andric       // register.
5132cab237bSDimitry Andric       if (Parts.empty())
5147ae0e2c9SDimitry Andric         continue;
5157ae0e2c9SDimitry Andric 
5167ae0e2c9SDimitry Andric       // Each part of Cand is a sub-register of this. Make the full Cand also
5177ae0e2c9SDimitry Andric       // a sub-register with a concatenated sub-register index.
5187ae0e2c9SDimitry Andric       CodeGenSubRegIndex *Concat = RegBank.getConcatSubRegIndex(Parts);
5192cab237bSDimitry Andric       std::pair<CodeGenSubRegIndex*,CodeGenRegister*> NewSubReg =
5202cab237bSDimitry Andric           std::make_pair(Concat, Cand);
5217ae0e2c9SDimitry Andric 
5222cab237bSDimitry Andric       if (!SubRegs.insert(NewSubReg).second)
5237ae0e2c9SDimitry Andric         continue;
5247ae0e2c9SDimitry Andric 
5252cab237bSDimitry Andric       // We inserted a new subregister.
5262cab237bSDimitry Andric       NewSubRegs.push_back(NewSubReg);
5272cab237bSDimitry Andric       SubRegQueue.push(NewSubReg);
5282cab237bSDimitry Andric       SubReg2Idx.insert(std::make_pair(Cand, Concat));
5292cab237bSDimitry Andric     }
5307ae0e2c9SDimitry Andric   }
5317ae0e2c9SDimitry Andric 
5327ae0e2c9SDimitry Andric   // Create sub-register index composition maps for the synthesized indices.
5337ae0e2c9SDimitry Andric   for (unsigned i = 0, e = NewSubRegs.size(); i != e; ++i) {
5347ae0e2c9SDimitry Andric     CodeGenSubRegIndex *NewIdx = NewSubRegs[i].first;
5357ae0e2c9SDimitry Andric     CodeGenRegister *NewSubReg = NewSubRegs[i].second;
5367ae0e2c9SDimitry Andric     for (SubRegMap::const_iterator SI = NewSubReg->SubRegs.begin(),
5377ae0e2c9SDimitry Andric            SE = NewSubReg->SubRegs.end(); SI != SE; ++SI) {
5387ae0e2c9SDimitry Andric       CodeGenSubRegIndex *SubIdx = getSubRegIndex(SI->second);
5397ae0e2c9SDimitry Andric       if (!SubIdx)
5403861d79fSDimitry Andric         PrintFatalError(TheDef->getLoc(), "No SubRegIndex for " +
5417ae0e2c9SDimitry Andric                         SI->second->getName() + " in " + getName());
5427ae0e2c9SDimitry Andric       NewIdx->addComposite(SI->first, SubIdx);
5437ae0e2c9SDimitry Andric     }
5447ae0e2c9SDimitry Andric   }
5457ae0e2c9SDimitry Andric }
5467ae0e2c9SDimitry Andric 
computeSuperRegs(CodeGenRegBank & RegBank)5477ae0e2c9SDimitry Andric void CodeGenRegister::computeSuperRegs(CodeGenRegBank &RegBank) {
5487ae0e2c9SDimitry Andric   // Only visit each register once.
5497ae0e2c9SDimitry Andric   if (SuperRegsComplete)
5507ae0e2c9SDimitry Andric     return;
5517ae0e2c9SDimitry Andric   SuperRegsComplete = true;
5527ae0e2c9SDimitry Andric 
5537ae0e2c9SDimitry Andric   // Make sure all sub-registers have been visited first, so the super-reg
5547ae0e2c9SDimitry Andric   // lists will be topologically ordered.
5557ae0e2c9SDimitry Andric   for (SubRegMap::const_iterator I = SubRegs.begin(), E = SubRegs.end();
5567ae0e2c9SDimitry Andric        I != E; ++I)
5577ae0e2c9SDimitry Andric     I->second->computeSuperRegs(RegBank);
5587ae0e2c9SDimitry Andric 
5597ae0e2c9SDimitry Andric   // Now add this as a super-register on all sub-registers.
5607ae0e2c9SDimitry Andric   // Also compute the TopoSigId in post-order.
5617ae0e2c9SDimitry Andric   TopoSigId Id;
5627ae0e2c9SDimitry Andric   for (SubRegMap::const_iterator I = SubRegs.begin(), E = SubRegs.end();
5637ae0e2c9SDimitry Andric        I != E; ++I) {
5647ae0e2c9SDimitry Andric     // Topological signature computed from SubIdx, TopoId(SubReg).
5657ae0e2c9SDimitry Andric     // Loops and idempotent indices have TopoSig = ~0u.
5667ae0e2c9SDimitry Andric     Id.push_back(I->first->EnumValue);
5677ae0e2c9SDimitry Andric     Id.push_back(I->second->TopoSig);
5687ae0e2c9SDimitry Andric 
5697ae0e2c9SDimitry Andric     // Don't add duplicate entries.
5707ae0e2c9SDimitry Andric     if (!I->second->SuperRegs.empty() && I->second->SuperRegs.back() == this)
5717ae0e2c9SDimitry Andric       continue;
5727ae0e2c9SDimitry Andric     I->second->SuperRegs.push_back(this);
5737ae0e2c9SDimitry Andric   }
5747ae0e2c9SDimitry Andric   TopoSig = RegBank.getTopoSig(Id);
5757ae0e2c9SDimitry Andric }
5767ae0e2c9SDimitry Andric 
57717a519f9SDimitry Andric void
addSubRegsPreOrder(SetVector<const CodeGenRegister * > & OSet,CodeGenRegBank & RegBank) const578dff0c46cSDimitry Andric CodeGenRegister::addSubRegsPreOrder(SetVector<const CodeGenRegister*> &OSet,
579dff0c46cSDimitry Andric                                     CodeGenRegBank &RegBank) const {
58017a519f9SDimitry Andric   assert(SubRegsComplete && "Must precompute sub-registers");
5817ae0e2c9SDimitry Andric   for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
5827ae0e2c9SDimitry Andric     CodeGenRegister *SR = ExplicitSubRegs[i];
58317a519f9SDimitry Andric     if (OSet.insert(SR))
584dff0c46cSDimitry Andric       SR->addSubRegsPreOrder(OSet, RegBank);
58517a519f9SDimitry Andric   }
5867ae0e2c9SDimitry Andric   // Add any secondary sub-registers that weren't part of the explicit tree.
5877ae0e2c9SDimitry Andric   for (SubRegMap::const_iterator I = SubRegs.begin(), E = SubRegs.end();
5887ae0e2c9SDimitry Andric        I != E; ++I)
5897ae0e2c9SDimitry Andric     OSet.insert(I->second);
5907ae0e2c9SDimitry Andric }
5917ae0e2c9SDimitry Andric 
592dff0c46cSDimitry Andric // Get the sum of this register's unit weights.
getWeight(const CodeGenRegBank & RegBank) const593dff0c46cSDimitry Andric unsigned CodeGenRegister::getWeight(const CodeGenRegBank &RegBank) const {
594dff0c46cSDimitry Andric   unsigned Weight = 0;
595ff0cc061SDimitry Andric   for (RegUnitList::iterator I = RegUnits.begin(), E = RegUnits.end();
596dff0c46cSDimitry Andric        I != E; ++I) {
5977ae0e2c9SDimitry Andric     Weight += RegBank.getRegUnit(*I).Weight;
598dff0c46cSDimitry Andric   }
599dff0c46cSDimitry Andric   return Weight;
600dff0c46cSDimitry Andric }
601dff0c46cSDimitry Andric 
60217a519f9SDimitry Andric //===----------------------------------------------------------------------===//
60317a519f9SDimitry Andric //                               RegisterTuples
60417a519f9SDimitry Andric //===----------------------------------------------------------------------===//
60517a519f9SDimitry Andric 
60617a519f9SDimitry Andric // A RegisterTuples def is used to generate pseudo-registers from lists of
60717a519f9SDimitry Andric // sub-registers. We provide a SetTheory expander class that returns the new
60817a519f9SDimitry Andric // registers.
60917a519f9SDimitry Andric namespace {
610d88c1a5aSDimitry Andric 
61117a519f9SDimitry Andric struct TupleExpander : SetTheory::Expander {
6124ba319b5SDimitry Andric   // Reference to SynthDefs in the containing CodeGenRegBank, to keep track of
6134ba319b5SDimitry Andric   // the synthesized definitions for their lifetime.
6144ba319b5SDimitry Andric   std::vector<std::unique_ptr<Record>> &SynthDefs;
6154ba319b5SDimitry Andric 
TupleExpander__anon9ef927ed0211::TupleExpander6164ba319b5SDimitry Andric   TupleExpander(std::vector<std::unique_ptr<Record>> &SynthDefs)
6174ba319b5SDimitry Andric       : SynthDefs(SynthDefs) {}
6184ba319b5SDimitry Andric 
expand__anon9ef927ed0211::TupleExpander61991bc56edSDimitry Andric   void expand(SetTheory &ST, Record *Def, SetTheory::RecSet &Elts) override {
62017a519f9SDimitry Andric     std::vector<Record*> Indices = Def->getValueAsListOfDefs("SubRegIndices");
62117a519f9SDimitry Andric     unsigned Dim = Indices.size();
62217a519f9SDimitry Andric     ListInit *SubRegs = Def->getValueAsListInit("SubRegs");
62397bc6c73SDimitry Andric     if (Dim != SubRegs->size())
6243861d79fSDimitry Andric       PrintFatalError(Def->getLoc(), "SubRegIndices and SubRegs size mismatch");
62517a519f9SDimitry Andric     if (Dim < 2)
6263861d79fSDimitry Andric       PrintFatalError(Def->getLoc(),
6273861d79fSDimitry Andric                       "Tuples must have at least 2 sub-registers");
62817a519f9SDimitry Andric 
62917a519f9SDimitry Andric     // Evaluate the sub-register lists to be zipped.
63017a519f9SDimitry Andric     unsigned Length = ~0u;
63117a519f9SDimitry Andric     SmallVector<SetTheory::RecSet, 4> Lists(Dim);
63217a519f9SDimitry Andric     for (unsigned i = 0; i != Dim; ++i) {
6333861d79fSDimitry Andric       ST.evaluate(SubRegs->getElement(i), Lists[i], Def->getLoc());
63417a519f9SDimitry Andric       Length = std::min(Length, unsigned(Lists[i].size()));
63517a519f9SDimitry Andric     }
63617a519f9SDimitry Andric 
63717a519f9SDimitry Andric     if (Length == 0)
63817a519f9SDimitry Andric       return;
63917a519f9SDimitry Andric 
64017a519f9SDimitry Andric     // Precompute some types.
64117a519f9SDimitry Andric     Record *RegisterCl = Def->getRecords().getClass("Register");
6426122f3e6SDimitry Andric     RecTy *RegisterRecTy = RecordRecTy::get(RegisterCl);
6436122f3e6SDimitry Andric     StringInit *BlankName = StringInit::get("");
64417a519f9SDimitry Andric 
64517a519f9SDimitry Andric     // Zip them up.
64617a519f9SDimitry Andric     for (unsigned n = 0; n != Length; ++n) {
64717a519f9SDimitry Andric       std::string Name;
64817a519f9SDimitry Andric       Record *Proto = Lists[0][n];
64917a519f9SDimitry Andric       std::vector<Init*> Tuple;
65017a519f9SDimitry Andric       unsigned CostPerUse = 0;
65117a519f9SDimitry Andric       for (unsigned i = 0; i != Dim; ++i) {
65217a519f9SDimitry Andric         Record *Reg = Lists[i][n];
65317a519f9SDimitry Andric         if (i) Name += '_';
65417a519f9SDimitry Andric         Name += Reg->getName();
6556122f3e6SDimitry Andric         Tuple.push_back(DefInit::get(Reg));
65617a519f9SDimitry Andric         CostPerUse = std::max(CostPerUse,
65717a519f9SDimitry Andric                               unsigned(Reg->getValueAsInt("CostPerUse")));
65817a519f9SDimitry Andric       }
65917a519f9SDimitry Andric 
66017a519f9SDimitry Andric       // Create a new Record representing the synthesized register. This record
66117a519f9SDimitry Andric       // is only for consumption by CodeGenRegister, it is not added to the
66217a519f9SDimitry Andric       // RecordKeeper.
6634ba319b5SDimitry Andric       SynthDefs.emplace_back(
6644ba319b5SDimitry Andric           llvm::make_unique<Record>(Name, Def->getLoc(), Def->getRecords()));
6654ba319b5SDimitry Andric       Record *NewReg = SynthDefs.back().get();
66617a519f9SDimitry Andric       Elts.insert(NewReg);
66717a519f9SDimitry Andric 
66817a519f9SDimitry Andric       // Copy Proto super-classes.
6693ca95b02SDimitry Andric       ArrayRef<std::pair<Record *, SMRange>> Supers = Proto->getSuperClasses();
6703ca95b02SDimitry Andric       for (const auto &SuperPair : Supers)
6713ca95b02SDimitry Andric         NewReg->addSuperClass(SuperPair.first, SuperPair.second);
67217a519f9SDimitry Andric 
67317a519f9SDimitry Andric       // Copy Proto fields.
67417a519f9SDimitry Andric       for (unsigned i = 0, e = Proto->getValues().size(); i != e; ++i) {
67517a519f9SDimitry Andric         RecordVal RV = Proto->getValues()[i];
67617a519f9SDimitry Andric 
677dff0c46cSDimitry Andric         // Skip existing fields, like NAME.
678dff0c46cSDimitry Andric         if (NewReg->getValue(RV.getNameInit()))
679dff0c46cSDimitry Andric           continue;
680dff0c46cSDimitry Andric 
681dff0c46cSDimitry Andric         StringRef Field = RV.getName();
682dff0c46cSDimitry Andric 
68317a519f9SDimitry Andric         // Replace the sub-register list with Tuple.
684dff0c46cSDimitry Andric         if (Field == "SubRegs")
6856122f3e6SDimitry Andric           RV.setValue(ListInit::get(Tuple, RegisterRecTy));
68617a519f9SDimitry Andric 
68717a519f9SDimitry Andric         // Provide a blank AsmName. MC hacks are required anyway.
688dff0c46cSDimitry Andric         if (Field == "AsmName")
68917a519f9SDimitry Andric           RV.setValue(BlankName);
69017a519f9SDimitry Andric 
69117a519f9SDimitry Andric         // CostPerUse is aggregated from all Tuple members.
692dff0c46cSDimitry Andric         if (Field == "CostPerUse")
6936122f3e6SDimitry Andric           RV.setValue(IntInit::get(CostPerUse));
69417a519f9SDimitry Andric 
695dff0c46cSDimitry Andric         // Composite registers are always covered by sub-registers.
696dff0c46cSDimitry Andric         if (Field == "CoveredBySubRegs")
697dff0c46cSDimitry Andric           RV.setValue(BitInit::get(true));
698dff0c46cSDimitry Andric 
69917a519f9SDimitry Andric         // Copy fields from the RegisterTuples def.
700dff0c46cSDimitry Andric         if (Field == "SubRegIndices" ||
701dff0c46cSDimitry Andric             Field == "CompositeIndices") {
702dff0c46cSDimitry Andric           NewReg->addValue(*Def->getValue(Field));
70317a519f9SDimitry Andric           continue;
70417a519f9SDimitry Andric         }
70517a519f9SDimitry Andric 
70617a519f9SDimitry Andric         // Some fields get their default uninitialized value.
707dff0c46cSDimitry Andric         if (Field == "DwarfNumbers" ||
708dff0c46cSDimitry Andric             Field == "DwarfAlias" ||
709dff0c46cSDimitry Andric             Field == "Aliases") {
710dff0c46cSDimitry Andric           if (const RecordVal *DefRV = RegisterCl->getValue(Field))
71117a519f9SDimitry Andric             NewReg->addValue(*DefRV);
71217a519f9SDimitry Andric           continue;
71317a519f9SDimitry Andric         }
71417a519f9SDimitry Andric 
71517a519f9SDimitry Andric         // Everything else is copied from Proto.
71617a519f9SDimitry Andric         NewReg->addValue(RV);
71717a519f9SDimitry Andric       }
71817a519f9SDimitry Andric     }
71917a519f9SDimitry Andric   }
72017a519f9SDimitry Andric };
721d88c1a5aSDimitry Andric 
722d88c1a5aSDimitry Andric } // end anonymous namespace
72317a519f9SDimitry Andric 
724bd5abe19SDimitry Andric //===----------------------------------------------------------------------===//
725bd5abe19SDimitry Andric //                            CodeGenRegisterClass
726bd5abe19SDimitry Andric //===----------------------------------------------------------------------===//
727bd5abe19SDimitry Andric 
sortAndUniqueRegisters(CodeGenRegister::Vec & M)728ff0cc061SDimitry Andric static void sortAndUniqueRegisters(CodeGenRegister::Vec &M) {
729*b5893f02SDimitry Andric   llvm::sort(M, deref<llvm::less>());
730ff0cc061SDimitry Andric   M.erase(std::unique(M.begin(), M.end(), deref<llvm::equal>()), M.end());
731ff0cc061SDimitry Andric }
732ff0cc061SDimitry Andric 
CodeGenRegisterClass(CodeGenRegBank & RegBank,Record * R)73317a519f9SDimitry Andric CodeGenRegisterClass::CodeGenRegisterClass(CodeGenRegBank &RegBank, Record *R)
7347ae0e2c9SDimitry Andric   : TheDef(R),
7357ae0e2c9SDimitry Andric     Name(R->getName()),
7367ae0e2c9SDimitry Andric     TopoSigs(RegBank.getNumTopoSigs()),
737d88c1a5aSDimitry Andric     EnumValue(-1) {
738bd5abe19SDimitry Andric 
739bd5abe19SDimitry Andric   std::vector<Record*> TypeList = R->getValueAsListOfDefs("RegTypes");
740bd5abe19SDimitry Andric   for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
741bd5abe19SDimitry Andric     Record *Type = TypeList[i];
742bd5abe19SDimitry Andric     if (!Type->isSubClassOf("ValueType"))
7433861d79fSDimitry Andric       PrintFatalError("RegTypes list member '" + Type->getName() +
7443861d79fSDimitry Andric         "' does not derive from the ValueType class!");
7452cab237bSDimitry Andric     VTs.push_back(getValueTypeByHwMode(Type, RegBank.getHwModes()));
746bd5abe19SDimitry Andric   }
747bd5abe19SDimitry Andric   assert(!VTs.empty() && "RegisterClass must contain at least one ValueType!");
748bd5abe19SDimitry Andric 
7496122f3e6SDimitry Andric   // Allocation order 0 is the full set. AltOrders provides others.
7506122f3e6SDimitry Andric   const SetTheory::RecVec *Elements = RegBank.getSets().expand(R);
7516122f3e6SDimitry Andric   ListInit *AltOrders = R->getValueAsListInit("AltOrders");
75297bc6c73SDimitry Andric   Orders.resize(1 + AltOrders->size());
7536122f3e6SDimitry Andric 
75417a519f9SDimitry Andric   // Default allocation order always contains all registers.
7554ba319b5SDimitry Andric   Artificial = true;
7566122f3e6SDimitry Andric   for (unsigned i = 0, e = Elements->size(); i != e; ++i) {
7576122f3e6SDimitry Andric     Orders[0].push_back((*Elements)[i]);
7587ae0e2c9SDimitry Andric     const CodeGenRegister *Reg = RegBank.getReg((*Elements)[i]);
759ff0cc061SDimitry Andric     Members.push_back(Reg);
7604ba319b5SDimitry Andric     Artificial &= Reg->Artificial;
7617ae0e2c9SDimitry Andric     TopoSigs.set(Reg->getTopoSig());
7626122f3e6SDimitry Andric   }
763ff0cc061SDimitry Andric   sortAndUniqueRegisters(Members);
76417a519f9SDimitry Andric 
76517a519f9SDimitry Andric   // Alternative allocation orders may be subsets.
76617a519f9SDimitry Andric   SetTheory::RecSet Order;
76797bc6c73SDimitry Andric   for (unsigned i = 0, e = AltOrders->size(); i != e; ++i) {
7683861d79fSDimitry Andric     RegBank.getSets().evaluate(AltOrders->getElement(i), Order, R->getLoc());
7696122f3e6SDimitry Andric     Orders[1 + i].append(Order.begin(), Order.end());
77017a519f9SDimitry Andric     // Verify that all altorder members are regclass members.
77117a519f9SDimitry Andric     while (!Order.empty()) {
77217a519f9SDimitry Andric       CodeGenRegister *Reg = RegBank.getReg(Order.back());
77317a519f9SDimitry Andric       Order.pop_back();
77417a519f9SDimitry Andric       if (!contains(Reg))
7753861d79fSDimitry Andric         PrintFatalError(R->getLoc(), " AltOrder register " + Reg->getName() +
77617a519f9SDimitry Andric                       " is not a class member");
77717a519f9SDimitry Andric     }
778bd5abe19SDimitry Andric   }
779bd5abe19SDimitry Andric 
780bd5abe19SDimitry Andric   Namespace = R->getValueAsString("Namespace");
7812cab237bSDimitry Andric 
7822cab237bSDimitry Andric   if (const RecordVal *RV = R->getValue("RegInfos"))
7832cab237bSDimitry Andric     if (DefInit *DI = dyn_cast_or_null<DefInit>(RV->getValue()))
7842cab237bSDimitry Andric       RSI = RegSizeInfoByHwMode(DI->getDef(), RegBank.getHwModes());
7852cab237bSDimitry Andric   unsigned Size = R->getValueAsInt("Size");
7862cab237bSDimitry Andric   assert((RSI.hasDefault() || Size != 0 || VTs[0].isSimple()) &&
7872cab237bSDimitry Andric          "Impossible to determine register size");
7882cab237bSDimitry Andric   if (!RSI.hasDefault()) {
7892cab237bSDimitry Andric     RegSizeInfo RI;
7902cab237bSDimitry Andric     RI.RegSize = RI.SpillSize = Size ? Size
7912cab237bSDimitry Andric                                      : VTs[0].getSimple().getSizeInBits();
7922cab237bSDimitry Andric     RI.SpillAlignment = R->getValueAsInt("Alignment");
7932cab237bSDimitry Andric     RSI.Map.insert({DefaultMode, RI});
7942cab237bSDimitry Andric   }
7952cab237bSDimitry Andric 
796bd5abe19SDimitry Andric   CopyCost = R->getValueAsInt("CopyCost");
797bd5abe19SDimitry Andric   Allocatable = R->getValueAsBit("isAllocatable");
798dff0c46cSDimitry Andric   AltOrderSelect = R->getValueAsString("AltOrderSelect");
799ff0cc061SDimitry Andric   int AllocationPriority = R->getValueAsInt("AllocationPriority");
800ff0cc061SDimitry Andric   if (AllocationPriority < 0 || AllocationPriority > 63)
801ff0cc061SDimitry Andric     PrintFatalError(R->getLoc(), "AllocationPriority out of range [0,63]");
802ff0cc061SDimitry Andric   this->AllocationPriority = AllocationPriority;
80317a519f9SDimitry Andric }
80417a519f9SDimitry Andric 
8056122f3e6SDimitry Andric // Create an inferred register class that was missing from the .td files.
8066122f3e6SDimitry Andric // Most properties will be inherited from the closest super-class after the
8076122f3e6SDimitry Andric // class structure has been computed.
CodeGenRegisterClass(CodeGenRegBank & RegBank,StringRef Name,Key Props)8087ae0e2c9SDimitry Andric CodeGenRegisterClass::CodeGenRegisterClass(CodeGenRegBank &RegBank,
8097ae0e2c9SDimitry Andric                                            StringRef Name, Key Props)
8106122f3e6SDimitry Andric   : Members(*Props.Members),
81191bc56edSDimitry Andric     TheDef(nullptr),
8126122f3e6SDimitry Andric     Name(Name),
8137ae0e2c9SDimitry Andric     TopoSigs(RegBank.getNumTopoSigs()),
8146122f3e6SDimitry Andric     EnumValue(-1),
8152cab237bSDimitry Andric     RSI(Props.RSI),
8166122f3e6SDimitry Andric     CopyCost(0),
817ff0cc061SDimitry Andric     Allocatable(true),
818ff0cc061SDimitry Andric     AllocationPriority(0) {
8194ba319b5SDimitry Andric   Artificial = true;
8204ba319b5SDimitry Andric   for (const auto R : Members) {
821ff0cc061SDimitry Andric     TopoSigs.set(R->getTopoSig());
8224ba319b5SDimitry Andric     Artificial &= R->Artificial;
8234ba319b5SDimitry Andric   }
8246122f3e6SDimitry Andric }
8256122f3e6SDimitry Andric 
8266122f3e6SDimitry Andric // Compute inherited propertied for a synthesized register class.
inheritProperties(CodeGenRegBank & RegBank)8276122f3e6SDimitry Andric void CodeGenRegisterClass::inheritProperties(CodeGenRegBank &RegBank) {
8286122f3e6SDimitry Andric   assert(!getDef() && "Only synthesized classes can inherit properties");
8296122f3e6SDimitry Andric   assert(!SuperClasses.empty() && "Synthesized class without super class");
8306122f3e6SDimitry Andric 
8316122f3e6SDimitry Andric   // The last super-class is the smallest one.
8326122f3e6SDimitry Andric   CodeGenRegisterClass &Super = *SuperClasses.back();
8336122f3e6SDimitry Andric 
8346122f3e6SDimitry Andric   // Most properties are copied directly.
8356122f3e6SDimitry Andric   // Exceptions are members, size, and alignment
8366122f3e6SDimitry Andric   Namespace = Super.Namespace;
8376122f3e6SDimitry Andric   VTs = Super.VTs;
8386122f3e6SDimitry Andric   CopyCost = Super.CopyCost;
8396122f3e6SDimitry Andric   Allocatable = Super.Allocatable;
8406122f3e6SDimitry Andric   AltOrderSelect = Super.AltOrderSelect;
841ff0cc061SDimitry Andric   AllocationPriority = Super.AllocationPriority;
8426122f3e6SDimitry Andric 
8436122f3e6SDimitry Andric   // Copy all allocation orders, filter out foreign registers from the larger
8446122f3e6SDimitry Andric   // super-class.
8456122f3e6SDimitry Andric   Orders.resize(Super.Orders.size());
8466122f3e6SDimitry Andric   for (unsigned i = 0, ie = Super.Orders.size(); i != ie; ++i)
8476122f3e6SDimitry Andric     for (unsigned j = 0, je = Super.Orders[i].size(); j != je; ++j)
8486122f3e6SDimitry Andric       if (contains(RegBank.getReg(Super.Orders[i][j])))
8496122f3e6SDimitry Andric         Orders[i].push_back(Super.Orders[i][j]);
8506122f3e6SDimitry Andric }
8516122f3e6SDimitry Andric 
contains(const CodeGenRegister * Reg) const85217a519f9SDimitry Andric bool CodeGenRegisterClass::contains(const CodeGenRegister *Reg) const {
853ff0cc061SDimitry Andric   return std::binary_search(Members.begin(), Members.end(), Reg,
854ff0cc061SDimitry Andric                             deref<llvm::less>());
85517a519f9SDimitry Andric }
85617a519f9SDimitry Andric 
8576122f3e6SDimitry Andric namespace llvm {
858d88c1a5aSDimitry Andric 
operator <<(raw_ostream & OS,const CodeGenRegisterClass::Key & K)8596122f3e6SDimitry Andric   raw_ostream &operator<<(raw_ostream &OS, const CodeGenRegisterClass::Key &K) {
8602cab237bSDimitry Andric     OS << "{ " << K.RSI;
861ff0cc061SDimitry Andric     for (const auto R : *K.Members)
862ff0cc061SDimitry Andric       OS << ", " << R->getName();
8636122f3e6SDimitry Andric     return OS << " }";
8646122f3e6SDimitry Andric   }
865d88c1a5aSDimitry Andric 
866d88c1a5aSDimitry Andric } // end namespace llvm
8676122f3e6SDimitry Andric 
8686122f3e6SDimitry Andric // This is a simple lexicographical order that can be used to search for sets.
8696122f3e6SDimitry Andric // It is not the same as the topological order provided by TopoOrderRC.
8706122f3e6SDimitry Andric bool CodeGenRegisterClass::Key::
operator <(const CodeGenRegisterClass::Key & B) const8716122f3e6SDimitry Andric operator<(const CodeGenRegisterClass::Key &B) const {
8726122f3e6SDimitry Andric   assert(Members && B.Members);
8732cab237bSDimitry Andric   return std::tie(*Members, RSI) < std::tie(*B.Members, B.RSI);
8746122f3e6SDimitry Andric }
8756122f3e6SDimitry Andric 
87617a519f9SDimitry Andric // Returns true if RC is a strict subclass.
87717a519f9SDimitry Andric // RC is a sub-class of this class if it is a valid replacement for any
87817a519f9SDimitry Andric // instruction operand where a register of this classis required. It must
87917a519f9SDimitry Andric // satisfy these conditions:
88017a519f9SDimitry Andric //
88117a519f9SDimitry Andric // 1. All RC registers are also in this.
88217a519f9SDimitry Andric // 2. The RC spill size must not be smaller than our spill size.
88317a519f9SDimitry Andric // 3. RC spill alignment must be compatible with ours.
88417a519f9SDimitry Andric //
testSubClass(const CodeGenRegisterClass * A,const CodeGenRegisterClass * B)8856122f3e6SDimitry Andric static bool testSubClass(const CodeGenRegisterClass *A,
8866122f3e6SDimitry Andric                          const CodeGenRegisterClass *B) {
8872cab237bSDimitry Andric   return A->RSI.isSubClassOf(B->RSI) &&
8886122f3e6SDimitry Andric          std::includes(A->getMembers().begin(), A->getMembers().end(),
8896122f3e6SDimitry Andric                        B->getMembers().begin(), B->getMembers().end(),
890ff0cc061SDimitry Andric                        deref<llvm::less>());
891bd5abe19SDimitry Andric }
892bd5abe19SDimitry Andric 
8936122f3e6SDimitry Andric /// Sorting predicate for register classes.  This provides a topological
8946122f3e6SDimitry Andric /// ordering that arranges all register classes before their sub-classes.
8956122f3e6SDimitry Andric ///
8966122f3e6SDimitry Andric /// Register classes with the same registers, spill size, and alignment form a
8976122f3e6SDimitry Andric /// clique.  They will be ordered alphabetically.
8986122f3e6SDimitry Andric ///
TopoOrderRC(const CodeGenRegisterClass & PA,const CodeGenRegisterClass & PB)89939d628a0SDimitry Andric static bool TopoOrderRC(const CodeGenRegisterClass &PA,
90039d628a0SDimitry Andric                         const CodeGenRegisterClass &PB) {
90139d628a0SDimitry Andric   auto *A = &PA;
90239d628a0SDimitry Andric   auto *B = &PB;
9036122f3e6SDimitry Andric   if (A == B)
904d88c1a5aSDimitry Andric     return false;
9056122f3e6SDimitry Andric 
9062cab237bSDimitry Andric   if (A->RSI < B->RSI)
90739d628a0SDimitry Andric     return true;
9082cab237bSDimitry Andric   if (A->RSI != B->RSI)
90939d628a0SDimitry Andric     return false;
9106122f3e6SDimitry Andric 
9117ae0e2c9SDimitry Andric   // Order by descending set size.  Note that the classes' allocation order may
9127ae0e2c9SDimitry Andric   // not have been computed yet.  The Members set is always vaild.
9137ae0e2c9SDimitry Andric   if (A->getMembers().size() > B->getMembers().size())
91439d628a0SDimitry Andric     return true;
9157ae0e2c9SDimitry Andric   if (A->getMembers().size() < B->getMembers().size())
91639d628a0SDimitry Andric     return false;
9177ae0e2c9SDimitry Andric 
9186122f3e6SDimitry Andric   // Finally order by name as a tie breaker.
91939d628a0SDimitry Andric   return StringRef(A->getName()) < B->getName();
9206122f3e6SDimitry Andric }
9216122f3e6SDimitry Andric 
getQualifiedName() const9226122f3e6SDimitry Andric std::string CodeGenRegisterClass::getQualifiedName() const {
9236122f3e6SDimitry Andric   if (Namespace.empty())
9246122f3e6SDimitry Andric     return getName();
9256122f3e6SDimitry Andric   else
926f9448bf3SDimitry Andric     return (Namespace + "::" + getName()).str();
9276122f3e6SDimitry Andric }
9286122f3e6SDimitry Andric 
9296122f3e6SDimitry Andric // Compute sub-classes of all register classes.
9306122f3e6SDimitry Andric // Assume the classes are ordered topologically.
computeSubClasses(CodeGenRegBank & RegBank)9316122f3e6SDimitry Andric void CodeGenRegisterClass::computeSubClasses(CodeGenRegBank &RegBank) {
93239d628a0SDimitry Andric   auto &RegClasses = RegBank.getRegClasses();
9336122f3e6SDimitry Andric 
9346122f3e6SDimitry Andric   // Visit backwards so sub-classes are seen first.
93539d628a0SDimitry Andric   for (auto I = RegClasses.rbegin(), E = RegClasses.rend(); I != E; ++I) {
93639d628a0SDimitry Andric     CodeGenRegisterClass &RC = *I;
9376122f3e6SDimitry Andric     RC.SubClasses.resize(RegClasses.size());
9386122f3e6SDimitry Andric     RC.SubClasses.set(RC.EnumValue);
9394ba319b5SDimitry Andric     if (RC.Artificial)
9404ba319b5SDimitry Andric       continue;
9416122f3e6SDimitry Andric 
9426122f3e6SDimitry Andric     // Normally, all subclasses have IDs >= rci, unless RC is part of a clique.
94339d628a0SDimitry Andric     for (auto I2 = I.base(), E2 = RegClasses.end(); I2 != E2; ++I2) {
94439d628a0SDimitry Andric       CodeGenRegisterClass &SubRC = *I2;
94539d628a0SDimitry Andric       if (RC.SubClasses.test(SubRC.EnumValue))
9466122f3e6SDimitry Andric         continue;
94739d628a0SDimitry Andric       if (!testSubClass(&RC, &SubRC))
9486122f3e6SDimitry Andric         continue;
9496122f3e6SDimitry Andric       // SubRC is a sub-class. Grap all its sub-classes so we won't have to
9506122f3e6SDimitry Andric       // check them again.
95139d628a0SDimitry Andric       RC.SubClasses |= SubRC.SubClasses;
9526122f3e6SDimitry Andric     }
9536122f3e6SDimitry Andric 
9547ae0e2c9SDimitry Andric     // Sweep up missed clique members.  They will be immediately preceding RC.
95539d628a0SDimitry Andric     for (auto I2 = std::next(I); I2 != E && testSubClass(&RC, &*I2); ++I2)
95639d628a0SDimitry Andric       RC.SubClasses.set(I2->EnumValue);
9576122f3e6SDimitry Andric   }
9586122f3e6SDimitry Andric 
9596122f3e6SDimitry Andric   // Compute the SuperClasses lists from the SubClasses vectors.
96039d628a0SDimitry Andric   for (auto &RC : RegClasses) {
96139d628a0SDimitry Andric     const BitVector &SC = RC.getSubClasses();
96239d628a0SDimitry Andric     auto I = RegClasses.begin();
96339d628a0SDimitry Andric     for (int s = 0, next_s = SC.find_first(); next_s != -1;
96439d628a0SDimitry Andric          next_s = SC.find_next(s)) {
96539d628a0SDimitry Andric       std::advance(I, next_s - s);
96639d628a0SDimitry Andric       s = next_s;
96739d628a0SDimitry Andric       if (&*I == &RC)
9686122f3e6SDimitry Andric         continue;
96939d628a0SDimitry Andric       I->SuperClasses.push_back(&RC);
9706122f3e6SDimitry Andric     }
9716122f3e6SDimitry Andric   }
9726122f3e6SDimitry Andric 
9736122f3e6SDimitry Andric   // With the class hierarchy in place, let synthesized register classes inherit
9746122f3e6SDimitry Andric   // properties from their closest super-class. The iteration order here can
9756122f3e6SDimitry Andric   // propagate properties down multiple levels.
97639d628a0SDimitry Andric   for (auto &RC : RegClasses)
97739d628a0SDimitry Andric     if (!RC.getDef())
97839d628a0SDimitry Andric       RC.inheritProperties(RegBank);
979bd5abe19SDimitry Andric }
980bd5abe19SDimitry Andric 
981a580b014SDimitry Andric Optional<std::pair<CodeGenRegisterClass *, CodeGenRegisterClass *>>
getMatchingSubClassWithSubRegs(CodeGenRegBank & RegBank,const CodeGenSubRegIndex * SubIdx) const982a580b014SDimitry Andric CodeGenRegisterClass::getMatchingSubClassWithSubRegs(
983a580b014SDimitry Andric     CodeGenRegBank &RegBank, const CodeGenSubRegIndex *SubIdx) const {
984a580b014SDimitry Andric   auto SizeOrder = [](const CodeGenRegisterClass *A,
985a580b014SDimitry Andric                       const CodeGenRegisterClass *B) {
986a580b014SDimitry Andric     return A->getMembers().size() > B->getMembers().size();
987a580b014SDimitry Andric   };
988a580b014SDimitry Andric 
989a580b014SDimitry Andric   auto &RegClasses = RegBank.getRegClasses();
990a580b014SDimitry Andric 
991a580b014SDimitry Andric   // Find all the subclasses of this one that fully support the sub-register
992a580b014SDimitry Andric   // index and order them by size. BiggestSuperRC should always be first.
993a580b014SDimitry Andric   CodeGenRegisterClass *BiggestSuperRegRC = getSubClassWithSubReg(SubIdx);
994a580b014SDimitry Andric   if (!BiggestSuperRegRC)
995a580b014SDimitry Andric     return None;
996a580b014SDimitry Andric   BitVector SuperRegRCsBV = BiggestSuperRegRC->getSubClasses();
997a580b014SDimitry Andric   std::vector<CodeGenRegisterClass *> SuperRegRCs;
998a580b014SDimitry Andric   for (auto &RC : RegClasses)
999a580b014SDimitry Andric     if (SuperRegRCsBV[RC.EnumValue])
1000a580b014SDimitry Andric       SuperRegRCs.emplace_back(&RC);
1001*b5893f02SDimitry Andric   llvm::sort(SuperRegRCs, SizeOrder);
1002a580b014SDimitry Andric   assert(SuperRegRCs.front() == BiggestSuperRegRC && "Biggest class wasn't first");
1003a580b014SDimitry Andric 
1004a580b014SDimitry Andric   // Find all the subreg classes and order them by size too.
1005a580b014SDimitry Andric   std::vector<std::pair<CodeGenRegisterClass *, BitVector>> SuperRegClasses;
1006a580b014SDimitry Andric   for (auto &RC: RegClasses) {
1007a580b014SDimitry Andric     BitVector SuperRegClassesBV(RegClasses.size());
1008a580b014SDimitry Andric     RC.getSuperRegClasses(SubIdx, SuperRegClassesBV);
1009a580b014SDimitry Andric     if (SuperRegClassesBV.any())
1010a580b014SDimitry Andric       SuperRegClasses.push_back(std::make_pair(&RC, SuperRegClassesBV));
1011a580b014SDimitry Andric   }
1012*b5893f02SDimitry Andric   llvm::sort(SuperRegClasses,
1013a580b014SDimitry Andric              [&](const std::pair<CodeGenRegisterClass *, BitVector> &A,
1014a580b014SDimitry Andric                  const std::pair<CodeGenRegisterClass *, BitVector> &B) {
1015a580b014SDimitry Andric                return SizeOrder(A.first, B.first);
1016a580b014SDimitry Andric              });
1017a580b014SDimitry Andric 
1018a580b014SDimitry Andric   // Find the biggest subclass and subreg class such that R:subidx is in the
1019a580b014SDimitry Andric   // subreg class for all R in subclass.
1020a580b014SDimitry Andric   //
1021a580b014SDimitry Andric   // For example:
1022a580b014SDimitry Andric   // All registers in X86's GR64 have a sub_32bit subregister but no class
1023a580b014SDimitry Andric   // exists that contains all the 32-bit subregisters because GR64 contains RIP
1024a580b014SDimitry Andric   // but GR32 does not contain EIP. Instead, we constrain SuperRegRC to
1025a580b014SDimitry Andric   // GR32_with_sub_8bit (which is identical to GR32_with_sub_32bit) and then,
1026a580b014SDimitry Andric   // having excluded RIP, we are able to find a SubRegRC (GR32).
1027a580b014SDimitry Andric   CodeGenRegisterClass *ChosenSuperRegClass = nullptr;
1028a580b014SDimitry Andric   CodeGenRegisterClass *SubRegRC = nullptr;
1029a580b014SDimitry Andric   for (auto *SuperRegRC : SuperRegRCs) {
1030a580b014SDimitry Andric     for (const auto &SuperRegClassPair : SuperRegClasses) {
1031a580b014SDimitry Andric       const BitVector &SuperRegClassBV = SuperRegClassPair.second;
1032a580b014SDimitry Andric       if (SuperRegClassBV[SuperRegRC->EnumValue]) {
1033a580b014SDimitry Andric         SubRegRC = SuperRegClassPair.first;
1034a580b014SDimitry Andric         ChosenSuperRegClass = SuperRegRC;
1035a580b014SDimitry Andric 
1036a580b014SDimitry Andric         // If SubRegRC is bigger than SuperRegRC then there are members of
1037a580b014SDimitry Andric         // SubRegRC that don't have super registers via SubIdx. Keep looking to
1038a580b014SDimitry Andric         // find a better fit and fall back on this one if there isn't one.
1039a580b014SDimitry Andric         //
1040a580b014SDimitry Andric         // This is intended to prevent X86 from making odd choices such as
1041a580b014SDimitry Andric         // picking LOW32_ADDR_ACCESS_RBP instead of GR32 in the example above.
1042a580b014SDimitry Andric         // LOW32_ADDR_ACCESS_RBP is a valid choice but contains registers that
1043a580b014SDimitry Andric         // aren't subregisters of SuperRegRC whereas GR32 has a direct 1:1
1044a580b014SDimitry Andric         // mapping.
1045a580b014SDimitry Andric         if (SuperRegRC->getMembers().size() >= SubRegRC->getMembers().size())
1046a580b014SDimitry Andric           return std::make_pair(ChosenSuperRegClass, SubRegRC);
1047a580b014SDimitry Andric       }
1048a580b014SDimitry Andric     }
1049a580b014SDimitry Andric 
1050a580b014SDimitry Andric     // If we found a fit but it wasn't quite ideal because SubRegRC had excess
1051a580b014SDimitry Andric     // registers, then we're done.
1052a580b014SDimitry Andric     if (ChosenSuperRegClass)
1053a580b014SDimitry Andric       return std::make_pair(ChosenSuperRegClass, SubRegRC);
1054a580b014SDimitry Andric   }
1055a580b014SDimitry Andric 
1056a580b014SDimitry Andric   return None;
1057a580b014SDimitry Andric }
1058a580b014SDimitry Andric 
getSuperRegClasses(const CodeGenSubRegIndex * SubIdx,BitVector & Out) const105939d628a0SDimitry Andric void CodeGenRegisterClass::getSuperRegClasses(const CodeGenSubRegIndex *SubIdx,
1060dff0c46cSDimitry Andric                                               BitVector &Out) const {
106139d628a0SDimitry Andric   auto FindI = SuperRegClasses.find(SubIdx);
1062dff0c46cSDimitry Andric   if (FindI == SuperRegClasses.end())
1063dff0c46cSDimitry Andric     return;
106439d628a0SDimitry Andric   for (CodeGenRegisterClass *RC : FindI->second)
106539d628a0SDimitry Andric     Out.set(RC->EnumValue);
1066dff0c46cSDimitry Andric }
1067dff0c46cSDimitry Andric 
1068dff0c46cSDimitry Andric // Populate a unique sorted list of units from a register set.
buildRegUnitSet(const CodeGenRegBank & RegBank,std::vector<unsigned> & RegUnits) const10694ba319b5SDimitry Andric void CodeGenRegisterClass::buildRegUnitSet(const CodeGenRegBank &RegBank,
1070dff0c46cSDimitry Andric   std::vector<unsigned> &RegUnits) const {
1071dff0c46cSDimitry Andric   std::vector<unsigned> TmpUnits;
10724ba319b5SDimitry Andric   for (RegUnitIterator UnitI(Members); UnitI.isValid(); ++UnitI) {
10734ba319b5SDimitry Andric     const RegUnit &RU = RegBank.getRegUnit(*UnitI);
10744ba319b5SDimitry Andric     if (!RU.Artificial)
1075dff0c46cSDimitry Andric       TmpUnits.push_back(*UnitI);
10764ba319b5SDimitry Andric   }
1077*b5893f02SDimitry Andric   llvm::sort(TmpUnits);
1078dff0c46cSDimitry Andric   std::unique_copy(TmpUnits.begin(), TmpUnits.end(),
1079dff0c46cSDimitry Andric                    std::back_inserter(RegUnits));
1080dff0c46cSDimitry Andric }
1081dff0c46cSDimitry Andric 
1082bd5abe19SDimitry Andric //===----------------------------------------------------------------------===//
1083bd5abe19SDimitry Andric //                               CodeGenRegBank
1084bd5abe19SDimitry Andric //===----------------------------------------------------------------------===//
1085bd5abe19SDimitry Andric 
CodeGenRegBank(RecordKeeper & Records,const CodeGenHwModes & Modes)10862cab237bSDimitry Andric CodeGenRegBank::CodeGenRegBank(RecordKeeper &Records,
10872cab237bSDimitry Andric                                const CodeGenHwModes &Modes) : CGH(Modes) {
108817a519f9SDimitry Andric   // Configure register Sets to understand register classes and tuples.
108917a519f9SDimitry Andric   Sets.addFieldExpander("RegisterClass", "MemberList");
1090dff0c46cSDimitry Andric   Sets.addFieldExpander("CalleeSavedRegs", "SaveList");
10914ba319b5SDimitry Andric   Sets.addExpander("RegisterTuples",
10924ba319b5SDimitry Andric                    llvm::make_unique<TupleExpander>(SynthDefs));
109317a519f9SDimitry Andric 
1094bd5abe19SDimitry Andric   // Read in the user-defined (named) sub-register indices.
1095bd5abe19SDimitry Andric   // More indices will be synthesized later.
1096dff0c46cSDimitry Andric   std::vector<Record*> SRIs = Records.getAllDerivedDefinitions("SubRegIndex");
1097*b5893f02SDimitry Andric   llvm::sort(SRIs, LessRecord());
1098dff0c46cSDimitry Andric   for (unsigned i = 0, e = SRIs.size(); i != e; ++i)
1099dff0c46cSDimitry Andric     getSubRegIdx(SRIs[i]);
1100dff0c46cSDimitry Andric   // Build composite maps from ComposedOf fields.
110139d628a0SDimitry Andric   for (auto &Idx : SubRegIndices)
110239d628a0SDimitry Andric     Idx.updateComponents(*this);
1103bd5abe19SDimitry Andric 
1104bd5abe19SDimitry Andric   // Read in the register definitions.
1105bd5abe19SDimitry Andric   std::vector<Record*> Regs = Records.getAllDerivedDefinitions("Register");
1106*b5893f02SDimitry Andric   llvm::sort(Regs, LessRecordRegister());
1107bd5abe19SDimitry Andric   // Assign the enumeration values.
1108bd5abe19SDimitry Andric   for (unsigned i = 0, e = Regs.size(); i != e; ++i)
110917a519f9SDimitry Andric     getReg(Regs[i]);
111017a519f9SDimitry Andric 
111117a519f9SDimitry Andric   // Expand tuples and number the new registers.
111217a519f9SDimitry Andric   std::vector<Record*> Tups =
111317a519f9SDimitry Andric     Records.getAllDerivedDefinitions("RegisterTuples");
1114f785676fSDimitry Andric 
111539d628a0SDimitry Andric   for (Record *R : Tups) {
111639d628a0SDimitry Andric     std::vector<Record *> TupRegs = *Sets.expand(R);
1117*b5893f02SDimitry Andric     llvm::sort(TupRegs, LessRecordRegister());
111839d628a0SDimitry Andric     for (Record *RC : TupRegs)
111939d628a0SDimitry Andric       getReg(RC);
112017a519f9SDimitry Andric   }
112117a519f9SDimitry Andric 
11227ae0e2c9SDimitry Andric   // Now all the registers are known. Build the object graph of explicit
11237ae0e2c9SDimitry Andric   // register-register references.
112439d628a0SDimitry Andric   for (auto &Reg : Registers)
112539d628a0SDimitry Andric     Reg.buildObjectGraph(*this);
11267ae0e2c9SDimitry Andric 
11273861d79fSDimitry Andric   // Compute register name map.
112839d628a0SDimitry Andric   for (auto &Reg : Registers)
112939d628a0SDimitry Andric     // FIXME: This could just be RegistersByName[name] = register, except that
113039d628a0SDimitry Andric     // causes some failures in MIPS - perhaps they have duplicate register name
113139d628a0SDimitry Andric     // entries? (or maybe there's a reason for it - I don't know much about this
113239d628a0SDimitry Andric     // code, just drive-by refactoring)
113339d628a0SDimitry Andric     RegistersByName.insert(
113439d628a0SDimitry Andric         std::make_pair(Reg.TheDef->getValueAsString("AsmName"), &Reg));
11353861d79fSDimitry Andric 
11367ae0e2c9SDimitry Andric   // Precompute all sub-register maps.
11377ae0e2c9SDimitry Andric   // This will create Composite entries for all inferred sub-register indices.
113839d628a0SDimitry Andric   for (auto &Reg : Registers)
113939d628a0SDimitry Andric     Reg.computeSubRegs(*this);
11407ae0e2c9SDimitry Andric 
11412cab237bSDimitry Andric   // Compute transitive closure of subregister index ConcatenationOf vectors
11422cab237bSDimitry Andric   // and initialize ConcatIdx map.
11432cab237bSDimitry Andric   for (CodeGenSubRegIndex &SRI : SubRegIndices) {
11442cab237bSDimitry Andric     SRI.computeConcatTransitiveClosure();
11452cab237bSDimitry Andric     if (!SRI.ConcatenationOf.empty())
11462cab237bSDimitry Andric       ConcatIdx.insert(std::make_pair(
11472cab237bSDimitry Andric           SmallVector<CodeGenSubRegIndex*,8>(SRI.ConcatenationOf.begin(),
11482cab237bSDimitry Andric                                              SRI.ConcatenationOf.end()), &SRI));
11492cab237bSDimitry Andric   }
11502cab237bSDimitry Andric 
11517ae0e2c9SDimitry Andric   // Infer even more sub-registers by combining leading super-registers.
115239d628a0SDimitry Andric   for (auto &Reg : Registers)
115339d628a0SDimitry Andric     if (Reg.CoveredBySubRegs)
115439d628a0SDimitry Andric       Reg.computeSecondarySubRegs(*this);
11557ae0e2c9SDimitry Andric 
11567ae0e2c9SDimitry Andric   // After the sub-register graph is complete, compute the topologically
11577ae0e2c9SDimitry Andric   // ordered SuperRegs list.
115839d628a0SDimitry Andric   for (auto &Reg : Registers)
115939d628a0SDimitry Andric     Reg.computeSuperRegs(*this);
11606122f3e6SDimitry Andric 
11614ba319b5SDimitry Andric   // For each pair of Reg:SR, if both are non-artificial, mark the
11624ba319b5SDimitry Andric   // corresponding sub-register index as non-artificial.
11634ba319b5SDimitry Andric   for (auto &Reg : Registers) {
11644ba319b5SDimitry Andric     if (Reg.Artificial)
11654ba319b5SDimitry Andric       continue;
11664ba319b5SDimitry Andric     for (auto P : Reg.getSubRegs()) {
11674ba319b5SDimitry Andric       const CodeGenRegister *SR = P.second;
11684ba319b5SDimitry Andric       if (!SR->Artificial)
11694ba319b5SDimitry Andric         P.first->Artificial = false;
11704ba319b5SDimitry Andric     }
11714ba319b5SDimitry Andric   }
11724ba319b5SDimitry Andric 
1173dff0c46cSDimitry Andric   // Native register units are associated with a leaf register. They've all been
1174dff0c46cSDimitry Andric   // discovered now.
11757ae0e2c9SDimitry Andric   NumNativeRegUnits = RegUnits.size();
1176dff0c46cSDimitry Andric 
117717a519f9SDimitry Andric   // Read in register class definitions.
117817a519f9SDimitry Andric   std::vector<Record*> RCs = Records.getAllDerivedDefinitions("RegisterClass");
117917a519f9SDimitry Andric   if (RCs.empty())
118091bc56edSDimitry Andric     PrintFatalError("No 'RegisterClass' subclasses defined!");
118117a519f9SDimitry Andric 
11826122f3e6SDimitry Andric   // Allocate user-defined register classes.
11834ba319b5SDimitry Andric   for (auto *R : RCs) {
11844ba319b5SDimitry Andric     RegClasses.emplace_back(*this, R);
11854ba319b5SDimitry Andric     CodeGenRegisterClass &RC = RegClasses.back();
11864ba319b5SDimitry Andric     if (!RC.Artificial)
11874ba319b5SDimitry Andric       addToMaps(&RC);
118839d628a0SDimitry Andric   }
11896122f3e6SDimitry Andric 
11906122f3e6SDimitry Andric   // Infer missing classes to create a full algebra.
11916122f3e6SDimitry Andric   computeInferredRegisterClasses();
11926122f3e6SDimitry Andric 
11936122f3e6SDimitry Andric   // Order register classes topologically and assign enum values.
119439d628a0SDimitry Andric   RegClasses.sort(TopoOrderRC);
119539d628a0SDimitry Andric   unsigned i = 0;
119639d628a0SDimitry Andric   for (auto &RC : RegClasses)
119739d628a0SDimitry Andric     RC.EnumValue = i++;
11986122f3e6SDimitry Andric   CodeGenRegisterClass::computeSubClasses(*this);
1199bd5abe19SDimitry Andric }
1200bd5abe19SDimitry Andric 
12017ae0e2c9SDimitry Andric // Create a synthetic CodeGenSubRegIndex without a corresponding Record.
12027ae0e2c9SDimitry Andric CodeGenSubRegIndex*
createSubRegIndex(StringRef Name,StringRef Namespace)12037ae0e2c9SDimitry Andric CodeGenRegBank::createSubRegIndex(StringRef Name, StringRef Namespace) {
120439d628a0SDimitry Andric   SubRegIndices.emplace_back(Name, Namespace, SubRegIndices.size() + 1);
120539d628a0SDimitry Andric   return &SubRegIndices.back();
12067ae0e2c9SDimitry Andric }
12077ae0e2c9SDimitry Andric 
getSubRegIdx(Record * Def)1208dff0c46cSDimitry Andric CodeGenSubRegIndex *CodeGenRegBank::getSubRegIdx(Record *Def) {
1209dff0c46cSDimitry Andric   CodeGenSubRegIndex *&Idx = Def2SubRegIdx[Def];
1210dff0c46cSDimitry Andric   if (Idx)
1211dff0c46cSDimitry Andric     return Idx;
121239d628a0SDimitry Andric   SubRegIndices.emplace_back(Def, SubRegIndices.size() + 1);
121339d628a0SDimitry Andric   Idx = &SubRegIndices.back();
1214dff0c46cSDimitry Andric   return Idx;
1215dff0c46cSDimitry Andric }
1216dff0c46cSDimitry Andric 
getReg(Record * Def)1217bd5abe19SDimitry Andric CodeGenRegister *CodeGenRegBank::getReg(Record *Def) {
121817a519f9SDimitry Andric   CodeGenRegister *&Reg = Def2Reg[Def];
121917a519f9SDimitry Andric   if (Reg)
1220bd5abe19SDimitry Andric     return Reg;
122139d628a0SDimitry Andric   Registers.emplace_back(Def, Registers.size() + 1);
122239d628a0SDimitry Andric   Reg = &Registers.back();
122317a519f9SDimitry Andric   return Reg;
122417a519f9SDimitry Andric }
1225bd5abe19SDimitry Andric 
addToMaps(CodeGenRegisterClass * RC)12266122f3e6SDimitry Andric void CodeGenRegBank::addToMaps(CodeGenRegisterClass *RC) {
12276122f3e6SDimitry Andric   if (Record *Def = RC->getDef())
12286122f3e6SDimitry Andric     Def2RC.insert(std::make_pair(Def, RC));
12296122f3e6SDimitry Andric 
12306122f3e6SDimitry Andric   // Duplicate classes are rejected by insert().
12316122f3e6SDimitry Andric   // That's OK, we only care about the properties handled by CGRC::Key.
12326122f3e6SDimitry Andric   CodeGenRegisterClass::Key K(*RC);
12336122f3e6SDimitry Andric   Key2RC.insert(std::make_pair(K, RC));
12346122f3e6SDimitry Andric }
12356122f3e6SDimitry Andric 
1236dff0c46cSDimitry Andric // Create a synthetic sub-class if it is missing.
1237dff0c46cSDimitry Andric CodeGenRegisterClass*
getOrCreateSubClass(const CodeGenRegisterClass * RC,const CodeGenRegister::Vec * Members,StringRef Name)1238dff0c46cSDimitry Andric CodeGenRegBank::getOrCreateSubClass(const CodeGenRegisterClass *RC,
1239ff0cc061SDimitry Andric                                     const CodeGenRegister::Vec *Members,
1240dff0c46cSDimitry Andric                                     StringRef Name) {
1241dff0c46cSDimitry Andric   // Synthetic sub-class has the same size and alignment as RC.
12422cab237bSDimitry Andric   CodeGenRegisterClass::Key K(Members, RC->RSI);
1243dff0c46cSDimitry Andric   RCKeyMap::const_iterator FoundI = Key2RC.find(K);
1244dff0c46cSDimitry Andric   if (FoundI != Key2RC.end())
1245dff0c46cSDimitry Andric     return FoundI->second;
1246dff0c46cSDimitry Andric 
1247dff0c46cSDimitry Andric   // Sub-class doesn't exist, create a new one.
124897bc6c73SDimitry Andric   RegClasses.emplace_back(*this, Name, K);
124939d628a0SDimitry Andric   addToMaps(&RegClasses.back());
125039d628a0SDimitry Andric   return &RegClasses.back();
1251dff0c46cSDimitry Andric }
1252dff0c46cSDimitry Andric 
getRegClass(Record * Def)12536122f3e6SDimitry Andric CodeGenRegisterClass *CodeGenRegBank::getRegClass(Record *Def) {
125417a519f9SDimitry Andric   if (CodeGenRegisterClass *RC = Def2RC[Def])
125517a519f9SDimitry Andric     return RC;
125617a519f9SDimitry Andric 
12573861d79fSDimitry Andric   PrintFatalError(Def->getLoc(), "Not a known RegisterClass!");
1258bd5abe19SDimitry Andric }
1259bd5abe19SDimitry Andric 
1260dff0c46cSDimitry Andric CodeGenSubRegIndex*
getCompositeSubRegIndex(CodeGenSubRegIndex * A,CodeGenSubRegIndex * B)1261dff0c46cSDimitry Andric CodeGenRegBank::getCompositeSubRegIndex(CodeGenSubRegIndex *A,
1262dff0c46cSDimitry Andric                                         CodeGenSubRegIndex *B) {
1263bd5abe19SDimitry Andric   // Look for an existing entry.
1264dff0c46cSDimitry Andric   CodeGenSubRegIndex *Comp = A->compose(B);
1265dff0c46cSDimitry Andric   if (Comp)
1266bd5abe19SDimitry Andric     return Comp;
1267bd5abe19SDimitry Andric 
1268bd5abe19SDimitry Andric   // None exists, synthesize one.
1269bd5abe19SDimitry Andric   std::string Name = A->getName() + "_then_" + B->getName();
12707ae0e2c9SDimitry Andric   Comp = createSubRegIndex(Name, A->getNamespace());
1271dff0c46cSDimitry Andric   A->addComposite(B, Comp);
1272bd5abe19SDimitry Andric   return Comp;
1273bd5abe19SDimitry Andric }
1274bd5abe19SDimitry Andric 
12757ae0e2c9SDimitry Andric CodeGenSubRegIndex *CodeGenRegBank::
getConcatSubRegIndex(const SmallVector<CodeGenSubRegIndex *,8> & Parts)12767ae0e2c9SDimitry Andric getConcatSubRegIndex(const SmallVector<CodeGenSubRegIndex *, 8> &Parts) {
12777ae0e2c9SDimitry Andric   assert(Parts.size() > 1 && "Need two parts to concatenate");
12782cab237bSDimitry Andric #ifndef NDEBUG
12792cab237bSDimitry Andric   for (CodeGenSubRegIndex *Idx : Parts) {
12802cab237bSDimitry Andric     assert(Idx->ConcatenationOf.empty() && "No transitive closure?");
12812cab237bSDimitry Andric   }
12822cab237bSDimitry Andric #endif
12837ae0e2c9SDimitry Andric 
12847ae0e2c9SDimitry Andric   // Look for an existing entry.
12857ae0e2c9SDimitry Andric   CodeGenSubRegIndex *&Idx = ConcatIdx[Parts];
12867ae0e2c9SDimitry Andric   if (Idx)
12877ae0e2c9SDimitry Andric     return Idx;
12887ae0e2c9SDimitry Andric 
12897ae0e2c9SDimitry Andric   // None exists, synthesize one.
12907ae0e2c9SDimitry Andric   std::string Name = Parts.front()->getName();
1291f785676fSDimitry Andric   // Determine whether all parts are contiguous.
1292f785676fSDimitry Andric   bool isContinuous = true;
1293f785676fSDimitry Andric   unsigned Size = Parts.front()->Size;
1294f785676fSDimitry Andric   unsigned LastOffset = Parts.front()->Offset;
1295f785676fSDimitry Andric   unsigned LastSize = Parts.front()->Size;
12967ae0e2c9SDimitry Andric   for (unsigned i = 1, e = Parts.size(); i != e; ++i) {
12977ae0e2c9SDimitry Andric     Name += '_';
12987ae0e2c9SDimitry Andric     Name += Parts[i]->getName();
1299f785676fSDimitry Andric     Size += Parts[i]->Size;
1300f785676fSDimitry Andric     if (Parts[i]->Offset != (LastOffset + LastSize))
1301f785676fSDimitry Andric       isContinuous = false;
1302f785676fSDimitry Andric     LastOffset = Parts[i]->Offset;
1303f785676fSDimitry Andric     LastSize = Parts[i]->Size;
13047ae0e2c9SDimitry Andric   }
1305f785676fSDimitry Andric   Idx = createSubRegIndex(Name, Parts.front()->getNamespace());
1306f785676fSDimitry Andric   Idx->Size = Size;
1307f785676fSDimitry Andric   Idx->Offset = isContinuous ? Parts.front()->Offset : -1;
13082cab237bSDimitry Andric   Idx->ConcatenationOf.assign(Parts.begin(), Parts.end());
1309f785676fSDimitry Andric   return Idx;
13107ae0e2c9SDimitry Andric }
13117ae0e2c9SDimitry Andric 
computeComposites()1312bd5abe19SDimitry Andric void CodeGenRegBank::computeComposites() {
1313*b5893f02SDimitry Andric   using RegMap = std::map<const CodeGenRegister*, const CodeGenRegister*>;
1314*b5893f02SDimitry Andric 
1315*b5893f02SDimitry Andric   // Subreg -> { Reg->Reg }, where the right-hand side is the mapping from
1316*b5893f02SDimitry Andric   // register to (sub)register associated with the action of the left-hand
1317*b5893f02SDimitry Andric   // side subregister.
1318*b5893f02SDimitry Andric   std::map<const CodeGenSubRegIndex*, RegMap> SubRegAction;
1319*b5893f02SDimitry Andric   for (const CodeGenRegister &R : Registers) {
1320*b5893f02SDimitry Andric     const CodeGenRegister::SubRegMap &SM = R.getSubRegs();
1321*b5893f02SDimitry Andric     for (std::pair<const CodeGenSubRegIndex*, const CodeGenRegister*> P : SM)
1322*b5893f02SDimitry Andric       SubRegAction[P.first].insert({&R, P.second});
1323*b5893f02SDimitry Andric   }
1324*b5893f02SDimitry Andric 
1325*b5893f02SDimitry Andric   // Calculate the composition of two subregisters as compositions of their
1326*b5893f02SDimitry Andric   // associated actions.
1327*b5893f02SDimitry Andric   auto compose = [&SubRegAction] (const CodeGenSubRegIndex *Sub1,
1328*b5893f02SDimitry Andric                                   const CodeGenSubRegIndex *Sub2) {
1329*b5893f02SDimitry Andric     RegMap C;
1330*b5893f02SDimitry Andric     const RegMap &Img1 = SubRegAction.at(Sub1);
1331*b5893f02SDimitry Andric     const RegMap &Img2 = SubRegAction.at(Sub2);
1332*b5893f02SDimitry Andric     for (std::pair<const CodeGenRegister*, const CodeGenRegister*> P : Img1) {
1333*b5893f02SDimitry Andric       auto F = Img2.find(P.second);
1334*b5893f02SDimitry Andric       if (F != Img2.end())
1335*b5893f02SDimitry Andric         C.insert({P.first, F->second});
1336*b5893f02SDimitry Andric     }
1337*b5893f02SDimitry Andric     return C;
1338*b5893f02SDimitry Andric   };
1339*b5893f02SDimitry Andric 
1340*b5893f02SDimitry Andric   // Check if the two maps agree on the intersection of their domains.
1341*b5893f02SDimitry Andric   auto agree = [] (const RegMap &Map1, const RegMap &Map2) {
1342*b5893f02SDimitry Andric     // Technically speaking, an empty map agrees with any other map, but
1343*b5893f02SDimitry Andric     // this could flag false positives. We're interested in non-vacuous
1344*b5893f02SDimitry Andric     // agreements.
1345*b5893f02SDimitry Andric     if (Map1.empty() || Map2.empty())
1346*b5893f02SDimitry Andric       return false;
1347*b5893f02SDimitry Andric     for (std::pair<const CodeGenRegister*, const CodeGenRegister*> P : Map1) {
1348*b5893f02SDimitry Andric       auto F = Map2.find(P.first);
1349*b5893f02SDimitry Andric       if (F == Map2.end() || P.second != F->second)
1350*b5893f02SDimitry Andric         return false;
1351*b5893f02SDimitry Andric     }
1352*b5893f02SDimitry Andric     return true;
1353*b5893f02SDimitry Andric   };
1354*b5893f02SDimitry Andric 
1355*b5893f02SDimitry Andric   using CompositePair = std::pair<const CodeGenSubRegIndex*,
1356*b5893f02SDimitry Andric                                   const CodeGenSubRegIndex*>;
1357*b5893f02SDimitry Andric   SmallSet<CompositePair,4> UserDefined;
1358*b5893f02SDimitry Andric   for (const CodeGenSubRegIndex &Idx : SubRegIndices)
1359*b5893f02SDimitry Andric     for (auto P : Idx.getComposites())
1360*b5893f02SDimitry Andric       UserDefined.insert(std::make_pair(&Idx, P.first));
1361*b5893f02SDimitry Andric 
13627ae0e2c9SDimitry Andric   // Keep track of TopoSigs visited. We only need to visit each TopoSig once,
13637ae0e2c9SDimitry Andric   // and many registers will share TopoSigs on regular architectures.
13647ae0e2c9SDimitry Andric   BitVector TopoSigs(getNumTopoSigs());
13657ae0e2c9SDimitry Andric 
136639d628a0SDimitry Andric   for (const auto &Reg1 : Registers) {
13677ae0e2c9SDimitry Andric     // Skip identical subreg structures already processed.
136839d628a0SDimitry Andric     if (TopoSigs.test(Reg1.getTopoSig()))
13697ae0e2c9SDimitry Andric       continue;
137039d628a0SDimitry Andric     TopoSigs.set(Reg1.getTopoSig());
13717ae0e2c9SDimitry Andric 
137239d628a0SDimitry Andric     const CodeGenRegister::SubRegMap &SRM1 = Reg1.getSubRegs();
1373bd5abe19SDimitry Andric     for (CodeGenRegister::SubRegMap::const_iterator i1 = SRM1.begin(),
1374bd5abe19SDimitry Andric          e1 = SRM1.end(); i1 != e1; ++i1) {
1375dff0c46cSDimitry Andric       CodeGenSubRegIndex *Idx1 = i1->first;
1376bd5abe19SDimitry Andric       CodeGenRegister *Reg2 = i1->second;
1377bd5abe19SDimitry Andric       // Ignore identity compositions.
137839d628a0SDimitry Andric       if (&Reg1 == Reg2)
1379bd5abe19SDimitry Andric         continue;
138017a519f9SDimitry Andric       const CodeGenRegister::SubRegMap &SRM2 = Reg2->getSubRegs();
1381bd5abe19SDimitry Andric       // Try composing Idx1 with another SubRegIndex.
1382bd5abe19SDimitry Andric       for (CodeGenRegister::SubRegMap::const_iterator i2 = SRM2.begin(),
1383bd5abe19SDimitry Andric            e2 = SRM2.end(); i2 != e2; ++i2) {
1384dff0c46cSDimitry Andric         CodeGenSubRegIndex *Idx2 = i2->first;
1385bd5abe19SDimitry Andric         CodeGenRegister *Reg3 = i2->second;
1386bd5abe19SDimitry Andric         // Ignore identity compositions.
1387bd5abe19SDimitry Andric         if (Reg2 == Reg3)
1388bd5abe19SDimitry Andric           continue;
1389bd5abe19SDimitry Andric         // OK Reg1:IdxPair == Reg3. Find the index with Reg:Idx == Reg3.
139039d628a0SDimitry Andric         CodeGenSubRegIndex *Idx3 = Reg1.getSubRegIndex(Reg3);
13917ae0e2c9SDimitry Andric         assert(Idx3 && "Sub-register doesn't have an index");
13927ae0e2c9SDimitry Andric 
1393bd5abe19SDimitry Andric         // Conflicting composition? Emit a warning but allow it.
1394*b5893f02SDimitry Andric         if (CodeGenSubRegIndex *Prev = Idx1->addComposite(Idx2, Idx3)) {
1395*b5893f02SDimitry Andric           // If the composition was not user-defined, always emit a warning.
1396*b5893f02SDimitry Andric           if (!UserDefined.count({Idx1, Idx2}) ||
1397*b5893f02SDimitry Andric               agree(compose(Idx1, Idx2), SubRegAction.at(Idx3)))
1398cb4dff85SDimitry Andric             PrintWarning(Twine("SubRegIndex ") + Idx1->getQualifiedName() +
1399cb4dff85SDimitry Andric                          " and " + Idx2->getQualifiedName() +
1400cb4dff85SDimitry Andric                          " compose ambiguously as " + Prev->getQualifiedName() +
14017ae0e2c9SDimitry Andric                          " or " + Idx3->getQualifiedName());
1402bd5abe19SDimitry Andric         }
1403bd5abe19SDimitry Andric       }
1404bd5abe19SDimitry Andric     }
14053861d79fSDimitry Andric   }
1406*b5893f02SDimitry Andric }
1407bd5abe19SDimitry Andric 
14083861d79fSDimitry Andric // Compute lane masks. This is similar to register units, but at the
14093861d79fSDimitry Andric // sub-register index level. Each bit in the lane mask is like a register unit
14103861d79fSDimitry Andric // class, and two lane masks will have a bit in common if two sub-register
14113861d79fSDimitry Andric // indices overlap in some register.
14123861d79fSDimitry Andric //
14133861d79fSDimitry Andric // Conservatively share a lane mask bit if two sub-register indices overlap in
14143861d79fSDimitry Andric // some registers, but not in others. That shouldn't happen a lot.
computeSubRegLaneMasks()141539d628a0SDimitry Andric void CodeGenRegBank::computeSubRegLaneMasks() {
14163861d79fSDimitry Andric   // First assign individual bits to all the leaf indices.
14173861d79fSDimitry Andric   unsigned Bit = 0;
1418f785676fSDimitry Andric   // Determine mask of lanes that cover their registers.
1419d88c1a5aSDimitry Andric   CoveringLanes = LaneBitmask::getAll();
142039d628a0SDimitry Andric   for (auto &Idx : SubRegIndices) {
142139d628a0SDimitry Andric     if (Idx.getComposites().empty()) {
1422b40b48b8SDimitry Andric       if (Bit > LaneBitmask::BitWidth) {
14237d523365SDimitry Andric         PrintFatalError(
14247d523365SDimitry Andric           Twine("Ran out of lanemask bits to represent subregister ")
14257d523365SDimitry Andric           + Idx.getName());
14267d523365SDimitry Andric       }
1427b40b48b8SDimitry Andric       Idx.LaneMask = LaneBitmask::getLane(Bit);
1428f785676fSDimitry Andric       ++Bit;
14293861d79fSDimitry Andric     } else {
1430d88c1a5aSDimitry Andric       Idx.LaneMask = LaneBitmask::getNone();
143139d628a0SDimitry Andric     }
143239d628a0SDimitry Andric   }
143339d628a0SDimitry Andric 
143439d628a0SDimitry Andric   // Compute transformation sequences for composeSubRegIndexLaneMask. The idea
143539d628a0SDimitry Andric   // here is that for each possible target subregister we look at the leafs
143639d628a0SDimitry Andric   // in the subregister graph that compose for this target and create
143739d628a0SDimitry Andric   // transformation sequences for the lanemasks. Each step in the sequence
143839d628a0SDimitry Andric   // consists of a bitmask and a bitrotate operation. As the rotation amounts
143939d628a0SDimitry Andric   // are usually the same for many subregisters we can easily combine the steps
144039d628a0SDimitry Andric   // by combining the masks.
144139d628a0SDimitry Andric   for (const auto &Idx : SubRegIndices) {
144239d628a0SDimitry Andric     const auto &Composites = Idx.getComposites();
144339d628a0SDimitry Andric     auto &LaneTransforms = Idx.CompositionLaneMaskTransform;
14443ca95b02SDimitry Andric 
14453ca95b02SDimitry Andric     if (Composites.empty()) {
14463ca95b02SDimitry Andric       // Moving from a class with no subregisters we just had a single lane:
14473ca95b02SDimitry Andric       // The subregister must be a leaf subregister and only occupies 1 bit.
14483ca95b02SDimitry Andric       // Move the bit from the class without subregisters into that position.
14492cab237bSDimitry Andric       unsigned DstBit = Idx.LaneMask.getHighestLane();
1450b40b48b8SDimitry Andric       assert(Idx.LaneMask == LaneBitmask::getLane(DstBit) &&
1451d88c1a5aSDimitry Andric              "Must be a leaf subregister");
1452b40b48b8SDimitry Andric       MaskRolPair MaskRol = { LaneBitmask::getLane(0), (uint8_t)DstBit };
14533ca95b02SDimitry Andric       LaneTransforms.push_back(MaskRol);
14543ca95b02SDimitry Andric     } else {
14553ca95b02SDimitry Andric       // Go through all leaf subregisters and find the ones that compose with
14563ca95b02SDimitry Andric       // Idx. These make out all possible valid bits in the lane mask we want to
145739d628a0SDimitry Andric       // transform. Looking only at the leafs ensure that only a single bit in
145839d628a0SDimitry Andric       // the mask is set.
145939d628a0SDimitry Andric       unsigned NextBit = 0;
146039d628a0SDimitry Andric       for (auto &Idx2 : SubRegIndices) {
146139d628a0SDimitry Andric         // Skip non-leaf subregisters.
146239d628a0SDimitry Andric         if (!Idx2.getComposites().empty())
146339d628a0SDimitry Andric           continue;
146439d628a0SDimitry Andric         // Replicate the behaviour from the lane mask generation loop above.
146539d628a0SDimitry Andric         unsigned SrcBit = NextBit;
1466b40b48b8SDimitry Andric         LaneBitmask SrcMask = LaneBitmask::getLane(SrcBit);
1467d88c1a5aSDimitry Andric         if (NextBit < LaneBitmask::BitWidth-1)
146839d628a0SDimitry Andric           ++NextBit;
146939d628a0SDimitry Andric         assert(Idx2.LaneMask == SrcMask);
147039d628a0SDimitry Andric 
147139d628a0SDimitry Andric         // Get the composed subregister if there is any.
147239d628a0SDimitry Andric         auto C = Composites.find(&Idx2);
147339d628a0SDimitry Andric         if (C == Composites.end())
147439d628a0SDimitry Andric           continue;
147539d628a0SDimitry Andric         const CodeGenSubRegIndex *Composite = C->second;
147639d628a0SDimitry Andric         // The Composed subreg should be a leaf subreg too
147739d628a0SDimitry Andric         assert(Composite->getComposites().empty());
147839d628a0SDimitry Andric 
147939d628a0SDimitry Andric         // Create Mask+Rotate operation and merge with existing ops if possible.
14802cab237bSDimitry Andric         unsigned DstBit = Composite->LaneMask.getHighestLane();
148139d628a0SDimitry Andric         int Shift = DstBit - SrcBit;
1482d88c1a5aSDimitry Andric         uint8_t RotateLeft = Shift >= 0 ? (uint8_t)Shift
1483d88c1a5aSDimitry Andric                                         : LaneBitmask::BitWidth + Shift;
148439d628a0SDimitry Andric         for (auto &I : LaneTransforms) {
148539d628a0SDimitry Andric           if (I.RotateLeft == RotateLeft) {
148639d628a0SDimitry Andric             I.Mask |= SrcMask;
1487d88c1a5aSDimitry Andric             SrcMask = LaneBitmask::getNone();
148839d628a0SDimitry Andric           }
148939d628a0SDimitry Andric         }
1490d88c1a5aSDimitry Andric         if (SrcMask.any()) {
149139d628a0SDimitry Andric           MaskRolPair MaskRol = { SrcMask, RotateLeft };
149239d628a0SDimitry Andric           LaneTransforms.push_back(MaskRol);
149339d628a0SDimitry Andric         }
149439d628a0SDimitry Andric       }
14953ca95b02SDimitry Andric     }
14963ca95b02SDimitry Andric 
149739d628a0SDimitry Andric     // Optimize if the transformation consists of one step only: Set mask to
149839d628a0SDimitry Andric     // 0xffffffff (including some irrelevant invalid bits) so that it should
149939d628a0SDimitry Andric     // merge with more entries later while compressing the table.
150039d628a0SDimitry Andric     if (LaneTransforms.size() == 1)
1501d88c1a5aSDimitry Andric       LaneTransforms[0].Mask = LaneBitmask::getAll();
150239d628a0SDimitry Andric 
150339d628a0SDimitry Andric     // Further compression optimization: For invalid compositions resulting
150439d628a0SDimitry Andric     // in a sequence with 0 entries we can just pick any other. Choose
150539d628a0SDimitry Andric     // Mask 0xffffffff with Rotation 0.
150639d628a0SDimitry Andric     if (LaneTransforms.size() == 0) {
1507d88c1a5aSDimitry Andric       MaskRolPair P = { LaneBitmask::getAll(), 0 };
150839d628a0SDimitry Andric       LaneTransforms.push_back(P);
15093861d79fSDimitry Andric     }
15103861d79fSDimitry Andric   }
15113861d79fSDimitry Andric 
15123861d79fSDimitry Andric   // FIXME: What if ad-hoc aliasing introduces overlaps that aren't represented
15133861d79fSDimitry Andric   // by the sub-register graph? This doesn't occur in any known targets.
15143861d79fSDimitry Andric 
15153861d79fSDimitry Andric   // Inherit lanes from composites.
151639d628a0SDimitry Andric   for (const auto &Idx : SubRegIndices) {
1517d88c1a5aSDimitry Andric     LaneBitmask Mask = Idx.computeLaneMask();
1518f785676fSDimitry Andric     // If some super-registers without CoveredBySubRegs use this index, we can
1519f785676fSDimitry Andric     // no longer assume that the lanes are covering their registers.
152039d628a0SDimitry Andric     if (!Idx.AllSuperRegsCovered)
1521f785676fSDimitry Andric       CoveringLanes &= ~Mask;
1522f785676fSDimitry Andric   }
152339d628a0SDimitry Andric 
152439d628a0SDimitry Andric   // Compute lane mask combinations for register classes.
152539d628a0SDimitry Andric   for (auto &RegClass : RegClasses) {
1526d88c1a5aSDimitry Andric     LaneBitmask LaneMask;
152739d628a0SDimitry Andric     for (const auto &SubRegIndex : SubRegIndices) {
1528ff0cc061SDimitry Andric       if (RegClass.getSubClassWithSubReg(&SubRegIndex) == nullptr)
152939d628a0SDimitry Andric         continue;
153039d628a0SDimitry Andric       LaneMask |= SubRegIndex.LaneMask;
153139d628a0SDimitry Andric     }
15327d523365SDimitry Andric 
15333ca95b02SDimitry Andric     // For classes without any subregisters set LaneMask to 1 instead of 0.
15347d523365SDimitry Andric     // This makes it easier for client code to handle classes uniformly.
1535d88c1a5aSDimitry Andric     if (LaneMask.none())
1536b40b48b8SDimitry Andric       LaneMask = LaneBitmask::getLane(0);
15377d523365SDimitry Andric 
153839d628a0SDimitry Andric     RegClass.LaneMask = LaneMask;
153939d628a0SDimitry Andric   }
1540dff0c46cSDimitry Andric }
1541dff0c46cSDimitry Andric 
1542dff0c46cSDimitry Andric namespace {
1543d88c1a5aSDimitry Andric 
1544dff0c46cSDimitry Andric // UberRegSet is a helper class for computeRegUnitWeights. Each UberRegSet is
1545dff0c46cSDimitry Andric // the transitive closure of the union of overlapping register
1546dff0c46cSDimitry Andric // classes. Together, the UberRegSets form a partition of the registers. If we
1547dff0c46cSDimitry Andric // consider overlapping register classes to be connected, then each UberRegSet
1548dff0c46cSDimitry Andric // is a set of connected components.
1549dff0c46cSDimitry Andric //
1550dff0c46cSDimitry Andric // An UberRegSet will likely be a horizontal slice of register names of
1551dff0c46cSDimitry Andric // the same width. Nontrivial subregisters should then be in a separate
1552dff0c46cSDimitry Andric // UberRegSet. But this property isn't required for valid computation of
1553dff0c46cSDimitry Andric // register unit weights.
1554dff0c46cSDimitry Andric //
1555dff0c46cSDimitry Andric // A Weight field caches the max per-register unit weight in each UberRegSet.
1556dff0c46cSDimitry Andric //
1557dff0c46cSDimitry Andric // A set of SingularDeterminants flags single units of some register in this set
1558dff0c46cSDimitry Andric // for which the unit weight equals the set weight. These units should not have
1559dff0c46cSDimitry Andric // their weight increased.
1560dff0c46cSDimitry Andric struct UberRegSet {
1561ff0cc061SDimitry Andric   CodeGenRegister::Vec Regs;
1562d88c1a5aSDimitry Andric   unsigned Weight = 0;
1563dff0c46cSDimitry Andric   CodeGenRegister::RegUnitList SingularDeterminants;
1564dff0c46cSDimitry Andric 
1565d88c1a5aSDimitry Andric   UberRegSet() = default;
1566dff0c46cSDimitry Andric };
1567d88c1a5aSDimitry Andric 
1568d88c1a5aSDimitry Andric } // end anonymous namespace
1569dff0c46cSDimitry Andric 
1570dff0c46cSDimitry Andric // Partition registers into UberRegSets, where each set is the transitive
1571dff0c46cSDimitry Andric // closure of the union of overlapping register classes.
1572dff0c46cSDimitry Andric //
1573dff0c46cSDimitry Andric // UberRegSets[0] is a special non-allocatable set.
computeUberSets(std::vector<UberRegSet> & UberSets,std::vector<UberRegSet * > & RegSets,CodeGenRegBank & RegBank)1574dff0c46cSDimitry Andric static void computeUberSets(std::vector<UberRegSet> &UberSets,
1575dff0c46cSDimitry Andric                             std::vector<UberRegSet*> &RegSets,
1576dff0c46cSDimitry Andric                             CodeGenRegBank &RegBank) {
157739d628a0SDimitry Andric   const auto &Registers = RegBank.getRegisters();
1578dff0c46cSDimitry Andric 
1579dff0c46cSDimitry Andric   // The Register EnumValue is one greater than its index into Registers.
158039d628a0SDimitry Andric   assert(Registers.size() == Registers.back().EnumValue &&
1581dff0c46cSDimitry Andric          "register enum value mismatch");
1582dff0c46cSDimitry Andric 
1583dff0c46cSDimitry Andric   // For simplicitly make the SetID the same as EnumValue.
1584dff0c46cSDimitry Andric   IntEqClasses UberSetIDs(Registers.size()+1);
1585dff0c46cSDimitry Andric   std::set<unsigned> AllocatableRegs;
158639d628a0SDimitry Andric   for (auto &RegClass : RegBank.getRegClasses()) {
158739d628a0SDimitry Andric     if (!RegClass.Allocatable)
1588dff0c46cSDimitry Andric       continue;
1589dff0c46cSDimitry Andric 
1590ff0cc061SDimitry Andric     const CodeGenRegister::Vec &Regs = RegClass.getMembers();
1591dff0c46cSDimitry Andric     if (Regs.empty())
1592dff0c46cSDimitry Andric       continue;
1593dff0c46cSDimitry Andric 
1594dff0c46cSDimitry Andric     unsigned USetID = UberSetIDs.findLeader((*Regs.begin())->EnumValue);
1595dff0c46cSDimitry Andric     assert(USetID && "register number 0 is invalid");
1596dff0c46cSDimitry Andric 
1597dff0c46cSDimitry Andric     AllocatableRegs.insert((*Regs.begin())->EnumValue);
1598ff0cc061SDimitry Andric     for (auto I = std::next(Regs.begin()), E = Regs.end(); I != E; ++I) {
1599dff0c46cSDimitry Andric       AllocatableRegs.insert((*I)->EnumValue);
1600dff0c46cSDimitry Andric       UberSetIDs.join(USetID, (*I)->EnumValue);
1601dff0c46cSDimitry Andric     }
1602dff0c46cSDimitry Andric   }
1603dff0c46cSDimitry Andric   // Combine non-allocatable regs.
160439d628a0SDimitry Andric   for (const auto &Reg : Registers) {
160539d628a0SDimitry Andric     unsigned RegNum = Reg.EnumValue;
1606dff0c46cSDimitry Andric     if (AllocatableRegs.count(RegNum))
1607dff0c46cSDimitry Andric       continue;
1608dff0c46cSDimitry Andric 
1609dff0c46cSDimitry Andric     UberSetIDs.join(0, RegNum);
1610dff0c46cSDimitry Andric   }
1611dff0c46cSDimitry Andric   UberSetIDs.compress();
1612dff0c46cSDimitry Andric 
1613dff0c46cSDimitry Andric   // Make the first UberSet a special unallocatable set.
1614dff0c46cSDimitry Andric   unsigned ZeroID = UberSetIDs[0];
1615dff0c46cSDimitry Andric 
1616dff0c46cSDimitry Andric   // Insert Registers into the UberSets formed by union-find.
1617dff0c46cSDimitry Andric   // Do not resize after this.
1618dff0c46cSDimitry Andric   UberSets.resize(UberSetIDs.getNumClasses());
161939d628a0SDimitry Andric   unsigned i = 0;
162039d628a0SDimitry Andric   for (const CodeGenRegister &Reg : Registers) {
162139d628a0SDimitry Andric     unsigned USetID = UberSetIDs[Reg.EnumValue];
1622dff0c46cSDimitry Andric     if (!USetID)
1623dff0c46cSDimitry Andric       USetID = ZeroID;
1624dff0c46cSDimitry Andric     else if (USetID == ZeroID)
1625dff0c46cSDimitry Andric       USetID = 0;
1626dff0c46cSDimitry Andric 
1627dff0c46cSDimitry Andric     UberRegSet *USet = &UberSets[USetID];
1628ff0cc061SDimitry Andric     USet->Regs.push_back(&Reg);
1629ff0cc061SDimitry Andric     sortAndUniqueRegisters(USet->Regs);
163039d628a0SDimitry Andric     RegSets[i++] = USet;
1631dff0c46cSDimitry Andric   }
1632dff0c46cSDimitry Andric }
1633dff0c46cSDimitry Andric 
1634dff0c46cSDimitry Andric // Recompute each UberSet weight after changing unit weights.
computeUberWeights(std::vector<UberRegSet> & UberSets,CodeGenRegBank & RegBank)1635dff0c46cSDimitry Andric static void computeUberWeights(std::vector<UberRegSet> &UberSets,
1636dff0c46cSDimitry Andric                                CodeGenRegBank &RegBank) {
1637dff0c46cSDimitry Andric   // Skip the first unallocatable set.
163891bc56edSDimitry Andric   for (std::vector<UberRegSet>::iterator I = std::next(UberSets.begin()),
1639dff0c46cSDimitry Andric          E = UberSets.end(); I != E; ++I) {
1640dff0c46cSDimitry Andric 
1641dff0c46cSDimitry Andric     // Initialize all unit weights in this set, and remember the max units/reg.
164291bc56edSDimitry Andric     const CodeGenRegister *Reg = nullptr;
1643dff0c46cSDimitry Andric     unsigned MaxWeight = 0, Weight = 0;
1644dff0c46cSDimitry Andric     for (RegUnitIterator UnitI(I->Regs); UnitI.isValid(); ++UnitI) {
1645dff0c46cSDimitry Andric       if (Reg != UnitI.getReg()) {
1646dff0c46cSDimitry Andric         if (Weight > MaxWeight)
1647dff0c46cSDimitry Andric           MaxWeight = Weight;
1648dff0c46cSDimitry Andric         Reg = UnitI.getReg();
1649dff0c46cSDimitry Andric         Weight = 0;
1650dff0c46cSDimitry Andric       }
16514ba319b5SDimitry Andric       if (!RegBank.getRegUnit(*UnitI).Artificial) {
16527ae0e2c9SDimitry Andric         unsigned UWeight = RegBank.getRegUnit(*UnitI).Weight;
1653dff0c46cSDimitry Andric         if (!UWeight) {
1654dff0c46cSDimitry Andric           UWeight = 1;
1655dff0c46cSDimitry Andric           RegBank.increaseRegUnitWeight(*UnitI, UWeight);
1656dff0c46cSDimitry Andric         }
1657dff0c46cSDimitry Andric         Weight += UWeight;
1658dff0c46cSDimitry Andric       }
16594ba319b5SDimitry Andric     }
1660dff0c46cSDimitry Andric     if (Weight > MaxWeight)
1661dff0c46cSDimitry Andric       MaxWeight = Weight;
1662f785676fSDimitry Andric     if (I->Weight != MaxWeight) {
16634ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "UberSet " << I - UberSets.begin() << " Weight "
16644ba319b5SDimitry Andric                         << MaxWeight;
16654ba319b5SDimitry Andric                  for (auto &Unit
16664ba319b5SDimitry Andric                       : I->Regs) dbgs()
16674ba319b5SDimitry Andric                  << " " << Unit->getName();
1668f785676fSDimitry Andric                  dbgs() << "\n");
1669dff0c46cSDimitry Andric       // Update the set weight.
1670dff0c46cSDimitry Andric       I->Weight = MaxWeight;
1671f785676fSDimitry Andric     }
1672dff0c46cSDimitry Andric 
1673dff0c46cSDimitry Andric     // Find singular determinants.
1674ff0cc061SDimitry Andric     for (const auto R : I->Regs) {
1675ff0cc061SDimitry Andric       if (R->getRegUnits().count() == 1 && R->getWeight(RegBank) == I->Weight) {
1676ff0cc061SDimitry Andric         I->SingularDeterminants |= R->getRegUnits();
1677ff0cc061SDimitry Andric       }
1678dff0c46cSDimitry Andric     }
1679dff0c46cSDimitry Andric   }
1680dff0c46cSDimitry Andric }
1681dff0c46cSDimitry Andric 
1682dff0c46cSDimitry Andric // normalizeWeight is a computeRegUnitWeights helper that adjusts the weight of
1683dff0c46cSDimitry Andric // a register and its subregisters so that they have the same weight as their
1684dff0c46cSDimitry Andric // UberSet. Self-recursion processes the subregister tree in postorder so
1685dff0c46cSDimitry Andric // subregisters are normalized first.
1686dff0c46cSDimitry Andric //
1687dff0c46cSDimitry Andric // Side effects:
1688dff0c46cSDimitry Andric // - creates new adopted register units
1689dff0c46cSDimitry Andric // - causes superregisters to inherit adopted units
1690dff0c46cSDimitry Andric // - increases the weight of "singular" units
1691dff0c46cSDimitry Andric // - induces recomputation of UberWeights.
normalizeWeight(CodeGenRegister * Reg,std::vector<UberRegSet> & UberSets,std::vector<UberRegSet * > & RegSets,BitVector & NormalRegs,CodeGenRegister::RegUnitList & NormalUnits,CodeGenRegBank & RegBank)1692dff0c46cSDimitry Andric static bool normalizeWeight(CodeGenRegister *Reg,
1693dff0c46cSDimitry Andric                             std::vector<UberRegSet> &UberSets,
1694dff0c46cSDimitry Andric                             std::vector<UberRegSet*> &RegSets,
16954ba319b5SDimitry Andric                             BitVector &NormalRegs,
1696dff0c46cSDimitry Andric                             CodeGenRegister::RegUnitList &NormalUnits,
1697dff0c46cSDimitry Andric                             CodeGenRegBank &RegBank) {
16984ba319b5SDimitry Andric   NormalRegs.resize(std::max(Reg->EnumValue + 1, NormalRegs.size()));
1699ff0cc061SDimitry Andric   if (NormalRegs.test(Reg->EnumValue))
1700ff0cc061SDimitry Andric     return false;
1701ff0cc061SDimitry Andric   NormalRegs.set(Reg->EnumValue);
17027ae0e2c9SDimitry Andric 
1703ff0cc061SDimitry Andric   bool Changed = false;
1704dff0c46cSDimitry Andric   const CodeGenRegister::SubRegMap &SRM = Reg->getSubRegs();
1705dff0c46cSDimitry Andric   for (CodeGenRegister::SubRegMap::const_iterator SRI = SRM.begin(),
1706dff0c46cSDimitry Andric          SRE = SRM.end(); SRI != SRE; ++SRI) {
1707dff0c46cSDimitry Andric     if (SRI->second == Reg)
1708dff0c46cSDimitry Andric       continue; // self-cycles happen
1709dff0c46cSDimitry Andric 
17107ae0e2c9SDimitry Andric     Changed |= normalizeWeight(SRI->second, UberSets, RegSets,
17117ae0e2c9SDimitry Andric                                NormalRegs, NormalUnits, RegBank);
1712dff0c46cSDimitry Andric   }
1713dff0c46cSDimitry Andric   // Postorder register normalization.
1714dff0c46cSDimitry Andric 
1715dff0c46cSDimitry Andric   // Inherit register units newly adopted by subregisters.
1716dff0c46cSDimitry Andric   if (Reg->inheritRegUnits(RegBank))
1717dff0c46cSDimitry Andric     computeUberWeights(UberSets, RegBank);
1718dff0c46cSDimitry Andric 
1719dff0c46cSDimitry Andric   // Check if this register is too skinny for its UberRegSet.
1720dff0c46cSDimitry Andric   UberRegSet *UberSet = RegSets[RegBank.getRegIndex(Reg)];
1721dff0c46cSDimitry Andric 
1722dff0c46cSDimitry Andric   unsigned RegWeight = Reg->getWeight(RegBank);
1723dff0c46cSDimitry Andric   if (UberSet->Weight > RegWeight) {
1724dff0c46cSDimitry Andric     // A register unit's weight can be adjusted only if it is the singular unit
1725dff0c46cSDimitry Andric     // for this register, has not been used to normalize a subregister's set,
1726dff0c46cSDimitry Andric     // and has not already been used to singularly determine this UberRegSet.
1727ff0cc061SDimitry Andric     unsigned AdjustUnit = *Reg->getRegUnits().begin();
1728ff0cc061SDimitry Andric     if (Reg->getRegUnits().count() != 1
1729dff0c46cSDimitry Andric         || hasRegUnit(NormalUnits, AdjustUnit)
1730dff0c46cSDimitry Andric         || hasRegUnit(UberSet->SingularDeterminants, AdjustUnit)) {
1731dff0c46cSDimitry Andric       // We don't have an adjustable unit, so adopt a new one.
1732dff0c46cSDimitry Andric       AdjustUnit = RegBank.newRegUnit(UberSet->Weight - RegWeight);
1733dff0c46cSDimitry Andric       Reg->adoptRegUnit(AdjustUnit);
1734dff0c46cSDimitry Andric       // Adopting a unit does not immediately require recomputing set weights.
1735dff0c46cSDimitry Andric     }
1736dff0c46cSDimitry Andric     else {
1737dff0c46cSDimitry Andric       // Adjust the existing single unit.
17384ba319b5SDimitry Andric       if (!RegBank.getRegUnit(AdjustUnit).Artificial)
1739dff0c46cSDimitry Andric         RegBank.increaseRegUnitWeight(AdjustUnit, UberSet->Weight - RegWeight);
1740dff0c46cSDimitry Andric       // The unit may be shared among sets and registers within this set.
1741dff0c46cSDimitry Andric       computeUberWeights(UberSets, RegBank);
1742dff0c46cSDimitry Andric     }
1743dff0c46cSDimitry Andric     Changed = true;
1744dff0c46cSDimitry Andric   }
1745dff0c46cSDimitry Andric 
1746dff0c46cSDimitry Andric   // Mark these units normalized so superregisters can't change their weights.
1747ff0cc061SDimitry Andric   NormalUnits |= Reg->getRegUnits();
1748dff0c46cSDimitry Andric 
1749dff0c46cSDimitry Andric   return Changed;
1750dff0c46cSDimitry Andric }
1751dff0c46cSDimitry Andric 
1752dff0c46cSDimitry Andric // Compute a weight for each register unit created during getSubRegs.
1753dff0c46cSDimitry Andric //
1754dff0c46cSDimitry Andric // The goal is that two registers in the same class will have the same weight,
1755dff0c46cSDimitry Andric // where each register's weight is defined as sum of its units' weights.
computeRegUnitWeights()1756dff0c46cSDimitry Andric void CodeGenRegBank::computeRegUnitWeights() {
1757dff0c46cSDimitry Andric   std::vector<UberRegSet> UberSets;
1758dff0c46cSDimitry Andric   std::vector<UberRegSet*> RegSets(Registers.size());
1759dff0c46cSDimitry Andric   computeUberSets(UberSets, RegSets, *this);
1760dff0c46cSDimitry Andric   // UberSets and RegSets are now immutable.
1761dff0c46cSDimitry Andric 
1762dff0c46cSDimitry Andric   computeUberWeights(UberSets, *this);
1763dff0c46cSDimitry Andric 
1764dff0c46cSDimitry Andric   // Iterate over each Register, normalizing the unit weights until reaching
1765dff0c46cSDimitry Andric   // a fix point.
1766dff0c46cSDimitry Andric   unsigned NumIters = 0;
1767dff0c46cSDimitry Andric   for (bool Changed = true; Changed; ++NumIters) {
1768dff0c46cSDimitry Andric     assert(NumIters <= NumNativeRegUnits && "Runaway register unit weights");
1769dff0c46cSDimitry Andric     Changed = false;
177039d628a0SDimitry Andric     for (auto &Reg : Registers) {
1771dff0c46cSDimitry Andric       CodeGenRegister::RegUnitList NormalUnits;
17724ba319b5SDimitry Andric       BitVector NormalRegs;
177339d628a0SDimitry Andric       Changed |= normalizeWeight(&Reg, UberSets, RegSets, NormalRegs,
177439d628a0SDimitry Andric                                  NormalUnits, *this);
1775dff0c46cSDimitry Andric     }
1776dff0c46cSDimitry Andric   }
1777dff0c46cSDimitry Andric }
1778dff0c46cSDimitry Andric 
1779dff0c46cSDimitry Andric // Find a set in UniqueSets with the same elements as Set.
1780dff0c46cSDimitry Andric // Return an iterator into UniqueSets.
1781dff0c46cSDimitry Andric static std::vector<RegUnitSet>::const_iterator
findRegUnitSet(const std::vector<RegUnitSet> & UniqueSets,const RegUnitSet & Set)1782dff0c46cSDimitry Andric findRegUnitSet(const std::vector<RegUnitSet> &UniqueSets,
1783dff0c46cSDimitry Andric                const RegUnitSet &Set) {
1784dff0c46cSDimitry Andric   std::vector<RegUnitSet>::const_iterator
1785dff0c46cSDimitry Andric     I = UniqueSets.begin(), E = UniqueSets.end();
1786dff0c46cSDimitry Andric   for(;I != E; ++I) {
1787dff0c46cSDimitry Andric     if (I->Units == Set.Units)
1788dff0c46cSDimitry Andric       break;
1789dff0c46cSDimitry Andric   }
1790dff0c46cSDimitry Andric   return I;
1791dff0c46cSDimitry Andric }
1792dff0c46cSDimitry Andric 
1793dff0c46cSDimitry Andric // Return true if the RUSubSet is a subset of RUSuperSet.
isRegUnitSubSet(const std::vector<unsigned> & RUSubSet,const std::vector<unsigned> & RUSuperSet)1794dff0c46cSDimitry Andric static bool isRegUnitSubSet(const std::vector<unsigned> &RUSubSet,
1795dff0c46cSDimitry Andric                             const std::vector<unsigned> &RUSuperSet) {
1796dff0c46cSDimitry Andric   return std::includes(RUSuperSet.begin(), RUSuperSet.end(),
1797dff0c46cSDimitry Andric                        RUSubSet.begin(), RUSubSet.end());
1798dff0c46cSDimitry Andric }
1799dff0c46cSDimitry Andric 
1800f785676fSDimitry Andric /// Iteratively prune unit sets. Prune subsets that are close to the superset,
1801f785676fSDimitry Andric /// but with one or two registers removed. We occasionally have registers like
1802f785676fSDimitry Andric /// APSR and PC thrown in with the general registers. We also see many
1803f785676fSDimitry Andric /// special-purpose register subsets, such as tail-call and Thumb
1804f785676fSDimitry Andric /// encodings. Generating all possible overlapping sets is combinatorial and
1805f785676fSDimitry Andric /// overkill for modeling pressure. Ideally we could fix this statically in
1806f785676fSDimitry Andric /// tablegen by (1) having the target define register classes that only include
1807f785676fSDimitry Andric /// the allocatable registers and marking other classes as non-allocatable and
1808f785676fSDimitry Andric /// (2) having a way to mark special purpose classes as "don't-care" classes for
1809f785676fSDimitry Andric /// the purpose of pressure.  However, we make an attempt to handle targets that
1810f785676fSDimitry Andric /// are not nicely defined by merging nearly identical register unit sets
1811f785676fSDimitry Andric /// statically. This generates smaller tables. Then, dynamically, we adjust the
1812f785676fSDimitry Andric /// set limit by filtering the reserved registers.
1813f785676fSDimitry Andric ///
1814f785676fSDimitry Andric /// Merge sets only if the units have the same weight. For example, on ARM,
1815f785676fSDimitry Andric /// Q-tuples with ssub index 0 include all S regs but also include D16+. We
1816f785676fSDimitry Andric /// should not expand the S set to include D regs.
pruneUnitSets()1817dff0c46cSDimitry Andric void CodeGenRegBank::pruneUnitSets() {
1818dff0c46cSDimitry Andric   assert(RegClassUnitSets.empty() && "this invalidates RegClassUnitSets");
1819dff0c46cSDimitry Andric 
1820dff0c46cSDimitry Andric   // Form an equivalence class of UnitSets with no significant difference.
1821dff0c46cSDimitry Andric   std::vector<unsigned> SuperSetIDs;
1822dff0c46cSDimitry Andric   for (unsigned SubIdx = 0, EndIdx = RegUnitSets.size();
1823dff0c46cSDimitry Andric        SubIdx != EndIdx; ++SubIdx) {
1824dff0c46cSDimitry Andric     const RegUnitSet &SubSet = RegUnitSets[SubIdx];
1825dff0c46cSDimitry Andric     unsigned SuperIdx = 0;
1826dff0c46cSDimitry Andric     for (; SuperIdx != EndIdx; ++SuperIdx) {
1827dff0c46cSDimitry Andric       if (SuperIdx == SubIdx)
1828dff0c46cSDimitry Andric         continue;
1829dff0c46cSDimitry Andric 
1830f785676fSDimitry Andric       unsigned UnitWeight = RegUnits[SubSet.Units[0]].Weight;
1831dff0c46cSDimitry Andric       const RegUnitSet &SuperSet = RegUnitSets[SuperIdx];
1832dff0c46cSDimitry Andric       if (isRegUnitSubSet(SubSet.Units, SuperSet.Units)
1833f785676fSDimitry Andric           && (SubSet.Units.size() + 3 > SuperSet.Units.size())
1834f785676fSDimitry Andric           && UnitWeight == RegUnits[SuperSet.Units[0]].Weight
1835f785676fSDimitry Andric           && UnitWeight == RegUnits[SuperSet.Units.back()].Weight) {
18364ba319b5SDimitry Andric         LLVM_DEBUG(dbgs() << "UnitSet " << SubIdx << " subsumed by " << SuperIdx
1837f785676fSDimitry Andric                           << "\n");
18387d523365SDimitry Andric         // We can pick any of the set names for the merged set. Go for the
18397d523365SDimitry Andric         // shortest one to avoid picking the name of one of the classes that are
18407d523365SDimitry Andric         // artificially created by tablegen. So "FPR128_lo" instead of
18417d523365SDimitry Andric         // "QQQQ_with_qsub3_in_FPR128_lo".
18427d523365SDimitry Andric         if (RegUnitSets[SubIdx].Name.size() < RegUnitSets[SuperIdx].Name.size())
18437d523365SDimitry Andric           RegUnitSets[SuperIdx].Name = RegUnitSets[SubIdx].Name;
1844dff0c46cSDimitry Andric         break;
1845dff0c46cSDimitry Andric       }
1846dff0c46cSDimitry Andric     }
1847dff0c46cSDimitry Andric     if (SuperIdx == EndIdx)
1848dff0c46cSDimitry Andric       SuperSetIDs.push_back(SubIdx);
1849dff0c46cSDimitry Andric   }
1850dff0c46cSDimitry Andric   // Populate PrunedUnitSets with each equivalence class's superset.
1851dff0c46cSDimitry Andric   std::vector<RegUnitSet> PrunedUnitSets(SuperSetIDs.size());
1852dff0c46cSDimitry Andric   for (unsigned i = 0, e = SuperSetIDs.size(); i != e; ++i) {
1853dff0c46cSDimitry Andric     unsigned SuperIdx = SuperSetIDs[i];
1854dff0c46cSDimitry Andric     PrunedUnitSets[i].Name = RegUnitSets[SuperIdx].Name;
1855dff0c46cSDimitry Andric     PrunedUnitSets[i].Units.swap(RegUnitSets[SuperIdx].Units);
1856dff0c46cSDimitry Andric   }
1857dff0c46cSDimitry Andric   RegUnitSets.swap(PrunedUnitSets);
1858dff0c46cSDimitry Andric }
1859dff0c46cSDimitry Andric 
1860dff0c46cSDimitry Andric // Create a RegUnitSet for each RegClass that contains all units in the class
1861dff0c46cSDimitry Andric // including adopted units that are necessary to model register pressure. Then
1862dff0c46cSDimitry Andric // iteratively compute RegUnitSets such that the union of any two overlapping
1863dff0c46cSDimitry Andric // RegUnitSets is repreresented.
1864dff0c46cSDimitry Andric //
1865dff0c46cSDimitry Andric // RegisterInfoEmitter will map each RegClass to its RegUnitClass and any
1866dff0c46cSDimitry Andric // RegUnitSet that is a superset of that RegUnitClass.
computeRegUnitSets()1867dff0c46cSDimitry Andric void CodeGenRegBank::computeRegUnitSets() {
1868f785676fSDimitry Andric   assert(RegUnitSets.empty() && "dirty RegUnitSets");
1869dff0c46cSDimitry Andric 
1870dff0c46cSDimitry Andric   // Compute a unique RegUnitSet for each RegClass.
187139d628a0SDimitry Andric   auto &RegClasses = getRegClasses();
187239d628a0SDimitry Andric   for (auto &RC : RegClasses) {
18734ba319b5SDimitry Andric     if (!RC.Allocatable || RC.Artificial)
1874dff0c46cSDimitry Andric       continue;
1875dff0c46cSDimitry Andric 
1876dff0c46cSDimitry Andric     // Speculatively grow the RegUnitSets to hold the new set.
1877dff0c46cSDimitry Andric     RegUnitSets.resize(RegUnitSets.size() + 1);
187839d628a0SDimitry Andric     RegUnitSets.back().Name = RC.getName();
1879dff0c46cSDimitry Andric 
1880dff0c46cSDimitry Andric     // Compute a sorted list of units in this class.
18814ba319b5SDimitry Andric     RC.buildRegUnitSet(*this, RegUnitSets.back().Units);
1882dff0c46cSDimitry Andric 
1883dff0c46cSDimitry Andric     // Find an existing RegUnitSet.
1884dff0c46cSDimitry Andric     std::vector<RegUnitSet>::const_iterator SetI =
1885dff0c46cSDimitry Andric       findRegUnitSet(RegUnitSets, RegUnitSets.back());
188691bc56edSDimitry Andric     if (SetI != std::prev(RegUnitSets.end()))
1887dff0c46cSDimitry Andric       RegUnitSets.pop_back();
1888dff0c46cSDimitry Andric   }
1889dff0c46cSDimitry Andric 
18904ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "\nBefore pruning:\n"; for (unsigned USIdx = 0,
18914ba319b5SDimitry Andric                                                    USEnd = RegUnitSets.size();
1892f785676fSDimitry Andric                                                    USIdx < USEnd; ++USIdx) {
18934ba319b5SDimitry Andric     dbgs() << "UnitSet " << USIdx << " " << RegUnitSets[USIdx].Name << ":";
189439d628a0SDimitry Andric     for (auto &U : RegUnitSets[USIdx].Units)
18957a7e6055SDimitry Andric       printRegUnitName(U);
1896f785676fSDimitry Andric     dbgs() << "\n";
1897f785676fSDimitry Andric   });
1898f785676fSDimitry Andric 
1899dff0c46cSDimitry Andric   // Iteratively prune unit sets.
1900dff0c46cSDimitry Andric   pruneUnitSets();
1901dff0c46cSDimitry Andric 
19024ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "\nBefore union:\n"; for (unsigned USIdx = 0,
19034ba319b5SDimitry Andric                                                  USEnd = RegUnitSets.size();
1904f785676fSDimitry Andric                                                  USIdx < USEnd; ++USIdx) {
19054ba319b5SDimitry Andric     dbgs() << "UnitSet " << USIdx << " " << RegUnitSets[USIdx].Name << ":";
190639d628a0SDimitry Andric     for (auto &U : RegUnitSets[USIdx].Units)
19077a7e6055SDimitry Andric       printRegUnitName(U);
1908f785676fSDimitry Andric     dbgs() << "\n";
19094ba319b5SDimitry Andric   } dbgs() << "\nUnion sets:\n");
1910f785676fSDimitry Andric 
1911dff0c46cSDimitry Andric   // Iterate over all unit sets, including new ones added by this loop.
1912dff0c46cSDimitry Andric   unsigned NumRegUnitSubSets = RegUnitSets.size();
1913dff0c46cSDimitry Andric   for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx) {
1914dff0c46cSDimitry Andric     // In theory, this is combinatorial. In practice, it needs to be bounded
1915dff0c46cSDimitry Andric     // by a small number of sets for regpressure to be efficient.
1916dff0c46cSDimitry Andric     // If the assert is hit, we need to implement pruning.
1917dff0c46cSDimitry Andric     assert(Idx < (2*NumRegUnitSubSets) && "runaway unit set inference");
1918dff0c46cSDimitry Andric 
1919dff0c46cSDimitry Andric     // Compare new sets with all original classes.
1920dff0c46cSDimitry Andric     for (unsigned SearchIdx = (Idx >= NumRegUnitSubSets) ? 0 : Idx+1;
1921dff0c46cSDimitry Andric          SearchIdx != EndIdx; ++SearchIdx) {
1922dff0c46cSDimitry Andric       std::set<unsigned> Intersection;
1923dff0c46cSDimitry Andric       std::set_intersection(RegUnitSets[Idx].Units.begin(),
1924dff0c46cSDimitry Andric                             RegUnitSets[Idx].Units.end(),
1925dff0c46cSDimitry Andric                             RegUnitSets[SearchIdx].Units.begin(),
1926dff0c46cSDimitry Andric                             RegUnitSets[SearchIdx].Units.end(),
1927dff0c46cSDimitry Andric                             std::inserter(Intersection, Intersection.begin()));
1928dff0c46cSDimitry Andric       if (Intersection.empty())
1929dff0c46cSDimitry Andric         continue;
1930dff0c46cSDimitry Andric 
1931dff0c46cSDimitry Andric       // Speculatively grow the RegUnitSets to hold the new set.
1932dff0c46cSDimitry Andric       RegUnitSets.resize(RegUnitSets.size() + 1);
1933dff0c46cSDimitry Andric       RegUnitSets.back().Name =
1934dff0c46cSDimitry Andric         RegUnitSets[Idx].Name + "+" + RegUnitSets[SearchIdx].Name;
1935dff0c46cSDimitry Andric 
1936dff0c46cSDimitry Andric       std::set_union(RegUnitSets[Idx].Units.begin(),
1937dff0c46cSDimitry Andric                      RegUnitSets[Idx].Units.end(),
1938dff0c46cSDimitry Andric                      RegUnitSets[SearchIdx].Units.begin(),
1939dff0c46cSDimitry Andric                      RegUnitSets[SearchIdx].Units.end(),
1940dff0c46cSDimitry Andric                      std::inserter(RegUnitSets.back().Units,
1941dff0c46cSDimitry Andric                                    RegUnitSets.back().Units.begin()));
1942dff0c46cSDimitry Andric 
1943dff0c46cSDimitry Andric       // Find an existing RegUnitSet, or add the union to the unique sets.
1944dff0c46cSDimitry Andric       std::vector<RegUnitSet>::const_iterator SetI =
1945dff0c46cSDimitry Andric         findRegUnitSet(RegUnitSets, RegUnitSets.back());
194691bc56edSDimitry Andric       if (SetI != std::prev(RegUnitSets.end()))
1947dff0c46cSDimitry Andric         RegUnitSets.pop_back();
1948f785676fSDimitry Andric       else {
19494ba319b5SDimitry Andric         LLVM_DEBUG(dbgs() << "UnitSet " << RegUnitSets.size() - 1 << " "
19504ba319b5SDimitry Andric                           << RegUnitSets.back().Name << ":";
19514ba319b5SDimitry Andric                    for (auto &U
19524ba319b5SDimitry Andric                         : RegUnitSets.back().Units) printRegUnitName(U);
1953f785676fSDimitry Andric                    dbgs() << "\n";);
1954f785676fSDimitry Andric       }
1955dff0c46cSDimitry Andric     }
1956dff0c46cSDimitry Andric   }
1957dff0c46cSDimitry Andric 
1958dff0c46cSDimitry Andric   // Iteratively prune unit sets after inferring supersets.
1959dff0c46cSDimitry Andric   pruneUnitSets();
1960dff0c46cSDimitry Andric 
19614ba319b5SDimitry Andric   LLVM_DEBUG(
19624ba319b5SDimitry Andric       dbgs() << "\n"; for (unsigned USIdx = 0, USEnd = RegUnitSets.size();
1963f785676fSDimitry Andric                            USIdx < USEnd; ++USIdx) {
19644ba319b5SDimitry Andric         dbgs() << "UnitSet " << USIdx << " " << RegUnitSets[USIdx].Name << ":";
196539d628a0SDimitry Andric         for (auto &U : RegUnitSets[USIdx].Units)
19667a7e6055SDimitry Andric           printRegUnitName(U);
1967f785676fSDimitry Andric         dbgs() << "\n";
1968f785676fSDimitry Andric       });
1969f785676fSDimitry Andric 
1970dff0c46cSDimitry Andric   // For each register class, list the UnitSets that are supersets.
197139d628a0SDimitry Andric   RegClassUnitSets.resize(RegClasses.size());
197239d628a0SDimitry Andric   int RCIdx = -1;
197339d628a0SDimitry Andric   for (auto &RC : RegClasses) {
197439d628a0SDimitry Andric     ++RCIdx;
197539d628a0SDimitry Andric     if (!RC.Allocatable)
1976dff0c46cSDimitry Andric       continue;
1977dff0c46cSDimitry Andric 
1978dff0c46cSDimitry Andric     // Recompute the sorted list of units in this class.
1979f785676fSDimitry Andric     std::vector<unsigned> RCRegUnits;
19804ba319b5SDimitry Andric     RC.buildRegUnitSet(*this, RCRegUnits);
1981dff0c46cSDimitry Andric 
1982dff0c46cSDimitry Andric     // Don't increase pressure for unallocatable regclasses.
1983f785676fSDimitry Andric     if (RCRegUnits.empty())
1984dff0c46cSDimitry Andric       continue;
1985dff0c46cSDimitry Andric 
19864ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "RC " << RC.getName() << " Units: \n";
19874ba319b5SDimitry Andric                for (auto U
19884ba319b5SDimitry Andric                     : RCRegUnits) printRegUnitName(U);
1989f785676fSDimitry Andric                dbgs() << "\n  UnitSetIDs:");
1990f785676fSDimitry Andric 
1991dff0c46cSDimitry Andric     // Find all supersets.
1992dff0c46cSDimitry Andric     for (unsigned USIdx = 0, USEnd = RegUnitSets.size();
1993dff0c46cSDimitry Andric          USIdx != USEnd; ++USIdx) {
1994f785676fSDimitry Andric       if (isRegUnitSubSet(RCRegUnits, RegUnitSets[USIdx].Units)) {
19954ba319b5SDimitry Andric         LLVM_DEBUG(dbgs() << " " << USIdx);
1996dff0c46cSDimitry Andric         RegClassUnitSets[RCIdx].push_back(USIdx);
1997dff0c46cSDimitry Andric       }
1998f785676fSDimitry Andric     }
19994ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "\n");
2000dff0c46cSDimitry Andric     assert(!RegClassUnitSets[RCIdx].empty() && "missing unit set for regclass");
2001bd5abe19SDimitry Andric   }
2002139f7f9bSDimitry Andric 
2003139f7f9bSDimitry Andric   // For each register unit, ensure that we have the list of UnitSets that
2004139f7f9bSDimitry Andric   // contain the unit. Normally, this matches an existing list of UnitSets for a
2005139f7f9bSDimitry Andric   // register class. If not, we create a new entry in RegClassUnitSets as a
2006139f7f9bSDimitry Andric   // "fake" register class.
2007139f7f9bSDimitry Andric   for (unsigned UnitIdx = 0, UnitEnd = NumNativeRegUnits;
2008139f7f9bSDimitry Andric        UnitIdx < UnitEnd; ++UnitIdx) {
2009139f7f9bSDimitry Andric     std::vector<unsigned> RUSets;
2010139f7f9bSDimitry Andric     for (unsigned i = 0, e = RegUnitSets.size(); i != e; ++i) {
2011139f7f9bSDimitry Andric       RegUnitSet &RUSet = RegUnitSets[i];
2012d88c1a5aSDimitry Andric       if (!is_contained(RUSet.Units, UnitIdx))
2013139f7f9bSDimitry Andric         continue;
2014139f7f9bSDimitry Andric       RUSets.push_back(i);
2015139f7f9bSDimitry Andric     }
2016139f7f9bSDimitry Andric     unsigned RCUnitSetsIdx = 0;
2017139f7f9bSDimitry Andric     for (unsigned e = RegClassUnitSets.size();
2018139f7f9bSDimitry Andric          RCUnitSetsIdx != e; ++RCUnitSetsIdx) {
2019139f7f9bSDimitry Andric       if (RegClassUnitSets[RCUnitSetsIdx] == RUSets) {
2020139f7f9bSDimitry Andric         break;
2021139f7f9bSDimitry Andric       }
2022139f7f9bSDimitry Andric     }
2023139f7f9bSDimitry Andric     RegUnits[UnitIdx].RegClassUnitSetsIdx = RCUnitSetsIdx;
2024139f7f9bSDimitry Andric     if (RCUnitSetsIdx == RegClassUnitSets.size()) {
2025139f7f9bSDimitry Andric       // Create a new list of UnitSets as a "fake" register class.
2026139f7f9bSDimitry Andric       RegClassUnitSets.resize(RCUnitSetsIdx + 1);
2027139f7f9bSDimitry Andric       RegClassUnitSets[RCUnitSetsIdx].swap(RUSets);
2028139f7f9bSDimitry Andric     }
2029139f7f9bSDimitry Andric   }
2030bd5abe19SDimitry Andric }
2031bd5abe19SDimitry Andric 
computeRegUnitLaneMasks()203239d628a0SDimitry Andric void CodeGenRegBank::computeRegUnitLaneMasks() {
203339d628a0SDimitry Andric   for (auto &Register : Registers) {
203439d628a0SDimitry Andric     // Create an initial lane mask for all register units.
203539d628a0SDimitry Andric     const auto &RegUnits = Register.getRegUnits();
2036d88c1a5aSDimitry Andric     CodeGenRegister::RegUnitLaneMaskList
2037d88c1a5aSDimitry Andric         RegUnitLaneMasks(RegUnits.count(), LaneBitmask::getNone());
203839d628a0SDimitry Andric     // Iterate through SubRegisters.
203939d628a0SDimitry Andric     typedef CodeGenRegister::SubRegMap SubRegMap;
204039d628a0SDimitry Andric     const SubRegMap &SubRegs = Register.getSubRegs();
204139d628a0SDimitry Andric     for (SubRegMap::const_iterator S = SubRegs.begin(),
204239d628a0SDimitry Andric          SE = SubRegs.end(); S != SE; ++S) {
204339d628a0SDimitry Andric       CodeGenRegister *SubReg = S->second;
204439d628a0SDimitry Andric       // Ignore non-leaf subregisters, their lane masks are fully covered by
204539d628a0SDimitry Andric       // the leaf subregisters anyway.
2046d88c1a5aSDimitry Andric       if (!SubReg->getSubRegs().empty())
204739d628a0SDimitry Andric         continue;
204839d628a0SDimitry Andric       CodeGenSubRegIndex *SubRegIndex = S->first;
204939d628a0SDimitry Andric       const CodeGenRegister *SubRegister = S->second;
2050d88c1a5aSDimitry Andric       LaneBitmask LaneMask = SubRegIndex->LaneMask;
205139d628a0SDimitry Andric       // Distribute LaneMask to Register Units touched.
2052ff0cc061SDimitry Andric       for (unsigned SUI : SubRegister->getRegUnits()) {
205339d628a0SDimitry Andric         bool Found = false;
2054ff0cc061SDimitry Andric         unsigned u = 0;
2055ff0cc061SDimitry Andric         for (unsigned RU : RegUnits) {
2056ff0cc061SDimitry Andric           if (SUI == RU) {
205739d628a0SDimitry Andric             RegUnitLaneMasks[u] |= LaneMask;
205839d628a0SDimitry Andric             assert(!Found);
205939d628a0SDimitry Andric             Found = true;
206039d628a0SDimitry Andric           }
2061ff0cc061SDimitry Andric           ++u;
206239d628a0SDimitry Andric         }
2063ff0cc061SDimitry Andric         (void)Found;
206439d628a0SDimitry Andric         assert(Found);
206539d628a0SDimitry Andric       }
206639d628a0SDimitry Andric     }
206739d628a0SDimitry Andric     Register.setRegUnitLaneMasks(RegUnitLaneMasks);
206839d628a0SDimitry Andric   }
206939d628a0SDimitry Andric }
207039d628a0SDimitry Andric 
computeDerivedInfo()2071bd5abe19SDimitry Andric void CodeGenRegBank::computeDerivedInfo() {
2072bd5abe19SDimitry Andric   computeComposites();
207339d628a0SDimitry Andric   computeSubRegLaneMasks();
2074dff0c46cSDimitry Andric 
2075dff0c46cSDimitry Andric   // Compute a weight for each register unit created during getSubRegs.
2076dff0c46cSDimitry Andric   // This may create adopted register units (with unit # >= NumNativeRegUnits).
2077dff0c46cSDimitry Andric   computeRegUnitWeights();
2078dff0c46cSDimitry Andric 
2079dff0c46cSDimitry Andric   // Compute a unique set of RegUnitSets. One for each RegClass and inferred
2080dff0c46cSDimitry Andric   // supersets for the union of overlapping sets.
2081dff0c46cSDimitry Andric   computeRegUnitSets();
2082f785676fSDimitry Andric 
208339d628a0SDimitry Andric   computeRegUnitLaneMasks();
208439d628a0SDimitry Andric 
20853ca95b02SDimitry Andric   // Compute register class HasDisjunctSubRegs/CoveredBySubRegs flag.
2086ff0cc061SDimitry Andric   for (CodeGenRegisterClass &RC : RegClasses) {
2087ff0cc061SDimitry Andric     RC.HasDisjunctSubRegs = false;
20883ca95b02SDimitry Andric     RC.CoveredBySubRegs = true;
20893ca95b02SDimitry Andric     for (const CodeGenRegister *Reg : RC.getMembers()) {
2090ff0cc061SDimitry Andric       RC.HasDisjunctSubRegs |= Reg->HasDisjunctSubRegs;
20913ca95b02SDimitry Andric       RC.CoveredBySubRegs &= Reg->CoveredBySubRegs;
20923ca95b02SDimitry Andric     }
2093ff0cc061SDimitry Andric   }
2094ff0cc061SDimitry Andric 
2095f785676fSDimitry Andric   // Get the weight of each set.
2096f785676fSDimitry Andric   for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx)
2097f785676fSDimitry Andric     RegUnitSets[Idx].Weight = getRegUnitSetWeight(RegUnitSets[Idx].Units);
2098f785676fSDimitry Andric 
2099f785676fSDimitry Andric   // Find the order of each set.
2100f785676fSDimitry Andric   RegUnitSetOrder.reserve(RegUnitSets.size());
2101f785676fSDimitry Andric   for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx)
2102f785676fSDimitry Andric     RegUnitSetOrder.push_back(Idx);
2103f785676fSDimitry Andric 
2104f785676fSDimitry Andric   std::stable_sort(RegUnitSetOrder.begin(), RegUnitSetOrder.end(),
210591bc56edSDimitry Andric                    [this](unsigned ID1, unsigned ID2) {
210691bc56edSDimitry Andric     return getRegPressureSet(ID1).Units.size() <
210791bc56edSDimitry Andric            getRegPressureSet(ID2).Units.size();
210891bc56edSDimitry Andric   });
2109f785676fSDimitry Andric   for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx) {
2110f785676fSDimitry Andric     RegUnitSets[RegUnitSetOrder[Idx]].Order = Idx;
2111f785676fSDimitry Andric   }
2112bd5abe19SDimitry Andric }
2113bd5abe19SDimitry Andric 
21146122f3e6SDimitry Andric //
2115dff0c46cSDimitry Andric // Synthesize missing register class intersections.
2116dff0c46cSDimitry Andric //
2117dff0c46cSDimitry Andric // Make sure that sub-classes of RC exists such that getCommonSubClass(RC, X)
2118dff0c46cSDimitry Andric // returns a maximal register class for all X.
2119dff0c46cSDimitry Andric //
inferCommonSubClass(CodeGenRegisterClass * RC)2120dff0c46cSDimitry Andric void CodeGenRegBank::inferCommonSubClass(CodeGenRegisterClass *RC) {
212139d628a0SDimitry Andric   assert(!RegClasses.empty());
212239d628a0SDimitry Andric   // Stash the iterator to the last element so that this loop doesn't visit
212339d628a0SDimitry Andric   // elements added by the getOrCreateSubClass call within it.
212439d628a0SDimitry Andric   for (auto I = RegClasses.begin(), E = std::prev(RegClasses.end());
212539d628a0SDimitry Andric        I != std::next(E); ++I) {
2126dff0c46cSDimitry Andric     CodeGenRegisterClass *RC1 = RC;
212739d628a0SDimitry Andric     CodeGenRegisterClass *RC2 = &*I;
2128dff0c46cSDimitry Andric     if (RC1 == RC2)
2129dff0c46cSDimitry Andric       continue;
21306122f3e6SDimitry Andric 
2131dff0c46cSDimitry Andric     // Compute the set intersection of RC1 and RC2.
2132ff0cc061SDimitry Andric     const CodeGenRegister::Vec &Memb1 = RC1->getMembers();
2133ff0cc061SDimitry Andric     const CodeGenRegister::Vec &Memb2 = RC2->getMembers();
2134ff0cc061SDimitry Andric     CodeGenRegister::Vec Intersection;
2135ff0cc061SDimitry Andric     std::set_intersection(
2136ff0cc061SDimitry Andric         Memb1.begin(), Memb1.end(), Memb2.begin(), Memb2.end(),
2137ff0cc061SDimitry Andric         std::inserter(Intersection, Intersection.begin()), deref<llvm::less>());
21386122f3e6SDimitry Andric 
2139dff0c46cSDimitry Andric     // Skip disjoint class pairs.
2140dff0c46cSDimitry Andric     if (Intersection.empty())
2141dff0c46cSDimitry Andric       continue;
2142dff0c46cSDimitry Andric 
2143dff0c46cSDimitry Andric     // If RC1 and RC2 have different spill sizes or alignments, use the
21442cab237bSDimitry Andric     // stricter one for sub-classing.  If they are equal, prefer RC1.
21452cab237bSDimitry Andric     if (RC2->RSI.hasStricterSpillThan(RC1->RSI))
2146dff0c46cSDimitry Andric       std::swap(RC1, RC2);
2147dff0c46cSDimitry Andric 
2148dff0c46cSDimitry Andric     getOrCreateSubClass(RC1, &Intersection,
2149dff0c46cSDimitry Andric                         RC1->getName() + "_and_" + RC2->getName());
2150dff0c46cSDimitry Andric   }
2151dff0c46cSDimitry Andric }
2152dff0c46cSDimitry Andric 
2153dff0c46cSDimitry Andric //
2154dff0c46cSDimitry Andric // Synthesize missing sub-classes for getSubClassWithSubReg().
2155dff0c46cSDimitry Andric //
2156dff0c46cSDimitry Andric // Make sure that the set of registers in RC with a given SubIdx sub-register
2157dff0c46cSDimitry Andric // form a register class.  Update RC->SubClassWithSubReg.
2158dff0c46cSDimitry Andric //
inferSubClassWithSubReg(CodeGenRegisterClass * RC)2159dff0c46cSDimitry Andric void CodeGenRegBank::inferSubClassWithSubReg(CodeGenRegisterClass *RC) {
2160dff0c46cSDimitry Andric   // Map SubRegIndex to set of registers in RC supporting that SubRegIndex.
2161ff0cc061SDimitry Andric   typedef std::map<const CodeGenSubRegIndex *, CodeGenRegister::Vec,
2162ff0cc061SDimitry Andric                    deref<llvm::less>> SubReg2SetMap;
21636122f3e6SDimitry Andric 
21646122f3e6SDimitry Andric   // Compute the set of registers supporting each SubRegIndex.
21656122f3e6SDimitry Andric   SubReg2SetMap SRSets;
2166ff0cc061SDimitry Andric   for (const auto R : RC->getMembers()) {
21674ba319b5SDimitry Andric     if (R->Artificial)
21684ba319b5SDimitry Andric       continue;
2169ff0cc061SDimitry Andric     const CodeGenRegister::SubRegMap &SRM = R->getSubRegs();
21706122f3e6SDimitry Andric     for (CodeGenRegister::SubRegMap::const_iterator I = SRM.begin(),
21714ba319b5SDimitry Andric          E = SRM.end(); I != E; ++I) {
21724ba319b5SDimitry Andric       if (!I->first->Artificial)
2173ff0cc061SDimitry Andric         SRSets[I->first].push_back(R);
21746122f3e6SDimitry Andric     }
21754ba319b5SDimitry Andric   }
21766122f3e6SDimitry Andric 
2177ff0cc061SDimitry Andric   for (auto I : SRSets)
2178ff0cc061SDimitry Andric     sortAndUniqueRegisters(I.second);
2179ff0cc061SDimitry Andric 
21806122f3e6SDimitry Andric   // Find matching classes for all SRSets entries.  Iterate in SubRegIndex
21816122f3e6SDimitry Andric   // numerical order to visit synthetic indices last.
218239d628a0SDimitry Andric   for (const auto &SubIdx : SubRegIndices) {
21834ba319b5SDimitry Andric     if (SubIdx.Artificial)
21844ba319b5SDimitry Andric       continue;
218539d628a0SDimitry Andric     SubReg2SetMap::const_iterator I = SRSets.find(&SubIdx);
21866122f3e6SDimitry Andric     // Unsupported SubRegIndex. Skip it.
21876122f3e6SDimitry Andric     if (I == SRSets.end())
21886122f3e6SDimitry Andric       continue;
21896122f3e6SDimitry Andric     // In most cases, all RC registers support the SubRegIndex.
2190dff0c46cSDimitry Andric     if (I->second.size() == RC->getMembers().size()) {
219139d628a0SDimitry Andric       RC->setSubClassWithSubReg(&SubIdx, RC);
21926122f3e6SDimitry Andric       continue;
21936122f3e6SDimitry Andric     }
21946122f3e6SDimitry Andric     // This is a real subset.  See if we have a matching class.
2195dff0c46cSDimitry Andric     CodeGenRegisterClass *SubRC =
2196dff0c46cSDimitry Andric       getOrCreateSubClass(RC, &I->second,
2197dff0c46cSDimitry Andric                           RC->getName() + "_with_" + I->first->getName());
219839d628a0SDimitry Andric     RC->setSubClassWithSubReg(&SubIdx, SubRC);
2199dff0c46cSDimitry Andric   }
22006122f3e6SDimitry Andric }
22016122f3e6SDimitry Andric 
2202dff0c46cSDimitry Andric //
2203dff0c46cSDimitry Andric // Synthesize missing sub-classes of RC for getMatchingSuperRegClass().
2204dff0c46cSDimitry Andric //
2205dff0c46cSDimitry Andric // Create sub-classes of RC such that getMatchingSuperRegClass(RC, SubIdx, X)
2206dff0c46cSDimitry Andric // has a maximal result for any SubIdx and any X >= FirstSubRegRC.
2207dff0c46cSDimitry Andric //
2208dff0c46cSDimitry Andric 
inferMatchingSuperRegClass(CodeGenRegisterClass * RC,std::list<CodeGenRegisterClass>::iterator FirstSubRegRC)2209dff0c46cSDimitry Andric void CodeGenRegBank::inferMatchingSuperRegClass(CodeGenRegisterClass *RC,
221039d628a0SDimitry Andric                                                 std::list<CodeGenRegisterClass>::iterator FirstSubRegRC) {
2211dff0c46cSDimitry Andric   SmallVector<std::pair<const CodeGenRegister*,
2212dff0c46cSDimitry Andric                         const CodeGenRegister*>, 16> SSPairs;
22137ae0e2c9SDimitry Andric   BitVector TopoSigs(getNumTopoSigs());
2214dff0c46cSDimitry Andric 
2215dff0c46cSDimitry Andric   // Iterate in SubRegIndex numerical order to visit synthetic indices last.
221639d628a0SDimitry Andric   for (auto &SubIdx : SubRegIndices) {
2217dff0c46cSDimitry Andric     // Skip indexes that aren't fully supported by RC's registers. This was
2218dff0c46cSDimitry Andric     // computed by inferSubClassWithSubReg() above which should have been
2219dff0c46cSDimitry Andric     // called first.
222039d628a0SDimitry Andric     if (RC->getSubClassWithSubReg(&SubIdx) != RC)
2221dff0c46cSDimitry Andric       continue;
2222dff0c46cSDimitry Andric 
2223dff0c46cSDimitry Andric     // Build list of (Super, Sub) pairs for this SubIdx.
2224dff0c46cSDimitry Andric     SSPairs.clear();
22257ae0e2c9SDimitry Andric     TopoSigs.reset();
2226ff0cc061SDimitry Andric     for (const auto Super : RC->getMembers()) {
222739d628a0SDimitry Andric       const CodeGenRegister *Sub = Super->getSubRegs().find(&SubIdx)->second;
2228dff0c46cSDimitry Andric       assert(Sub && "Missing sub-register");
2229dff0c46cSDimitry Andric       SSPairs.push_back(std::make_pair(Super, Sub));
22307ae0e2c9SDimitry Andric       TopoSigs.set(Sub->getTopoSig());
2231dff0c46cSDimitry Andric     }
2232dff0c46cSDimitry Andric 
2233dff0c46cSDimitry Andric     // Iterate over sub-register class candidates.  Ignore classes created by
2234dff0c46cSDimitry Andric     // this loop. They will never be useful.
223539d628a0SDimitry Andric     // Store an iterator to the last element (not end) so that this loop doesn't
223639d628a0SDimitry Andric     // visit newly inserted elements.
223739d628a0SDimitry Andric     assert(!RegClasses.empty());
223839d628a0SDimitry Andric     for (auto I = FirstSubRegRC, E = std::prev(RegClasses.end());
223939d628a0SDimitry Andric          I != std::next(E); ++I) {
224039d628a0SDimitry Andric       CodeGenRegisterClass &SubRC = *I;
22414ba319b5SDimitry Andric       if (SubRC.Artificial)
22424ba319b5SDimitry Andric         continue;
22437ae0e2c9SDimitry Andric       // Topological shortcut: SubRC members have the wrong shape.
224439d628a0SDimitry Andric       if (!TopoSigs.anyCommon(SubRC.getTopoSigs()))
22457ae0e2c9SDimitry Andric         continue;
2246dff0c46cSDimitry Andric       // Compute the subset of RC that maps into SubRC.
2247ff0cc061SDimitry Andric       CodeGenRegister::Vec SubSetVec;
2248dff0c46cSDimitry Andric       for (unsigned i = 0, e = SSPairs.size(); i != e; ++i)
224939d628a0SDimitry Andric         if (SubRC.contains(SSPairs[i].second))
2250ff0cc061SDimitry Andric           SubSetVec.push_back(SSPairs[i].first);
2251ff0cc061SDimitry Andric 
2252ff0cc061SDimitry Andric       if (SubSetVec.empty())
2253dff0c46cSDimitry Andric         continue;
2254ff0cc061SDimitry Andric 
2255dff0c46cSDimitry Andric       // RC injects completely into SubRC.
2256ff0cc061SDimitry Andric       sortAndUniqueRegisters(SubSetVec);
2257ff0cc061SDimitry Andric       if (SubSetVec.size() == SSPairs.size()) {
225839d628a0SDimitry Andric         SubRC.addSuperRegClass(&SubIdx, RC);
2259dff0c46cSDimitry Andric         continue;
2260dff0c46cSDimitry Andric       }
2261ff0cc061SDimitry Andric 
2262dff0c46cSDimitry Andric       // Only a subset of RC maps into SubRC. Make sure it is represented by a
2263dff0c46cSDimitry Andric       // class.
2264ff0cc061SDimitry Andric       getOrCreateSubClass(RC, &SubSetVec, RC->getName() + "_with_" +
226539d628a0SDimitry Andric                                           SubIdx.getName() + "_in_" +
226639d628a0SDimitry Andric                                           SubRC.getName());
2267dff0c46cSDimitry Andric     }
2268dff0c46cSDimitry Andric   }
2269dff0c46cSDimitry Andric }
2270dff0c46cSDimitry Andric 
2271dff0c46cSDimitry Andric //
2272dff0c46cSDimitry Andric // Infer missing register classes.
2273dff0c46cSDimitry Andric //
computeInferredRegisterClasses()2274dff0c46cSDimitry Andric void CodeGenRegBank::computeInferredRegisterClasses() {
227539d628a0SDimitry Andric   assert(!RegClasses.empty());
2276dff0c46cSDimitry Andric   // When this function is called, the register classes have not been sorted
2277dff0c46cSDimitry Andric   // and assigned EnumValues yet.  That means getSubClasses(),
2278dff0c46cSDimitry Andric   // getSuperClasses(), and hasSubClass() functions are defunct.
227939d628a0SDimitry Andric 
228039d628a0SDimitry Andric   // Use one-before-the-end so it doesn't move forward when new elements are
228139d628a0SDimitry Andric   // added.
228239d628a0SDimitry Andric   auto FirstNewRC = std::prev(RegClasses.end());
2283dff0c46cSDimitry Andric 
2284dff0c46cSDimitry Andric   // Visit all register classes, including the ones being added by the loop.
228539d628a0SDimitry Andric   // Watch out for iterator invalidation here.
228639d628a0SDimitry Andric   for (auto I = RegClasses.begin(), E = RegClasses.end(); I != E; ++I) {
228739d628a0SDimitry Andric     CodeGenRegisterClass *RC = &*I;
22884ba319b5SDimitry Andric     if (RC->Artificial)
22894ba319b5SDimitry Andric       continue;
2290dff0c46cSDimitry Andric 
2291dff0c46cSDimitry Andric     // Synthesize answers for getSubClassWithSubReg().
2292dff0c46cSDimitry Andric     inferSubClassWithSubReg(RC);
2293dff0c46cSDimitry Andric 
2294dff0c46cSDimitry Andric     // Synthesize answers for getCommonSubClass().
2295dff0c46cSDimitry Andric     inferCommonSubClass(RC);
2296dff0c46cSDimitry Andric 
2297dff0c46cSDimitry Andric     // Synthesize answers for getMatchingSuperRegClass().
2298dff0c46cSDimitry Andric     inferMatchingSuperRegClass(RC);
2299dff0c46cSDimitry Andric 
2300dff0c46cSDimitry Andric     // New register classes are created while this loop is running, and we need
2301dff0c46cSDimitry Andric     // to visit all of them.  I  particular, inferMatchingSuperRegClass needs
2302dff0c46cSDimitry Andric     // to match old super-register classes with sub-register classes created
2303dff0c46cSDimitry Andric     // after inferMatchingSuperRegClass was called.  At this point,
2304dff0c46cSDimitry Andric     // inferMatchingSuperRegClass has checked SuperRC = [0..rci] with SubRC =
2305dff0c46cSDimitry Andric     // [0..FirstNewRC).  We need to cover SubRC = [FirstNewRC..rci].
230639d628a0SDimitry Andric     if (I == FirstNewRC) {
230739d628a0SDimitry Andric       auto NextNewRC = std::prev(RegClasses.end());
230839d628a0SDimitry Andric       for (auto I2 = RegClasses.begin(), E2 = std::next(FirstNewRC); I2 != E2;
230939d628a0SDimitry Andric            ++I2)
231039d628a0SDimitry Andric         inferMatchingSuperRegClass(&*I2, E2);
2311dff0c46cSDimitry Andric       FirstNewRC = NextNewRC;
23126122f3e6SDimitry Andric     }
23136122f3e6SDimitry Andric   }
23146122f3e6SDimitry Andric }
23156122f3e6SDimitry Andric 
231617a519f9SDimitry Andric /// getRegisterClassForRegister - Find the register class that contains the
231717a519f9SDimitry Andric /// specified physical register.  If the register is not in a register class,
231817a519f9SDimitry Andric /// return null. If the register is in multiple classes, and the classes have a
231917a519f9SDimitry Andric /// superset-subset relationship and the same set of types, return the
232017a519f9SDimitry Andric /// superclass.  Otherwise return null.
232117a519f9SDimitry Andric const CodeGenRegisterClass*
getRegClassForRegister(Record * R)232217a519f9SDimitry Andric CodeGenRegBank::getRegClassForRegister(Record *R) {
232317a519f9SDimitry Andric   const CodeGenRegister *Reg = getReg(R);
232491bc56edSDimitry Andric   const CodeGenRegisterClass *FoundRC = nullptr;
232539d628a0SDimitry Andric   for (const auto &RC : getRegClasses()) {
232617a519f9SDimitry Andric     if (!RC.contains(Reg))
232717a519f9SDimitry Andric       continue;
232817a519f9SDimitry Andric 
232917a519f9SDimitry Andric     // If this is the first class that contains the register,
233017a519f9SDimitry Andric     // make a note of it and go on to the next class.
233117a519f9SDimitry Andric     if (!FoundRC) {
233217a519f9SDimitry Andric       FoundRC = &RC;
233317a519f9SDimitry Andric       continue;
233417a519f9SDimitry Andric     }
233517a519f9SDimitry Andric 
233617a519f9SDimitry Andric     // If a register's classes have different types, return null.
233717a519f9SDimitry Andric     if (RC.getValueTypes() != FoundRC->getValueTypes())
233891bc56edSDimitry Andric       return nullptr;
233917a519f9SDimitry Andric 
234017a519f9SDimitry Andric     // Check to see if the previously found class that contains
234117a519f9SDimitry Andric     // the register is a subclass of the current class. If so,
234217a519f9SDimitry Andric     // prefer the superclass.
234317a519f9SDimitry Andric     if (RC.hasSubClass(FoundRC)) {
234417a519f9SDimitry Andric       FoundRC = &RC;
234517a519f9SDimitry Andric       continue;
234617a519f9SDimitry Andric     }
234717a519f9SDimitry Andric 
234817a519f9SDimitry Andric     // Check to see if the previously found class that contains
234917a519f9SDimitry Andric     // the register is a superclass of the current class. If so,
235017a519f9SDimitry Andric     // prefer the superclass.
235117a519f9SDimitry Andric     if (FoundRC->hasSubClass(&RC))
235217a519f9SDimitry Andric       continue;
235317a519f9SDimitry Andric 
235417a519f9SDimitry Andric     // Multiple classes, and neither is a superclass of the other.
235517a519f9SDimitry Andric     // Return null.
235691bc56edSDimitry Andric     return nullptr;
235717a519f9SDimitry Andric   }
235817a519f9SDimitry Andric   return FoundRC;
235917a519f9SDimitry Andric }
2360dff0c46cSDimitry Andric 
computeCoveredRegisters(ArrayRef<Record * > Regs)2361dff0c46cSDimitry Andric BitVector CodeGenRegBank::computeCoveredRegisters(ArrayRef<Record*> Regs) {
2362dff0c46cSDimitry Andric   SetVector<const CodeGenRegister*> Set;
2363dff0c46cSDimitry Andric 
2364dff0c46cSDimitry Andric   // First add Regs with all sub-registers.
2365dff0c46cSDimitry Andric   for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
2366dff0c46cSDimitry Andric     CodeGenRegister *Reg = getReg(Regs[i]);
2367dff0c46cSDimitry Andric     if (Set.insert(Reg))
2368dff0c46cSDimitry Andric       // Reg is new, add all sub-registers.
2369dff0c46cSDimitry Andric       // The pre-ordering is not important here.
2370dff0c46cSDimitry Andric       Reg->addSubRegsPreOrder(Set, *this);
2371dff0c46cSDimitry Andric   }
2372dff0c46cSDimitry Andric 
2373dff0c46cSDimitry Andric   // Second, find all super-registers that are completely covered by the set.
2374dff0c46cSDimitry Andric   for (unsigned i = 0; i != Set.size(); ++i) {
2375dff0c46cSDimitry Andric     const CodeGenRegister::SuperRegList &SR = Set[i]->getSuperRegs();
2376dff0c46cSDimitry Andric     for (unsigned j = 0, e = SR.size(); j != e; ++j) {
2377dff0c46cSDimitry Andric       const CodeGenRegister *Super = SR[j];
2378dff0c46cSDimitry Andric       if (!Super->CoveredBySubRegs || Set.count(Super))
2379dff0c46cSDimitry Andric         continue;
2380dff0c46cSDimitry Andric       // This new super-register is covered by its sub-registers.
2381dff0c46cSDimitry Andric       bool AllSubsInSet = true;
2382dff0c46cSDimitry Andric       const CodeGenRegister::SubRegMap &SRM = Super->getSubRegs();
2383dff0c46cSDimitry Andric       for (CodeGenRegister::SubRegMap::const_iterator I = SRM.begin(),
2384dff0c46cSDimitry Andric              E = SRM.end(); I != E; ++I)
2385dff0c46cSDimitry Andric         if (!Set.count(I->second)) {
2386dff0c46cSDimitry Andric           AllSubsInSet = false;
2387dff0c46cSDimitry Andric           break;
2388dff0c46cSDimitry Andric         }
2389dff0c46cSDimitry Andric       // All sub-registers in Set, add Super as well.
2390dff0c46cSDimitry Andric       // We will visit Super later to recheck its super-registers.
2391dff0c46cSDimitry Andric       if (AllSubsInSet)
2392dff0c46cSDimitry Andric         Set.insert(Super);
2393dff0c46cSDimitry Andric     }
2394dff0c46cSDimitry Andric   }
2395dff0c46cSDimitry Andric 
2396dff0c46cSDimitry Andric   // Convert to BitVector.
2397dff0c46cSDimitry Andric   BitVector BV(Registers.size() + 1);
2398dff0c46cSDimitry Andric   for (unsigned i = 0, e = Set.size(); i != e; ++i)
2399dff0c46cSDimitry Andric     BV.set(Set[i]->EnumValue);
2400dff0c46cSDimitry Andric   return BV;
2401dff0c46cSDimitry Andric }
24027a7e6055SDimitry Andric 
printRegUnitName(unsigned Unit) const24037a7e6055SDimitry Andric void CodeGenRegBank::printRegUnitName(unsigned Unit) const {
24047a7e6055SDimitry Andric   if (Unit < NumNativeRegUnits)
24057a7e6055SDimitry Andric     dbgs() << ' ' << RegUnits[Unit].Roots[0]->getName();
24067a7e6055SDimitry Andric   else
24077a7e6055SDimitry Andric     dbgs() << " #" << Unit;
24087a7e6055SDimitry Andric }
2409