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   // Reference to SynthDefs in the containing CodeGenRegBank, to keep track of
609   // the synthesized definitions for their lifetime.
610   std::vector<std::unique_ptr<Record>> &SynthDefs;
611 
612   TupleExpander(std::vector<std::unique_ptr<Record>> &SynthDefs)
613       : SynthDefs(SynthDefs) {}
614 
615   void expand(SetTheory &ST, Record *Def, SetTheory::RecSet &Elts) override {
616     std::vector<Record*> Indices = Def->getValueAsListOfDefs("SubRegIndices");
617     unsigned Dim = Indices.size();
618     ListInit *SubRegs = Def->getValueAsListInit("SubRegs");
619     if (Dim != SubRegs->size())
620       PrintFatalError(Def->getLoc(), "SubRegIndices and SubRegs size mismatch");
621     if (Dim < 2)
622       PrintFatalError(Def->getLoc(),
623                       "Tuples must have at least 2 sub-registers");
624 
625     // Evaluate the sub-register lists to be zipped.
626     unsigned Length = ~0u;
627     SmallVector<SetTheory::RecSet, 4> Lists(Dim);
628     for (unsigned i = 0; i != Dim; ++i) {
629       ST.evaluate(SubRegs->getElement(i), Lists[i], Def->getLoc());
630       Length = std::min(Length, unsigned(Lists[i].size()));
631     }
632 
633     if (Length == 0)
634       return;
635 
636     // Precompute some types.
637     Record *RegisterCl = Def->getRecords().getClass("Register");
638     RecTy *RegisterRecTy = RecordRecTy::get(RegisterCl);
639     StringInit *BlankName = StringInit::get("");
640 
641     // Zip them up.
642     for (unsigned n = 0; n != Length; ++n) {
643       std::string Name;
644       Record *Proto = Lists[0][n];
645       std::vector<Init*> Tuple;
646       unsigned CostPerUse = 0;
647       for (unsigned i = 0; i != Dim; ++i) {
648         Record *Reg = Lists[i][n];
649         if (i) Name += '_';
650         Name += Reg->getName();
651         Tuple.push_back(DefInit::get(Reg));
652         CostPerUse = std::max(CostPerUse,
653                               unsigned(Reg->getValueAsInt("CostPerUse")));
654       }
655 
656       // Create a new Record representing the synthesized register. This record
657       // is only for consumption by CodeGenRegister, it is not added to the
658       // RecordKeeper.
659       SynthDefs.emplace_back(
660           llvm::make_unique<Record>(Name, Def->getLoc(), Def->getRecords()));
661       Record *NewReg = SynthDefs.back().get();
662       Elts.insert(NewReg);
663 
664       // Copy Proto super-classes.
665       ArrayRef<std::pair<Record *, SMRange>> Supers = Proto->getSuperClasses();
666       for (const auto &SuperPair : Supers)
667         NewReg->addSuperClass(SuperPair.first, SuperPair.second);
668 
669       // Copy Proto fields.
670       for (unsigned i = 0, e = Proto->getValues().size(); i != e; ++i) {
671         RecordVal RV = Proto->getValues()[i];
672 
673         // Skip existing fields, like NAME.
674         if (NewReg->getValue(RV.getNameInit()))
675           continue;
676 
677         StringRef Field = RV.getName();
678 
679         // Replace the sub-register list with Tuple.
680         if (Field == "SubRegs")
681           RV.setValue(ListInit::get(Tuple, RegisterRecTy));
682 
683         // Provide a blank AsmName. MC hacks are required anyway.
684         if (Field == "AsmName")
685           RV.setValue(BlankName);
686 
687         // CostPerUse is aggregated from all Tuple members.
688         if (Field == "CostPerUse")
689           RV.setValue(IntInit::get(CostPerUse));
690 
691         // Composite registers are always covered by sub-registers.
692         if (Field == "CoveredBySubRegs")
693           RV.setValue(BitInit::get(true));
694 
695         // Copy fields from the RegisterTuples def.
696         if (Field == "SubRegIndices" ||
697             Field == "CompositeIndices") {
698           NewReg->addValue(*Def->getValue(Field));
699           continue;
700         }
701 
702         // Some fields get their default uninitialized value.
703         if (Field == "DwarfNumbers" ||
704             Field == "DwarfAlias" ||
705             Field == "Aliases") {
706           if (const RecordVal *DefRV = RegisterCl->getValue(Field))
707             NewReg->addValue(*DefRV);
708           continue;
709         }
710 
711         // Everything else is copied from Proto.
712         NewReg->addValue(RV);
713       }
714     }
715   }
716 };
717 
718 } // end anonymous namespace
719 
720 //===----------------------------------------------------------------------===//
721 //                            CodeGenRegisterClass
722 //===----------------------------------------------------------------------===//
723 
724 static void sortAndUniqueRegisters(CodeGenRegister::Vec &M) {
725   llvm::sort(M.begin(), M.end(), deref<llvm::less>());
726   M.erase(std::unique(M.begin(), M.end(), deref<llvm::equal>()), M.end());
727 }
728 
729 CodeGenRegisterClass::CodeGenRegisterClass(CodeGenRegBank &RegBank, Record *R)
730   : TheDef(R),
731     Name(R->getName()),
732     TopoSigs(RegBank.getNumTopoSigs()),
733     EnumValue(-1) {
734 
735   std::vector<Record*> TypeList = R->getValueAsListOfDefs("RegTypes");
736   for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
737     Record *Type = TypeList[i];
738     if (!Type->isSubClassOf("ValueType"))
739       PrintFatalError("RegTypes list member '" + Type->getName() +
740         "' does not derive from the ValueType class!");
741     VTs.push_back(getValueTypeByHwMode(Type, RegBank.getHwModes()));
742   }
743   assert(!VTs.empty() && "RegisterClass must contain at least one ValueType!");
744 
745   // Allocation order 0 is the full set. AltOrders provides others.
746   const SetTheory::RecVec *Elements = RegBank.getSets().expand(R);
747   ListInit *AltOrders = R->getValueAsListInit("AltOrders");
748   Orders.resize(1 + AltOrders->size());
749 
750   // Default allocation order always contains all registers.
751   Artificial = true;
752   for (unsigned i = 0, e = Elements->size(); i != e; ++i) {
753     Orders[0].push_back((*Elements)[i]);
754     const CodeGenRegister *Reg = RegBank.getReg((*Elements)[i]);
755     Members.push_back(Reg);
756     Artificial &= Reg->Artificial;
757     TopoSigs.set(Reg->getTopoSig());
758   }
759   sortAndUniqueRegisters(Members);
760 
761   // Alternative allocation orders may be subsets.
762   SetTheory::RecSet Order;
763   for (unsigned i = 0, e = AltOrders->size(); i != e; ++i) {
764     RegBank.getSets().evaluate(AltOrders->getElement(i), Order, R->getLoc());
765     Orders[1 + i].append(Order.begin(), Order.end());
766     // Verify that all altorder members are regclass members.
767     while (!Order.empty()) {
768       CodeGenRegister *Reg = RegBank.getReg(Order.back());
769       Order.pop_back();
770       if (!contains(Reg))
771         PrintFatalError(R->getLoc(), " AltOrder register " + Reg->getName() +
772                       " is not a class member");
773     }
774   }
775 
776   Namespace = R->getValueAsString("Namespace");
777 
778   if (const RecordVal *RV = R->getValue("RegInfos"))
779     if (DefInit *DI = dyn_cast_or_null<DefInit>(RV->getValue()))
780       RSI = RegSizeInfoByHwMode(DI->getDef(), RegBank.getHwModes());
781   unsigned Size = R->getValueAsInt("Size");
782   assert((RSI.hasDefault() || Size != 0 || VTs[0].isSimple()) &&
783          "Impossible to determine register size");
784   if (!RSI.hasDefault()) {
785     RegSizeInfo RI;
786     RI.RegSize = RI.SpillSize = Size ? Size
787                                      : VTs[0].getSimple().getSizeInBits();
788     RI.SpillAlignment = R->getValueAsInt("Alignment");
789     RSI.Map.insert({DefaultMode, RI});
790   }
791 
792   CopyCost = R->getValueAsInt("CopyCost");
793   Allocatable = R->getValueAsBit("isAllocatable");
794   AltOrderSelect = R->getValueAsString("AltOrderSelect");
795   int AllocationPriority = R->getValueAsInt("AllocationPriority");
796   if (AllocationPriority < 0 || AllocationPriority > 63)
797     PrintFatalError(R->getLoc(), "AllocationPriority out of range [0,63]");
798   this->AllocationPriority = AllocationPriority;
799 }
800 
801 // Create an inferred register class that was missing from the .td files.
802 // Most properties will be inherited from the closest super-class after the
803 // class structure has been computed.
804 CodeGenRegisterClass::CodeGenRegisterClass(CodeGenRegBank &RegBank,
805                                            StringRef Name, Key Props)
806   : Members(*Props.Members),
807     TheDef(nullptr),
808     Name(Name),
809     TopoSigs(RegBank.getNumTopoSigs()),
810     EnumValue(-1),
811     RSI(Props.RSI),
812     CopyCost(0),
813     Allocatable(true),
814     AllocationPriority(0) {
815   Artificial = true;
816   for (const auto R : Members) {
817     TopoSigs.set(R->getTopoSig());
818     Artificial &= R->Artificial;
819   }
820 }
821 
822 // Compute inherited propertied for a synthesized register class.
823 void CodeGenRegisterClass::inheritProperties(CodeGenRegBank &RegBank) {
824   assert(!getDef() && "Only synthesized classes can inherit properties");
825   assert(!SuperClasses.empty() && "Synthesized class without super class");
826 
827   // The last super-class is the smallest one.
828   CodeGenRegisterClass &Super = *SuperClasses.back();
829 
830   // Most properties are copied directly.
831   // Exceptions are members, size, and alignment
832   Namespace = Super.Namespace;
833   VTs = Super.VTs;
834   CopyCost = Super.CopyCost;
835   Allocatable = Super.Allocatable;
836   AltOrderSelect = Super.AltOrderSelect;
837   AllocationPriority = Super.AllocationPriority;
838 
839   // Copy all allocation orders, filter out foreign registers from the larger
840   // super-class.
841   Orders.resize(Super.Orders.size());
842   for (unsigned i = 0, ie = Super.Orders.size(); i != ie; ++i)
843     for (unsigned j = 0, je = Super.Orders[i].size(); j != je; ++j)
844       if (contains(RegBank.getReg(Super.Orders[i][j])))
845         Orders[i].push_back(Super.Orders[i][j]);
846 }
847 
848 bool CodeGenRegisterClass::contains(const CodeGenRegister *Reg) const {
849   return std::binary_search(Members.begin(), Members.end(), Reg,
850                             deref<llvm::less>());
851 }
852 
853 namespace llvm {
854 
855   raw_ostream &operator<<(raw_ostream &OS, const CodeGenRegisterClass::Key &K) {
856     OS << "{ " << K.RSI;
857     for (const auto R : *K.Members)
858       OS << ", " << R->getName();
859     return OS << " }";
860   }
861 
862 } // end namespace llvm
863 
864 // This is a simple lexicographical order that can be used to search for sets.
865 // It is not the same as the topological order provided by TopoOrderRC.
866 bool CodeGenRegisterClass::Key::
867 operator<(const CodeGenRegisterClass::Key &B) const {
868   assert(Members && B.Members);
869   return std::tie(*Members, RSI) < std::tie(*B.Members, B.RSI);
870 }
871 
872 // Returns true if RC is a strict subclass.
873 // RC is a sub-class of this class if it is a valid replacement for any
874 // instruction operand where a register of this classis required. It must
875 // satisfy these conditions:
876 //
877 // 1. All RC registers are also in this.
878 // 2. The RC spill size must not be smaller than our spill size.
879 // 3. RC spill alignment must be compatible with ours.
880 //
881 static bool testSubClass(const CodeGenRegisterClass *A,
882                          const CodeGenRegisterClass *B) {
883   return A->RSI.isSubClassOf(B->RSI) &&
884          std::includes(A->getMembers().begin(), A->getMembers().end(),
885                        B->getMembers().begin(), B->getMembers().end(),
886                        deref<llvm::less>());
887 }
888 
889 /// Sorting predicate for register classes.  This provides a topological
890 /// ordering that arranges all register classes before their sub-classes.
891 ///
892 /// Register classes with the same registers, spill size, and alignment form a
893 /// clique.  They will be ordered alphabetically.
894 ///
895 static bool TopoOrderRC(const CodeGenRegisterClass &PA,
896                         const CodeGenRegisterClass &PB) {
897   auto *A = &PA;
898   auto *B = &PB;
899   if (A == B)
900     return false;
901 
902   if (A->RSI < B->RSI)
903     return true;
904   if (A->RSI != B->RSI)
905     return false;
906 
907   // Order by descending set size.  Note that the classes' allocation order may
908   // not have been computed yet.  The Members set is always vaild.
909   if (A->getMembers().size() > B->getMembers().size())
910     return true;
911   if (A->getMembers().size() < B->getMembers().size())
912     return false;
913 
914   // Finally order by name as a tie breaker.
915   return StringRef(A->getName()) < B->getName();
916 }
917 
918 std::string CodeGenRegisterClass::getQualifiedName() const {
919   if (Namespace.empty())
920     return getName();
921   else
922     return (Namespace + "::" + getName()).str();
923 }
924 
925 // Compute sub-classes of all register classes.
926 // Assume the classes are ordered topologically.
927 void CodeGenRegisterClass::computeSubClasses(CodeGenRegBank &RegBank) {
928   auto &RegClasses = RegBank.getRegClasses();
929 
930   // Visit backwards so sub-classes are seen first.
931   for (auto I = RegClasses.rbegin(), E = RegClasses.rend(); I != E; ++I) {
932     CodeGenRegisterClass &RC = *I;
933     RC.SubClasses.resize(RegClasses.size());
934     RC.SubClasses.set(RC.EnumValue);
935     if (RC.Artificial)
936       continue;
937 
938     // Normally, all subclasses have IDs >= rci, unless RC is part of a clique.
939     for (auto I2 = I.base(), E2 = RegClasses.end(); I2 != E2; ++I2) {
940       CodeGenRegisterClass &SubRC = *I2;
941       if (RC.SubClasses.test(SubRC.EnumValue))
942         continue;
943       if (!testSubClass(&RC, &SubRC))
944         continue;
945       // SubRC is a sub-class. Grap all its sub-classes so we won't have to
946       // check them again.
947       RC.SubClasses |= SubRC.SubClasses;
948     }
949 
950     // Sweep up missed clique members.  They will be immediately preceding RC.
951     for (auto I2 = std::next(I); I2 != E && testSubClass(&RC, &*I2); ++I2)
952       RC.SubClasses.set(I2->EnumValue);
953   }
954 
955   // Compute the SuperClasses lists from the SubClasses vectors.
956   for (auto &RC : RegClasses) {
957     const BitVector &SC = RC.getSubClasses();
958     auto I = RegClasses.begin();
959     for (int s = 0, next_s = SC.find_first(); next_s != -1;
960          next_s = SC.find_next(s)) {
961       std::advance(I, next_s - s);
962       s = next_s;
963       if (&*I == &RC)
964         continue;
965       I->SuperClasses.push_back(&RC);
966     }
967   }
968 
969   // With the class hierarchy in place, let synthesized register classes inherit
970   // properties from their closest super-class. The iteration order here can
971   // propagate properties down multiple levels.
972   for (auto &RC : RegClasses)
973     if (!RC.getDef())
974       RC.inheritProperties(RegBank);
975 }
976 
977 Optional<std::pair<CodeGenRegisterClass *, CodeGenRegisterClass *>>
978 CodeGenRegisterClass::getMatchingSubClassWithSubRegs(
979     CodeGenRegBank &RegBank, const CodeGenSubRegIndex *SubIdx) const {
980   auto SizeOrder = [](const CodeGenRegisterClass *A,
981                       const CodeGenRegisterClass *B) {
982     return A->getMembers().size() > B->getMembers().size();
983   };
984 
985   auto &RegClasses = RegBank.getRegClasses();
986 
987   // Find all the subclasses of this one that fully support the sub-register
988   // index and order them by size. BiggestSuperRC should always be first.
989   CodeGenRegisterClass *BiggestSuperRegRC = getSubClassWithSubReg(SubIdx);
990   if (!BiggestSuperRegRC)
991     return None;
992   BitVector SuperRegRCsBV = BiggestSuperRegRC->getSubClasses();
993   std::vector<CodeGenRegisterClass *> SuperRegRCs;
994   for (auto &RC : RegClasses)
995     if (SuperRegRCsBV[RC.EnumValue])
996       SuperRegRCs.emplace_back(&RC);
997   llvm::sort(SuperRegRCs.begin(), SuperRegRCs.end(), SizeOrder);
998   assert(SuperRegRCs.front() == BiggestSuperRegRC && "Biggest class wasn't first");
999 
1000   // Find all the subreg classes and order them by size too.
1001   std::vector<std::pair<CodeGenRegisterClass *, BitVector>> SuperRegClasses;
1002   for (auto &RC: RegClasses) {
1003     BitVector SuperRegClassesBV(RegClasses.size());
1004     RC.getSuperRegClasses(SubIdx, SuperRegClassesBV);
1005     if (SuperRegClassesBV.any())
1006       SuperRegClasses.push_back(std::make_pair(&RC, SuperRegClassesBV));
1007   }
1008   llvm::sort(SuperRegClasses.begin(), SuperRegClasses.end(),
1009              [&](const std::pair<CodeGenRegisterClass *, BitVector> &A,
1010                  const std::pair<CodeGenRegisterClass *, BitVector> &B) {
1011                return SizeOrder(A.first, B.first);
1012              });
1013 
1014   // Find the biggest subclass and subreg class such that R:subidx is in the
1015   // subreg class for all R in subclass.
1016   //
1017   // For example:
1018   // All registers in X86's GR64 have a sub_32bit subregister but no class
1019   // exists that contains all the 32-bit subregisters because GR64 contains RIP
1020   // but GR32 does not contain EIP. Instead, we constrain SuperRegRC to
1021   // GR32_with_sub_8bit (which is identical to GR32_with_sub_32bit) and then,
1022   // having excluded RIP, we are able to find a SubRegRC (GR32).
1023   CodeGenRegisterClass *ChosenSuperRegClass = nullptr;
1024   CodeGenRegisterClass *SubRegRC = nullptr;
1025   for (auto *SuperRegRC : SuperRegRCs) {
1026     for (const auto &SuperRegClassPair : SuperRegClasses) {
1027       const BitVector &SuperRegClassBV = SuperRegClassPair.second;
1028       if (SuperRegClassBV[SuperRegRC->EnumValue]) {
1029         SubRegRC = SuperRegClassPair.first;
1030         ChosenSuperRegClass = SuperRegRC;
1031 
1032         // If SubRegRC is bigger than SuperRegRC then there are members of
1033         // SubRegRC that don't have super registers via SubIdx. Keep looking to
1034         // find a better fit and fall back on this one if there isn't one.
1035         //
1036         // This is intended to prevent X86 from making odd choices such as
1037         // picking LOW32_ADDR_ACCESS_RBP instead of GR32 in the example above.
1038         // LOW32_ADDR_ACCESS_RBP is a valid choice but contains registers that
1039         // aren't subregisters of SuperRegRC whereas GR32 has a direct 1:1
1040         // mapping.
1041         if (SuperRegRC->getMembers().size() >= SubRegRC->getMembers().size())
1042           return std::make_pair(ChosenSuperRegClass, SubRegRC);
1043       }
1044     }
1045 
1046     // If we found a fit but it wasn't quite ideal because SubRegRC had excess
1047     // registers, then we're done.
1048     if (ChosenSuperRegClass)
1049       return std::make_pair(ChosenSuperRegClass, SubRegRC);
1050   }
1051 
1052   return None;
1053 }
1054 
1055 void CodeGenRegisterClass::getSuperRegClasses(const CodeGenSubRegIndex *SubIdx,
1056                                               BitVector &Out) const {
1057   auto FindI = SuperRegClasses.find(SubIdx);
1058   if (FindI == SuperRegClasses.end())
1059     return;
1060   for (CodeGenRegisterClass *RC : FindI->second)
1061     Out.set(RC->EnumValue);
1062 }
1063 
1064 // Populate a unique sorted list of units from a register set.
1065 void CodeGenRegisterClass::buildRegUnitSet(const CodeGenRegBank &RegBank,
1066   std::vector<unsigned> &RegUnits) const {
1067   std::vector<unsigned> TmpUnits;
1068   for (RegUnitIterator UnitI(Members); UnitI.isValid(); ++UnitI) {
1069     const RegUnit &RU = RegBank.getRegUnit(*UnitI);
1070     if (!RU.Artificial)
1071       TmpUnits.push_back(*UnitI);
1072   }
1073   llvm::sort(TmpUnits.begin(), TmpUnits.end());
1074   std::unique_copy(TmpUnits.begin(), TmpUnits.end(),
1075                    std::back_inserter(RegUnits));
1076 }
1077 
1078 //===----------------------------------------------------------------------===//
1079 //                               CodeGenRegBank
1080 //===----------------------------------------------------------------------===//
1081 
1082 CodeGenRegBank::CodeGenRegBank(RecordKeeper &Records,
1083                                const CodeGenHwModes &Modes) : CGH(Modes) {
1084   // Configure register Sets to understand register classes and tuples.
1085   Sets.addFieldExpander("RegisterClass", "MemberList");
1086   Sets.addFieldExpander("CalleeSavedRegs", "SaveList");
1087   Sets.addExpander("RegisterTuples",
1088                    llvm::make_unique<TupleExpander>(SynthDefs));
1089 
1090   // Read in the user-defined (named) sub-register indices.
1091   // More indices will be synthesized later.
1092   std::vector<Record*> SRIs = Records.getAllDerivedDefinitions("SubRegIndex");
1093   llvm::sort(SRIs.begin(), SRIs.end(), LessRecord());
1094   for (unsigned i = 0, e = SRIs.size(); i != e; ++i)
1095     getSubRegIdx(SRIs[i]);
1096   // Build composite maps from ComposedOf fields.
1097   for (auto &Idx : SubRegIndices)
1098     Idx.updateComponents(*this);
1099 
1100   // Read in the register definitions.
1101   std::vector<Record*> Regs = Records.getAllDerivedDefinitions("Register");
1102   llvm::sort(Regs.begin(), Regs.end(), LessRecordRegister());
1103   // Assign the enumeration values.
1104   for (unsigned i = 0, e = Regs.size(); i != e; ++i)
1105     getReg(Regs[i]);
1106 
1107   // Expand tuples and number the new registers.
1108   std::vector<Record*> Tups =
1109     Records.getAllDerivedDefinitions("RegisterTuples");
1110 
1111   for (Record *R : Tups) {
1112     std::vector<Record *> TupRegs = *Sets.expand(R);
1113     llvm::sort(TupRegs.begin(), TupRegs.end(), LessRecordRegister());
1114     for (Record *RC : TupRegs)
1115       getReg(RC);
1116   }
1117 
1118   // Now all the registers are known. Build the object graph of explicit
1119   // register-register references.
1120   for (auto &Reg : Registers)
1121     Reg.buildObjectGraph(*this);
1122 
1123   // Compute register name map.
1124   for (auto &Reg : Registers)
1125     // FIXME: This could just be RegistersByName[name] = register, except that
1126     // causes some failures in MIPS - perhaps they have duplicate register name
1127     // entries? (or maybe there's a reason for it - I don't know much about this
1128     // code, just drive-by refactoring)
1129     RegistersByName.insert(
1130         std::make_pair(Reg.TheDef->getValueAsString("AsmName"), &Reg));
1131 
1132   // Precompute all sub-register maps.
1133   // This will create Composite entries for all inferred sub-register indices.
1134   for (auto &Reg : Registers)
1135     Reg.computeSubRegs(*this);
1136 
1137   // Compute transitive closure of subregister index ConcatenationOf vectors
1138   // and initialize ConcatIdx map.
1139   for (CodeGenSubRegIndex &SRI : SubRegIndices) {
1140     SRI.computeConcatTransitiveClosure();
1141     if (!SRI.ConcatenationOf.empty())
1142       ConcatIdx.insert(std::make_pair(
1143           SmallVector<CodeGenSubRegIndex*,8>(SRI.ConcatenationOf.begin(),
1144                                              SRI.ConcatenationOf.end()), &SRI));
1145   }
1146 
1147   // Infer even more sub-registers by combining leading super-registers.
1148   for (auto &Reg : Registers)
1149     if (Reg.CoveredBySubRegs)
1150       Reg.computeSecondarySubRegs(*this);
1151 
1152   // After the sub-register graph is complete, compute the topologically
1153   // ordered SuperRegs list.
1154   for (auto &Reg : Registers)
1155     Reg.computeSuperRegs(*this);
1156 
1157   // For each pair of Reg:SR, if both are non-artificial, mark the
1158   // corresponding sub-register index as non-artificial.
1159   for (auto &Reg : Registers) {
1160     if (Reg.Artificial)
1161       continue;
1162     for (auto P : Reg.getSubRegs()) {
1163       const CodeGenRegister *SR = P.second;
1164       if (!SR->Artificial)
1165         P.first->Artificial = false;
1166     }
1167   }
1168 
1169   // Native register units are associated with a leaf register. They've all been
1170   // discovered now.
1171   NumNativeRegUnits = RegUnits.size();
1172 
1173   // Read in register class definitions.
1174   std::vector<Record*> RCs = Records.getAllDerivedDefinitions("RegisterClass");
1175   if (RCs.empty())
1176     PrintFatalError("No 'RegisterClass' subclasses defined!");
1177 
1178   // Allocate user-defined register classes.
1179   for (auto *R : RCs) {
1180     RegClasses.emplace_back(*this, R);
1181     CodeGenRegisterClass &RC = RegClasses.back();
1182     if (!RC.Artificial)
1183       addToMaps(&RC);
1184   }
1185 
1186   // Infer missing classes to create a full algebra.
1187   computeInferredRegisterClasses();
1188 
1189   // Order register classes topologically and assign enum values.
1190   RegClasses.sort(TopoOrderRC);
1191   unsigned i = 0;
1192   for (auto &RC : RegClasses)
1193     RC.EnumValue = i++;
1194   CodeGenRegisterClass::computeSubClasses(*this);
1195 }
1196 
1197 // Create a synthetic CodeGenSubRegIndex without a corresponding Record.
1198 CodeGenSubRegIndex*
1199 CodeGenRegBank::createSubRegIndex(StringRef Name, StringRef Namespace) {
1200   SubRegIndices.emplace_back(Name, Namespace, SubRegIndices.size() + 1);
1201   return &SubRegIndices.back();
1202 }
1203 
1204 CodeGenSubRegIndex *CodeGenRegBank::getSubRegIdx(Record *Def) {
1205   CodeGenSubRegIndex *&Idx = Def2SubRegIdx[Def];
1206   if (Idx)
1207     return Idx;
1208   SubRegIndices.emplace_back(Def, SubRegIndices.size() + 1);
1209   Idx = &SubRegIndices.back();
1210   return Idx;
1211 }
1212 
1213 CodeGenRegister *CodeGenRegBank::getReg(Record *Def) {
1214   CodeGenRegister *&Reg = Def2Reg[Def];
1215   if (Reg)
1216     return Reg;
1217   Registers.emplace_back(Def, Registers.size() + 1);
1218   Reg = &Registers.back();
1219   return Reg;
1220 }
1221 
1222 void CodeGenRegBank::addToMaps(CodeGenRegisterClass *RC) {
1223   if (Record *Def = RC->getDef())
1224     Def2RC.insert(std::make_pair(Def, RC));
1225 
1226   // Duplicate classes are rejected by insert().
1227   // That's OK, we only care about the properties handled by CGRC::Key.
1228   CodeGenRegisterClass::Key K(*RC);
1229   Key2RC.insert(std::make_pair(K, RC));
1230 }
1231 
1232 // Create a synthetic sub-class if it is missing.
1233 CodeGenRegisterClass*
1234 CodeGenRegBank::getOrCreateSubClass(const CodeGenRegisterClass *RC,
1235                                     const CodeGenRegister::Vec *Members,
1236                                     StringRef Name) {
1237   // Synthetic sub-class has the same size and alignment as RC.
1238   CodeGenRegisterClass::Key K(Members, RC->RSI);
1239   RCKeyMap::const_iterator FoundI = Key2RC.find(K);
1240   if (FoundI != Key2RC.end())
1241     return FoundI->second;
1242 
1243   // Sub-class doesn't exist, create a new one.
1244   RegClasses.emplace_back(*this, Name, K);
1245   addToMaps(&RegClasses.back());
1246   return &RegClasses.back();
1247 }
1248 
1249 CodeGenRegisterClass *CodeGenRegBank::getRegClass(Record *Def) {
1250   if (CodeGenRegisterClass *RC = Def2RC[Def])
1251     return RC;
1252 
1253   PrintFatalError(Def->getLoc(), "Not a known RegisterClass!");
1254 }
1255 
1256 CodeGenSubRegIndex*
1257 CodeGenRegBank::getCompositeSubRegIndex(CodeGenSubRegIndex *A,
1258                                         CodeGenSubRegIndex *B) {
1259   // Look for an existing entry.
1260   CodeGenSubRegIndex *Comp = A->compose(B);
1261   if (Comp)
1262     return Comp;
1263 
1264   // None exists, synthesize one.
1265   std::string Name = A->getName() + "_then_" + B->getName();
1266   Comp = createSubRegIndex(Name, A->getNamespace());
1267   A->addComposite(B, Comp);
1268   return Comp;
1269 }
1270 
1271 CodeGenSubRegIndex *CodeGenRegBank::
1272 getConcatSubRegIndex(const SmallVector<CodeGenSubRegIndex *, 8> &Parts) {
1273   assert(Parts.size() > 1 && "Need two parts to concatenate");
1274 #ifndef NDEBUG
1275   for (CodeGenSubRegIndex *Idx : Parts) {
1276     assert(Idx->ConcatenationOf.empty() && "No transitive closure?");
1277   }
1278 #endif
1279 
1280   // Look for an existing entry.
1281   CodeGenSubRegIndex *&Idx = ConcatIdx[Parts];
1282   if (Idx)
1283     return Idx;
1284 
1285   // None exists, synthesize one.
1286   std::string Name = Parts.front()->getName();
1287   // Determine whether all parts are contiguous.
1288   bool isContinuous = true;
1289   unsigned Size = Parts.front()->Size;
1290   unsigned LastOffset = Parts.front()->Offset;
1291   unsigned LastSize = Parts.front()->Size;
1292   for (unsigned i = 1, e = Parts.size(); i != e; ++i) {
1293     Name += '_';
1294     Name += Parts[i]->getName();
1295     Size += Parts[i]->Size;
1296     if (Parts[i]->Offset != (LastOffset + LastSize))
1297       isContinuous = false;
1298     LastOffset = Parts[i]->Offset;
1299     LastSize = Parts[i]->Size;
1300   }
1301   Idx = createSubRegIndex(Name, Parts.front()->getNamespace());
1302   Idx->Size = Size;
1303   Idx->Offset = isContinuous ? Parts.front()->Offset : -1;
1304   Idx->ConcatenationOf.assign(Parts.begin(), Parts.end());
1305   return Idx;
1306 }
1307 
1308 void CodeGenRegBank::computeComposites() {
1309   // Keep track of TopoSigs visited. We only need to visit each TopoSig once,
1310   // and many registers will share TopoSigs on regular architectures.
1311   BitVector TopoSigs(getNumTopoSigs());
1312 
1313   for (const auto &Reg1 : Registers) {
1314     // Skip identical subreg structures already processed.
1315     if (TopoSigs.test(Reg1.getTopoSig()))
1316       continue;
1317     TopoSigs.set(Reg1.getTopoSig());
1318 
1319     const CodeGenRegister::SubRegMap &SRM1 = Reg1.getSubRegs();
1320     for (CodeGenRegister::SubRegMap::const_iterator i1 = SRM1.begin(),
1321          e1 = SRM1.end(); i1 != e1; ++i1) {
1322       CodeGenSubRegIndex *Idx1 = i1->first;
1323       CodeGenRegister *Reg2 = i1->second;
1324       // Ignore identity compositions.
1325       if (&Reg1 == Reg2)
1326         continue;
1327       const CodeGenRegister::SubRegMap &SRM2 = Reg2->getSubRegs();
1328       // Try composing Idx1 with another SubRegIndex.
1329       for (CodeGenRegister::SubRegMap::const_iterator i2 = SRM2.begin(),
1330            e2 = SRM2.end(); i2 != e2; ++i2) {
1331         CodeGenSubRegIndex *Idx2 = i2->first;
1332         CodeGenRegister *Reg3 = i2->second;
1333         // Ignore identity compositions.
1334         if (Reg2 == Reg3)
1335           continue;
1336         // OK Reg1:IdxPair == Reg3. Find the index with Reg:Idx == Reg3.
1337         CodeGenSubRegIndex *Idx3 = Reg1.getSubRegIndex(Reg3);
1338         assert(Idx3 && "Sub-register doesn't have an index");
1339 
1340         // Conflicting composition? Emit a warning but allow it.
1341         if (CodeGenSubRegIndex *Prev = Idx1->addComposite(Idx2, Idx3))
1342           PrintWarning(Twine("SubRegIndex ") + Idx1->getQualifiedName() +
1343                        " and " + Idx2->getQualifiedName() +
1344                        " compose ambiguously as " + Prev->getQualifiedName() +
1345                        " or " + Idx3->getQualifiedName());
1346       }
1347     }
1348   }
1349 }
1350 
1351 // Compute lane masks. This is similar to register units, but at the
1352 // sub-register index level. Each bit in the lane mask is like a register unit
1353 // class, and two lane masks will have a bit in common if two sub-register
1354 // indices overlap in some register.
1355 //
1356 // Conservatively share a lane mask bit if two sub-register indices overlap in
1357 // some registers, but not in others. That shouldn't happen a lot.
1358 void CodeGenRegBank::computeSubRegLaneMasks() {
1359   // First assign individual bits to all the leaf indices.
1360   unsigned Bit = 0;
1361   // Determine mask of lanes that cover their registers.
1362   CoveringLanes = LaneBitmask::getAll();
1363   for (auto &Idx : SubRegIndices) {
1364     if (Idx.getComposites().empty()) {
1365       if (Bit > LaneBitmask::BitWidth) {
1366         PrintFatalError(
1367           Twine("Ran out of lanemask bits to represent subregister ")
1368           + Idx.getName());
1369       }
1370       Idx.LaneMask = LaneBitmask::getLane(Bit);
1371       ++Bit;
1372     } else {
1373       Idx.LaneMask = LaneBitmask::getNone();
1374     }
1375   }
1376 
1377   // Compute transformation sequences for composeSubRegIndexLaneMask. The idea
1378   // here is that for each possible target subregister we look at the leafs
1379   // in the subregister graph that compose for this target and create
1380   // transformation sequences for the lanemasks. Each step in the sequence
1381   // consists of a bitmask and a bitrotate operation. As the rotation amounts
1382   // are usually the same for many subregisters we can easily combine the steps
1383   // by combining the masks.
1384   for (const auto &Idx : SubRegIndices) {
1385     const auto &Composites = Idx.getComposites();
1386     auto &LaneTransforms = Idx.CompositionLaneMaskTransform;
1387 
1388     if (Composites.empty()) {
1389       // Moving from a class with no subregisters we just had a single lane:
1390       // The subregister must be a leaf subregister and only occupies 1 bit.
1391       // Move the bit from the class without subregisters into that position.
1392       unsigned DstBit = Idx.LaneMask.getHighestLane();
1393       assert(Idx.LaneMask == LaneBitmask::getLane(DstBit) &&
1394              "Must be a leaf subregister");
1395       MaskRolPair MaskRol = { LaneBitmask::getLane(0), (uint8_t)DstBit };
1396       LaneTransforms.push_back(MaskRol);
1397     } else {
1398       // Go through all leaf subregisters and find the ones that compose with
1399       // Idx. These make out all possible valid bits in the lane mask we want to
1400       // transform. Looking only at the leafs ensure that only a single bit in
1401       // the mask is set.
1402       unsigned NextBit = 0;
1403       for (auto &Idx2 : SubRegIndices) {
1404         // Skip non-leaf subregisters.
1405         if (!Idx2.getComposites().empty())
1406           continue;
1407         // Replicate the behaviour from the lane mask generation loop above.
1408         unsigned SrcBit = NextBit;
1409         LaneBitmask SrcMask = LaneBitmask::getLane(SrcBit);
1410         if (NextBit < LaneBitmask::BitWidth-1)
1411           ++NextBit;
1412         assert(Idx2.LaneMask == SrcMask);
1413 
1414         // Get the composed subregister if there is any.
1415         auto C = Composites.find(&Idx2);
1416         if (C == Composites.end())
1417           continue;
1418         const CodeGenSubRegIndex *Composite = C->second;
1419         // The Composed subreg should be a leaf subreg too
1420         assert(Composite->getComposites().empty());
1421 
1422         // Create Mask+Rotate operation and merge with existing ops if possible.
1423         unsigned DstBit = Composite->LaneMask.getHighestLane();
1424         int Shift = DstBit - SrcBit;
1425         uint8_t RotateLeft = Shift >= 0 ? (uint8_t)Shift
1426                                         : LaneBitmask::BitWidth + Shift;
1427         for (auto &I : LaneTransforms) {
1428           if (I.RotateLeft == RotateLeft) {
1429             I.Mask |= SrcMask;
1430             SrcMask = LaneBitmask::getNone();
1431           }
1432         }
1433         if (SrcMask.any()) {
1434           MaskRolPair MaskRol = { SrcMask, RotateLeft };
1435           LaneTransforms.push_back(MaskRol);
1436         }
1437       }
1438     }
1439 
1440     // Optimize if the transformation consists of one step only: Set mask to
1441     // 0xffffffff (including some irrelevant invalid bits) so that it should
1442     // merge with more entries later while compressing the table.
1443     if (LaneTransforms.size() == 1)
1444       LaneTransforms[0].Mask = LaneBitmask::getAll();
1445 
1446     // Further compression optimization: For invalid compositions resulting
1447     // in a sequence with 0 entries we can just pick any other. Choose
1448     // Mask 0xffffffff with Rotation 0.
1449     if (LaneTransforms.size() == 0) {
1450       MaskRolPair P = { LaneBitmask::getAll(), 0 };
1451       LaneTransforms.push_back(P);
1452     }
1453   }
1454 
1455   // FIXME: What if ad-hoc aliasing introduces overlaps that aren't represented
1456   // by the sub-register graph? This doesn't occur in any known targets.
1457 
1458   // Inherit lanes from composites.
1459   for (const auto &Idx : SubRegIndices) {
1460     LaneBitmask Mask = Idx.computeLaneMask();
1461     // If some super-registers without CoveredBySubRegs use this index, we can
1462     // no longer assume that the lanes are covering their registers.
1463     if (!Idx.AllSuperRegsCovered)
1464       CoveringLanes &= ~Mask;
1465   }
1466 
1467   // Compute lane mask combinations for register classes.
1468   for (auto &RegClass : RegClasses) {
1469     LaneBitmask LaneMask;
1470     for (const auto &SubRegIndex : SubRegIndices) {
1471       if (RegClass.getSubClassWithSubReg(&SubRegIndex) == nullptr)
1472         continue;
1473       LaneMask |= SubRegIndex.LaneMask;
1474     }
1475 
1476     // For classes without any subregisters set LaneMask to 1 instead of 0.
1477     // This makes it easier for client code to handle classes uniformly.
1478     if (LaneMask.none())
1479       LaneMask = LaneBitmask::getLane(0);
1480 
1481     RegClass.LaneMask = LaneMask;
1482   }
1483 }
1484 
1485 namespace {
1486 
1487 // UberRegSet is a helper class for computeRegUnitWeights. Each UberRegSet is
1488 // the transitive closure of the union of overlapping register
1489 // classes. Together, the UberRegSets form a partition of the registers. If we
1490 // consider overlapping register classes to be connected, then each UberRegSet
1491 // is a set of connected components.
1492 //
1493 // An UberRegSet will likely be a horizontal slice of register names of
1494 // the same width. Nontrivial subregisters should then be in a separate
1495 // UberRegSet. But this property isn't required for valid computation of
1496 // register unit weights.
1497 //
1498 // A Weight field caches the max per-register unit weight in each UberRegSet.
1499 //
1500 // A set of SingularDeterminants flags single units of some register in this set
1501 // for which the unit weight equals the set weight. These units should not have
1502 // their weight increased.
1503 struct UberRegSet {
1504   CodeGenRegister::Vec Regs;
1505   unsigned Weight = 0;
1506   CodeGenRegister::RegUnitList SingularDeterminants;
1507 
1508   UberRegSet() = default;
1509 };
1510 
1511 } // end anonymous namespace
1512 
1513 // Partition registers into UberRegSets, where each set is the transitive
1514 // closure of the union of overlapping register classes.
1515 //
1516 // UberRegSets[0] is a special non-allocatable set.
1517 static void computeUberSets(std::vector<UberRegSet> &UberSets,
1518                             std::vector<UberRegSet*> &RegSets,
1519                             CodeGenRegBank &RegBank) {
1520   const auto &Registers = RegBank.getRegisters();
1521 
1522   // The Register EnumValue is one greater than its index into Registers.
1523   assert(Registers.size() == Registers.back().EnumValue &&
1524          "register enum value mismatch");
1525 
1526   // For simplicitly make the SetID the same as EnumValue.
1527   IntEqClasses UberSetIDs(Registers.size()+1);
1528   std::set<unsigned> AllocatableRegs;
1529   for (auto &RegClass : RegBank.getRegClasses()) {
1530     if (!RegClass.Allocatable)
1531       continue;
1532 
1533     const CodeGenRegister::Vec &Regs = RegClass.getMembers();
1534     if (Regs.empty())
1535       continue;
1536 
1537     unsigned USetID = UberSetIDs.findLeader((*Regs.begin())->EnumValue);
1538     assert(USetID && "register number 0 is invalid");
1539 
1540     AllocatableRegs.insert((*Regs.begin())->EnumValue);
1541     for (auto I = std::next(Regs.begin()), E = Regs.end(); I != E; ++I) {
1542       AllocatableRegs.insert((*I)->EnumValue);
1543       UberSetIDs.join(USetID, (*I)->EnumValue);
1544     }
1545   }
1546   // Combine non-allocatable regs.
1547   for (const auto &Reg : Registers) {
1548     unsigned RegNum = Reg.EnumValue;
1549     if (AllocatableRegs.count(RegNum))
1550       continue;
1551 
1552     UberSetIDs.join(0, RegNum);
1553   }
1554   UberSetIDs.compress();
1555 
1556   // Make the first UberSet a special unallocatable set.
1557   unsigned ZeroID = UberSetIDs[0];
1558 
1559   // Insert Registers into the UberSets formed by union-find.
1560   // Do not resize after this.
1561   UberSets.resize(UberSetIDs.getNumClasses());
1562   unsigned i = 0;
1563   for (const CodeGenRegister &Reg : Registers) {
1564     unsigned USetID = UberSetIDs[Reg.EnumValue];
1565     if (!USetID)
1566       USetID = ZeroID;
1567     else if (USetID == ZeroID)
1568       USetID = 0;
1569 
1570     UberRegSet *USet = &UberSets[USetID];
1571     USet->Regs.push_back(&Reg);
1572     sortAndUniqueRegisters(USet->Regs);
1573     RegSets[i++] = USet;
1574   }
1575 }
1576 
1577 // Recompute each UberSet weight after changing unit weights.
1578 static void computeUberWeights(std::vector<UberRegSet> &UberSets,
1579                                CodeGenRegBank &RegBank) {
1580   // Skip the first unallocatable set.
1581   for (std::vector<UberRegSet>::iterator I = std::next(UberSets.begin()),
1582          E = UberSets.end(); I != E; ++I) {
1583 
1584     // Initialize all unit weights in this set, and remember the max units/reg.
1585     const CodeGenRegister *Reg = nullptr;
1586     unsigned MaxWeight = 0, Weight = 0;
1587     for (RegUnitIterator UnitI(I->Regs); UnitI.isValid(); ++UnitI) {
1588       if (Reg != UnitI.getReg()) {
1589         if (Weight > MaxWeight)
1590           MaxWeight = Weight;
1591         Reg = UnitI.getReg();
1592         Weight = 0;
1593       }
1594       if (!RegBank.getRegUnit(*UnitI).Artificial) {
1595         unsigned UWeight = RegBank.getRegUnit(*UnitI).Weight;
1596         if (!UWeight) {
1597           UWeight = 1;
1598           RegBank.increaseRegUnitWeight(*UnitI, UWeight);
1599         }
1600         Weight += UWeight;
1601       }
1602     }
1603     if (Weight > MaxWeight)
1604       MaxWeight = Weight;
1605     if (I->Weight != MaxWeight) {
1606       LLVM_DEBUG(dbgs() << "UberSet " << I - UberSets.begin() << " Weight "
1607                         << MaxWeight;
1608                  for (auto &Unit
1609                       : I->Regs) dbgs()
1610                  << " " << Unit->getName();
1611                  dbgs() << "\n");
1612       // Update the set weight.
1613       I->Weight = MaxWeight;
1614     }
1615 
1616     // Find singular determinants.
1617     for (const auto R : I->Regs) {
1618       if (R->getRegUnits().count() == 1 && R->getWeight(RegBank) == I->Weight) {
1619         I->SingularDeterminants |= R->getRegUnits();
1620       }
1621     }
1622   }
1623 }
1624 
1625 // normalizeWeight is a computeRegUnitWeights helper that adjusts the weight of
1626 // a register and its subregisters so that they have the same weight as their
1627 // UberSet. Self-recursion processes the subregister tree in postorder so
1628 // subregisters are normalized first.
1629 //
1630 // Side effects:
1631 // - creates new adopted register units
1632 // - causes superregisters to inherit adopted units
1633 // - increases the weight of "singular" units
1634 // - induces recomputation of UberWeights.
1635 static bool normalizeWeight(CodeGenRegister *Reg,
1636                             std::vector<UberRegSet> &UberSets,
1637                             std::vector<UberRegSet*> &RegSets,
1638                             SparseBitVector<> &NormalRegs,
1639                             CodeGenRegister::RegUnitList &NormalUnits,
1640                             CodeGenRegBank &RegBank) {
1641   if (NormalRegs.test(Reg->EnumValue))
1642     return false;
1643   NormalRegs.set(Reg->EnumValue);
1644 
1645   bool Changed = false;
1646   const CodeGenRegister::SubRegMap &SRM = Reg->getSubRegs();
1647   for (CodeGenRegister::SubRegMap::const_iterator SRI = SRM.begin(),
1648          SRE = SRM.end(); SRI != SRE; ++SRI) {
1649     if (SRI->second == Reg)
1650       continue; // self-cycles happen
1651 
1652     Changed |= normalizeWeight(SRI->second, UberSets, RegSets,
1653                                NormalRegs, NormalUnits, RegBank);
1654   }
1655   // Postorder register normalization.
1656 
1657   // Inherit register units newly adopted by subregisters.
1658   if (Reg->inheritRegUnits(RegBank))
1659     computeUberWeights(UberSets, RegBank);
1660 
1661   // Check if this register is too skinny for its UberRegSet.
1662   UberRegSet *UberSet = RegSets[RegBank.getRegIndex(Reg)];
1663 
1664   unsigned RegWeight = Reg->getWeight(RegBank);
1665   if (UberSet->Weight > RegWeight) {
1666     // A register unit's weight can be adjusted only if it is the singular unit
1667     // for this register, has not been used to normalize a subregister's set,
1668     // and has not already been used to singularly determine this UberRegSet.
1669     unsigned AdjustUnit = *Reg->getRegUnits().begin();
1670     if (Reg->getRegUnits().count() != 1
1671         || hasRegUnit(NormalUnits, AdjustUnit)
1672         || hasRegUnit(UberSet->SingularDeterminants, AdjustUnit)) {
1673       // We don't have an adjustable unit, so adopt a new one.
1674       AdjustUnit = RegBank.newRegUnit(UberSet->Weight - RegWeight);
1675       Reg->adoptRegUnit(AdjustUnit);
1676       // Adopting a unit does not immediately require recomputing set weights.
1677     }
1678     else {
1679       // Adjust the existing single unit.
1680       if (!RegBank.getRegUnit(AdjustUnit).Artificial)
1681         RegBank.increaseRegUnitWeight(AdjustUnit, UberSet->Weight - RegWeight);
1682       // The unit may be shared among sets and registers within this set.
1683       computeUberWeights(UberSets, RegBank);
1684     }
1685     Changed = true;
1686   }
1687 
1688   // Mark these units normalized so superregisters can't change their weights.
1689   NormalUnits |= Reg->getRegUnits();
1690 
1691   return Changed;
1692 }
1693 
1694 // Compute a weight for each register unit created during getSubRegs.
1695 //
1696 // The goal is that two registers in the same class will have the same weight,
1697 // where each register's weight is defined as sum of its units' weights.
1698 void CodeGenRegBank::computeRegUnitWeights() {
1699   std::vector<UberRegSet> UberSets;
1700   std::vector<UberRegSet*> RegSets(Registers.size());
1701   computeUberSets(UberSets, RegSets, *this);
1702   // UberSets and RegSets are now immutable.
1703 
1704   computeUberWeights(UberSets, *this);
1705 
1706   // Iterate over each Register, normalizing the unit weights until reaching
1707   // a fix point.
1708   unsigned NumIters = 0;
1709   for (bool Changed = true; Changed; ++NumIters) {
1710     assert(NumIters <= NumNativeRegUnits && "Runaway register unit weights");
1711     Changed = false;
1712     for (auto &Reg : Registers) {
1713       CodeGenRegister::RegUnitList NormalUnits;
1714       SparseBitVector<> NormalRegs;
1715       Changed |= normalizeWeight(&Reg, UberSets, RegSets, NormalRegs,
1716                                  NormalUnits, *this);
1717     }
1718   }
1719 }
1720 
1721 // Find a set in UniqueSets with the same elements as Set.
1722 // Return an iterator into UniqueSets.
1723 static std::vector<RegUnitSet>::const_iterator
1724 findRegUnitSet(const std::vector<RegUnitSet> &UniqueSets,
1725                const RegUnitSet &Set) {
1726   std::vector<RegUnitSet>::const_iterator
1727     I = UniqueSets.begin(), E = UniqueSets.end();
1728   for(;I != E; ++I) {
1729     if (I->Units == Set.Units)
1730       break;
1731   }
1732   return I;
1733 }
1734 
1735 // Return true if the RUSubSet is a subset of RUSuperSet.
1736 static bool isRegUnitSubSet(const std::vector<unsigned> &RUSubSet,
1737                             const std::vector<unsigned> &RUSuperSet) {
1738   return std::includes(RUSuperSet.begin(), RUSuperSet.end(),
1739                        RUSubSet.begin(), RUSubSet.end());
1740 }
1741 
1742 /// Iteratively prune unit sets. Prune subsets that are close to the superset,
1743 /// but with one or two registers removed. We occasionally have registers like
1744 /// APSR and PC thrown in with the general registers. We also see many
1745 /// special-purpose register subsets, such as tail-call and Thumb
1746 /// encodings. Generating all possible overlapping sets is combinatorial and
1747 /// overkill for modeling pressure. Ideally we could fix this statically in
1748 /// tablegen by (1) having the target define register classes that only include
1749 /// the allocatable registers and marking other classes as non-allocatable and
1750 /// (2) having a way to mark special purpose classes as "don't-care" classes for
1751 /// the purpose of pressure.  However, we make an attempt to handle targets that
1752 /// are not nicely defined by merging nearly identical register unit sets
1753 /// statically. This generates smaller tables. Then, dynamically, we adjust the
1754 /// set limit by filtering the reserved registers.
1755 ///
1756 /// Merge sets only if the units have the same weight. For example, on ARM,
1757 /// Q-tuples with ssub index 0 include all S regs but also include D16+. We
1758 /// should not expand the S set to include D regs.
1759 void CodeGenRegBank::pruneUnitSets() {
1760   assert(RegClassUnitSets.empty() && "this invalidates RegClassUnitSets");
1761 
1762   // Form an equivalence class of UnitSets with no significant difference.
1763   std::vector<unsigned> SuperSetIDs;
1764   for (unsigned SubIdx = 0, EndIdx = RegUnitSets.size();
1765        SubIdx != EndIdx; ++SubIdx) {
1766     const RegUnitSet &SubSet = RegUnitSets[SubIdx];
1767     unsigned SuperIdx = 0;
1768     for (; SuperIdx != EndIdx; ++SuperIdx) {
1769       if (SuperIdx == SubIdx)
1770         continue;
1771 
1772       unsigned UnitWeight = RegUnits[SubSet.Units[0]].Weight;
1773       const RegUnitSet &SuperSet = RegUnitSets[SuperIdx];
1774       if (isRegUnitSubSet(SubSet.Units, SuperSet.Units)
1775           && (SubSet.Units.size() + 3 > SuperSet.Units.size())
1776           && UnitWeight == RegUnits[SuperSet.Units[0]].Weight
1777           && UnitWeight == RegUnits[SuperSet.Units.back()].Weight) {
1778         LLVM_DEBUG(dbgs() << "UnitSet " << SubIdx << " subsumed by " << SuperIdx
1779                           << "\n");
1780         // We can pick any of the set names for the merged set. Go for the
1781         // shortest one to avoid picking the name of one of the classes that are
1782         // artificially created by tablegen. So "FPR128_lo" instead of
1783         // "QQQQ_with_qsub3_in_FPR128_lo".
1784         if (RegUnitSets[SubIdx].Name.size() < RegUnitSets[SuperIdx].Name.size())
1785           RegUnitSets[SuperIdx].Name = RegUnitSets[SubIdx].Name;
1786         break;
1787       }
1788     }
1789     if (SuperIdx == EndIdx)
1790       SuperSetIDs.push_back(SubIdx);
1791   }
1792   // Populate PrunedUnitSets with each equivalence class's superset.
1793   std::vector<RegUnitSet> PrunedUnitSets(SuperSetIDs.size());
1794   for (unsigned i = 0, e = SuperSetIDs.size(); i != e; ++i) {
1795     unsigned SuperIdx = SuperSetIDs[i];
1796     PrunedUnitSets[i].Name = RegUnitSets[SuperIdx].Name;
1797     PrunedUnitSets[i].Units.swap(RegUnitSets[SuperIdx].Units);
1798   }
1799   RegUnitSets.swap(PrunedUnitSets);
1800 }
1801 
1802 // Create a RegUnitSet for each RegClass that contains all units in the class
1803 // including adopted units that are necessary to model register pressure. Then
1804 // iteratively compute RegUnitSets such that the union of any two overlapping
1805 // RegUnitSets is repreresented.
1806 //
1807 // RegisterInfoEmitter will map each RegClass to its RegUnitClass and any
1808 // RegUnitSet that is a superset of that RegUnitClass.
1809 void CodeGenRegBank::computeRegUnitSets() {
1810   assert(RegUnitSets.empty() && "dirty RegUnitSets");
1811 
1812   // Compute a unique RegUnitSet for each RegClass.
1813   auto &RegClasses = getRegClasses();
1814   for (auto &RC : RegClasses) {
1815     if (!RC.Allocatable || RC.Artificial)
1816       continue;
1817 
1818     // Speculatively grow the RegUnitSets to hold the new set.
1819     RegUnitSets.resize(RegUnitSets.size() + 1);
1820     RegUnitSets.back().Name = RC.getName();
1821 
1822     // Compute a sorted list of units in this class.
1823     RC.buildRegUnitSet(*this, RegUnitSets.back().Units);
1824 
1825     // Find an existing RegUnitSet.
1826     std::vector<RegUnitSet>::const_iterator SetI =
1827       findRegUnitSet(RegUnitSets, RegUnitSets.back());
1828     if (SetI != std::prev(RegUnitSets.end()))
1829       RegUnitSets.pop_back();
1830   }
1831 
1832   LLVM_DEBUG(dbgs() << "\nBefore pruning:\n"; for (unsigned USIdx = 0,
1833                                                    USEnd = RegUnitSets.size();
1834                                                    USIdx < USEnd; ++USIdx) {
1835     dbgs() << "UnitSet " << USIdx << " " << RegUnitSets[USIdx].Name << ":";
1836     for (auto &U : RegUnitSets[USIdx].Units)
1837       printRegUnitName(U);
1838     dbgs() << "\n";
1839   });
1840 
1841   // Iteratively prune unit sets.
1842   pruneUnitSets();
1843 
1844   LLVM_DEBUG(dbgs() << "\nBefore union:\n"; for (unsigned USIdx = 0,
1845                                                  USEnd = RegUnitSets.size();
1846                                                  USIdx < USEnd; ++USIdx) {
1847     dbgs() << "UnitSet " << USIdx << " " << RegUnitSets[USIdx].Name << ":";
1848     for (auto &U : RegUnitSets[USIdx].Units)
1849       printRegUnitName(U);
1850     dbgs() << "\n";
1851   } dbgs() << "\nUnion sets:\n");
1852 
1853   // Iterate over all unit sets, including new ones added by this loop.
1854   unsigned NumRegUnitSubSets = RegUnitSets.size();
1855   for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx) {
1856     // In theory, this is combinatorial. In practice, it needs to be bounded
1857     // by a small number of sets for regpressure to be efficient.
1858     // If the assert is hit, we need to implement pruning.
1859     assert(Idx < (2*NumRegUnitSubSets) && "runaway unit set inference");
1860 
1861     // Compare new sets with all original classes.
1862     for (unsigned SearchIdx = (Idx >= NumRegUnitSubSets) ? 0 : Idx+1;
1863          SearchIdx != EndIdx; ++SearchIdx) {
1864       std::set<unsigned> Intersection;
1865       std::set_intersection(RegUnitSets[Idx].Units.begin(),
1866                             RegUnitSets[Idx].Units.end(),
1867                             RegUnitSets[SearchIdx].Units.begin(),
1868                             RegUnitSets[SearchIdx].Units.end(),
1869                             std::inserter(Intersection, Intersection.begin()));
1870       if (Intersection.empty())
1871         continue;
1872 
1873       // Speculatively grow the RegUnitSets to hold the new set.
1874       RegUnitSets.resize(RegUnitSets.size() + 1);
1875       RegUnitSets.back().Name =
1876         RegUnitSets[Idx].Name + "+" + RegUnitSets[SearchIdx].Name;
1877 
1878       std::set_union(RegUnitSets[Idx].Units.begin(),
1879                      RegUnitSets[Idx].Units.end(),
1880                      RegUnitSets[SearchIdx].Units.begin(),
1881                      RegUnitSets[SearchIdx].Units.end(),
1882                      std::inserter(RegUnitSets.back().Units,
1883                                    RegUnitSets.back().Units.begin()));
1884 
1885       // Find an existing RegUnitSet, or add the union to the unique sets.
1886       std::vector<RegUnitSet>::const_iterator SetI =
1887         findRegUnitSet(RegUnitSets, RegUnitSets.back());
1888       if (SetI != std::prev(RegUnitSets.end()))
1889         RegUnitSets.pop_back();
1890       else {
1891         LLVM_DEBUG(dbgs() << "UnitSet " << RegUnitSets.size() - 1 << " "
1892                           << RegUnitSets.back().Name << ":";
1893                    for (auto &U
1894                         : RegUnitSets.back().Units) printRegUnitName(U);
1895                    dbgs() << "\n";);
1896       }
1897     }
1898   }
1899 
1900   // Iteratively prune unit sets after inferring supersets.
1901   pruneUnitSets();
1902 
1903   LLVM_DEBUG(
1904       dbgs() << "\n"; for (unsigned USIdx = 0, USEnd = RegUnitSets.size();
1905                            USIdx < USEnd; ++USIdx) {
1906         dbgs() << "UnitSet " << USIdx << " " << RegUnitSets[USIdx].Name << ":";
1907         for (auto &U : RegUnitSets[USIdx].Units)
1908           printRegUnitName(U);
1909         dbgs() << "\n";
1910       });
1911 
1912   // For each register class, list the UnitSets that are supersets.
1913   RegClassUnitSets.resize(RegClasses.size());
1914   int RCIdx = -1;
1915   for (auto &RC : RegClasses) {
1916     ++RCIdx;
1917     if (!RC.Allocatable)
1918       continue;
1919 
1920     // Recompute the sorted list of units in this class.
1921     std::vector<unsigned> RCRegUnits;
1922     RC.buildRegUnitSet(*this, RCRegUnits);
1923 
1924     // Don't increase pressure for unallocatable regclasses.
1925     if (RCRegUnits.empty())
1926       continue;
1927 
1928     LLVM_DEBUG(dbgs() << "RC " << RC.getName() << " Units: \n";
1929                for (auto U
1930                     : RCRegUnits) printRegUnitName(U);
1931                dbgs() << "\n  UnitSetIDs:");
1932 
1933     // Find all supersets.
1934     for (unsigned USIdx = 0, USEnd = RegUnitSets.size();
1935          USIdx != USEnd; ++USIdx) {
1936       if (isRegUnitSubSet(RCRegUnits, RegUnitSets[USIdx].Units)) {
1937         LLVM_DEBUG(dbgs() << " " << USIdx);
1938         RegClassUnitSets[RCIdx].push_back(USIdx);
1939       }
1940     }
1941     LLVM_DEBUG(dbgs() << "\n");
1942     assert(!RegClassUnitSets[RCIdx].empty() && "missing unit set for regclass");
1943   }
1944 
1945   // For each register unit, ensure that we have the list of UnitSets that
1946   // contain the unit. Normally, this matches an existing list of UnitSets for a
1947   // register class. If not, we create a new entry in RegClassUnitSets as a
1948   // "fake" register class.
1949   for (unsigned UnitIdx = 0, UnitEnd = NumNativeRegUnits;
1950        UnitIdx < UnitEnd; ++UnitIdx) {
1951     std::vector<unsigned> RUSets;
1952     for (unsigned i = 0, e = RegUnitSets.size(); i != e; ++i) {
1953       RegUnitSet &RUSet = RegUnitSets[i];
1954       if (!is_contained(RUSet.Units, UnitIdx))
1955         continue;
1956       RUSets.push_back(i);
1957     }
1958     unsigned RCUnitSetsIdx = 0;
1959     for (unsigned e = RegClassUnitSets.size();
1960          RCUnitSetsIdx != e; ++RCUnitSetsIdx) {
1961       if (RegClassUnitSets[RCUnitSetsIdx] == RUSets) {
1962         break;
1963       }
1964     }
1965     RegUnits[UnitIdx].RegClassUnitSetsIdx = RCUnitSetsIdx;
1966     if (RCUnitSetsIdx == RegClassUnitSets.size()) {
1967       // Create a new list of UnitSets as a "fake" register class.
1968       RegClassUnitSets.resize(RCUnitSetsIdx + 1);
1969       RegClassUnitSets[RCUnitSetsIdx].swap(RUSets);
1970     }
1971   }
1972 }
1973 
1974 void CodeGenRegBank::computeRegUnitLaneMasks() {
1975   for (auto &Register : Registers) {
1976     // Create an initial lane mask for all register units.
1977     const auto &RegUnits = Register.getRegUnits();
1978     CodeGenRegister::RegUnitLaneMaskList
1979         RegUnitLaneMasks(RegUnits.count(), LaneBitmask::getNone());
1980     // Iterate through SubRegisters.
1981     typedef CodeGenRegister::SubRegMap SubRegMap;
1982     const SubRegMap &SubRegs = Register.getSubRegs();
1983     for (SubRegMap::const_iterator S = SubRegs.begin(),
1984          SE = SubRegs.end(); S != SE; ++S) {
1985       CodeGenRegister *SubReg = S->second;
1986       // Ignore non-leaf subregisters, their lane masks are fully covered by
1987       // the leaf subregisters anyway.
1988       if (!SubReg->getSubRegs().empty())
1989         continue;
1990       CodeGenSubRegIndex *SubRegIndex = S->first;
1991       const CodeGenRegister *SubRegister = S->second;
1992       LaneBitmask LaneMask = SubRegIndex->LaneMask;
1993       // Distribute LaneMask to Register Units touched.
1994       for (unsigned SUI : SubRegister->getRegUnits()) {
1995         bool Found = false;
1996         unsigned u = 0;
1997         for (unsigned RU : RegUnits) {
1998           if (SUI == RU) {
1999             RegUnitLaneMasks[u] |= LaneMask;
2000             assert(!Found);
2001             Found = true;
2002           }
2003           ++u;
2004         }
2005         (void)Found;
2006         assert(Found);
2007       }
2008     }
2009     Register.setRegUnitLaneMasks(RegUnitLaneMasks);
2010   }
2011 }
2012 
2013 void CodeGenRegBank::computeDerivedInfo() {
2014   computeComposites();
2015   computeSubRegLaneMasks();
2016 
2017   // Compute a weight for each register unit created during getSubRegs.
2018   // This may create adopted register units (with unit # >= NumNativeRegUnits).
2019   computeRegUnitWeights();
2020 
2021   // Compute a unique set of RegUnitSets. One for each RegClass and inferred
2022   // supersets for the union of overlapping sets.
2023   computeRegUnitSets();
2024 
2025   computeRegUnitLaneMasks();
2026 
2027   // Compute register class HasDisjunctSubRegs/CoveredBySubRegs flag.
2028   for (CodeGenRegisterClass &RC : RegClasses) {
2029     RC.HasDisjunctSubRegs = false;
2030     RC.CoveredBySubRegs = true;
2031     for (const CodeGenRegister *Reg : RC.getMembers()) {
2032       RC.HasDisjunctSubRegs |= Reg->HasDisjunctSubRegs;
2033       RC.CoveredBySubRegs &= Reg->CoveredBySubRegs;
2034     }
2035   }
2036 
2037   // Get the weight of each set.
2038   for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx)
2039     RegUnitSets[Idx].Weight = getRegUnitSetWeight(RegUnitSets[Idx].Units);
2040 
2041   // Find the order of each set.
2042   RegUnitSetOrder.reserve(RegUnitSets.size());
2043   for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx)
2044     RegUnitSetOrder.push_back(Idx);
2045 
2046   std::stable_sort(RegUnitSetOrder.begin(), RegUnitSetOrder.end(),
2047                    [this](unsigned ID1, unsigned ID2) {
2048     return getRegPressureSet(ID1).Units.size() <
2049            getRegPressureSet(ID2).Units.size();
2050   });
2051   for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx) {
2052     RegUnitSets[RegUnitSetOrder[Idx]].Order = Idx;
2053   }
2054 }
2055 
2056 //
2057 // Synthesize missing register class intersections.
2058 //
2059 // Make sure that sub-classes of RC exists such that getCommonSubClass(RC, X)
2060 // returns a maximal register class for all X.
2061 //
2062 void CodeGenRegBank::inferCommonSubClass(CodeGenRegisterClass *RC) {
2063   assert(!RegClasses.empty());
2064   // Stash the iterator to the last element so that this loop doesn't visit
2065   // elements added by the getOrCreateSubClass call within it.
2066   for (auto I = RegClasses.begin(), E = std::prev(RegClasses.end());
2067        I != std::next(E); ++I) {
2068     CodeGenRegisterClass *RC1 = RC;
2069     CodeGenRegisterClass *RC2 = &*I;
2070     if (RC1 == RC2)
2071       continue;
2072 
2073     // Compute the set intersection of RC1 and RC2.
2074     const CodeGenRegister::Vec &Memb1 = RC1->getMembers();
2075     const CodeGenRegister::Vec &Memb2 = RC2->getMembers();
2076     CodeGenRegister::Vec Intersection;
2077     std::set_intersection(
2078         Memb1.begin(), Memb1.end(), Memb2.begin(), Memb2.end(),
2079         std::inserter(Intersection, Intersection.begin()), deref<llvm::less>());
2080 
2081     // Skip disjoint class pairs.
2082     if (Intersection.empty())
2083       continue;
2084 
2085     // If RC1 and RC2 have different spill sizes or alignments, use the
2086     // stricter one for sub-classing.  If they are equal, prefer RC1.
2087     if (RC2->RSI.hasStricterSpillThan(RC1->RSI))
2088       std::swap(RC1, RC2);
2089 
2090     getOrCreateSubClass(RC1, &Intersection,
2091                         RC1->getName() + "_and_" + RC2->getName());
2092   }
2093 }
2094 
2095 //
2096 // Synthesize missing sub-classes for getSubClassWithSubReg().
2097 //
2098 // Make sure that the set of registers in RC with a given SubIdx sub-register
2099 // form a register class.  Update RC->SubClassWithSubReg.
2100 //
2101 void CodeGenRegBank::inferSubClassWithSubReg(CodeGenRegisterClass *RC) {
2102   // Map SubRegIndex to set of registers in RC supporting that SubRegIndex.
2103   typedef std::map<const CodeGenSubRegIndex *, CodeGenRegister::Vec,
2104                    deref<llvm::less>> SubReg2SetMap;
2105 
2106   // Compute the set of registers supporting each SubRegIndex.
2107   SubReg2SetMap SRSets;
2108   for (const auto R : RC->getMembers()) {
2109     if (R->Artificial)
2110       continue;
2111     const CodeGenRegister::SubRegMap &SRM = R->getSubRegs();
2112     for (CodeGenRegister::SubRegMap::const_iterator I = SRM.begin(),
2113          E = SRM.end(); I != E; ++I) {
2114       if (!I->first->Artificial)
2115         SRSets[I->first].push_back(R);
2116     }
2117   }
2118 
2119   for (auto I : SRSets)
2120     sortAndUniqueRegisters(I.second);
2121 
2122   // Find matching classes for all SRSets entries.  Iterate in SubRegIndex
2123   // numerical order to visit synthetic indices last.
2124   for (const auto &SubIdx : SubRegIndices) {
2125     if (SubIdx.Artificial)
2126       continue;
2127     SubReg2SetMap::const_iterator I = SRSets.find(&SubIdx);
2128     // Unsupported SubRegIndex. Skip it.
2129     if (I == SRSets.end())
2130       continue;
2131     // In most cases, all RC registers support the SubRegIndex.
2132     if (I->second.size() == RC->getMembers().size()) {
2133       RC->setSubClassWithSubReg(&SubIdx, RC);
2134       continue;
2135     }
2136     // This is a real subset.  See if we have a matching class.
2137     CodeGenRegisterClass *SubRC =
2138       getOrCreateSubClass(RC, &I->second,
2139                           RC->getName() + "_with_" + I->first->getName());
2140     RC->setSubClassWithSubReg(&SubIdx, SubRC);
2141   }
2142 }
2143 
2144 //
2145 // Synthesize missing sub-classes of RC for getMatchingSuperRegClass().
2146 //
2147 // Create sub-classes of RC such that getMatchingSuperRegClass(RC, SubIdx, X)
2148 // has a maximal result for any SubIdx and any X >= FirstSubRegRC.
2149 //
2150 
2151 void CodeGenRegBank::inferMatchingSuperRegClass(CodeGenRegisterClass *RC,
2152                                                 std::list<CodeGenRegisterClass>::iterator FirstSubRegRC) {
2153   SmallVector<std::pair<const CodeGenRegister*,
2154                         const CodeGenRegister*>, 16> SSPairs;
2155   BitVector TopoSigs(getNumTopoSigs());
2156 
2157   // Iterate in SubRegIndex numerical order to visit synthetic indices last.
2158   for (auto &SubIdx : SubRegIndices) {
2159     // Skip indexes that aren't fully supported by RC's registers. This was
2160     // computed by inferSubClassWithSubReg() above which should have been
2161     // called first.
2162     if (RC->getSubClassWithSubReg(&SubIdx) != RC)
2163       continue;
2164 
2165     // Build list of (Super, Sub) pairs for this SubIdx.
2166     SSPairs.clear();
2167     TopoSigs.reset();
2168     for (const auto Super : RC->getMembers()) {
2169       const CodeGenRegister *Sub = Super->getSubRegs().find(&SubIdx)->second;
2170       assert(Sub && "Missing sub-register");
2171       SSPairs.push_back(std::make_pair(Super, Sub));
2172       TopoSigs.set(Sub->getTopoSig());
2173     }
2174 
2175     // Iterate over sub-register class candidates.  Ignore classes created by
2176     // this loop. They will never be useful.
2177     // Store an iterator to the last element (not end) so that this loop doesn't
2178     // visit newly inserted elements.
2179     assert(!RegClasses.empty());
2180     for (auto I = FirstSubRegRC, E = std::prev(RegClasses.end());
2181          I != std::next(E); ++I) {
2182       CodeGenRegisterClass &SubRC = *I;
2183       // Topological shortcut: SubRC members have the wrong shape.
2184       if (!TopoSigs.anyCommon(SubRC.getTopoSigs()))
2185         continue;
2186       // Compute the subset of RC that maps into SubRC.
2187       CodeGenRegister::Vec SubSetVec;
2188       for (unsigned i = 0, e = SSPairs.size(); i != e; ++i)
2189         if (SubRC.contains(SSPairs[i].second))
2190           SubSetVec.push_back(SSPairs[i].first);
2191 
2192       if (SubSetVec.empty())
2193         continue;
2194 
2195       // RC injects completely into SubRC.
2196       sortAndUniqueRegisters(SubSetVec);
2197       if (SubSetVec.size() == SSPairs.size()) {
2198         SubRC.addSuperRegClass(&SubIdx, RC);
2199         continue;
2200       }
2201 
2202       // Only a subset of RC maps into SubRC. Make sure it is represented by a
2203       // class.
2204       getOrCreateSubClass(RC, &SubSetVec, RC->getName() + "_with_" +
2205                                           SubIdx.getName() + "_in_" +
2206                                           SubRC.getName());
2207     }
2208   }
2209 }
2210 
2211 //
2212 // Infer missing register classes.
2213 //
2214 void CodeGenRegBank::computeInferredRegisterClasses() {
2215   assert(!RegClasses.empty());
2216   // When this function is called, the register classes have not been sorted
2217   // and assigned EnumValues yet.  That means getSubClasses(),
2218   // getSuperClasses(), and hasSubClass() functions are defunct.
2219 
2220   // Use one-before-the-end so it doesn't move forward when new elements are
2221   // added.
2222   auto FirstNewRC = std::prev(RegClasses.end());
2223 
2224   // Visit all register classes, including the ones being added by the loop.
2225   // Watch out for iterator invalidation here.
2226   for (auto I = RegClasses.begin(), E = RegClasses.end(); I != E; ++I) {
2227     CodeGenRegisterClass *RC = &*I;
2228     if (RC->Artificial)
2229       continue;
2230 
2231     // Synthesize answers for getSubClassWithSubReg().
2232     inferSubClassWithSubReg(RC);
2233 
2234     // Synthesize answers for getCommonSubClass().
2235     inferCommonSubClass(RC);
2236 
2237     // Synthesize answers for getMatchingSuperRegClass().
2238     inferMatchingSuperRegClass(RC);
2239 
2240     // New register classes are created while this loop is running, and we need
2241     // to visit all of them.  I  particular, inferMatchingSuperRegClass needs
2242     // to match old super-register classes with sub-register classes created
2243     // after inferMatchingSuperRegClass was called.  At this point,
2244     // inferMatchingSuperRegClass has checked SuperRC = [0..rci] with SubRC =
2245     // [0..FirstNewRC).  We need to cover SubRC = [FirstNewRC..rci].
2246     if (I == FirstNewRC) {
2247       auto NextNewRC = std::prev(RegClasses.end());
2248       for (auto I2 = RegClasses.begin(), E2 = std::next(FirstNewRC); I2 != E2;
2249            ++I2)
2250         inferMatchingSuperRegClass(&*I2, E2);
2251       FirstNewRC = NextNewRC;
2252     }
2253   }
2254 }
2255 
2256 /// getRegisterClassForRegister - Find the register class that contains the
2257 /// specified physical register.  If the register is not in a register class,
2258 /// return null. If the register is in multiple classes, and the classes have a
2259 /// superset-subset relationship and the same set of types, return the
2260 /// superclass.  Otherwise return null.
2261 const CodeGenRegisterClass*
2262 CodeGenRegBank::getRegClassForRegister(Record *R) {
2263   const CodeGenRegister *Reg = getReg(R);
2264   const CodeGenRegisterClass *FoundRC = nullptr;
2265   for (const auto &RC : getRegClasses()) {
2266     if (!RC.contains(Reg))
2267       continue;
2268 
2269     // If this is the first class that contains the register,
2270     // make a note of it and go on to the next class.
2271     if (!FoundRC) {
2272       FoundRC = &RC;
2273       continue;
2274     }
2275 
2276     // If a register's classes have different types, return null.
2277     if (RC.getValueTypes() != FoundRC->getValueTypes())
2278       return nullptr;
2279 
2280     // Check to see if the previously found class that contains
2281     // the register is a subclass of the current class. If so,
2282     // prefer the superclass.
2283     if (RC.hasSubClass(FoundRC)) {
2284       FoundRC = &RC;
2285       continue;
2286     }
2287 
2288     // Check to see if the previously found class that contains
2289     // the register is a superclass of the current class. If so,
2290     // prefer the superclass.
2291     if (FoundRC->hasSubClass(&RC))
2292       continue;
2293 
2294     // Multiple classes, and neither is a superclass of the other.
2295     // Return null.
2296     return nullptr;
2297   }
2298   return FoundRC;
2299 }
2300 
2301 BitVector CodeGenRegBank::computeCoveredRegisters(ArrayRef<Record*> Regs) {
2302   SetVector<const CodeGenRegister*> Set;
2303 
2304   // First add Regs with all sub-registers.
2305   for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
2306     CodeGenRegister *Reg = getReg(Regs[i]);
2307     if (Set.insert(Reg))
2308       // Reg is new, add all sub-registers.
2309       // The pre-ordering is not important here.
2310       Reg->addSubRegsPreOrder(Set, *this);
2311   }
2312 
2313   // Second, find all super-registers that are completely covered by the set.
2314   for (unsigned i = 0; i != Set.size(); ++i) {
2315     const CodeGenRegister::SuperRegList &SR = Set[i]->getSuperRegs();
2316     for (unsigned j = 0, e = SR.size(); j != e; ++j) {
2317       const CodeGenRegister *Super = SR[j];
2318       if (!Super->CoveredBySubRegs || Set.count(Super))
2319         continue;
2320       // This new super-register is covered by its sub-registers.
2321       bool AllSubsInSet = true;
2322       const CodeGenRegister::SubRegMap &SRM = Super->getSubRegs();
2323       for (CodeGenRegister::SubRegMap::const_iterator I = SRM.begin(),
2324              E = SRM.end(); I != E; ++I)
2325         if (!Set.count(I->second)) {
2326           AllSubsInSet = false;
2327           break;
2328         }
2329       // All sub-registers in Set, add Super as well.
2330       // We will visit Super later to recheck its super-registers.
2331       if (AllSubsInSet)
2332         Set.insert(Super);
2333     }
2334   }
2335 
2336   // Convert to BitVector.
2337   BitVector BV(Registers.size() + 1);
2338   for (unsigned i = 0, e = Set.size(); i != e; ++i)
2339     BV.set(Set[i]->EnumValue);
2340   return BV;
2341 }
2342 
2343 void CodeGenRegBank::printRegUnitName(unsigned Unit) const {
2344   if (Unit < NumNativeRegUnits)
2345     dbgs() << ' ' << RegUnits[Unit].Roots[0]->getName();
2346   else
2347     dbgs() << " #" << Unit;
2348 }
2349