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