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