1 //===- CodeGenRegisters.cpp - Register and RegisterClass Info -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines structures to encapsulate information gleaned from the
11 // target register and register class definitions.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "CodeGenRegisters.h"
16 #include "CodeGenTarget.h"
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/BitVector.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/IntEqClasses.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/SparseBitVector.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringRef.h"
28 #include "llvm/ADT/Twine.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/MathExtras.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/TableGen/Error.h"
33 #include "llvm/TableGen/Record.h"
34 #include <algorithm>
35 #include <cassert>
36 #include <cstdint>
37 #include <iterator>
38 #include <map>
39 #include <queue>
40 #include <set>
41 #include <string>
42 #include <tuple>
43 #include <utility>
44 #include <vector>
45 
46 using namespace llvm;
47 
48 #define DEBUG_TYPE "regalloc-emitter"
49 
50 //===----------------------------------------------------------------------===//
51 //                             CodeGenSubRegIndex
52 //===----------------------------------------------------------------------===//
53 
54 CodeGenSubRegIndex::CodeGenSubRegIndex(Record *R, unsigned Enum)
55   : TheDef(R), EnumValue(Enum), AllSuperRegsCovered(true), Artificial(true) {
56   Name = R->getName();
57   if (R->getValue("Namespace"))
58     Namespace = R->getValueAsString("Namespace");
59   Size = R->getValueAsInt("Size");
60   Offset = R->getValueAsInt("Offset");
61 }
62 
63 CodeGenSubRegIndex::CodeGenSubRegIndex(StringRef N, StringRef Nspace,
64                                        unsigned Enum)
65   : TheDef(nullptr), Name(N), Namespace(Nspace), Size(-1), Offset(-1),
66     EnumValue(Enum), AllSuperRegsCovered(true), Artificial(true) {
67 }
68 
69 std::string CodeGenSubRegIndex::getQualifiedName() const {
70   std::string N = getNamespace();
71   if (!N.empty())
72     N += "::";
73   N += getName();
74   return N;
75 }
76 
77 void CodeGenSubRegIndex::updateComponents(CodeGenRegBank &RegBank) {
78   if (!TheDef)
79     return;
80 
81   std::vector<Record*> Comps = TheDef->getValueAsListOfDefs("ComposedOf");
82   if (!Comps.empty()) {
83     if (Comps.size() != 2)
84       PrintFatalError(TheDef->getLoc(),
85                       "ComposedOf must have exactly two entries");
86     CodeGenSubRegIndex *A = RegBank.getSubRegIdx(Comps[0]);
87     CodeGenSubRegIndex *B = RegBank.getSubRegIdx(Comps[1]);
88     CodeGenSubRegIndex *X = A->addComposite(B, this);
89     if (X)
90       PrintFatalError(TheDef->getLoc(), "Ambiguous ComposedOf entries");
91   }
92 
93   std::vector<Record*> Parts =
94     TheDef->getValueAsListOfDefs("CoveringSubRegIndices");
95   if (!Parts.empty()) {
96     if (Parts.size() < 2)
97       PrintFatalError(TheDef->getLoc(),
98                       "CoveredBySubRegs must have two or more entries");
99     SmallVector<CodeGenSubRegIndex*, 8> IdxParts;
100     for (Record *Part : Parts)
101       IdxParts.push_back(RegBank.getSubRegIdx(Part));
102     setConcatenationOf(IdxParts);
103   }
104 }
105 
106 LaneBitmask CodeGenSubRegIndex::computeLaneMask() const {
107   // Already computed?
108   if (LaneMask.any())
109     return LaneMask;
110 
111   // Recursion guard, shouldn't be required.
112   LaneMask = LaneBitmask::getAll();
113 
114   // The lane mask is simply the union of all sub-indices.
115   LaneBitmask M;
116   for (const auto &C : Composed)
117     M |= C.second->computeLaneMask();
118   assert(M.any() && "Missing lane mask, sub-register cycle?");
119   LaneMask = M;
120   return LaneMask;
121 }
122 
123 void CodeGenSubRegIndex::setConcatenationOf(
124     ArrayRef<CodeGenSubRegIndex*> Parts) {
125   if (ConcatenationOf.empty())
126     ConcatenationOf.assign(Parts.begin(), Parts.end());
127   else
128     assert(std::equal(Parts.begin(), Parts.end(),
129                       ConcatenationOf.begin()) && "parts consistent");
130 }
131 
132 void CodeGenSubRegIndex::computeConcatTransitiveClosure() {
133   for (SmallVectorImpl<CodeGenSubRegIndex*>::iterator
134        I = ConcatenationOf.begin(); I != ConcatenationOf.end(); /*empty*/) {
135     CodeGenSubRegIndex *SubIdx = *I;
136     SubIdx->computeConcatTransitiveClosure();
137 #ifndef NDEBUG
138     for (CodeGenSubRegIndex *SRI : SubIdx->ConcatenationOf)
139       assert(SRI->ConcatenationOf.empty() && "No transitive closure?");
140 #endif
141 
142     if (SubIdx->ConcatenationOf.empty()) {
143       ++I;
144     } else {
145       I = ConcatenationOf.erase(I);
146       I = ConcatenationOf.insert(I, SubIdx->ConcatenationOf.begin(),
147                                  SubIdx->ConcatenationOf.end());
148       I += SubIdx->ConcatenationOf.size();
149     }
150   }
151 }
152 
153 //===----------------------------------------------------------------------===//
154 //                              CodeGenRegister
155 //===----------------------------------------------------------------------===//
156 
157 CodeGenRegister::CodeGenRegister(Record *R, unsigned Enum)
158   : TheDef(R),
159     EnumValue(Enum),
160     CostPerUse(R->getValueAsInt("CostPerUse")),
161     CoveredBySubRegs(R->getValueAsBit("CoveredBySubRegs")),
162     HasDisjunctSubRegs(false),
163     SubRegsComplete(false),
164     SuperRegsComplete(false),
165     TopoSig(~0u) {
166   Artificial = R->getValueAsBit("isArtificial");
167 }
168 
169 void CodeGenRegister::buildObjectGraph(CodeGenRegBank &RegBank) {
170   std::vector<Record*> SRIs = TheDef->getValueAsListOfDefs("SubRegIndices");
171   std::vector<Record*> SRs = TheDef->getValueAsListOfDefs("SubRegs");
172 
173   if (SRIs.size() != SRs.size())
174     PrintFatalError(TheDef->getLoc(),
175                     "SubRegs and SubRegIndices must have the same size");
176 
177   for (unsigned i = 0, e = SRIs.size(); i != e; ++i) {
178     ExplicitSubRegIndices.push_back(RegBank.getSubRegIdx(SRIs[i]));
179     ExplicitSubRegs.push_back(RegBank.getReg(SRs[i]));
180   }
181 
182   // Also compute leading super-registers. Each register has a list of
183   // covered-by-subregs super-registers where it appears as the first explicit
184   // sub-register.
185   //
186   // This is used by computeSecondarySubRegs() to find candidates.
187   if (CoveredBySubRegs && !ExplicitSubRegs.empty())
188     ExplicitSubRegs.front()->LeadingSuperRegs.push_back(this);
189 
190   // Add ad hoc alias links. This is a symmetric relationship between two
191   // registers, so build a symmetric graph by adding links in both ends.
192   std::vector<Record*> Aliases = TheDef->getValueAsListOfDefs("Aliases");
193   for (Record *Alias : Aliases) {
194     CodeGenRegister *Reg = RegBank.getReg(Alias);
195     ExplicitAliases.push_back(Reg);
196     Reg->ExplicitAliases.push_back(this);
197   }
198 }
199 
200 const StringRef CodeGenRegister::getName() const {
201   assert(TheDef && "no def");
202   return TheDef->getName();
203 }
204 
205 namespace {
206 
207 // Iterate over all register units in a set of registers.
208 class RegUnitIterator {
209   CodeGenRegister::Vec::const_iterator RegI, RegE;
210   CodeGenRegister::RegUnitList::iterator UnitI, UnitE;
211 
212 public:
213   RegUnitIterator(const CodeGenRegister::Vec &Regs):
214     RegI(Regs.begin()), RegE(Regs.end()) {
215 
216     if (RegI != RegE) {
217       UnitI = (*RegI)->getRegUnits().begin();
218       UnitE = (*RegI)->getRegUnits().end();
219       advance();
220     }
221   }
222 
223   bool isValid() const { return UnitI != UnitE; }
224 
225   unsigned operator* () const { assert(isValid()); return *UnitI; }
226 
227   const CodeGenRegister *getReg() const { assert(isValid()); return *RegI; }
228 
229   /// Preincrement.  Move to the next unit.
230   void operator++() {
231     assert(isValid() && "Cannot advance beyond the last operand");
232     ++UnitI;
233     advance();
234   }
235 
236 protected:
237   void advance() {
238     while (UnitI == UnitE) {
239       if (++RegI == RegE)
240         break;
241       UnitI = (*RegI)->getRegUnits().begin();
242       UnitE = (*RegI)->getRegUnits().end();
243     }
244   }
245 };
246 
247 } // end anonymous namespace
248 
249 // Return true of this unit appears in RegUnits.
250 static bool hasRegUnit(CodeGenRegister::RegUnitList &RegUnits, unsigned Unit) {
251   return RegUnits.test(Unit);
252 }
253 
254 // Inherit register units from subregisters.
255 // Return true if the RegUnits changed.
256 bool CodeGenRegister::inheritRegUnits(CodeGenRegBank &RegBank) {
257   bool changed = false;
258   for (const auto &SubReg : SubRegs) {
259     CodeGenRegister *SR = SubReg.second;
260     // Merge the subregister's units into this register's RegUnits.
261     changed |= (RegUnits |= SR->RegUnits);
262   }
263 
264   return changed;
265 }
266 
267 const CodeGenRegister::SubRegMap &
268 CodeGenRegister::computeSubRegs(CodeGenRegBank &RegBank) {
269   // Only compute this map once.
270   if (SubRegsComplete)
271     return SubRegs;
272   SubRegsComplete = true;
273 
274   HasDisjunctSubRegs = ExplicitSubRegs.size() > 1;
275 
276   // First insert the explicit subregs and make sure they are fully indexed.
277   for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
278     CodeGenRegister *SR = ExplicitSubRegs[i];
279     CodeGenSubRegIndex *Idx = ExplicitSubRegIndices[i];
280     if (!SR->Artificial)
281       Idx->Artificial = false;
282     if (!SubRegs.insert(std::make_pair(Idx, SR)).second)
283       PrintFatalError(TheDef->getLoc(), "SubRegIndex " + Idx->getName() +
284                       " appears twice in Register " + getName());
285     // Map explicit sub-registers first, so the names take precedence.
286     // The inherited sub-registers are mapped below.
287     SubReg2Idx.insert(std::make_pair(SR, Idx));
288   }
289 
290   // Keep track of inherited subregs and how they can be reached.
291   SmallPtrSet<CodeGenRegister*, 8> Orphans;
292 
293   // Clone inherited subregs and place duplicate entries in Orphans.
294   // Here the order is important - earlier subregs take precedence.
295   for (CodeGenRegister *ESR : ExplicitSubRegs) {
296     const SubRegMap &Map = ESR->computeSubRegs(RegBank);
297     HasDisjunctSubRegs |= ESR->HasDisjunctSubRegs;
298 
299     for (const auto &SR : Map) {
300       if (!SubRegs.insert(SR).second)
301         Orphans.insert(SR.second);
302     }
303   }
304 
305   // Expand any composed subreg indices.
306   // If dsub_2 has ComposedOf = [qsub_1, dsub_0], and this register has a
307   // qsub_1 subreg, add a dsub_2 subreg.  Keep growing Indices and process
308   // expanded subreg indices recursively.
309   SmallVector<CodeGenSubRegIndex*, 8> Indices = ExplicitSubRegIndices;
310   for (unsigned i = 0; i != Indices.size(); ++i) {
311     CodeGenSubRegIndex *Idx = Indices[i];
312     const CodeGenSubRegIndex::CompMap &Comps = Idx->getComposites();
313     CodeGenRegister *SR = SubRegs[Idx];
314     const SubRegMap &Map = SR->computeSubRegs(RegBank);
315 
316     // Look at the possible compositions of Idx.
317     // They may not all be supported by SR.
318     for (CodeGenSubRegIndex::CompMap::const_iterator I = Comps.begin(),
319            E = Comps.end(); I != E; ++I) {
320       SubRegMap::const_iterator SRI = Map.find(I->first);
321       if (SRI == Map.end())
322         continue; // Idx + I->first doesn't exist in SR.
323       // Add I->second as a name for the subreg SRI->second, assuming it is
324       // orphaned, and the name isn't already used for something else.
325       if (SubRegs.count(I->second) || !Orphans.erase(SRI->second))
326         continue;
327       // We found a new name for the orphaned sub-register.
328       SubRegs.insert(std::make_pair(I->second, SRI->second));
329       Indices.push_back(I->second);
330     }
331   }
332 
333   // Now Orphans contains the inherited subregisters without a direct index.
334   // Create inferred indexes for all missing entries.
335   // Work backwards in the Indices vector in order to compose subregs bottom-up.
336   // Consider this subreg sequence:
337   //
338   //   qsub_1 -> dsub_0 -> ssub_0
339   //
340   // The qsub_1 -> dsub_0 composition becomes dsub_2, so the ssub_0 register
341   // can be reached in two different ways:
342   //
343   //   qsub_1 -> ssub_0
344   //   dsub_2 -> ssub_0
345   //
346   // We pick the latter composition because another register may have [dsub_0,
347   // dsub_1, dsub_2] subregs without necessarily having a qsub_1 subreg.  The
348   // dsub_2 -> ssub_0 composition can be shared.
349   while (!Indices.empty() && !Orphans.empty()) {
350     CodeGenSubRegIndex *Idx = Indices.pop_back_val();
351     CodeGenRegister *SR = SubRegs[Idx];
352     const SubRegMap &Map = SR->computeSubRegs(RegBank);
353     for (const auto &SubReg : Map)
354       if (Orphans.erase(SubReg.second))
355         SubRegs[RegBank.getCompositeSubRegIndex(Idx, SubReg.first)] = SubReg.second;
356   }
357 
358   // Compute the inverse SubReg -> Idx map.
359   for (const auto &SubReg : SubRegs) {
360     if (SubReg.second == this) {
361       ArrayRef<SMLoc> Loc;
362       if (TheDef)
363         Loc = TheDef->getLoc();
364       PrintFatalError(Loc, "Register " + getName() +
365                       " has itself as a sub-register");
366     }
367 
368     // Compute AllSuperRegsCovered.
369     if (!CoveredBySubRegs)
370       SubReg.first->AllSuperRegsCovered = false;
371 
372     // Ensure that every sub-register has a unique name.
373     DenseMap<const CodeGenRegister*, CodeGenSubRegIndex*>::iterator Ins =
374       SubReg2Idx.insert(std::make_pair(SubReg.second, SubReg.first)).first;
375     if (Ins->second == SubReg.first)
376       continue;
377     // Trouble: Two different names for SubReg.second.
378     ArrayRef<SMLoc> Loc;
379     if (TheDef)
380       Loc = TheDef->getLoc();
381     PrintFatalError(Loc, "Sub-register can't have two names: " +
382                   SubReg.second->getName() + " available as " +
383                   SubReg.first->getName() + " and " + Ins->second->getName());
384   }
385 
386   // Derive possible names for sub-register concatenations from any explicit
387   // sub-registers. By doing this before computeSecondarySubRegs(), we ensure
388   // that getConcatSubRegIndex() won't invent any concatenated indices that the
389   // user already specified.
390   for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
391     CodeGenRegister *SR = ExplicitSubRegs[i];
392     if (!SR->CoveredBySubRegs || SR->ExplicitSubRegs.size() <= 1)
393       continue;
394 
395     // SR is composed of multiple sub-regs. Find their names in this register.
396     SmallVector<CodeGenSubRegIndex*, 8> Parts;
397     for (unsigned j = 0, e = SR->ExplicitSubRegs.size(); j != e; ++j)
398       Parts.push_back(getSubRegIndex(SR->ExplicitSubRegs[j]));
399 
400     // Offer this as an existing spelling for the concatenation of Parts.
401     CodeGenSubRegIndex &Idx = *ExplicitSubRegIndices[i];
402     Idx.setConcatenationOf(Parts);
403   }
404 
405   // Initialize RegUnitList. Because getSubRegs is called recursively, this
406   // processes the register hierarchy in postorder.
407   //
408   // Inherit all sub-register units. It is good enough to look at the explicit
409   // sub-registers, the other registers won't contribute any more units.
410   for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
411     CodeGenRegister *SR = ExplicitSubRegs[i];
412     RegUnits |= SR->RegUnits;
413   }
414 
415   // Absent any ad hoc aliasing, we create one register unit per leaf register.
416   // These units correspond to the maximal cliques in the register overlap
417   // graph which is optimal.
418   //
419   // When there is ad hoc aliasing, we simply create one unit per edge in the
420   // undirected ad hoc aliasing graph. Technically, we could do better by
421   // identifying maximal cliques in the ad hoc graph, but cliques larger than 2
422   // are extremely rare anyway (I've never seen one), so we don't bother with
423   // the added complexity.
424   for (unsigned i = 0, e = ExplicitAliases.size(); i != e; ++i) {
425     CodeGenRegister *AR = ExplicitAliases[i];
426     // Only visit each edge once.
427     if (AR->SubRegsComplete)
428       continue;
429     // Create a RegUnit representing this alias edge, and add it to both
430     // registers.
431     unsigned Unit = RegBank.newRegUnit(this, AR);
432     RegUnits.set(Unit);
433     AR->RegUnits.set(Unit);
434   }
435 
436   // Finally, create units for leaf registers without ad hoc aliases. Note that
437   // a leaf register with ad hoc aliases doesn't get its own unit - it isn't
438   // necessary. This means the aliasing leaf registers can share a single unit.
439   if (RegUnits.empty())
440     RegUnits.set(RegBank.newRegUnit(this));
441 
442   // We have now computed the native register units. More may be adopted later
443   // for balancing purposes.
444   NativeRegUnits = RegUnits;
445 
446   return SubRegs;
447 }
448 
449 // In a register that is covered by its sub-registers, try to find redundant
450 // sub-registers. For example:
451 //
452 //   QQ0 = {Q0, Q1}
453 //   Q0 = {D0, D1}
454 //   Q1 = {D2, D3}
455 //
456 // We can infer that D1_D2 is also a sub-register, even if it wasn't named in
457 // the register definition.
458 //
459 // The explicitly specified registers form a tree. This function discovers
460 // sub-register relationships that would force a DAG.
461 //
462 void CodeGenRegister::computeSecondarySubRegs(CodeGenRegBank &RegBank) {
463   SmallVector<SubRegMap::value_type, 8> NewSubRegs;
464 
465   std::queue<std::pair<CodeGenSubRegIndex*,CodeGenRegister*>> SubRegQueue;
466   for (std::pair<CodeGenSubRegIndex*,CodeGenRegister*> P : SubRegs)
467     SubRegQueue.push(P);
468 
469   // Look at the leading super-registers of each sub-register. Those are the
470   // candidates for new sub-registers, assuming they are fully contained in
471   // this register.
472   while (!SubRegQueue.empty()) {
473     CodeGenSubRegIndex *SubRegIdx;
474     const CodeGenRegister *SubReg;
475     std::tie(SubRegIdx, SubReg) = SubRegQueue.front();
476     SubRegQueue.pop();
477 
478     const CodeGenRegister::SuperRegList &Leads = SubReg->LeadingSuperRegs;
479     for (unsigned i = 0, e = Leads.size(); i != e; ++i) {
480       CodeGenRegister *Cand = const_cast<CodeGenRegister*>(Leads[i]);
481       // Already got this sub-register?
482       if (Cand == this || getSubRegIndex(Cand))
483         continue;
484       // Check if each component of Cand is already a sub-register.
485       assert(!Cand->ExplicitSubRegs.empty() &&
486              "Super-register has no sub-registers");
487       if (Cand->ExplicitSubRegs.size() == 1)
488         continue;
489       SmallVector<CodeGenSubRegIndex*, 8> Parts;
490       // We know that the first component is (SubRegIdx,SubReg). However we
491       // may still need to split it into smaller subregister parts.
492       assert(Cand->ExplicitSubRegs[0] == SubReg && "LeadingSuperRegs correct");
493       assert(getSubRegIndex(SubReg) == SubRegIdx && "LeadingSuperRegs correct");
494       for (CodeGenRegister *SubReg : Cand->ExplicitSubRegs) {
495         if (CodeGenSubRegIndex *SubRegIdx = getSubRegIndex(SubReg)) {
496           if (SubRegIdx->ConcatenationOf.empty()) {
497             Parts.push_back(SubRegIdx);
498           } else
499             for (CodeGenSubRegIndex *SubIdx : SubRegIdx->ConcatenationOf)
500               Parts.push_back(SubIdx);
501         } else {
502           // Sub-register doesn't exist.
503           Parts.clear();
504           break;
505         }
506       }
507       // There is nothing to do if some Cand sub-register is not part of this
508       // register.
509       if (Parts.empty())
510         continue;
511 
512       // Each part of Cand is a sub-register of this. Make the full Cand also
513       // a sub-register with a concatenated sub-register index.
514       CodeGenSubRegIndex *Concat = RegBank.getConcatSubRegIndex(Parts);
515       std::pair<CodeGenSubRegIndex*,CodeGenRegister*> NewSubReg =
516           std::make_pair(Concat, Cand);
517 
518       if (!SubRegs.insert(NewSubReg).second)
519         continue;
520 
521       // We inserted a new subregister.
522       NewSubRegs.push_back(NewSubReg);
523       SubRegQueue.push(NewSubReg);
524       SubReg2Idx.insert(std::make_pair(Cand, Concat));
525     }
526   }
527 
528   // Create sub-register index composition maps for the synthesized indices.
529   for (unsigned i = 0, e = NewSubRegs.size(); i != e; ++i) {
530     CodeGenSubRegIndex *NewIdx = NewSubRegs[i].first;
531     CodeGenRegister *NewSubReg = NewSubRegs[i].second;
532     for (SubRegMap::const_iterator SI = NewSubReg->SubRegs.begin(),
533            SE = NewSubReg->SubRegs.end(); SI != SE; ++SI) {
534       CodeGenSubRegIndex *SubIdx = getSubRegIndex(SI->second);
535       if (!SubIdx)
536         PrintFatalError(TheDef->getLoc(), "No SubRegIndex for " +
537                         SI->second->getName() + " in " + getName());
538       NewIdx->addComposite(SI->first, SubIdx);
539     }
540   }
541 }
542 
543 void CodeGenRegister::computeSuperRegs(CodeGenRegBank &RegBank) {
544   // Only visit each register once.
545   if (SuperRegsComplete)
546     return;
547   SuperRegsComplete = true;
548 
549   // Make sure all sub-registers have been visited first, so the super-reg
550   // lists will be topologically ordered.
551   for (SubRegMap::const_iterator I = SubRegs.begin(), E = SubRegs.end();
552        I != E; ++I)
553     I->second->computeSuperRegs(RegBank);
554 
555   // Now add this as a super-register on all sub-registers.
556   // Also compute the TopoSigId in post-order.
557   TopoSigId Id;
558   for (SubRegMap::const_iterator I = SubRegs.begin(), E = SubRegs.end();
559        I != E; ++I) {
560     // Topological signature computed from SubIdx, TopoId(SubReg).
561     // Loops and idempotent indices have TopoSig = ~0u.
562     Id.push_back(I->first->EnumValue);
563     Id.push_back(I->second->TopoSig);
564 
565     // Don't add duplicate entries.
566     if (!I->second->SuperRegs.empty() && I->second->SuperRegs.back() == this)
567       continue;
568     I->second->SuperRegs.push_back(this);
569   }
570   TopoSig = RegBank.getTopoSig(Id);
571 }
572 
573 void
574 CodeGenRegister::addSubRegsPreOrder(SetVector<const CodeGenRegister*> &OSet,
575                                     CodeGenRegBank &RegBank) const {
576   assert(SubRegsComplete && "Must precompute sub-registers");
577   for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
578     CodeGenRegister *SR = ExplicitSubRegs[i];
579     if (OSet.insert(SR))
580       SR->addSubRegsPreOrder(OSet, RegBank);
581   }
582   // Add any secondary sub-registers that weren't part of the explicit tree.
583   for (SubRegMap::const_iterator I = SubRegs.begin(), E = SubRegs.end();
584        I != E; ++I)
585     OSet.insert(I->second);
586 }
587 
588 // Get the sum of this register's unit weights.
589 unsigned CodeGenRegister::getWeight(const CodeGenRegBank &RegBank) const {
590   unsigned Weight = 0;
591   for (RegUnitList::iterator I = RegUnits.begin(), E = RegUnits.end();
592        I != E; ++I) {
593     Weight += RegBank.getRegUnit(*I).Weight;
594   }
595   return Weight;
596 }
597 
598 //===----------------------------------------------------------------------===//
599 //                               RegisterTuples
600 //===----------------------------------------------------------------------===//
601 
602 // A RegisterTuples def is used to generate pseudo-registers from lists of
603 // sub-registers. We provide a SetTheory expander class that returns the new
604 // registers.
605 namespace {
606 
607 struct TupleExpander : SetTheory::Expander {
608   void expand(SetTheory &ST, Record *Def, SetTheory::RecSet &Elts) override {
609     std::vector<Record*> Indices = Def->getValueAsListOfDefs("SubRegIndices");
610     unsigned Dim = Indices.size();
611     ListInit *SubRegs = Def->getValueAsListInit("SubRegs");
612     if (Dim != SubRegs->size())
613       PrintFatalError(Def->getLoc(), "SubRegIndices and SubRegs size mismatch");
614     if (Dim < 2)
615       PrintFatalError(Def->getLoc(),
616                       "Tuples must have at least 2 sub-registers");
617 
618     // Evaluate the sub-register lists to be zipped.
619     unsigned Length = ~0u;
620     SmallVector<SetTheory::RecSet, 4> Lists(Dim);
621     for (unsigned i = 0; i != Dim; ++i) {
622       ST.evaluate(SubRegs->getElement(i), Lists[i], Def->getLoc());
623       Length = std::min(Length, unsigned(Lists[i].size()));
624     }
625 
626     if (Length == 0)
627       return;
628 
629     // Precompute some types.
630     Record *RegisterCl = Def->getRecords().getClass("Register");
631     RecTy *RegisterRecTy = RecordRecTy::get(RegisterCl);
632     StringInit *BlankName = StringInit::get("");
633 
634     // Zip them up.
635     for (unsigned n = 0; n != Length; ++n) {
636       std::string Name;
637       Record *Proto = Lists[0][n];
638       std::vector<Init*> Tuple;
639       unsigned CostPerUse = 0;
640       for (unsigned i = 0; i != Dim; ++i) {
641         Record *Reg = Lists[i][n];
642         if (i) Name += '_';
643         Name += Reg->getName();
644         Tuple.push_back(DefInit::get(Reg));
645         CostPerUse = std::max(CostPerUse,
646                               unsigned(Reg->getValueAsInt("CostPerUse")));
647       }
648 
649       // Create a new Record representing the synthesized register. This record
650       // is only for consumption by CodeGenRegister, it is not added to the
651       // RecordKeeper.
652       Record *NewReg = new Record(Name, Def->getLoc(), Def->getRecords());
653       Elts.insert(NewReg);
654 
655       // Copy Proto super-classes.
656       ArrayRef<std::pair<Record *, SMRange>> Supers = Proto->getSuperClasses();
657       for (const auto &SuperPair : Supers)
658         NewReg->addSuperClass(SuperPair.first, SuperPair.second);
659 
660       // Copy Proto fields.
661       for (unsigned i = 0, e = Proto->getValues().size(); i != e; ++i) {
662         RecordVal RV = Proto->getValues()[i];
663 
664         // Skip existing fields, like NAME.
665         if (NewReg->getValue(RV.getNameInit()))
666           continue;
667 
668         StringRef Field = RV.getName();
669 
670         // Replace the sub-register list with Tuple.
671         if (Field == "SubRegs")
672           RV.setValue(ListInit::get(Tuple, RegisterRecTy));
673 
674         // Provide a blank AsmName. MC hacks are required anyway.
675         if (Field == "AsmName")
676           RV.setValue(BlankName);
677 
678         // CostPerUse is aggregated from all Tuple members.
679         if (Field == "CostPerUse")
680           RV.setValue(IntInit::get(CostPerUse));
681 
682         // Composite registers are always covered by sub-registers.
683         if (Field == "CoveredBySubRegs")
684           RV.setValue(BitInit::get(true));
685 
686         // Copy fields from the RegisterTuples def.
687         if (Field == "SubRegIndices" ||
688             Field == "CompositeIndices") {
689           NewReg->addValue(*Def->getValue(Field));
690           continue;
691         }
692 
693         // Some fields get their default uninitialized value.
694         if (Field == "DwarfNumbers" ||
695             Field == "DwarfAlias" ||
696             Field == "Aliases") {
697           if (const RecordVal *DefRV = RegisterCl->getValue(Field))
698             NewReg->addValue(*DefRV);
699           continue;
700         }
701 
702         // Everything else is copied from Proto.
703         NewReg->addValue(RV);
704       }
705     }
706   }
707 };
708 
709 } // end anonymous namespace
710 
711 //===----------------------------------------------------------------------===//
712 //                            CodeGenRegisterClass
713 //===----------------------------------------------------------------------===//
714 
715 static void sortAndUniqueRegisters(CodeGenRegister::Vec &M) {
716   llvm::sort(M.begin(), M.end(), deref<llvm::less>());
717   M.erase(std::unique(M.begin(), M.end(), deref<llvm::equal>()), M.end());
718 }
719 
720 CodeGenRegisterClass::CodeGenRegisterClass(CodeGenRegBank &RegBank, Record *R)
721   : TheDef(R),
722     Name(R->getName()),
723     TopoSigs(RegBank.getNumTopoSigs()),
724     EnumValue(-1) {
725 
726   std::vector<Record*> TypeList = R->getValueAsListOfDefs("RegTypes");
727   for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
728     Record *Type = TypeList[i];
729     if (!Type->isSubClassOf("ValueType"))
730       PrintFatalError("RegTypes list member '" + Type->getName() +
731         "' does not derive from the ValueType class!");
732     VTs.push_back(getValueTypeByHwMode(Type, RegBank.getHwModes()));
733   }
734   assert(!VTs.empty() && "RegisterClass must contain at least one ValueType!");
735 
736   // Allocation order 0 is the full set. AltOrders provides others.
737   const SetTheory::RecVec *Elements = RegBank.getSets().expand(R);
738   ListInit *AltOrders = R->getValueAsListInit("AltOrders");
739   Orders.resize(1 + AltOrders->size());
740 
741   // Default allocation order always contains all registers.
742   Artificial = true;
743   for (unsigned i = 0, e = Elements->size(); i != e; ++i) {
744     Orders[0].push_back((*Elements)[i]);
745     const CodeGenRegister *Reg = RegBank.getReg((*Elements)[i]);
746     Members.push_back(Reg);
747     Artificial &= Reg->Artificial;
748     TopoSigs.set(Reg->getTopoSig());
749   }
750   sortAndUniqueRegisters(Members);
751 
752   // Alternative allocation orders may be subsets.
753   SetTheory::RecSet Order;
754   for (unsigned i = 0, e = AltOrders->size(); i != e; ++i) {
755     RegBank.getSets().evaluate(AltOrders->getElement(i), Order, R->getLoc());
756     Orders[1 + i].append(Order.begin(), Order.end());
757     // Verify that all altorder members are regclass members.
758     while (!Order.empty()) {
759       CodeGenRegister *Reg = RegBank.getReg(Order.back());
760       Order.pop_back();
761       if (!contains(Reg))
762         PrintFatalError(R->getLoc(), " AltOrder register " + Reg->getName() +
763                       " is not a class member");
764     }
765   }
766 
767   Namespace = R->getValueAsString("Namespace");
768 
769   if (const RecordVal *RV = R->getValue("RegInfos"))
770     if (DefInit *DI = dyn_cast_or_null<DefInit>(RV->getValue()))
771       RSI = RegSizeInfoByHwMode(DI->getDef(), RegBank.getHwModes());
772   unsigned Size = R->getValueAsInt("Size");
773   assert((RSI.hasDefault() || Size != 0 || VTs[0].isSimple()) &&
774          "Impossible to determine register size");
775   if (!RSI.hasDefault()) {
776     RegSizeInfo RI;
777     RI.RegSize = RI.SpillSize = Size ? Size
778                                      : VTs[0].getSimple().getSizeInBits();
779     RI.SpillAlignment = R->getValueAsInt("Alignment");
780     RSI.Map.insert({DefaultMode, RI});
781   }
782 
783   CopyCost = R->getValueAsInt("CopyCost");
784   Allocatable = R->getValueAsBit("isAllocatable");
785   AltOrderSelect = R->getValueAsString("AltOrderSelect");
786   int AllocationPriority = R->getValueAsInt("AllocationPriority");
787   if (AllocationPriority < 0 || AllocationPriority > 63)
788     PrintFatalError(R->getLoc(), "AllocationPriority out of range [0,63]");
789   this->AllocationPriority = AllocationPriority;
790 }
791 
792 // Create an inferred register class that was missing from the .td files.
793 // Most properties will be inherited from the closest super-class after the
794 // class structure has been computed.
795 CodeGenRegisterClass::CodeGenRegisterClass(CodeGenRegBank &RegBank,
796                                            StringRef Name, Key Props)
797   : Members(*Props.Members),
798     TheDef(nullptr),
799     Name(Name),
800     TopoSigs(RegBank.getNumTopoSigs()),
801     EnumValue(-1),
802     RSI(Props.RSI),
803     CopyCost(0),
804     Allocatable(true),
805     AllocationPriority(0) {
806   Artificial = true;
807   for (const auto R : Members) {
808     TopoSigs.set(R->getTopoSig());
809     Artificial &= R->Artificial;
810   }
811 }
812 
813 // Compute inherited propertied for a synthesized register class.
814 void CodeGenRegisterClass::inheritProperties(CodeGenRegBank &RegBank) {
815   assert(!getDef() && "Only synthesized classes can inherit properties");
816   assert(!SuperClasses.empty() && "Synthesized class without super class");
817 
818   // The last super-class is the smallest one.
819   CodeGenRegisterClass &Super = *SuperClasses.back();
820 
821   // Most properties are copied directly.
822   // Exceptions are members, size, and alignment
823   Namespace = Super.Namespace;
824   VTs = Super.VTs;
825   CopyCost = Super.CopyCost;
826   Allocatable = Super.Allocatable;
827   AltOrderSelect = Super.AltOrderSelect;
828   AllocationPriority = Super.AllocationPriority;
829 
830   // Copy all allocation orders, filter out foreign registers from the larger
831   // super-class.
832   Orders.resize(Super.Orders.size());
833   for (unsigned i = 0, ie = Super.Orders.size(); i != ie; ++i)
834     for (unsigned j = 0, je = Super.Orders[i].size(); j != je; ++j)
835       if (contains(RegBank.getReg(Super.Orders[i][j])))
836         Orders[i].push_back(Super.Orders[i][j]);
837 }
838 
839 bool CodeGenRegisterClass::contains(const CodeGenRegister *Reg) const {
840   return std::binary_search(Members.begin(), Members.end(), Reg,
841                             deref<llvm::less>());
842 }
843 
844 namespace llvm {
845 
846   raw_ostream &operator<<(raw_ostream &OS, const CodeGenRegisterClass::Key &K) {
847     OS << "{ " << K.RSI;
848     for (const auto R : *K.Members)
849       OS << ", " << R->getName();
850     return OS << " }";
851   }
852 
853 } // end namespace llvm
854 
855 // This is a simple lexicographical order that can be used to search for sets.
856 // It is not the same as the topological order provided by TopoOrderRC.
857 bool CodeGenRegisterClass::Key::
858 operator<(const CodeGenRegisterClass::Key &B) const {
859   assert(Members && B.Members);
860   return std::tie(*Members, RSI) < std::tie(*B.Members, B.RSI);
861 }
862 
863 // Returns true if RC is a strict subclass.
864 // RC is a sub-class of this class if it is a valid replacement for any
865 // instruction operand where a register of this classis required. It must
866 // satisfy these conditions:
867 //
868 // 1. All RC registers are also in this.
869 // 2. The RC spill size must not be smaller than our spill size.
870 // 3. RC spill alignment must be compatible with ours.
871 //
872 static bool testSubClass(const CodeGenRegisterClass *A,
873                          const CodeGenRegisterClass *B) {
874   return A->RSI.isSubClassOf(B->RSI) &&
875          std::includes(A->getMembers().begin(), A->getMembers().end(),
876                        B->getMembers().begin(), B->getMembers().end(),
877                        deref<llvm::less>());
878 }
879 
880 /// Sorting predicate for register classes.  This provides a topological
881 /// ordering that arranges all register classes before their sub-classes.
882 ///
883 /// Register classes with the same registers, spill size, and alignment form a
884 /// clique.  They will be ordered alphabetically.
885 ///
886 static bool TopoOrderRC(const CodeGenRegisterClass &PA,
887                         const CodeGenRegisterClass &PB) {
888   auto *A = &PA;
889   auto *B = &PB;
890   if (A == B)
891     return false;
892 
893   if (A->RSI < B->RSI)
894     return true;
895   if (A->RSI != B->RSI)
896     return false;
897 
898   // Order by descending set size.  Note that the classes' allocation order may
899   // not have been computed yet.  The Members set is always vaild.
900   if (A->getMembers().size() > B->getMembers().size())
901     return true;
902   if (A->getMembers().size() < B->getMembers().size())
903     return false;
904 
905   // Finally order by name as a tie breaker.
906   return StringRef(A->getName()) < B->getName();
907 }
908 
909 std::string CodeGenRegisterClass::getQualifiedName() const {
910   if (Namespace.empty())
911     return getName();
912   else
913     return (Namespace + "::" + getName()).str();
914 }
915 
916 // Compute sub-classes of all register classes.
917 // Assume the classes are ordered topologically.
918 void CodeGenRegisterClass::computeSubClasses(CodeGenRegBank &RegBank) {
919   auto &RegClasses = RegBank.getRegClasses();
920 
921   // Visit backwards so sub-classes are seen first.
922   for (auto I = RegClasses.rbegin(), E = RegClasses.rend(); I != E; ++I) {
923     CodeGenRegisterClass &RC = *I;
924     RC.SubClasses.resize(RegClasses.size());
925     RC.SubClasses.set(RC.EnumValue);
926     if (RC.Artificial)
927       continue;
928 
929     // Normally, all subclasses have IDs >= rci, unless RC is part of a clique.
930     for (auto I2 = I.base(), E2 = RegClasses.end(); I2 != E2; ++I2) {
931       CodeGenRegisterClass &SubRC = *I2;
932       if (RC.SubClasses.test(SubRC.EnumValue))
933         continue;
934       if (!testSubClass(&RC, &SubRC))
935         continue;
936       // SubRC is a sub-class. Grap all its sub-classes so we won't have to
937       // check them again.
938       RC.SubClasses |= SubRC.SubClasses;
939     }
940 
941     // Sweep up missed clique members.  They will be immediately preceding RC.
942     for (auto I2 = std::next(I); I2 != E && testSubClass(&RC, &*I2); ++I2)
943       RC.SubClasses.set(I2->EnumValue);
944   }
945 
946   // Compute the SuperClasses lists from the SubClasses vectors.
947   for (auto &RC : RegClasses) {
948     const BitVector &SC = RC.getSubClasses();
949     auto I = RegClasses.begin();
950     for (int s = 0, next_s = SC.find_first(); next_s != -1;
951          next_s = SC.find_next(s)) {
952       std::advance(I, next_s - s);
953       s = next_s;
954       if (&*I == &RC)
955         continue;
956       I->SuperClasses.push_back(&RC);
957     }
958   }
959 
960   // With the class hierarchy in place, let synthesized register classes inherit
961   // properties from their closest super-class. The iteration order here can
962   // propagate properties down multiple levels.
963   for (auto &RC : RegClasses)
964     if (!RC.getDef())
965       RC.inheritProperties(RegBank);
966 }
967 
968 Optional<std::pair<CodeGenRegisterClass *, CodeGenRegisterClass *>>
969 CodeGenRegisterClass::getMatchingSubClassWithSubRegs(
970     CodeGenRegBank &RegBank, const CodeGenSubRegIndex *SubIdx) const {
971   auto SizeOrder = [](const CodeGenRegisterClass *A,
972                       const CodeGenRegisterClass *B) {
973     return A->getMembers().size() > B->getMembers().size();
974   };
975 
976   auto &RegClasses = RegBank.getRegClasses();
977 
978   // Find all the subclasses of this one that fully support the sub-register
979   // index and order them by size. BiggestSuperRC should always be first.
980   CodeGenRegisterClass *BiggestSuperRegRC = getSubClassWithSubReg(SubIdx);
981   if (!BiggestSuperRegRC)
982     return None;
983   BitVector SuperRegRCsBV = BiggestSuperRegRC->getSubClasses();
984   std::vector<CodeGenRegisterClass *> SuperRegRCs;
985   for (auto &RC : RegClasses)
986     if (SuperRegRCsBV[RC.EnumValue])
987       SuperRegRCs.emplace_back(&RC);
988   llvm::sort(SuperRegRCs.begin(), SuperRegRCs.end(), SizeOrder);
989   assert(SuperRegRCs.front() == BiggestSuperRegRC && "Biggest class wasn't first");
990 
991   // Find all the subreg classes and order them by size too.
992   std::vector<std::pair<CodeGenRegisterClass *, BitVector>> SuperRegClasses;
993   for (auto &RC: RegClasses) {
994     BitVector SuperRegClassesBV(RegClasses.size());
995     RC.getSuperRegClasses(SubIdx, SuperRegClassesBV);
996     if (SuperRegClassesBV.any())
997       SuperRegClasses.push_back(std::make_pair(&RC, SuperRegClassesBV));
998   }
999   llvm::sort(SuperRegClasses.begin(), SuperRegClasses.end(),
1000              [&](const std::pair<CodeGenRegisterClass *, BitVector> &A,
1001                  const std::pair<CodeGenRegisterClass *, BitVector> &B) {
1002                return SizeOrder(A.first, B.first);
1003              });
1004 
1005   // Find the biggest subclass and subreg class such that R:subidx is in the
1006   // subreg class for all R in subclass.
1007   //
1008   // For example:
1009   // All registers in X86's GR64 have a sub_32bit subregister but no class
1010   // exists that contains all the 32-bit subregisters because GR64 contains RIP
1011   // but GR32 does not contain EIP. Instead, we constrain SuperRegRC to
1012   // GR32_with_sub_8bit (which is identical to GR32_with_sub_32bit) and then,
1013   // having excluded RIP, we are able to find a SubRegRC (GR32).
1014   CodeGenRegisterClass *ChosenSuperRegClass = nullptr;
1015   CodeGenRegisterClass *SubRegRC = nullptr;
1016   for (auto *SuperRegRC : SuperRegRCs) {
1017     for (const auto &SuperRegClassPair : SuperRegClasses) {
1018       const BitVector &SuperRegClassBV = SuperRegClassPair.second;
1019       if (SuperRegClassBV[SuperRegRC->EnumValue]) {
1020         SubRegRC = SuperRegClassPair.first;
1021         ChosenSuperRegClass = SuperRegRC;
1022 
1023         // If SubRegRC is bigger than SuperRegRC then there are members of
1024         // SubRegRC that don't have super registers via SubIdx. Keep looking to
1025         // find a better fit and fall back on this one if there isn't one.
1026         //
1027         // This is intended to prevent X86 from making odd choices such as
1028         // picking LOW32_ADDR_ACCESS_RBP instead of GR32 in the example above.
1029         // LOW32_ADDR_ACCESS_RBP is a valid choice but contains registers that
1030         // aren't subregisters of SuperRegRC whereas GR32 has a direct 1:1
1031         // mapping.
1032         if (SuperRegRC->getMembers().size() >= SubRegRC->getMembers().size())
1033           return std::make_pair(ChosenSuperRegClass, SubRegRC);
1034       }
1035     }
1036 
1037     // If we found a fit but it wasn't quite ideal because SubRegRC had excess
1038     // registers, then we're done.
1039     if (ChosenSuperRegClass)
1040       return std::make_pair(ChosenSuperRegClass, SubRegRC);
1041   }
1042 
1043   return None;
1044 }
1045 
1046 void CodeGenRegisterClass::getSuperRegClasses(const CodeGenSubRegIndex *SubIdx,
1047                                               BitVector &Out) const {
1048   auto FindI = SuperRegClasses.find(SubIdx);
1049   if (FindI == SuperRegClasses.end())
1050     return;
1051   for (CodeGenRegisterClass *RC : FindI->second)
1052     Out.set(RC->EnumValue);
1053 }
1054 
1055 // Populate a unique sorted list of units from a register set.
1056 void CodeGenRegisterClass::buildRegUnitSet(const CodeGenRegBank &RegBank,
1057   std::vector<unsigned> &RegUnits) const {
1058   std::vector<unsigned> TmpUnits;
1059   for (RegUnitIterator UnitI(Members); UnitI.isValid(); ++UnitI) {
1060     const RegUnit &RU = RegBank.getRegUnit(*UnitI);
1061     if (!RU.Artificial)
1062       TmpUnits.push_back(*UnitI);
1063   }
1064   llvm::sort(TmpUnits.begin(), TmpUnits.end());
1065   std::unique_copy(TmpUnits.begin(), TmpUnits.end(),
1066                    std::back_inserter(RegUnits));
1067 }
1068 
1069 //===----------------------------------------------------------------------===//
1070 //                               CodeGenRegBank
1071 //===----------------------------------------------------------------------===//
1072 
1073 CodeGenRegBank::CodeGenRegBank(RecordKeeper &Records,
1074                                const CodeGenHwModes &Modes) : CGH(Modes) {
1075   // Configure register Sets to understand register classes and tuples.
1076   Sets.addFieldExpander("RegisterClass", "MemberList");
1077   Sets.addFieldExpander("CalleeSavedRegs", "SaveList");
1078   Sets.addExpander("RegisterTuples", llvm::make_unique<TupleExpander>());
1079 
1080   // Read in the user-defined (named) sub-register indices.
1081   // More indices will be synthesized later.
1082   std::vector<Record*> SRIs = Records.getAllDerivedDefinitions("SubRegIndex");
1083   llvm::sort(SRIs.begin(), SRIs.end(), LessRecord());
1084   for (unsigned i = 0, e = SRIs.size(); i != e; ++i)
1085     getSubRegIdx(SRIs[i]);
1086   // Build composite maps from ComposedOf fields.
1087   for (auto &Idx : SubRegIndices)
1088     Idx.updateComponents(*this);
1089 
1090   // Read in the register definitions.
1091   std::vector<Record*> Regs = Records.getAllDerivedDefinitions("Register");
1092   llvm::sort(Regs.begin(), Regs.end(), LessRecordRegister());
1093   // Assign the enumeration values.
1094   for (unsigned i = 0, e = Regs.size(); i != e; ++i)
1095     getReg(Regs[i]);
1096 
1097   // Expand tuples and number the new registers.
1098   std::vector<Record*> Tups =
1099     Records.getAllDerivedDefinitions("RegisterTuples");
1100 
1101   for (Record *R : Tups) {
1102     std::vector<Record *> TupRegs = *Sets.expand(R);
1103     llvm::sort(TupRegs.begin(), TupRegs.end(), LessRecordRegister());
1104     for (Record *RC : TupRegs)
1105       getReg(RC);
1106   }
1107 
1108   // Now all the registers are known. Build the object graph of explicit
1109   // register-register references.
1110   for (auto &Reg : Registers)
1111     Reg.buildObjectGraph(*this);
1112 
1113   // Compute register name map.
1114   for (auto &Reg : Registers)
1115     // FIXME: This could just be RegistersByName[name] = register, except that
1116     // causes some failures in MIPS - perhaps they have duplicate register name
1117     // entries? (or maybe there's a reason for it - I don't know much about this
1118     // code, just drive-by refactoring)
1119     RegistersByName.insert(
1120         std::make_pair(Reg.TheDef->getValueAsString("AsmName"), &Reg));
1121 
1122   // Precompute all sub-register maps.
1123   // This will create Composite entries for all inferred sub-register indices.
1124   for (auto &Reg : Registers)
1125     Reg.computeSubRegs(*this);
1126 
1127   // Compute transitive closure of subregister index ConcatenationOf vectors
1128   // and initialize ConcatIdx map.
1129   for (CodeGenSubRegIndex &SRI : SubRegIndices) {
1130     SRI.computeConcatTransitiveClosure();
1131     if (!SRI.ConcatenationOf.empty())
1132       ConcatIdx.insert(std::make_pair(
1133           SmallVector<CodeGenSubRegIndex*,8>(SRI.ConcatenationOf.begin(),
1134                                              SRI.ConcatenationOf.end()), &SRI));
1135   }
1136 
1137   // Infer even more sub-registers by combining leading super-registers.
1138   for (auto &Reg : Registers)
1139     if (Reg.CoveredBySubRegs)
1140       Reg.computeSecondarySubRegs(*this);
1141 
1142   // After the sub-register graph is complete, compute the topologically
1143   // ordered SuperRegs list.
1144   for (auto &Reg : Registers)
1145     Reg.computeSuperRegs(*this);
1146 
1147   // For each pair of Reg:SR, if both are non-artificial, mark the
1148   // corresponding sub-register index as non-artificial.
1149   for (auto &Reg : Registers) {
1150     if (Reg.Artificial)
1151       continue;
1152     for (auto P : Reg.getSubRegs()) {
1153       const CodeGenRegister *SR = P.second;
1154       if (!SR->Artificial)
1155         P.first->Artificial = false;
1156     }
1157   }
1158 
1159   // Native register units are associated with a leaf register. They've all been
1160   // discovered now.
1161   NumNativeRegUnits = RegUnits.size();
1162 
1163   // Read in register class definitions.
1164   std::vector<Record*> RCs = Records.getAllDerivedDefinitions("RegisterClass");
1165   if (RCs.empty())
1166     PrintFatalError("No 'RegisterClass' subclasses defined!");
1167 
1168   // Allocate user-defined register classes.
1169   for (auto *R : RCs) {
1170     RegClasses.emplace_back(*this, R);
1171     CodeGenRegisterClass &RC = RegClasses.back();
1172     if (!RC.Artificial)
1173       addToMaps(&RC);
1174   }
1175 
1176   // Infer missing classes to create a full algebra.
1177   computeInferredRegisterClasses();
1178 
1179   // Order register classes topologically and assign enum values.
1180   RegClasses.sort(TopoOrderRC);
1181   unsigned i = 0;
1182   for (auto &RC : RegClasses)
1183     RC.EnumValue = i++;
1184   CodeGenRegisterClass::computeSubClasses(*this);
1185 }
1186 
1187 // Create a synthetic CodeGenSubRegIndex without a corresponding Record.
1188 CodeGenSubRegIndex*
1189 CodeGenRegBank::createSubRegIndex(StringRef Name, StringRef Namespace) {
1190   SubRegIndices.emplace_back(Name, Namespace, SubRegIndices.size() + 1);
1191   return &SubRegIndices.back();
1192 }
1193 
1194 CodeGenSubRegIndex *CodeGenRegBank::getSubRegIdx(Record *Def) {
1195   CodeGenSubRegIndex *&Idx = Def2SubRegIdx[Def];
1196   if (Idx)
1197     return Idx;
1198   SubRegIndices.emplace_back(Def, SubRegIndices.size() + 1);
1199   Idx = &SubRegIndices.back();
1200   return Idx;
1201 }
1202 
1203 CodeGenRegister *CodeGenRegBank::getReg(Record *Def) {
1204   CodeGenRegister *&Reg = Def2Reg[Def];
1205   if (Reg)
1206     return Reg;
1207   Registers.emplace_back(Def, Registers.size() + 1);
1208   Reg = &Registers.back();
1209   return Reg;
1210 }
1211 
1212 void CodeGenRegBank::addToMaps(CodeGenRegisterClass *RC) {
1213   if (Record *Def = RC->getDef())
1214     Def2RC.insert(std::make_pair(Def, RC));
1215 
1216   // Duplicate classes are rejected by insert().
1217   // That's OK, we only care about the properties handled by CGRC::Key.
1218   CodeGenRegisterClass::Key K(*RC);
1219   Key2RC.insert(std::make_pair(K, RC));
1220 }
1221 
1222 // Create a synthetic sub-class if it is missing.
1223 CodeGenRegisterClass*
1224 CodeGenRegBank::getOrCreateSubClass(const CodeGenRegisterClass *RC,
1225                                     const CodeGenRegister::Vec *Members,
1226                                     StringRef Name) {
1227   // Synthetic sub-class has the same size and alignment as RC.
1228   CodeGenRegisterClass::Key K(Members, RC->RSI);
1229   RCKeyMap::const_iterator FoundI = Key2RC.find(K);
1230   if (FoundI != Key2RC.end())
1231     return FoundI->second;
1232 
1233   // Sub-class doesn't exist, create a new one.
1234   RegClasses.emplace_back(*this, Name, K);
1235   addToMaps(&RegClasses.back());
1236   return &RegClasses.back();
1237 }
1238 
1239 CodeGenRegisterClass *CodeGenRegBank::getRegClass(Record *Def) {
1240   if (CodeGenRegisterClass *RC = Def2RC[Def])
1241     return RC;
1242 
1243   PrintFatalError(Def->getLoc(), "Not a known RegisterClass!");
1244 }
1245 
1246 CodeGenSubRegIndex*
1247 CodeGenRegBank::getCompositeSubRegIndex(CodeGenSubRegIndex *A,
1248                                         CodeGenSubRegIndex *B) {
1249   // Look for an existing entry.
1250   CodeGenSubRegIndex *Comp = A->compose(B);
1251   if (Comp)
1252     return Comp;
1253 
1254   // None exists, synthesize one.
1255   std::string Name = A->getName() + "_then_" + B->getName();
1256   Comp = createSubRegIndex(Name, A->getNamespace());
1257   A->addComposite(B, Comp);
1258   return Comp;
1259 }
1260 
1261 CodeGenSubRegIndex *CodeGenRegBank::
1262 getConcatSubRegIndex(const SmallVector<CodeGenSubRegIndex *, 8> &Parts) {
1263   assert(Parts.size() > 1 && "Need two parts to concatenate");
1264 #ifndef NDEBUG
1265   for (CodeGenSubRegIndex *Idx : Parts) {
1266     assert(Idx->ConcatenationOf.empty() && "No transitive closure?");
1267   }
1268 #endif
1269 
1270   // Look for an existing entry.
1271   CodeGenSubRegIndex *&Idx = ConcatIdx[Parts];
1272   if (Idx)
1273     return Idx;
1274 
1275   // None exists, synthesize one.
1276   std::string Name = Parts.front()->getName();
1277   // Determine whether all parts are contiguous.
1278   bool isContinuous = true;
1279   unsigned Size = Parts.front()->Size;
1280   unsigned LastOffset = Parts.front()->Offset;
1281   unsigned LastSize = Parts.front()->Size;
1282   for (unsigned i = 1, e = Parts.size(); i != e; ++i) {
1283     Name += '_';
1284     Name += Parts[i]->getName();
1285     Size += Parts[i]->Size;
1286     if (Parts[i]->Offset != (LastOffset + LastSize))
1287       isContinuous = false;
1288     LastOffset = Parts[i]->Offset;
1289     LastSize = Parts[i]->Size;
1290   }
1291   Idx = createSubRegIndex(Name, Parts.front()->getNamespace());
1292   Idx->Size = Size;
1293   Idx->Offset = isContinuous ? Parts.front()->Offset : -1;
1294   Idx->ConcatenationOf.assign(Parts.begin(), Parts.end());
1295   return Idx;
1296 }
1297 
1298 void CodeGenRegBank::computeComposites() {
1299   // Keep track of TopoSigs visited. We only need to visit each TopoSig once,
1300   // and many registers will share TopoSigs on regular architectures.
1301   BitVector TopoSigs(getNumTopoSigs());
1302 
1303   for (const auto &Reg1 : Registers) {
1304     // Skip identical subreg structures already processed.
1305     if (TopoSigs.test(Reg1.getTopoSig()))
1306       continue;
1307     TopoSigs.set(Reg1.getTopoSig());
1308 
1309     const CodeGenRegister::SubRegMap &SRM1 = Reg1.getSubRegs();
1310     for (CodeGenRegister::SubRegMap::const_iterator i1 = SRM1.begin(),
1311          e1 = SRM1.end(); i1 != e1; ++i1) {
1312       CodeGenSubRegIndex *Idx1 = i1->first;
1313       CodeGenRegister *Reg2 = i1->second;
1314       // Ignore identity compositions.
1315       if (&Reg1 == Reg2)
1316         continue;
1317       const CodeGenRegister::SubRegMap &SRM2 = Reg2->getSubRegs();
1318       // Try composing Idx1 with another SubRegIndex.
1319       for (CodeGenRegister::SubRegMap::const_iterator i2 = SRM2.begin(),
1320            e2 = SRM2.end(); i2 != e2; ++i2) {
1321         CodeGenSubRegIndex *Idx2 = i2->first;
1322         CodeGenRegister *Reg3 = i2->second;
1323         // Ignore identity compositions.
1324         if (Reg2 == Reg3)
1325           continue;
1326         // OK Reg1:IdxPair == Reg3. Find the index with Reg:Idx == Reg3.
1327         CodeGenSubRegIndex *Idx3 = Reg1.getSubRegIndex(Reg3);
1328         assert(Idx3 && "Sub-register doesn't have an index");
1329 
1330         // Conflicting composition? Emit a warning but allow it.
1331         if (CodeGenSubRegIndex *Prev = Idx1->addComposite(Idx2, Idx3))
1332           PrintWarning(Twine("SubRegIndex ") + Idx1->getQualifiedName() +
1333                        " and " + Idx2->getQualifiedName() +
1334                        " compose ambiguously as " + Prev->getQualifiedName() +
1335                        " or " + Idx3->getQualifiedName());
1336       }
1337     }
1338   }
1339 }
1340 
1341 // Compute lane masks. This is similar to register units, but at the
1342 // sub-register index level. Each bit in the lane mask is like a register unit
1343 // class, and two lane masks will have a bit in common if two sub-register
1344 // indices overlap in some register.
1345 //
1346 // Conservatively share a lane mask bit if two sub-register indices overlap in
1347 // some registers, but not in others. That shouldn't happen a lot.
1348 void CodeGenRegBank::computeSubRegLaneMasks() {
1349   // First assign individual bits to all the leaf indices.
1350   unsigned Bit = 0;
1351   // Determine mask of lanes that cover their registers.
1352   CoveringLanes = LaneBitmask::getAll();
1353   for (auto &Idx : SubRegIndices) {
1354     if (Idx.getComposites().empty()) {
1355       if (Bit > LaneBitmask::BitWidth) {
1356         PrintFatalError(
1357           Twine("Ran out of lanemask bits to represent subregister ")
1358           + Idx.getName());
1359       }
1360       Idx.LaneMask = LaneBitmask::getLane(Bit);
1361       ++Bit;
1362     } else {
1363       Idx.LaneMask = LaneBitmask::getNone();
1364     }
1365   }
1366 
1367   // Compute transformation sequences for composeSubRegIndexLaneMask. The idea
1368   // here is that for each possible target subregister we look at the leafs
1369   // in the subregister graph that compose for this target and create
1370   // transformation sequences for the lanemasks. Each step in the sequence
1371   // consists of a bitmask and a bitrotate operation. As the rotation amounts
1372   // are usually the same for many subregisters we can easily combine the steps
1373   // by combining the masks.
1374   for (const auto &Idx : SubRegIndices) {
1375     const auto &Composites = Idx.getComposites();
1376     auto &LaneTransforms = Idx.CompositionLaneMaskTransform;
1377 
1378     if (Composites.empty()) {
1379       // Moving from a class with no subregisters we just had a single lane:
1380       // The subregister must be a leaf subregister and only occupies 1 bit.
1381       // Move the bit from the class without subregisters into that position.
1382       unsigned DstBit = Idx.LaneMask.getHighestLane();
1383       assert(Idx.LaneMask == LaneBitmask::getLane(DstBit) &&
1384              "Must be a leaf subregister");
1385       MaskRolPair MaskRol = { LaneBitmask::getLane(0), (uint8_t)DstBit };
1386       LaneTransforms.push_back(MaskRol);
1387     } else {
1388       // Go through all leaf subregisters and find the ones that compose with
1389       // Idx. These make out all possible valid bits in the lane mask we want to
1390       // transform. Looking only at the leafs ensure that only a single bit in
1391       // the mask is set.
1392       unsigned NextBit = 0;
1393       for (auto &Idx2 : SubRegIndices) {
1394         // Skip non-leaf subregisters.
1395         if (!Idx2.getComposites().empty())
1396           continue;
1397         // Replicate the behaviour from the lane mask generation loop above.
1398         unsigned SrcBit = NextBit;
1399         LaneBitmask SrcMask = LaneBitmask::getLane(SrcBit);
1400         if (NextBit < LaneBitmask::BitWidth-1)
1401           ++NextBit;
1402         assert(Idx2.LaneMask == SrcMask);
1403 
1404         // Get the composed subregister if there is any.
1405         auto C = Composites.find(&Idx2);
1406         if (C == Composites.end())
1407           continue;
1408         const CodeGenSubRegIndex *Composite = C->second;
1409         // The Composed subreg should be a leaf subreg too
1410         assert(Composite->getComposites().empty());
1411 
1412         // Create Mask+Rotate operation and merge with existing ops if possible.
1413         unsigned DstBit = Composite->LaneMask.getHighestLane();
1414         int Shift = DstBit - SrcBit;
1415         uint8_t RotateLeft = Shift >= 0 ? (uint8_t)Shift
1416                                         : LaneBitmask::BitWidth + Shift;
1417         for (auto &I : LaneTransforms) {
1418           if (I.RotateLeft == RotateLeft) {
1419             I.Mask |= SrcMask;
1420             SrcMask = LaneBitmask::getNone();
1421           }
1422         }
1423         if (SrcMask.any()) {
1424           MaskRolPair MaskRol = { SrcMask, RotateLeft };
1425           LaneTransforms.push_back(MaskRol);
1426         }
1427       }
1428     }
1429 
1430     // Optimize if the transformation consists of one step only: Set mask to
1431     // 0xffffffff (including some irrelevant invalid bits) so that it should
1432     // merge with more entries later while compressing the table.
1433     if (LaneTransforms.size() == 1)
1434       LaneTransforms[0].Mask = LaneBitmask::getAll();
1435 
1436     // Further compression optimization: For invalid compositions resulting
1437     // in a sequence with 0 entries we can just pick any other. Choose
1438     // Mask 0xffffffff with Rotation 0.
1439     if (LaneTransforms.size() == 0) {
1440       MaskRolPair P = { LaneBitmask::getAll(), 0 };
1441       LaneTransforms.push_back(P);
1442     }
1443   }
1444 
1445   // FIXME: What if ad-hoc aliasing introduces overlaps that aren't represented
1446   // by the sub-register graph? This doesn't occur in any known targets.
1447 
1448   // Inherit lanes from composites.
1449   for (const auto &Idx : SubRegIndices) {
1450     LaneBitmask Mask = Idx.computeLaneMask();
1451     // If some super-registers without CoveredBySubRegs use this index, we can
1452     // no longer assume that the lanes are covering their registers.
1453     if (!Idx.AllSuperRegsCovered)
1454       CoveringLanes &= ~Mask;
1455   }
1456 
1457   // Compute lane mask combinations for register classes.
1458   for (auto &RegClass : RegClasses) {
1459     LaneBitmask LaneMask;
1460     for (const auto &SubRegIndex : SubRegIndices) {
1461       if (RegClass.getSubClassWithSubReg(&SubRegIndex) == nullptr)
1462         continue;
1463       LaneMask |= SubRegIndex.LaneMask;
1464     }
1465 
1466     // For classes without any subregisters set LaneMask to 1 instead of 0.
1467     // This makes it easier for client code to handle classes uniformly.
1468     if (LaneMask.none())
1469       LaneMask = LaneBitmask::getLane(0);
1470 
1471     RegClass.LaneMask = LaneMask;
1472   }
1473 }
1474 
1475 namespace {
1476 
1477 // UberRegSet is a helper class for computeRegUnitWeights. Each UberRegSet is
1478 // the transitive closure of the union of overlapping register
1479 // classes. Together, the UberRegSets form a partition of the registers. If we
1480 // consider overlapping register classes to be connected, then each UberRegSet
1481 // is a set of connected components.
1482 //
1483 // An UberRegSet will likely be a horizontal slice of register names of
1484 // the same width. Nontrivial subregisters should then be in a separate
1485 // UberRegSet. But this property isn't required for valid computation of
1486 // register unit weights.
1487 //
1488 // A Weight field caches the max per-register unit weight in each UberRegSet.
1489 //
1490 // A set of SingularDeterminants flags single units of some register in this set
1491 // for which the unit weight equals the set weight. These units should not have
1492 // their weight increased.
1493 struct UberRegSet {
1494   CodeGenRegister::Vec Regs;
1495   unsigned Weight = 0;
1496   CodeGenRegister::RegUnitList SingularDeterminants;
1497 
1498   UberRegSet() = default;
1499 };
1500 
1501 } // end anonymous namespace
1502 
1503 // Partition registers into UberRegSets, where each set is the transitive
1504 // closure of the union of overlapping register classes.
1505 //
1506 // UberRegSets[0] is a special non-allocatable set.
1507 static void computeUberSets(std::vector<UberRegSet> &UberSets,
1508                             std::vector<UberRegSet*> &RegSets,
1509                             CodeGenRegBank &RegBank) {
1510   const auto &Registers = RegBank.getRegisters();
1511 
1512   // The Register EnumValue is one greater than its index into Registers.
1513   assert(Registers.size() == Registers.back().EnumValue &&
1514          "register enum value mismatch");
1515 
1516   // For simplicitly make the SetID the same as EnumValue.
1517   IntEqClasses UberSetIDs(Registers.size()+1);
1518   std::set<unsigned> AllocatableRegs;
1519   for (auto &RegClass : RegBank.getRegClasses()) {
1520     if (!RegClass.Allocatable)
1521       continue;
1522 
1523     const CodeGenRegister::Vec &Regs = RegClass.getMembers();
1524     if (Regs.empty())
1525       continue;
1526 
1527     unsigned USetID = UberSetIDs.findLeader((*Regs.begin())->EnumValue);
1528     assert(USetID && "register number 0 is invalid");
1529 
1530     AllocatableRegs.insert((*Regs.begin())->EnumValue);
1531     for (auto I = std::next(Regs.begin()), E = Regs.end(); I != E; ++I) {
1532       AllocatableRegs.insert((*I)->EnumValue);
1533       UberSetIDs.join(USetID, (*I)->EnumValue);
1534     }
1535   }
1536   // Combine non-allocatable regs.
1537   for (const auto &Reg : Registers) {
1538     unsigned RegNum = Reg.EnumValue;
1539     if (AllocatableRegs.count(RegNum))
1540       continue;
1541 
1542     UberSetIDs.join(0, RegNum);
1543   }
1544   UberSetIDs.compress();
1545 
1546   // Make the first UberSet a special unallocatable set.
1547   unsigned ZeroID = UberSetIDs[0];
1548 
1549   // Insert Registers into the UberSets formed by union-find.
1550   // Do not resize after this.
1551   UberSets.resize(UberSetIDs.getNumClasses());
1552   unsigned i = 0;
1553   for (const CodeGenRegister &Reg : Registers) {
1554     unsigned USetID = UberSetIDs[Reg.EnumValue];
1555     if (!USetID)
1556       USetID = ZeroID;
1557     else if (USetID == ZeroID)
1558       USetID = 0;
1559 
1560     UberRegSet *USet = &UberSets[USetID];
1561     USet->Regs.push_back(&Reg);
1562     sortAndUniqueRegisters(USet->Regs);
1563     RegSets[i++] = USet;
1564   }
1565 }
1566 
1567 // Recompute each UberSet weight after changing unit weights.
1568 static void computeUberWeights(std::vector<UberRegSet> &UberSets,
1569                                CodeGenRegBank &RegBank) {
1570   // Skip the first unallocatable set.
1571   for (std::vector<UberRegSet>::iterator I = std::next(UberSets.begin()),
1572          E = UberSets.end(); I != E; ++I) {
1573 
1574     // Initialize all unit weights in this set, and remember the max units/reg.
1575     const CodeGenRegister *Reg = nullptr;
1576     unsigned MaxWeight = 0, Weight = 0;
1577     for (RegUnitIterator UnitI(I->Regs); UnitI.isValid(); ++UnitI) {
1578       if (Reg != UnitI.getReg()) {
1579         if (Weight > MaxWeight)
1580           MaxWeight = Weight;
1581         Reg = UnitI.getReg();
1582         Weight = 0;
1583       }
1584       if (!RegBank.getRegUnit(*UnitI).Artificial) {
1585         unsigned UWeight = RegBank.getRegUnit(*UnitI).Weight;
1586         if (!UWeight) {
1587           UWeight = 1;
1588           RegBank.increaseRegUnitWeight(*UnitI, UWeight);
1589         }
1590         Weight += UWeight;
1591       }
1592     }
1593     if (Weight > MaxWeight)
1594       MaxWeight = Weight;
1595     if (I->Weight != MaxWeight) {
1596       LLVM_DEBUG(dbgs() << "UberSet " << I - UberSets.begin() << " Weight "
1597                         << MaxWeight;
1598                  for (auto &Unit
1599                       : I->Regs) dbgs()
1600                  << " " << Unit->getName();
1601                  dbgs() << "\n");
1602       // Update the set weight.
1603       I->Weight = MaxWeight;
1604     }
1605 
1606     // Find singular determinants.
1607     for (const auto R : I->Regs) {
1608       if (R->getRegUnits().count() == 1 && R->getWeight(RegBank) == I->Weight) {
1609         I->SingularDeterminants |= R->getRegUnits();
1610       }
1611     }
1612   }
1613 }
1614 
1615 // normalizeWeight is a computeRegUnitWeights helper that adjusts the weight of
1616 // a register and its subregisters so that they have the same weight as their
1617 // UberSet. Self-recursion processes the subregister tree in postorder so
1618 // subregisters are normalized first.
1619 //
1620 // Side effects:
1621 // - creates new adopted register units
1622 // - causes superregisters to inherit adopted units
1623 // - increases the weight of "singular" units
1624 // - induces recomputation of UberWeights.
1625 static bool normalizeWeight(CodeGenRegister *Reg,
1626                             std::vector<UberRegSet> &UberSets,
1627                             std::vector<UberRegSet*> &RegSets,
1628                             SparseBitVector<> &NormalRegs,
1629                             CodeGenRegister::RegUnitList &NormalUnits,
1630                             CodeGenRegBank &RegBank) {
1631   if (NormalRegs.test(Reg->EnumValue))
1632     return false;
1633   NormalRegs.set(Reg->EnumValue);
1634 
1635   bool Changed = false;
1636   const CodeGenRegister::SubRegMap &SRM = Reg->getSubRegs();
1637   for (CodeGenRegister::SubRegMap::const_iterator SRI = SRM.begin(),
1638          SRE = SRM.end(); SRI != SRE; ++SRI) {
1639     if (SRI->second == Reg)
1640       continue; // self-cycles happen
1641 
1642     Changed |= normalizeWeight(SRI->second, UberSets, RegSets,
1643                                NormalRegs, NormalUnits, RegBank);
1644   }
1645   // Postorder register normalization.
1646 
1647   // Inherit register units newly adopted by subregisters.
1648   if (Reg->inheritRegUnits(RegBank))
1649     computeUberWeights(UberSets, RegBank);
1650 
1651   // Check if this register is too skinny for its UberRegSet.
1652   UberRegSet *UberSet = RegSets[RegBank.getRegIndex(Reg)];
1653 
1654   unsigned RegWeight = Reg->getWeight(RegBank);
1655   if (UberSet->Weight > RegWeight) {
1656     // A register unit's weight can be adjusted only if it is the singular unit
1657     // for this register, has not been used to normalize a subregister's set,
1658     // and has not already been used to singularly determine this UberRegSet.
1659     unsigned AdjustUnit = *Reg->getRegUnits().begin();
1660     if (Reg->getRegUnits().count() != 1
1661         || hasRegUnit(NormalUnits, AdjustUnit)
1662         || hasRegUnit(UberSet->SingularDeterminants, AdjustUnit)) {
1663       // We don't have an adjustable unit, so adopt a new one.
1664       AdjustUnit = RegBank.newRegUnit(UberSet->Weight - RegWeight);
1665       Reg->adoptRegUnit(AdjustUnit);
1666       // Adopting a unit does not immediately require recomputing set weights.
1667     }
1668     else {
1669       // Adjust the existing single unit.
1670       if (!RegBank.getRegUnit(AdjustUnit).Artificial)
1671         RegBank.increaseRegUnitWeight(AdjustUnit, UberSet->Weight - RegWeight);
1672       // The unit may be shared among sets and registers within this set.
1673       computeUberWeights(UberSets, RegBank);
1674     }
1675     Changed = true;
1676   }
1677 
1678   // Mark these units normalized so superregisters can't change their weights.
1679   NormalUnits |= Reg->getRegUnits();
1680 
1681   return Changed;
1682 }
1683 
1684 // Compute a weight for each register unit created during getSubRegs.
1685 //
1686 // The goal is that two registers in the same class will have the same weight,
1687 // where each register's weight is defined as sum of its units' weights.
1688 void CodeGenRegBank::computeRegUnitWeights() {
1689   std::vector<UberRegSet> UberSets;
1690   std::vector<UberRegSet*> RegSets(Registers.size());
1691   computeUberSets(UberSets, RegSets, *this);
1692   // UberSets and RegSets are now immutable.
1693 
1694   computeUberWeights(UberSets, *this);
1695 
1696   // Iterate over each Register, normalizing the unit weights until reaching
1697   // a fix point.
1698   unsigned NumIters = 0;
1699   for (bool Changed = true; Changed; ++NumIters) {
1700     assert(NumIters <= NumNativeRegUnits && "Runaway register unit weights");
1701     Changed = false;
1702     for (auto &Reg : Registers) {
1703       CodeGenRegister::RegUnitList NormalUnits;
1704       SparseBitVector<> NormalRegs;
1705       Changed |= normalizeWeight(&Reg, UberSets, RegSets, NormalRegs,
1706                                  NormalUnits, *this);
1707     }
1708   }
1709 }
1710 
1711 // Find a set in UniqueSets with the same elements as Set.
1712 // Return an iterator into UniqueSets.
1713 static std::vector<RegUnitSet>::const_iterator
1714 findRegUnitSet(const std::vector<RegUnitSet> &UniqueSets,
1715                const RegUnitSet &Set) {
1716   std::vector<RegUnitSet>::const_iterator
1717     I = UniqueSets.begin(), E = UniqueSets.end();
1718   for(;I != E; ++I) {
1719     if (I->Units == Set.Units)
1720       break;
1721   }
1722   return I;
1723 }
1724 
1725 // Return true if the RUSubSet is a subset of RUSuperSet.
1726 static bool isRegUnitSubSet(const std::vector<unsigned> &RUSubSet,
1727                             const std::vector<unsigned> &RUSuperSet) {
1728   return std::includes(RUSuperSet.begin(), RUSuperSet.end(),
1729                        RUSubSet.begin(), RUSubSet.end());
1730 }
1731 
1732 /// Iteratively prune unit sets. Prune subsets that are close to the superset,
1733 /// but with one or two registers removed. We occasionally have registers like
1734 /// APSR and PC thrown in with the general registers. We also see many
1735 /// special-purpose register subsets, such as tail-call and Thumb
1736 /// encodings. Generating all possible overlapping sets is combinatorial and
1737 /// overkill for modeling pressure. Ideally we could fix this statically in
1738 /// tablegen by (1) having the target define register classes that only include
1739 /// the allocatable registers and marking other classes as non-allocatable and
1740 /// (2) having a way to mark special purpose classes as "don't-care" classes for
1741 /// the purpose of pressure.  However, we make an attempt to handle targets that
1742 /// are not nicely defined by merging nearly identical register unit sets
1743 /// statically. This generates smaller tables. Then, dynamically, we adjust the
1744 /// set limit by filtering the reserved registers.
1745 ///
1746 /// Merge sets only if the units have the same weight. For example, on ARM,
1747 /// Q-tuples with ssub index 0 include all S regs but also include D16+. We
1748 /// should not expand the S set to include D regs.
1749 void CodeGenRegBank::pruneUnitSets() {
1750   assert(RegClassUnitSets.empty() && "this invalidates RegClassUnitSets");
1751 
1752   // Form an equivalence class of UnitSets with no significant difference.
1753   std::vector<unsigned> SuperSetIDs;
1754   for (unsigned SubIdx = 0, EndIdx = RegUnitSets.size();
1755        SubIdx != EndIdx; ++SubIdx) {
1756     const RegUnitSet &SubSet = RegUnitSets[SubIdx];
1757     unsigned SuperIdx = 0;
1758     for (; SuperIdx != EndIdx; ++SuperIdx) {
1759       if (SuperIdx == SubIdx)
1760         continue;
1761 
1762       unsigned UnitWeight = RegUnits[SubSet.Units[0]].Weight;
1763       const RegUnitSet &SuperSet = RegUnitSets[SuperIdx];
1764       if (isRegUnitSubSet(SubSet.Units, SuperSet.Units)
1765           && (SubSet.Units.size() + 3 > SuperSet.Units.size())
1766           && UnitWeight == RegUnits[SuperSet.Units[0]].Weight
1767           && UnitWeight == RegUnits[SuperSet.Units.back()].Weight) {
1768         LLVM_DEBUG(dbgs() << "UnitSet " << SubIdx << " subsumed by " << SuperIdx
1769                           << "\n");
1770         // We can pick any of the set names for the merged set. Go for the
1771         // shortest one to avoid picking the name of one of the classes that are
1772         // artificially created by tablegen. So "FPR128_lo" instead of
1773         // "QQQQ_with_qsub3_in_FPR128_lo".
1774         if (RegUnitSets[SubIdx].Name.size() < RegUnitSets[SuperIdx].Name.size())
1775           RegUnitSets[SuperIdx].Name = RegUnitSets[SubIdx].Name;
1776         break;
1777       }
1778     }
1779     if (SuperIdx == EndIdx)
1780       SuperSetIDs.push_back(SubIdx);
1781   }
1782   // Populate PrunedUnitSets with each equivalence class's superset.
1783   std::vector<RegUnitSet> PrunedUnitSets(SuperSetIDs.size());
1784   for (unsigned i = 0, e = SuperSetIDs.size(); i != e; ++i) {
1785     unsigned SuperIdx = SuperSetIDs[i];
1786     PrunedUnitSets[i].Name = RegUnitSets[SuperIdx].Name;
1787     PrunedUnitSets[i].Units.swap(RegUnitSets[SuperIdx].Units);
1788   }
1789   RegUnitSets.swap(PrunedUnitSets);
1790 }
1791 
1792 // Create a RegUnitSet for each RegClass that contains all units in the class
1793 // including adopted units that are necessary to model register pressure. Then
1794 // iteratively compute RegUnitSets such that the union of any two overlapping
1795 // RegUnitSets is repreresented.
1796 //
1797 // RegisterInfoEmitter will map each RegClass to its RegUnitClass and any
1798 // RegUnitSet that is a superset of that RegUnitClass.
1799 void CodeGenRegBank::computeRegUnitSets() {
1800   assert(RegUnitSets.empty() && "dirty RegUnitSets");
1801 
1802   // Compute a unique RegUnitSet for each RegClass.
1803   auto &RegClasses = getRegClasses();
1804   for (auto &RC : RegClasses) {
1805     if (!RC.Allocatable || RC.Artificial)
1806       continue;
1807 
1808     // Speculatively grow the RegUnitSets to hold the new set.
1809     RegUnitSets.resize(RegUnitSets.size() + 1);
1810     RegUnitSets.back().Name = RC.getName();
1811 
1812     // Compute a sorted list of units in this class.
1813     RC.buildRegUnitSet(*this, RegUnitSets.back().Units);
1814 
1815     // Find an existing RegUnitSet.
1816     std::vector<RegUnitSet>::const_iterator SetI =
1817       findRegUnitSet(RegUnitSets, RegUnitSets.back());
1818     if (SetI != std::prev(RegUnitSets.end()))
1819       RegUnitSets.pop_back();
1820   }
1821 
1822   LLVM_DEBUG(dbgs() << "\nBefore pruning:\n"; for (unsigned USIdx = 0,
1823                                                    USEnd = RegUnitSets.size();
1824                                                    USIdx < USEnd; ++USIdx) {
1825     dbgs() << "UnitSet " << USIdx << " " << RegUnitSets[USIdx].Name << ":";
1826     for (auto &U : RegUnitSets[USIdx].Units)
1827       printRegUnitName(U);
1828     dbgs() << "\n";
1829   });
1830 
1831   // Iteratively prune unit sets.
1832   pruneUnitSets();
1833 
1834   LLVM_DEBUG(dbgs() << "\nBefore union:\n"; for (unsigned USIdx = 0,
1835                                                  USEnd = RegUnitSets.size();
1836                                                  USIdx < USEnd; ++USIdx) {
1837     dbgs() << "UnitSet " << USIdx << " " << RegUnitSets[USIdx].Name << ":";
1838     for (auto &U : RegUnitSets[USIdx].Units)
1839       printRegUnitName(U);
1840     dbgs() << "\n";
1841   } dbgs() << "\nUnion sets:\n");
1842 
1843   // Iterate over all unit sets, including new ones added by this loop.
1844   unsigned NumRegUnitSubSets = RegUnitSets.size();
1845   for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx) {
1846     // In theory, this is combinatorial. In practice, it needs to be bounded
1847     // by a small number of sets for regpressure to be efficient.
1848     // If the assert is hit, we need to implement pruning.
1849     assert(Idx < (2*NumRegUnitSubSets) && "runaway unit set inference");
1850 
1851     // Compare new sets with all original classes.
1852     for (unsigned SearchIdx = (Idx >= NumRegUnitSubSets) ? 0 : Idx+1;
1853          SearchIdx != EndIdx; ++SearchIdx) {
1854       std::set<unsigned> Intersection;
1855       std::set_intersection(RegUnitSets[Idx].Units.begin(),
1856                             RegUnitSets[Idx].Units.end(),
1857                             RegUnitSets[SearchIdx].Units.begin(),
1858                             RegUnitSets[SearchIdx].Units.end(),
1859                             std::inserter(Intersection, Intersection.begin()));
1860       if (Intersection.empty())
1861         continue;
1862 
1863       // Speculatively grow the RegUnitSets to hold the new set.
1864       RegUnitSets.resize(RegUnitSets.size() + 1);
1865       RegUnitSets.back().Name =
1866         RegUnitSets[Idx].Name + "+" + RegUnitSets[SearchIdx].Name;
1867 
1868       std::set_union(RegUnitSets[Idx].Units.begin(),
1869                      RegUnitSets[Idx].Units.end(),
1870                      RegUnitSets[SearchIdx].Units.begin(),
1871                      RegUnitSets[SearchIdx].Units.end(),
1872                      std::inserter(RegUnitSets.back().Units,
1873                                    RegUnitSets.back().Units.begin()));
1874 
1875       // Find an existing RegUnitSet, or add the union to the unique sets.
1876       std::vector<RegUnitSet>::const_iterator SetI =
1877         findRegUnitSet(RegUnitSets, RegUnitSets.back());
1878       if (SetI != std::prev(RegUnitSets.end()))
1879         RegUnitSets.pop_back();
1880       else {
1881         LLVM_DEBUG(dbgs() << "UnitSet " << RegUnitSets.size() - 1 << " "
1882                           << RegUnitSets.back().Name << ":";
1883                    for (auto &U
1884                         : RegUnitSets.back().Units) printRegUnitName(U);
1885                    dbgs() << "\n";);
1886       }
1887     }
1888   }
1889 
1890   // Iteratively prune unit sets after inferring supersets.
1891   pruneUnitSets();
1892 
1893   LLVM_DEBUG(
1894       dbgs() << "\n"; for (unsigned USIdx = 0, USEnd = RegUnitSets.size();
1895                            USIdx < USEnd; ++USIdx) {
1896         dbgs() << "UnitSet " << USIdx << " " << RegUnitSets[USIdx].Name << ":";
1897         for (auto &U : RegUnitSets[USIdx].Units)
1898           printRegUnitName(U);
1899         dbgs() << "\n";
1900       });
1901 
1902   // For each register class, list the UnitSets that are supersets.
1903   RegClassUnitSets.resize(RegClasses.size());
1904   int RCIdx = -1;
1905   for (auto &RC : RegClasses) {
1906     ++RCIdx;
1907     if (!RC.Allocatable)
1908       continue;
1909 
1910     // Recompute the sorted list of units in this class.
1911     std::vector<unsigned> RCRegUnits;
1912     RC.buildRegUnitSet(*this, RCRegUnits);
1913 
1914     // Don't increase pressure for unallocatable regclasses.
1915     if (RCRegUnits.empty())
1916       continue;
1917 
1918     LLVM_DEBUG(dbgs() << "RC " << RC.getName() << " Units: \n";
1919                for (auto U
1920                     : RCRegUnits) printRegUnitName(U);
1921                dbgs() << "\n  UnitSetIDs:");
1922 
1923     // Find all supersets.
1924     for (unsigned USIdx = 0, USEnd = RegUnitSets.size();
1925          USIdx != USEnd; ++USIdx) {
1926       if (isRegUnitSubSet(RCRegUnits, RegUnitSets[USIdx].Units)) {
1927         LLVM_DEBUG(dbgs() << " " << USIdx);
1928         RegClassUnitSets[RCIdx].push_back(USIdx);
1929       }
1930     }
1931     LLVM_DEBUG(dbgs() << "\n");
1932     assert(!RegClassUnitSets[RCIdx].empty() && "missing unit set for regclass");
1933   }
1934 
1935   // For each register unit, ensure that we have the list of UnitSets that
1936   // contain the unit. Normally, this matches an existing list of UnitSets for a
1937   // register class. If not, we create a new entry in RegClassUnitSets as a
1938   // "fake" register class.
1939   for (unsigned UnitIdx = 0, UnitEnd = NumNativeRegUnits;
1940        UnitIdx < UnitEnd; ++UnitIdx) {
1941     std::vector<unsigned> RUSets;
1942     for (unsigned i = 0, e = RegUnitSets.size(); i != e; ++i) {
1943       RegUnitSet &RUSet = RegUnitSets[i];
1944       if (!is_contained(RUSet.Units, UnitIdx))
1945         continue;
1946       RUSets.push_back(i);
1947     }
1948     unsigned RCUnitSetsIdx = 0;
1949     for (unsigned e = RegClassUnitSets.size();
1950          RCUnitSetsIdx != e; ++RCUnitSetsIdx) {
1951       if (RegClassUnitSets[RCUnitSetsIdx] == RUSets) {
1952         break;
1953       }
1954     }
1955     RegUnits[UnitIdx].RegClassUnitSetsIdx = RCUnitSetsIdx;
1956     if (RCUnitSetsIdx == RegClassUnitSets.size()) {
1957       // Create a new list of UnitSets as a "fake" register class.
1958       RegClassUnitSets.resize(RCUnitSetsIdx + 1);
1959       RegClassUnitSets[RCUnitSetsIdx].swap(RUSets);
1960     }
1961   }
1962 }
1963 
1964 void CodeGenRegBank::computeRegUnitLaneMasks() {
1965   for (auto &Register : Registers) {
1966     // Create an initial lane mask for all register units.
1967     const auto &RegUnits = Register.getRegUnits();
1968     CodeGenRegister::RegUnitLaneMaskList
1969         RegUnitLaneMasks(RegUnits.count(), LaneBitmask::getNone());
1970     // Iterate through SubRegisters.
1971     typedef CodeGenRegister::SubRegMap SubRegMap;
1972     const SubRegMap &SubRegs = Register.getSubRegs();
1973     for (SubRegMap::const_iterator S = SubRegs.begin(),
1974          SE = SubRegs.end(); S != SE; ++S) {
1975       CodeGenRegister *SubReg = S->second;
1976       // Ignore non-leaf subregisters, their lane masks are fully covered by
1977       // the leaf subregisters anyway.
1978       if (!SubReg->getSubRegs().empty())
1979         continue;
1980       CodeGenSubRegIndex *SubRegIndex = S->first;
1981       const CodeGenRegister *SubRegister = S->second;
1982       LaneBitmask LaneMask = SubRegIndex->LaneMask;
1983       // Distribute LaneMask to Register Units touched.
1984       for (unsigned SUI : SubRegister->getRegUnits()) {
1985         bool Found = false;
1986         unsigned u = 0;
1987         for (unsigned RU : RegUnits) {
1988           if (SUI == RU) {
1989             RegUnitLaneMasks[u] |= LaneMask;
1990             assert(!Found);
1991             Found = true;
1992           }
1993           ++u;
1994         }
1995         (void)Found;
1996         assert(Found);
1997       }
1998     }
1999     Register.setRegUnitLaneMasks(RegUnitLaneMasks);
2000   }
2001 }
2002 
2003 void CodeGenRegBank::computeDerivedInfo() {
2004   computeComposites();
2005   computeSubRegLaneMasks();
2006 
2007   // Compute a weight for each register unit created during getSubRegs.
2008   // This may create adopted register units (with unit # >= NumNativeRegUnits).
2009   computeRegUnitWeights();
2010 
2011   // Compute a unique set of RegUnitSets. One for each RegClass and inferred
2012   // supersets for the union of overlapping sets.
2013   computeRegUnitSets();
2014 
2015   computeRegUnitLaneMasks();
2016 
2017   // Compute register class HasDisjunctSubRegs/CoveredBySubRegs flag.
2018   for (CodeGenRegisterClass &RC : RegClasses) {
2019     RC.HasDisjunctSubRegs = false;
2020     RC.CoveredBySubRegs = true;
2021     for (const CodeGenRegister *Reg : RC.getMembers()) {
2022       RC.HasDisjunctSubRegs |= Reg->HasDisjunctSubRegs;
2023       RC.CoveredBySubRegs &= Reg->CoveredBySubRegs;
2024     }
2025   }
2026 
2027   // Get the weight of each set.
2028   for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx)
2029     RegUnitSets[Idx].Weight = getRegUnitSetWeight(RegUnitSets[Idx].Units);
2030 
2031   // Find the order of each set.
2032   RegUnitSetOrder.reserve(RegUnitSets.size());
2033   for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx)
2034     RegUnitSetOrder.push_back(Idx);
2035 
2036   std::stable_sort(RegUnitSetOrder.begin(), RegUnitSetOrder.end(),
2037                    [this](unsigned ID1, unsigned ID2) {
2038     return getRegPressureSet(ID1).Units.size() <
2039            getRegPressureSet(ID2).Units.size();
2040   });
2041   for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx) {
2042     RegUnitSets[RegUnitSetOrder[Idx]].Order = Idx;
2043   }
2044 }
2045 
2046 //
2047 // Synthesize missing register class intersections.
2048 //
2049 // Make sure that sub-classes of RC exists such that getCommonSubClass(RC, X)
2050 // returns a maximal register class for all X.
2051 //
2052 void CodeGenRegBank::inferCommonSubClass(CodeGenRegisterClass *RC) {
2053   assert(!RegClasses.empty());
2054   // Stash the iterator to the last element so that this loop doesn't visit
2055   // elements added by the getOrCreateSubClass call within it.
2056   for (auto I = RegClasses.begin(), E = std::prev(RegClasses.end());
2057        I != std::next(E); ++I) {
2058     CodeGenRegisterClass *RC1 = RC;
2059     CodeGenRegisterClass *RC2 = &*I;
2060     if (RC1 == RC2)
2061       continue;
2062 
2063     // Compute the set intersection of RC1 and RC2.
2064     const CodeGenRegister::Vec &Memb1 = RC1->getMembers();
2065     const CodeGenRegister::Vec &Memb2 = RC2->getMembers();
2066     CodeGenRegister::Vec Intersection;
2067     std::set_intersection(
2068         Memb1.begin(), Memb1.end(), Memb2.begin(), Memb2.end(),
2069         std::inserter(Intersection, Intersection.begin()), deref<llvm::less>());
2070 
2071     // Skip disjoint class pairs.
2072     if (Intersection.empty())
2073       continue;
2074 
2075     // If RC1 and RC2 have different spill sizes or alignments, use the
2076     // stricter one for sub-classing.  If they are equal, prefer RC1.
2077     if (RC2->RSI.hasStricterSpillThan(RC1->RSI))
2078       std::swap(RC1, RC2);
2079 
2080     getOrCreateSubClass(RC1, &Intersection,
2081                         RC1->getName() + "_and_" + RC2->getName());
2082   }
2083 }
2084 
2085 //
2086 // Synthesize missing sub-classes for getSubClassWithSubReg().
2087 //
2088 // Make sure that the set of registers in RC with a given SubIdx sub-register
2089 // form a register class.  Update RC->SubClassWithSubReg.
2090 //
2091 void CodeGenRegBank::inferSubClassWithSubReg(CodeGenRegisterClass *RC) {
2092   // Map SubRegIndex to set of registers in RC supporting that SubRegIndex.
2093   typedef std::map<const CodeGenSubRegIndex *, CodeGenRegister::Vec,
2094                    deref<llvm::less>> SubReg2SetMap;
2095 
2096   // Compute the set of registers supporting each SubRegIndex.
2097   SubReg2SetMap SRSets;
2098   for (const auto R : RC->getMembers()) {
2099     if (R->Artificial)
2100       continue;
2101     const CodeGenRegister::SubRegMap &SRM = R->getSubRegs();
2102     for (CodeGenRegister::SubRegMap::const_iterator I = SRM.begin(),
2103          E = SRM.end(); I != E; ++I) {
2104       if (!I->first->Artificial)
2105         SRSets[I->first].push_back(R);
2106     }
2107   }
2108 
2109   for (auto I : SRSets)
2110     sortAndUniqueRegisters(I.second);
2111 
2112   // Find matching classes for all SRSets entries.  Iterate in SubRegIndex
2113   // numerical order to visit synthetic indices last.
2114   for (const auto &SubIdx : SubRegIndices) {
2115     if (SubIdx.Artificial)
2116       continue;
2117     SubReg2SetMap::const_iterator I = SRSets.find(&SubIdx);
2118     // Unsupported SubRegIndex. Skip it.
2119     if (I == SRSets.end())
2120       continue;
2121     // In most cases, all RC registers support the SubRegIndex.
2122     if (I->second.size() == RC->getMembers().size()) {
2123       RC->setSubClassWithSubReg(&SubIdx, RC);
2124       continue;
2125     }
2126     // This is a real subset.  See if we have a matching class.
2127     CodeGenRegisterClass *SubRC =
2128       getOrCreateSubClass(RC, &I->second,
2129                           RC->getName() + "_with_" + I->first->getName());
2130     RC->setSubClassWithSubReg(&SubIdx, SubRC);
2131   }
2132 }
2133 
2134 //
2135 // Synthesize missing sub-classes of RC for getMatchingSuperRegClass().
2136 //
2137 // Create sub-classes of RC such that getMatchingSuperRegClass(RC, SubIdx, X)
2138 // has a maximal result for any SubIdx and any X >= FirstSubRegRC.
2139 //
2140 
2141 void CodeGenRegBank::inferMatchingSuperRegClass(CodeGenRegisterClass *RC,
2142                                                 std::list<CodeGenRegisterClass>::iterator FirstSubRegRC) {
2143   SmallVector<std::pair<const CodeGenRegister*,
2144                         const CodeGenRegister*>, 16> SSPairs;
2145   BitVector TopoSigs(getNumTopoSigs());
2146 
2147   // Iterate in SubRegIndex numerical order to visit synthetic indices last.
2148   for (auto &SubIdx : SubRegIndices) {
2149     // Skip indexes that aren't fully supported by RC's registers. This was
2150     // computed by inferSubClassWithSubReg() above which should have been
2151     // called first.
2152     if (RC->getSubClassWithSubReg(&SubIdx) != RC)
2153       continue;
2154 
2155     // Build list of (Super, Sub) pairs for this SubIdx.
2156     SSPairs.clear();
2157     TopoSigs.reset();
2158     for (const auto Super : RC->getMembers()) {
2159       const CodeGenRegister *Sub = Super->getSubRegs().find(&SubIdx)->second;
2160       assert(Sub && "Missing sub-register");
2161       SSPairs.push_back(std::make_pair(Super, Sub));
2162       TopoSigs.set(Sub->getTopoSig());
2163     }
2164 
2165     // Iterate over sub-register class candidates.  Ignore classes created by
2166     // this loop. They will never be useful.
2167     // Store an iterator to the last element (not end) so that this loop doesn't
2168     // visit newly inserted elements.
2169     assert(!RegClasses.empty());
2170     for (auto I = FirstSubRegRC, E = std::prev(RegClasses.end());
2171          I != std::next(E); ++I) {
2172       CodeGenRegisterClass &SubRC = *I;
2173       // Topological shortcut: SubRC members have the wrong shape.
2174       if (!TopoSigs.anyCommon(SubRC.getTopoSigs()))
2175         continue;
2176       // Compute the subset of RC that maps into SubRC.
2177       CodeGenRegister::Vec SubSetVec;
2178       for (unsigned i = 0, e = SSPairs.size(); i != e; ++i)
2179         if (SubRC.contains(SSPairs[i].second))
2180           SubSetVec.push_back(SSPairs[i].first);
2181 
2182       if (SubSetVec.empty())
2183         continue;
2184 
2185       // RC injects completely into SubRC.
2186       sortAndUniqueRegisters(SubSetVec);
2187       if (SubSetVec.size() == SSPairs.size()) {
2188         SubRC.addSuperRegClass(&SubIdx, RC);
2189         continue;
2190       }
2191 
2192       // Only a subset of RC maps into SubRC. Make sure it is represented by a
2193       // class.
2194       getOrCreateSubClass(RC, &SubSetVec, RC->getName() + "_with_" +
2195                                           SubIdx.getName() + "_in_" +
2196                                           SubRC.getName());
2197     }
2198   }
2199 }
2200 
2201 //
2202 // Infer missing register classes.
2203 //
2204 void CodeGenRegBank::computeInferredRegisterClasses() {
2205   assert(!RegClasses.empty());
2206   // When this function is called, the register classes have not been sorted
2207   // and assigned EnumValues yet.  That means getSubClasses(),
2208   // getSuperClasses(), and hasSubClass() functions are defunct.
2209 
2210   // Use one-before-the-end so it doesn't move forward when new elements are
2211   // added.
2212   auto FirstNewRC = std::prev(RegClasses.end());
2213 
2214   // Visit all register classes, including the ones being added by the loop.
2215   // Watch out for iterator invalidation here.
2216   for (auto I = RegClasses.begin(), E = RegClasses.end(); I != E; ++I) {
2217     CodeGenRegisterClass *RC = &*I;
2218     if (RC->Artificial)
2219       continue;
2220 
2221     // Synthesize answers for getSubClassWithSubReg().
2222     inferSubClassWithSubReg(RC);
2223 
2224     // Synthesize answers for getCommonSubClass().
2225     inferCommonSubClass(RC);
2226 
2227     // Synthesize answers for getMatchingSuperRegClass().
2228     inferMatchingSuperRegClass(RC);
2229 
2230     // New register classes are created while this loop is running, and we need
2231     // to visit all of them.  I  particular, inferMatchingSuperRegClass needs
2232     // to match old super-register classes with sub-register classes created
2233     // after inferMatchingSuperRegClass was called.  At this point,
2234     // inferMatchingSuperRegClass has checked SuperRC = [0..rci] with SubRC =
2235     // [0..FirstNewRC).  We need to cover SubRC = [FirstNewRC..rci].
2236     if (I == FirstNewRC) {
2237       auto NextNewRC = std::prev(RegClasses.end());
2238       for (auto I2 = RegClasses.begin(), E2 = std::next(FirstNewRC); I2 != E2;
2239            ++I2)
2240         inferMatchingSuperRegClass(&*I2, E2);
2241       FirstNewRC = NextNewRC;
2242     }
2243   }
2244 }
2245 
2246 /// getRegisterClassForRegister - Find the register class that contains the
2247 /// specified physical register.  If the register is not in a register class,
2248 /// return null. If the register is in multiple classes, and the classes have a
2249 /// superset-subset relationship and the same set of types, return the
2250 /// superclass.  Otherwise return null.
2251 const CodeGenRegisterClass*
2252 CodeGenRegBank::getRegClassForRegister(Record *R) {
2253   const CodeGenRegister *Reg = getReg(R);
2254   const CodeGenRegisterClass *FoundRC = nullptr;
2255   for (const auto &RC : getRegClasses()) {
2256     if (!RC.contains(Reg))
2257       continue;
2258 
2259     // If this is the first class that contains the register,
2260     // make a note of it and go on to the next class.
2261     if (!FoundRC) {
2262       FoundRC = &RC;
2263       continue;
2264     }
2265 
2266     // If a register's classes have different types, return null.
2267     if (RC.getValueTypes() != FoundRC->getValueTypes())
2268       return nullptr;
2269 
2270     // Check to see if the previously found class that contains
2271     // the register is a subclass of the current class. If so,
2272     // prefer the superclass.
2273     if (RC.hasSubClass(FoundRC)) {
2274       FoundRC = &RC;
2275       continue;
2276     }
2277 
2278     // Check to see if the previously found class that contains
2279     // the register is a superclass of the current class. If so,
2280     // prefer the superclass.
2281     if (FoundRC->hasSubClass(&RC))
2282       continue;
2283 
2284     // Multiple classes, and neither is a superclass of the other.
2285     // Return null.
2286     return nullptr;
2287   }
2288   return FoundRC;
2289 }
2290 
2291 BitVector CodeGenRegBank::computeCoveredRegisters(ArrayRef<Record*> Regs) {
2292   SetVector<const CodeGenRegister*> Set;
2293 
2294   // First add Regs with all sub-registers.
2295   for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
2296     CodeGenRegister *Reg = getReg(Regs[i]);
2297     if (Set.insert(Reg))
2298       // Reg is new, add all sub-registers.
2299       // The pre-ordering is not important here.
2300       Reg->addSubRegsPreOrder(Set, *this);
2301   }
2302 
2303   // Second, find all super-registers that are completely covered by the set.
2304   for (unsigned i = 0; i != Set.size(); ++i) {
2305     const CodeGenRegister::SuperRegList &SR = Set[i]->getSuperRegs();
2306     for (unsigned j = 0, e = SR.size(); j != e; ++j) {
2307       const CodeGenRegister *Super = SR[j];
2308       if (!Super->CoveredBySubRegs || Set.count(Super))
2309         continue;
2310       // This new super-register is covered by its sub-registers.
2311       bool AllSubsInSet = true;
2312       const CodeGenRegister::SubRegMap &SRM = Super->getSubRegs();
2313       for (CodeGenRegister::SubRegMap::const_iterator I = SRM.begin(),
2314              E = SRM.end(); I != E; ++I)
2315         if (!Set.count(I->second)) {
2316           AllSubsInSet = false;
2317           break;
2318         }
2319       // All sub-registers in Set, add Super as well.
2320       // We will visit Super later to recheck its super-registers.
2321       if (AllSubsInSet)
2322         Set.insert(Super);
2323     }
2324   }
2325 
2326   // Convert to BitVector.
2327   BitVector BV(Registers.size() + 1);
2328   for (unsigned i = 0, e = Set.size(); i != e; ++i)
2329     BV.set(Set[i]->EnumValue);
2330   return BV;
2331 }
2332 
2333 void CodeGenRegBank::printRegUnitName(unsigned Unit) const {
2334   if (Unit < NumNativeRegUnits)
2335     dbgs() << ' ' << RegUnits[Unit].Roots[0]->getName();
2336   else
2337     dbgs() << " #" << Unit;
2338 }
2339