1 //===- CodeGenRegisters.cpp - Register and RegisterClass Info -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines structures to encapsulate information gleaned from the
11 // target register and register class definitions.
13 //===----------------------------------------------------------------------===//
15 #include "CodeGenRegisters.h"
16 #include "CodeGenTarget.h"
17 #include "llvm/ADT/IntEqClasses.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/ADT/Twine.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/TableGen/Error.h"
27 #define DEBUG_TYPE "regalloc-emitter"
29 //===----------------------------------------------------------------------===//
31 //===----------------------------------------------------------------------===//
33 CodeGenSubRegIndex::CodeGenSubRegIndex(Record *R, unsigned Enum)
34 : TheDef(R), EnumValue(Enum), LaneMask(0), AllSuperRegsCovered(true) {
36 if (R->getValue("Namespace"))
37 Namespace = R->getValueAsString("Namespace");
38 Size = R->getValueAsInt("Size");
39 Offset = R->getValueAsInt("Offset");
42 CodeGenSubRegIndex::CodeGenSubRegIndex(StringRef N, StringRef Nspace,
44 : TheDef(nullptr), Name(N), Namespace(Nspace), Size(-1), Offset(-1),
45 EnumValue(Enum), LaneMask(0), AllSuperRegsCovered(true) {
48 std::string CodeGenSubRegIndex::getQualifiedName() const {
49 std::string N = getNamespace();
56 void CodeGenSubRegIndex::updateComponents(CodeGenRegBank &RegBank) {
60 std::vector<Record*> Comps = TheDef->getValueAsListOfDefs("ComposedOf");
62 if (Comps.size() != 2)
63 PrintFatalError(TheDef->getLoc(),
64 "ComposedOf must have exactly two entries");
65 CodeGenSubRegIndex *A = RegBank.getSubRegIdx(Comps[0]);
66 CodeGenSubRegIndex *B = RegBank.getSubRegIdx(Comps[1]);
67 CodeGenSubRegIndex *X = A->addComposite(B, this);
69 PrintFatalError(TheDef->getLoc(), "Ambiguous ComposedOf entries");
72 std::vector<Record*> Parts =
73 TheDef->getValueAsListOfDefs("CoveringSubRegIndices");
76 PrintFatalError(TheDef->getLoc(),
77 "CoveredBySubRegs must have two or more entries");
78 SmallVector<CodeGenSubRegIndex*, 8> IdxParts;
79 for (unsigned i = 0, e = Parts.size(); i != e; ++i)
80 IdxParts.push_back(RegBank.getSubRegIdx(Parts[i]));
81 RegBank.addConcatSubRegIndex(IdxParts, this);
85 unsigned CodeGenSubRegIndex::computeLaneMask() const {
90 // Recursion guard, shouldn't be required.
93 // The lane mask is simply the union of all sub-indices.
95 for (const auto &C : Composed)
96 M |= C.second->computeLaneMask();
97 assert(M && "Missing lane mask, sub-register cycle?");
102 //===----------------------------------------------------------------------===//
104 //===----------------------------------------------------------------------===//
106 CodeGenRegister::CodeGenRegister(Record *R, unsigned Enum)
109 CostPerUse(R->getValueAsInt("CostPerUse")),
110 CoveredBySubRegs(R->getValueAsBit("CoveredBySubRegs")),
111 NumNativeRegUnits(0),
112 SubRegsComplete(false),
113 SuperRegsComplete(false),
117 void CodeGenRegister::buildObjectGraph(CodeGenRegBank &RegBank) {
118 std::vector<Record*> SRIs = TheDef->getValueAsListOfDefs("SubRegIndices");
119 std::vector<Record*> SRs = TheDef->getValueAsListOfDefs("SubRegs");
121 if (SRIs.size() != SRs.size())
122 PrintFatalError(TheDef->getLoc(),
123 "SubRegs and SubRegIndices must have the same size");
125 for (unsigned i = 0, e = SRIs.size(); i != e; ++i) {
126 ExplicitSubRegIndices.push_back(RegBank.getSubRegIdx(SRIs[i]));
127 ExplicitSubRegs.push_back(RegBank.getReg(SRs[i]));
130 // Also compute leading super-registers. Each register has a list of
131 // covered-by-subregs super-registers where it appears as the first explicit
134 // This is used by computeSecondarySubRegs() to find candidates.
135 if (CoveredBySubRegs && !ExplicitSubRegs.empty())
136 ExplicitSubRegs.front()->LeadingSuperRegs.push_back(this);
138 // Add ad hoc alias links. This is a symmetric relationship between two
139 // registers, so build a symmetric graph by adding links in both ends.
140 std::vector<Record*> Aliases = TheDef->getValueAsListOfDefs("Aliases");
141 for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
142 CodeGenRegister *Reg = RegBank.getReg(Aliases[i]);
143 ExplicitAliases.push_back(Reg);
144 Reg->ExplicitAliases.push_back(this);
148 const std::string &CodeGenRegister::getName() const {
149 return TheDef->getName();
153 // Iterate over all register units in a set of registers.
154 class RegUnitIterator {
155 CodeGenRegister::Set::const_iterator RegI, RegE;
156 CodeGenRegister::RegUnitList::const_iterator UnitI, UnitE;
159 RegUnitIterator(const CodeGenRegister::Set &Regs):
160 RegI(Regs.begin()), RegE(Regs.end()), UnitI(), UnitE() {
163 UnitI = (*RegI)->getRegUnits().begin();
164 UnitE = (*RegI)->getRegUnits().end();
169 bool isValid() const { return UnitI != UnitE; }
171 unsigned operator* () const { assert(isValid()); return *UnitI; }
173 const CodeGenRegister *getReg() const { assert(isValid()); return *RegI; }
175 /// Preincrement. Move to the next unit.
177 assert(isValid() && "Cannot advance beyond the last operand");
184 while (UnitI == UnitE) {
187 UnitI = (*RegI)->getRegUnits().begin();
188 UnitE = (*RegI)->getRegUnits().end();
194 // Merge two RegUnitLists maintaining the order and removing duplicates.
195 // Overwrites MergedRU in the process.
196 static void mergeRegUnits(CodeGenRegister::RegUnitList &MergedRU,
197 const CodeGenRegister::RegUnitList &RRU) {
198 CodeGenRegister::RegUnitList LRU = MergedRU;
200 std::set_union(LRU.begin(), LRU.end(), RRU.begin(), RRU.end(),
201 std::back_inserter(MergedRU));
204 // Return true of this unit appears in RegUnits.
205 static bool hasRegUnit(CodeGenRegister::RegUnitList &RegUnits, unsigned Unit) {
206 return std::count(RegUnits.begin(), RegUnits.end(), Unit);
209 // Inherit register units from subregisters.
210 // Return true if the RegUnits changed.
211 bool CodeGenRegister::inheritRegUnits(CodeGenRegBank &RegBank) {
212 unsigned OldNumUnits = RegUnits.size();
213 for (SubRegMap::const_iterator I = SubRegs.begin(), E = SubRegs.end();
215 CodeGenRegister *SR = I->second;
216 // Merge the subregister's units into this register's RegUnits.
217 mergeRegUnits(RegUnits, SR->RegUnits);
219 return OldNumUnits != RegUnits.size();
222 const CodeGenRegister::SubRegMap &
223 CodeGenRegister::computeSubRegs(CodeGenRegBank &RegBank) {
224 // Only compute this map once.
227 SubRegsComplete = true;
229 // First insert the explicit subregs and make sure they are fully indexed.
230 for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
231 CodeGenRegister *SR = ExplicitSubRegs[i];
232 CodeGenSubRegIndex *Idx = ExplicitSubRegIndices[i];
233 if (!SubRegs.insert(std::make_pair(Idx, SR)).second)
234 PrintFatalError(TheDef->getLoc(), "SubRegIndex " + Idx->getName() +
235 " appears twice in Register " + getName());
236 // Map explicit sub-registers first, so the names take precedence.
237 // The inherited sub-registers are mapped below.
238 SubReg2Idx.insert(std::make_pair(SR, Idx));
241 // Keep track of inherited subregs and how they can be reached.
242 SmallPtrSet<CodeGenRegister*, 8> Orphans;
244 // Clone inherited subregs and place duplicate entries in Orphans.
245 // Here the order is important - earlier subregs take precedence.
246 for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
247 CodeGenRegister *SR = ExplicitSubRegs[i];
248 const SubRegMap &Map = SR->computeSubRegs(RegBank);
250 for (SubRegMap::const_iterator SI = Map.begin(), SE = Map.end(); SI != SE;
252 if (!SubRegs.insert(*SI).second)
253 Orphans.insert(SI->second);
257 // Expand any composed subreg indices.
258 // If dsub_2 has ComposedOf = [qsub_1, dsub_0], and this register has a
259 // qsub_1 subreg, add a dsub_2 subreg. Keep growing Indices and process
260 // expanded subreg indices recursively.
261 SmallVector<CodeGenSubRegIndex*, 8> Indices = ExplicitSubRegIndices;
262 for (unsigned i = 0; i != Indices.size(); ++i) {
263 CodeGenSubRegIndex *Idx = Indices[i];
264 const CodeGenSubRegIndex::CompMap &Comps = Idx->getComposites();
265 CodeGenRegister *SR = SubRegs[Idx];
266 const SubRegMap &Map = SR->computeSubRegs(RegBank);
268 // Look at the possible compositions of Idx.
269 // They may not all be supported by SR.
270 for (CodeGenSubRegIndex::CompMap::const_iterator I = Comps.begin(),
271 E = Comps.end(); I != E; ++I) {
272 SubRegMap::const_iterator SRI = Map.find(I->first);
273 if (SRI == Map.end())
274 continue; // Idx + I->first doesn't exist in SR.
275 // Add I->second as a name for the subreg SRI->second, assuming it is
276 // orphaned, and the name isn't already used for something else.
277 if (SubRegs.count(I->second) || !Orphans.erase(SRI->second))
279 // We found a new name for the orphaned sub-register.
280 SubRegs.insert(std::make_pair(I->second, SRI->second));
281 Indices.push_back(I->second);
285 // Now Orphans contains the inherited subregisters without a direct index.
286 // Create inferred indexes for all missing entries.
287 // Work backwards in the Indices vector in order to compose subregs bottom-up.
288 // Consider this subreg sequence:
290 // qsub_1 -> dsub_0 -> ssub_0
292 // The qsub_1 -> dsub_0 composition becomes dsub_2, so the ssub_0 register
293 // can be reached in two different ways:
298 // We pick the latter composition because another register may have [dsub_0,
299 // dsub_1, dsub_2] subregs without necessarily having a qsub_1 subreg. The
300 // dsub_2 -> ssub_0 composition can be shared.
301 while (!Indices.empty() && !Orphans.empty()) {
302 CodeGenSubRegIndex *Idx = Indices.pop_back_val();
303 CodeGenRegister *SR = SubRegs[Idx];
304 const SubRegMap &Map = SR->computeSubRegs(RegBank);
305 for (SubRegMap::const_iterator SI = Map.begin(), SE = Map.end(); SI != SE;
307 if (Orphans.erase(SI->second))
308 SubRegs[RegBank.getCompositeSubRegIndex(Idx, SI->first)] = SI->second;
311 // Compute the inverse SubReg -> Idx map.
312 for (SubRegMap::const_iterator SI = SubRegs.begin(), SE = SubRegs.end();
314 if (SI->second == this) {
317 Loc = TheDef->getLoc();
318 PrintFatalError(Loc, "Register " + getName() +
319 " has itself as a sub-register");
322 // Compute AllSuperRegsCovered.
323 if (!CoveredBySubRegs)
324 SI->first->AllSuperRegsCovered = false;
326 // Ensure that every sub-register has a unique name.
327 DenseMap<const CodeGenRegister*, CodeGenSubRegIndex*>::iterator Ins =
328 SubReg2Idx.insert(std::make_pair(SI->second, SI->first)).first;
329 if (Ins->second == SI->first)
331 // Trouble: Two different names for SI->second.
334 Loc = TheDef->getLoc();
335 PrintFatalError(Loc, "Sub-register can't have two names: " +
336 SI->second->getName() + " available as " +
337 SI->first->getName() + " and " + Ins->second->getName());
340 // Derive possible names for sub-register concatenations from any explicit
341 // sub-registers. By doing this before computeSecondarySubRegs(), we ensure
342 // that getConcatSubRegIndex() won't invent any concatenated indices that the
343 // user already specified.
344 for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
345 CodeGenRegister *SR = ExplicitSubRegs[i];
346 if (!SR->CoveredBySubRegs || SR->ExplicitSubRegs.size() <= 1)
349 // SR is composed of multiple sub-regs. Find their names in this register.
350 SmallVector<CodeGenSubRegIndex*, 8> Parts;
351 for (unsigned j = 0, e = SR->ExplicitSubRegs.size(); j != e; ++j)
352 Parts.push_back(getSubRegIndex(SR->ExplicitSubRegs[j]));
354 // Offer this as an existing spelling for the concatenation of Parts.
355 RegBank.addConcatSubRegIndex(Parts, ExplicitSubRegIndices[i]);
358 // Initialize RegUnitList. Because getSubRegs is called recursively, this
359 // processes the register hierarchy in postorder.
361 // Inherit all sub-register units. It is good enough to look at the explicit
362 // sub-registers, the other registers won't contribute any more units.
363 for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
364 CodeGenRegister *SR = ExplicitSubRegs[i];
365 // Explicit sub-registers are usually disjoint, so this is a good way of
366 // computing the union. We may pick up a few duplicates that will be
368 unsigned N = RegUnits.size();
369 RegUnits.append(SR->RegUnits.begin(), SR->RegUnits.end());
370 std::inplace_merge(RegUnits.begin(), RegUnits.begin() + N, RegUnits.end());
372 RegUnits.erase(std::unique(RegUnits.begin(), RegUnits.end()), RegUnits.end());
374 // Absent any ad hoc aliasing, we create one register unit per leaf register.
375 // These units correspond to the maximal cliques in the register overlap
376 // graph which is optimal.
378 // When there is ad hoc aliasing, we simply create one unit per edge in the
379 // undirected ad hoc aliasing graph. Technically, we could do better by
380 // identifying maximal cliques in the ad hoc graph, but cliques larger than 2
381 // are extremely rare anyway (I've never seen one), so we don't bother with
382 // the added complexity.
383 for (unsigned i = 0, e = ExplicitAliases.size(); i != e; ++i) {
384 CodeGenRegister *AR = ExplicitAliases[i];
385 // Only visit each edge once.
386 if (AR->SubRegsComplete)
388 // Create a RegUnit representing this alias edge, and add it to both
390 unsigned Unit = RegBank.newRegUnit(this, AR);
391 RegUnits.push_back(Unit);
392 AR->RegUnits.push_back(Unit);
395 // Finally, create units for leaf registers without ad hoc aliases. Note that
396 // a leaf register with ad hoc aliases doesn't get its own unit - it isn't
397 // necessary. This means the aliasing leaf registers can share a single unit.
398 if (RegUnits.empty())
399 RegUnits.push_back(RegBank.newRegUnit(this));
401 // We have now computed the native register units. More may be adopted later
402 // for balancing purposes.
403 NumNativeRegUnits = RegUnits.size();
408 // In a register that is covered by its sub-registers, try to find redundant
409 // sub-registers. For example:
415 // We can infer that D1_D2 is also a sub-register, even if it wasn't named in
416 // the register definition.
418 // The explicitly specified registers form a tree. This function discovers
419 // sub-register relationships that would force a DAG.
421 void CodeGenRegister::computeSecondarySubRegs(CodeGenRegBank &RegBank) {
422 // Collect new sub-registers first, add them later.
423 SmallVector<SubRegMap::value_type, 8> NewSubRegs;
425 // Look at the leading super-registers of each sub-register. Those are the
426 // candidates for new sub-registers, assuming they are fully contained in
428 for (SubRegMap::iterator I = SubRegs.begin(), E = SubRegs.end(); I != E; ++I){
429 const CodeGenRegister *SubReg = I->second;
430 const CodeGenRegister::SuperRegList &Leads = SubReg->LeadingSuperRegs;
431 for (unsigned i = 0, e = Leads.size(); i != e; ++i) {
432 CodeGenRegister *Cand = const_cast<CodeGenRegister*>(Leads[i]);
433 // Already got this sub-register?
434 if (Cand == this || getSubRegIndex(Cand))
436 // Check if each component of Cand is already a sub-register.
437 // We know that the first component is I->second, and is present with the
439 SmallVector<CodeGenSubRegIndex*, 8> Parts(1, I->first);
440 assert(!Cand->ExplicitSubRegs.empty() &&
441 "Super-register has no sub-registers");
442 for (unsigned j = 1, e = Cand->ExplicitSubRegs.size(); j != e; ++j) {
443 if (CodeGenSubRegIndex *Idx = getSubRegIndex(Cand->ExplicitSubRegs[j]))
444 Parts.push_back(Idx);
446 // Sub-register doesn't exist.
451 // If some Cand sub-register is not part of this register, or if Cand only
452 // has one sub-register, there is nothing to do.
453 if (Parts.size() <= 1)
456 // Each part of Cand is a sub-register of this. Make the full Cand also
457 // a sub-register with a concatenated sub-register index.
458 CodeGenSubRegIndex *Concat= RegBank.getConcatSubRegIndex(Parts);
459 NewSubRegs.push_back(std::make_pair(Concat, Cand));
463 // Now add all the new sub-registers.
464 for (unsigned i = 0, e = NewSubRegs.size(); i != e; ++i) {
465 // Don't add Cand if another sub-register is already using the index.
466 if (!SubRegs.insert(NewSubRegs[i]).second)
469 CodeGenSubRegIndex *NewIdx = NewSubRegs[i].first;
470 CodeGenRegister *NewSubReg = NewSubRegs[i].second;
471 SubReg2Idx.insert(std::make_pair(NewSubReg, NewIdx));
474 // Create sub-register index composition maps for the synthesized indices.
475 for (unsigned i = 0, e = NewSubRegs.size(); i != e; ++i) {
476 CodeGenSubRegIndex *NewIdx = NewSubRegs[i].first;
477 CodeGenRegister *NewSubReg = NewSubRegs[i].second;
478 for (SubRegMap::const_iterator SI = NewSubReg->SubRegs.begin(),
479 SE = NewSubReg->SubRegs.end(); SI != SE; ++SI) {
480 CodeGenSubRegIndex *SubIdx = getSubRegIndex(SI->second);
482 PrintFatalError(TheDef->getLoc(), "No SubRegIndex for " +
483 SI->second->getName() + " in " + getName());
484 NewIdx->addComposite(SI->first, SubIdx);
489 void CodeGenRegister::computeSuperRegs(CodeGenRegBank &RegBank) {
490 // Only visit each register once.
491 if (SuperRegsComplete)
493 SuperRegsComplete = true;
495 // Make sure all sub-registers have been visited first, so the super-reg
496 // lists will be topologically ordered.
497 for (SubRegMap::const_iterator I = SubRegs.begin(), E = SubRegs.end();
499 I->second->computeSuperRegs(RegBank);
501 // Now add this as a super-register on all sub-registers.
502 // Also compute the TopoSigId in post-order.
504 for (SubRegMap::const_iterator I = SubRegs.begin(), E = SubRegs.end();
506 // Topological signature computed from SubIdx, TopoId(SubReg).
507 // Loops and idempotent indices have TopoSig = ~0u.
508 Id.push_back(I->first->EnumValue);
509 Id.push_back(I->second->TopoSig);
511 // Don't add duplicate entries.
512 if (!I->second->SuperRegs.empty() && I->second->SuperRegs.back() == this)
514 I->second->SuperRegs.push_back(this);
516 TopoSig = RegBank.getTopoSig(Id);
520 CodeGenRegister::addSubRegsPreOrder(SetVector<const CodeGenRegister*> &OSet,
521 CodeGenRegBank &RegBank) const {
522 assert(SubRegsComplete && "Must precompute sub-registers");
523 for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
524 CodeGenRegister *SR = ExplicitSubRegs[i];
526 SR->addSubRegsPreOrder(OSet, RegBank);
528 // Add any secondary sub-registers that weren't part of the explicit tree.
529 for (SubRegMap::const_iterator I = SubRegs.begin(), E = SubRegs.end();
531 OSet.insert(I->second);
534 // Get the sum of this register's unit weights.
535 unsigned CodeGenRegister::getWeight(const CodeGenRegBank &RegBank) const {
537 for (RegUnitList::const_iterator I = RegUnits.begin(), E = RegUnits.end();
539 Weight += RegBank.getRegUnit(*I).Weight;
544 //===----------------------------------------------------------------------===//
546 //===----------------------------------------------------------------------===//
548 // A RegisterTuples def is used to generate pseudo-registers from lists of
549 // sub-registers. We provide a SetTheory expander class that returns the new
552 struct TupleExpander : SetTheory::Expander {
553 void expand(SetTheory &ST, Record *Def, SetTheory::RecSet &Elts) override {
554 std::vector<Record*> Indices = Def->getValueAsListOfDefs("SubRegIndices");
555 unsigned Dim = Indices.size();
556 ListInit *SubRegs = Def->getValueAsListInit("SubRegs");
557 if (Dim != SubRegs->getSize())
558 PrintFatalError(Def->getLoc(), "SubRegIndices and SubRegs size mismatch");
560 PrintFatalError(Def->getLoc(),
561 "Tuples must have at least 2 sub-registers");
563 // Evaluate the sub-register lists to be zipped.
564 unsigned Length = ~0u;
565 SmallVector<SetTheory::RecSet, 4> Lists(Dim);
566 for (unsigned i = 0; i != Dim; ++i) {
567 ST.evaluate(SubRegs->getElement(i), Lists[i], Def->getLoc());
568 Length = std::min(Length, unsigned(Lists[i].size()));
574 // Precompute some types.
575 Record *RegisterCl = Def->getRecords().getClass("Register");
576 RecTy *RegisterRecTy = RecordRecTy::get(RegisterCl);
577 StringInit *BlankName = StringInit::get("");
580 for (unsigned n = 0; n != Length; ++n) {
582 Record *Proto = Lists[0][n];
583 std::vector<Init*> Tuple;
584 unsigned CostPerUse = 0;
585 for (unsigned i = 0; i != Dim; ++i) {
586 Record *Reg = Lists[i][n];
588 Name += Reg->getName();
589 Tuple.push_back(DefInit::get(Reg));
590 CostPerUse = std::max(CostPerUse,
591 unsigned(Reg->getValueAsInt("CostPerUse")));
594 // Create a new Record representing the synthesized register. This record
595 // is only for consumption by CodeGenRegister, it is not added to the
597 Record *NewReg = new Record(Name, Def->getLoc(), Def->getRecords());
600 // Copy Proto super-classes.
601 ArrayRef<Record *> Supers = Proto->getSuperClasses();
602 ArrayRef<SMRange> Ranges = Proto->getSuperClassRanges();
603 for (unsigned i = 0, e = Supers.size(); i != e; ++i)
604 NewReg->addSuperClass(Supers[i], Ranges[i]);
606 // Copy Proto fields.
607 for (unsigned i = 0, e = Proto->getValues().size(); i != e; ++i) {
608 RecordVal RV = Proto->getValues()[i];
610 // Skip existing fields, like NAME.
611 if (NewReg->getValue(RV.getNameInit()))
614 StringRef Field = RV.getName();
616 // Replace the sub-register list with Tuple.
617 if (Field == "SubRegs")
618 RV.setValue(ListInit::get(Tuple, RegisterRecTy));
620 // Provide a blank AsmName. MC hacks are required anyway.
621 if (Field == "AsmName")
622 RV.setValue(BlankName);
624 // CostPerUse is aggregated from all Tuple members.
625 if (Field == "CostPerUse")
626 RV.setValue(IntInit::get(CostPerUse));
628 // Composite registers are always covered by sub-registers.
629 if (Field == "CoveredBySubRegs")
630 RV.setValue(BitInit::get(true));
632 // Copy fields from the RegisterTuples def.
633 if (Field == "SubRegIndices" ||
634 Field == "CompositeIndices") {
635 NewReg->addValue(*Def->getValue(Field));
639 // Some fields get their default uninitialized value.
640 if (Field == "DwarfNumbers" ||
641 Field == "DwarfAlias" ||
642 Field == "Aliases") {
643 if (const RecordVal *DefRV = RegisterCl->getValue(Field))
644 NewReg->addValue(*DefRV);
648 // Everything else is copied from Proto.
649 NewReg->addValue(RV);
656 //===----------------------------------------------------------------------===//
657 // CodeGenRegisterClass
658 //===----------------------------------------------------------------------===//
660 CodeGenRegisterClass::CodeGenRegisterClass(CodeGenRegBank &RegBank, Record *R)
663 TopoSigs(RegBank.getNumTopoSigs()),
665 // Rename anonymous register classes.
666 if (R->getName().size() > 9 && R->getName()[9] == '.') {
667 static unsigned AnonCounter = 0;
668 R->setName("AnonRegClass_" + utostr(AnonCounter));
669 // MSVC2012 ICEs if AnonCounter++ is directly passed to utostr.
673 std::vector<Record*> TypeList = R->getValueAsListOfDefs("RegTypes");
674 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
675 Record *Type = TypeList[i];
676 if (!Type->isSubClassOf("ValueType"))
677 PrintFatalError("RegTypes list member '" + Type->getName() +
678 "' does not derive from the ValueType class!");
679 VTs.push_back(getValueType(Type));
681 assert(!VTs.empty() && "RegisterClass must contain at least one ValueType!");
683 // Allocation order 0 is the full set. AltOrders provides others.
684 const SetTheory::RecVec *Elements = RegBank.getSets().expand(R);
685 ListInit *AltOrders = R->getValueAsListInit("AltOrders");
686 Orders.resize(1 + AltOrders->size());
688 // Default allocation order always contains all registers.
689 for (unsigned i = 0, e = Elements->size(); i != e; ++i) {
690 Orders[0].push_back((*Elements)[i]);
691 const CodeGenRegister *Reg = RegBank.getReg((*Elements)[i]);
693 TopoSigs.set(Reg->getTopoSig());
696 // Alternative allocation orders may be subsets.
697 SetTheory::RecSet Order;
698 for (unsigned i = 0, e = AltOrders->size(); i != e; ++i) {
699 RegBank.getSets().evaluate(AltOrders->getElement(i), Order, R->getLoc());
700 Orders[1 + i].append(Order.begin(), Order.end());
701 // Verify that all altorder members are regclass members.
702 while (!Order.empty()) {
703 CodeGenRegister *Reg = RegBank.getReg(Order.back());
706 PrintFatalError(R->getLoc(), " AltOrder register " + Reg->getName() +
707 " is not a class member");
711 // Allow targets to override the size in bits of the RegisterClass.
712 unsigned Size = R->getValueAsInt("Size");
714 Namespace = R->getValueAsString("Namespace");
715 SpillSize = Size ? Size : MVT(VTs[0]).getSizeInBits();
716 SpillAlignment = R->getValueAsInt("Alignment");
717 CopyCost = R->getValueAsInt("CopyCost");
718 Allocatable = R->getValueAsBit("isAllocatable");
719 AltOrderSelect = R->getValueAsString("AltOrderSelect");
722 // Create an inferred register class that was missing from the .td files.
723 // Most properties will be inherited from the closest super-class after the
724 // class structure has been computed.
725 CodeGenRegisterClass::CodeGenRegisterClass(CodeGenRegBank &RegBank,
726 StringRef Name, Key Props)
727 : Members(*Props.Members),
730 TopoSigs(RegBank.getNumTopoSigs()),
732 SpillSize(Props.SpillSize),
733 SpillAlignment(Props.SpillAlignment),
736 for (CodeGenRegister::Set::iterator I = Members.begin(), E = Members.end();
738 TopoSigs.set((*I)->getTopoSig());
741 // Compute inherited propertied for a synthesized register class.
742 void CodeGenRegisterClass::inheritProperties(CodeGenRegBank &RegBank) {
743 assert(!getDef() && "Only synthesized classes can inherit properties");
744 assert(!SuperClasses.empty() && "Synthesized class without super class");
746 // The last super-class is the smallest one.
747 CodeGenRegisterClass &Super = *SuperClasses.back();
749 // Most properties are copied directly.
750 // Exceptions are members, size, and alignment
751 Namespace = Super.Namespace;
753 CopyCost = Super.CopyCost;
754 Allocatable = Super.Allocatable;
755 AltOrderSelect = Super.AltOrderSelect;
757 // Copy all allocation orders, filter out foreign registers from the larger
759 Orders.resize(Super.Orders.size());
760 for (unsigned i = 0, ie = Super.Orders.size(); i != ie; ++i)
761 for (unsigned j = 0, je = Super.Orders[i].size(); j != je; ++j)
762 if (contains(RegBank.getReg(Super.Orders[i][j])))
763 Orders[i].push_back(Super.Orders[i][j]);
766 bool CodeGenRegisterClass::contains(const CodeGenRegister *Reg) const {
767 return Members.count(Reg);
771 raw_ostream &operator<<(raw_ostream &OS, const CodeGenRegisterClass::Key &K) {
772 OS << "{ S=" << K.SpillSize << ", A=" << K.SpillAlignment;
773 for (CodeGenRegister::Set::const_iterator I = K.Members->begin(),
774 E = K.Members->end(); I != E; ++I)
775 OS << ", " << (*I)->getName();
780 // This is a simple lexicographical order that can be used to search for sets.
781 // It is not the same as the topological order provided by TopoOrderRC.
782 bool CodeGenRegisterClass::Key::
783 operator<(const CodeGenRegisterClass::Key &B) const {
784 assert(Members && B.Members);
785 return std::tie(*Members, SpillSize, SpillAlignment) <
786 std::tie(*B.Members, B.SpillSize, B.SpillAlignment);
789 // Returns true if RC is a strict subclass.
790 // RC is a sub-class of this class if it is a valid replacement for any
791 // instruction operand where a register of this classis required. It must
792 // satisfy these conditions:
794 // 1. All RC registers are also in this.
795 // 2. The RC spill size must not be smaller than our spill size.
796 // 3. RC spill alignment must be compatible with ours.
798 static bool testSubClass(const CodeGenRegisterClass *A,
799 const CodeGenRegisterClass *B) {
800 return A->SpillAlignment && B->SpillAlignment % A->SpillAlignment == 0 &&
801 A->SpillSize <= B->SpillSize &&
802 std::includes(A->getMembers().begin(), A->getMembers().end(),
803 B->getMembers().begin(), B->getMembers().end(),
804 CodeGenRegister::Less());
807 /// Sorting predicate for register classes. This provides a topological
808 /// ordering that arranges all register classes before their sub-classes.
810 /// Register classes with the same registers, spill size, and alignment form a
811 /// clique. They will be ordered alphabetically.
813 static bool TopoOrderRC(const CodeGenRegisterClass &PA,
814 const CodeGenRegisterClass &PB) {
820 // Order by ascending spill size.
821 if (A->SpillSize < B->SpillSize)
823 if (A->SpillSize > B->SpillSize)
826 // Order by ascending spill alignment.
827 if (A->SpillAlignment < B->SpillAlignment)
829 if (A->SpillAlignment > B->SpillAlignment)
832 // Order by descending set size. Note that the classes' allocation order may
833 // not have been computed yet. The Members set is always vaild.
834 if (A->getMembers().size() > B->getMembers().size())
836 if (A->getMembers().size() < B->getMembers().size())
839 // Finally order by name as a tie breaker.
840 return StringRef(A->getName()) < B->getName();
843 std::string CodeGenRegisterClass::getQualifiedName() const {
844 if (Namespace.empty())
847 return Namespace + "::" + getName();
850 // Compute sub-classes of all register classes.
851 // Assume the classes are ordered topologically.
852 void CodeGenRegisterClass::computeSubClasses(CodeGenRegBank &RegBank) {
853 auto &RegClasses = RegBank.getRegClasses();
855 // Visit backwards so sub-classes are seen first.
856 for (auto I = RegClasses.rbegin(), E = RegClasses.rend(); I != E; ++I) {
857 CodeGenRegisterClass &RC = *I;
858 RC.SubClasses.resize(RegClasses.size());
859 RC.SubClasses.set(RC.EnumValue);
861 // Normally, all subclasses have IDs >= rci, unless RC is part of a clique.
862 for (auto I2 = I.base(), E2 = RegClasses.end(); I2 != E2; ++I2) {
863 CodeGenRegisterClass &SubRC = *I2;
864 if (RC.SubClasses.test(SubRC.EnumValue))
866 if (!testSubClass(&RC, &SubRC))
868 // SubRC is a sub-class. Grap all its sub-classes so we won't have to
870 RC.SubClasses |= SubRC.SubClasses;
873 // Sweep up missed clique members. They will be immediately preceding RC.
874 for (auto I2 = std::next(I); I2 != E && testSubClass(&RC, &*I2); ++I2)
875 RC.SubClasses.set(I2->EnumValue);
878 // Compute the SuperClasses lists from the SubClasses vectors.
879 for (auto &RC : RegClasses) {
880 const BitVector &SC = RC.getSubClasses();
881 auto I = RegClasses.begin();
882 for (int s = 0, next_s = SC.find_first(); next_s != -1;
883 next_s = SC.find_next(s)) {
884 std::advance(I, next_s - s);
888 I->SuperClasses.push_back(&RC);
892 // With the class hierarchy in place, let synthesized register classes inherit
893 // properties from their closest super-class. The iteration order here can
894 // propagate properties down multiple levels.
895 for (auto &RC : RegClasses)
897 RC.inheritProperties(RegBank);
900 void CodeGenRegisterClass::getSuperRegClasses(const CodeGenSubRegIndex *SubIdx,
901 BitVector &Out) const {
902 auto FindI = SuperRegClasses.find(SubIdx);
903 if (FindI == SuperRegClasses.end())
905 for (CodeGenRegisterClass *RC : FindI->second)
906 Out.set(RC->EnumValue);
909 // Populate a unique sorted list of units from a register set.
910 void CodeGenRegisterClass::buildRegUnitSet(
911 std::vector<unsigned> &RegUnits) const {
912 std::vector<unsigned> TmpUnits;
913 for (RegUnitIterator UnitI(Members); UnitI.isValid(); ++UnitI)
914 TmpUnits.push_back(*UnitI);
915 std::sort(TmpUnits.begin(), TmpUnits.end());
916 std::unique_copy(TmpUnits.begin(), TmpUnits.end(),
917 std::back_inserter(RegUnits));
920 //===----------------------------------------------------------------------===//
922 //===----------------------------------------------------------------------===//
924 CodeGenRegBank::CodeGenRegBank(RecordKeeper &Records) {
925 // Configure register Sets to understand register classes and tuples.
926 Sets.addFieldExpander("RegisterClass", "MemberList");
927 Sets.addFieldExpander("CalleeSavedRegs", "SaveList");
928 Sets.addExpander("RegisterTuples", new TupleExpander());
930 // Read in the user-defined (named) sub-register indices.
931 // More indices will be synthesized later.
932 std::vector<Record*> SRIs = Records.getAllDerivedDefinitions("SubRegIndex");
933 std::sort(SRIs.begin(), SRIs.end(), LessRecord());
934 for (unsigned i = 0, e = SRIs.size(); i != e; ++i)
935 getSubRegIdx(SRIs[i]);
936 // Build composite maps from ComposedOf fields.
937 for (auto &Idx : SubRegIndices)
938 Idx.updateComponents(*this);
940 // Read in the register definitions.
941 std::vector<Record*> Regs = Records.getAllDerivedDefinitions("Register");
942 std::sort(Regs.begin(), Regs.end(), LessRecordRegister());
943 // Assign the enumeration values.
944 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
947 // Expand tuples and number the new registers.
948 std::vector<Record*> Tups =
949 Records.getAllDerivedDefinitions("RegisterTuples");
951 for (Record *R : Tups) {
952 std::vector<Record *> TupRegs = *Sets.expand(R);
953 std::sort(TupRegs.begin(), TupRegs.end(), LessRecordRegister());
954 for (Record *RC : TupRegs)
958 // Now all the registers are known. Build the object graph of explicit
959 // register-register references.
960 for (auto &Reg : Registers)
961 Reg.buildObjectGraph(*this);
963 // Compute register name map.
964 for (auto &Reg : Registers)
965 // FIXME: This could just be RegistersByName[name] = register, except that
966 // causes some failures in MIPS - perhaps they have duplicate register name
967 // entries? (or maybe there's a reason for it - I don't know much about this
968 // code, just drive-by refactoring)
969 RegistersByName.insert(
970 std::make_pair(Reg.TheDef->getValueAsString("AsmName"), &Reg));
972 // Precompute all sub-register maps.
973 // This will create Composite entries for all inferred sub-register indices.
974 for (auto &Reg : Registers)
975 Reg.computeSubRegs(*this);
977 // Infer even more sub-registers by combining leading super-registers.
978 for (auto &Reg : Registers)
979 if (Reg.CoveredBySubRegs)
980 Reg.computeSecondarySubRegs(*this);
982 // After the sub-register graph is complete, compute the topologically
983 // ordered SuperRegs list.
984 for (auto &Reg : Registers)
985 Reg.computeSuperRegs(*this);
987 // Native register units are associated with a leaf register. They've all been
989 NumNativeRegUnits = RegUnits.size();
991 // Read in register class definitions.
992 std::vector<Record*> RCs = Records.getAllDerivedDefinitions("RegisterClass");
994 PrintFatalError("No 'RegisterClass' subclasses defined!");
996 // Allocate user-defined register classes.
997 for (auto *RC : RCs) {
998 RegClasses.push_back(CodeGenRegisterClass(*this, RC));
999 addToMaps(&RegClasses.back());
1002 // Infer missing classes to create a full algebra.
1003 computeInferredRegisterClasses();
1005 // Order register classes topologically and assign enum values.
1006 RegClasses.sort(TopoOrderRC);
1008 for (auto &RC : RegClasses)
1010 CodeGenRegisterClass::computeSubClasses(*this);
1013 // Create a synthetic CodeGenSubRegIndex without a corresponding Record.
1015 CodeGenRegBank::createSubRegIndex(StringRef Name, StringRef Namespace) {
1016 SubRegIndices.emplace_back(Name, Namespace, SubRegIndices.size() + 1);
1017 return &SubRegIndices.back();
1020 CodeGenSubRegIndex *CodeGenRegBank::getSubRegIdx(Record *Def) {
1021 CodeGenSubRegIndex *&Idx = Def2SubRegIdx[Def];
1024 SubRegIndices.emplace_back(Def, SubRegIndices.size() + 1);
1025 Idx = &SubRegIndices.back();
1029 CodeGenRegister *CodeGenRegBank::getReg(Record *Def) {
1030 CodeGenRegister *&Reg = Def2Reg[Def];
1033 Registers.emplace_back(Def, Registers.size() + 1);
1034 Reg = &Registers.back();
1038 void CodeGenRegBank::addToMaps(CodeGenRegisterClass *RC) {
1039 if (Record *Def = RC->getDef())
1040 Def2RC.insert(std::make_pair(Def, RC));
1042 // Duplicate classes are rejected by insert().
1043 // That's OK, we only care about the properties handled by CGRC::Key.
1044 CodeGenRegisterClass::Key K(*RC);
1045 Key2RC.insert(std::make_pair(K, RC));
1048 // Create a synthetic sub-class if it is missing.
1049 CodeGenRegisterClass*
1050 CodeGenRegBank::getOrCreateSubClass(const CodeGenRegisterClass *RC,
1051 const CodeGenRegister::Set *Members,
1053 // Synthetic sub-class has the same size and alignment as RC.
1054 CodeGenRegisterClass::Key K(Members, RC->SpillSize, RC->SpillAlignment);
1055 RCKeyMap::const_iterator FoundI = Key2RC.find(K);
1056 if (FoundI != Key2RC.end())
1057 return FoundI->second;
1059 // Sub-class doesn't exist, create a new one.
1060 RegClasses.push_back(CodeGenRegisterClass(*this, Name, K));
1061 addToMaps(&RegClasses.back());
1062 return &RegClasses.back();
1065 CodeGenRegisterClass *CodeGenRegBank::getRegClass(Record *Def) {
1066 if (CodeGenRegisterClass *RC = Def2RC[Def])
1069 PrintFatalError(Def->getLoc(), "Not a known RegisterClass!");
1073 CodeGenRegBank::getCompositeSubRegIndex(CodeGenSubRegIndex *A,
1074 CodeGenSubRegIndex *B) {
1075 // Look for an existing entry.
1076 CodeGenSubRegIndex *Comp = A->compose(B);
1080 // None exists, synthesize one.
1081 std::string Name = A->getName() + "_then_" + B->getName();
1082 Comp = createSubRegIndex(Name, A->getNamespace());
1083 A->addComposite(B, Comp);
1087 CodeGenSubRegIndex *CodeGenRegBank::
1088 getConcatSubRegIndex(const SmallVector<CodeGenSubRegIndex *, 8> &Parts) {
1089 assert(Parts.size() > 1 && "Need two parts to concatenate");
1091 // Look for an existing entry.
1092 CodeGenSubRegIndex *&Idx = ConcatIdx[Parts];
1096 // None exists, synthesize one.
1097 std::string Name = Parts.front()->getName();
1098 // Determine whether all parts are contiguous.
1099 bool isContinuous = true;
1100 unsigned Size = Parts.front()->Size;
1101 unsigned LastOffset = Parts.front()->Offset;
1102 unsigned LastSize = Parts.front()->Size;
1103 for (unsigned i = 1, e = Parts.size(); i != e; ++i) {
1105 Name += Parts[i]->getName();
1106 Size += Parts[i]->Size;
1107 if (Parts[i]->Offset != (LastOffset + LastSize))
1108 isContinuous = false;
1109 LastOffset = Parts[i]->Offset;
1110 LastSize = Parts[i]->Size;
1112 Idx = createSubRegIndex(Name, Parts.front()->getNamespace());
1114 Idx->Offset = isContinuous ? Parts.front()->Offset : -1;
1118 void CodeGenRegBank::computeComposites() {
1119 // Keep track of TopoSigs visited. We only need to visit each TopoSig once,
1120 // and many registers will share TopoSigs on regular architectures.
1121 BitVector TopoSigs(getNumTopoSigs());
1123 for (const auto &Reg1 : Registers) {
1124 // Skip identical subreg structures already processed.
1125 if (TopoSigs.test(Reg1.getTopoSig()))
1127 TopoSigs.set(Reg1.getTopoSig());
1129 const CodeGenRegister::SubRegMap &SRM1 = Reg1.getSubRegs();
1130 for (CodeGenRegister::SubRegMap::const_iterator i1 = SRM1.begin(),
1131 e1 = SRM1.end(); i1 != e1; ++i1) {
1132 CodeGenSubRegIndex *Idx1 = i1->first;
1133 CodeGenRegister *Reg2 = i1->second;
1134 // Ignore identity compositions.
1137 const CodeGenRegister::SubRegMap &SRM2 = Reg2->getSubRegs();
1138 // Try composing Idx1 with another SubRegIndex.
1139 for (CodeGenRegister::SubRegMap::const_iterator i2 = SRM2.begin(),
1140 e2 = SRM2.end(); i2 != e2; ++i2) {
1141 CodeGenSubRegIndex *Idx2 = i2->first;
1142 CodeGenRegister *Reg3 = i2->second;
1143 // Ignore identity compositions.
1146 // OK Reg1:IdxPair == Reg3. Find the index with Reg:Idx == Reg3.
1147 CodeGenSubRegIndex *Idx3 = Reg1.getSubRegIndex(Reg3);
1148 assert(Idx3 && "Sub-register doesn't have an index");
1150 // Conflicting composition? Emit a warning but allow it.
1151 if (CodeGenSubRegIndex *Prev = Idx1->addComposite(Idx2, Idx3))
1152 PrintWarning(Twine("SubRegIndex ") + Idx1->getQualifiedName() +
1153 " and " + Idx2->getQualifiedName() +
1154 " compose ambiguously as " + Prev->getQualifiedName() +
1155 " or " + Idx3->getQualifiedName());
1161 // Compute lane masks. This is similar to register units, but at the
1162 // sub-register index level. Each bit in the lane mask is like a register unit
1163 // class, and two lane masks will have a bit in common if two sub-register
1164 // indices overlap in some register.
1166 // Conservatively share a lane mask bit if two sub-register indices overlap in
1167 // some registers, but not in others. That shouldn't happen a lot.
1168 void CodeGenRegBank::computeSubRegIndexLaneMasks() {
1169 // First assign individual bits to all the leaf indices.
1171 // Determine mask of lanes that cover their registers.
1172 CoveringLanes = ~0u;
1173 for (auto &Idx : SubRegIndices) {
1174 if (Idx.getComposites().empty()) {
1175 Idx.LaneMask = 1u << Bit;
1176 // Share bit 31 in the unlikely case there are more than 32 leafs.
1178 // Sharing bits is harmless; it allows graceful degradation in targets
1179 // with more than 32 vector lanes. They simply get a limited resolution
1180 // view of lanes beyond the 32nd.
1182 // See also the comment for getSubRegIndexLaneMask().
1186 // Once bit 31 is shared among multiple leafs, the 'lane' it represents
1187 // is no longer covering its registers.
1188 CoveringLanes &= ~(1u << Bit);
1194 // FIXME: What if ad-hoc aliasing introduces overlaps that aren't represented
1195 // by the sub-register graph? This doesn't occur in any known targets.
1197 // Inherit lanes from composites.
1198 for (const auto &Idx : SubRegIndices) {
1199 unsigned Mask = Idx.computeLaneMask();
1200 // If some super-registers without CoveredBySubRegs use this index, we can
1201 // no longer assume that the lanes are covering their registers.
1202 if (!Idx.AllSuperRegsCovered)
1203 CoveringLanes &= ~Mask;
1208 // UberRegSet is a helper class for computeRegUnitWeights. Each UberRegSet is
1209 // the transitive closure of the union of overlapping register
1210 // classes. Together, the UberRegSets form a partition of the registers. If we
1211 // consider overlapping register classes to be connected, then each UberRegSet
1212 // is a set of connected components.
1214 // An UberRegSet will likely be a horizontal slice of register names of
1215 // the same width. Nontrivial subregisters should then be in a separate
1216 // UberRegSet. But this property isn't required for valid computation of
1217 // register unit weights.
1219 // A Weight field caches the max per-register unit weight in each UberRegSet.
1221 // A set of SingularDeterminants flags single units of some register in this set
1222 // for which the unit weight equals the set weight. These units should not have
1223 // their weight increased.
1225 CodeGenRegister::Set Regs;
1227 CodeGenRegister::RegUnitList SingularDeterminants;
1229 UberRegSet(): Weight(0) {}
1233 // Partition registers into UberRegSets, where each set is the transitive
1234 // closure of the union of overlapping register classes.
1236 // UberRegSets[0] is a special non-allocatable set.
1237 static void computeUberSets(std::vector<UberRegSet> &UberSets,
1238 std::vector<UberRegSet*> &RegSets,
1239 CodeGenRegBank &RegBank) {
1241 const auto &Registers = RegBank.getRegisters();
1243 // The Register EnumValue is one greater than its index into Registers.
1244 assert(Registers.size() == Registers.back().EnumValue &&
1245 "register enum value mismatch");
1247 // For simplicitly make the SetID the same as EnumValue.
1248 IntEqClasses UberSetIDs(Registers.size()+1);
1249 std::set<unsigned> AllocatableRegs;
1250 for (auto &RegClass : RegBank.getRegClasses()) {
1251 if (!RegClass.Allocatable)
1254 const CodeGenRegister::Set &Regs = RegClass.getMembers();
1258 unsigned USetID = UberSetIDs.findLeader((*Regs.begin())->EnumValue);
1259 assert(USetID && "register number 0 is invalid");
1261 AllocatableRegs.insert((*Regs.begin())->EnumValue);
1262 for (CodeGenRegister::Set::const_iterator I = std::next(Regs.begin()),
1263 E = Regs.end(); I != E; ++I) {
1264 AllocatableRegs.insert((*I)->EnumValue);
1265 UberSetIDs.join(USetID, (*I)->EnumValue);
1268 // Combine non-allocatable regs.
1269 for (const auto &Reg : Registers) {
1270 unsigned RegNum = Reg.EnumValue;
1271 if (AllocatableRegs.count(RegNum))
1274 UberSetIDs.join(0, RegNum);
1276 UberSetIDs.compress();
1278 // Make the first UberSet a special unallocatable set.
1279 unsigned ZeroID = UberSetIDs[0];
1281 // Insert Registers into the UberSets formed by union-find.
1282 // Do not resize after this.
1283 UberSets.resize(UberSetIDs.getNumClasses());
1285 for (const CodeGenRegister &Reg : Registers) {
1286 unsigned USetID = UberSetIDs[Reg.EnumValue];
1289 else if (USetID == ZeroID)
1292 UberRegSet *USet = &UberSets[USetID];
1293 USet->Regs.insert(&Reg);
1294 RegSets[i++] = USet;
1298 // Recompute each UberSet weight after changing unit weights.
1299 static void computeUberWeights(std::vector<UberRegSet> &UberSets,
1300 CodeGenRegBank &RegBank) {
1301 // Skip the first unallocatable set.
1302 for (std::vector<UberRegSet>::iterator I = std::next(UberSets.begin()),
1303 E = UberSets.end(); I != E; ++I) {
1305 // Initialize all unit weights in this set, and remember the max units/reg.
1306 const CodeGenRegister *Reg = nullptr;
1307 unsigned MaxWeight = 0, Weight = 0;
1308 for (RegUnitIterator UnitI(I->Regs); UnitI.isValid(); ++UnitI) {
1309 if (Reg != UnitI.getReg()) {
1310 if (Weight > MaxWeight)
1312 Reg = UnitI.getReg();
1315 unsigned UWeight = RegBank.getRegUnit(*UnitI).Weight;
1318 RegBank.increaseRegUnitWeight(*UnitI, UWeight);
1322 if (Weight > MaxWeight)
1324 if (I->Weight != MaxWeight) {
1326 dbgs() << "UberSet " << I - UberSets.begin() << " Weight " << MaxWeight;
1327 for (CodeGenRegister::Set::iterator
1328 UnitI = I->Regs.begin(), UnitE = I->Regs.end();
1329 UnitI != UnitE; ++UnitI) {
1330 dbgs() << " " << (*UnitI)->getName();
1333 // Update the set weight.
1334 I->Weight = MaxWeight;
1337 // Find singular determinants.
1338 for (CodeGenRegister::Set::iterator RegI = I->Regs.begin(),
1339 RegE = I->Regs.end(); RegI != RegE; ++RegI) {
1340 if ((*RegI)->getRegUnits().size() == 1
1341 && (*RegI)->getWeight(RegBank) == I->Weight)
1342 mergeRegUnits(I->SingularDeterminants, (*RegI)->getRegUnits());
1347 // normalizeWeight is a computeRegUnitWeights helper that adjusts the weight of
1348 // a register and its subregisters so that they have the same weight as their
1349 // UberSet. Self-recursion processes the subregister tree in postorder so
1350 // subregisters are normalized first.
1353 // - creates new adopted register units
1354 // - causes superregisters to inherit adopted units
1355 // - increases the weight of "singular" units
1356 // - induces recomputation of UberWeights.
1357 static bool normalizeWeight(CodeGenRegister *Reg,
1358 std::vector<UberRegSet> &UberSets,
1359 std::vector<UberRegSet*> &RegSets,
1360 std::set<unsigned> &NormalRegs,
1361 CodeGenRegister::RegUnitList &NormalUnits,
1362 CodeGenRegBank &RegBank) {
1363 bool Changed = false;
1364 if (!NormalRegs.insert(Reg->EnumValue).second)
1367 const CodeGenRegister::SubRegMap &SRM = Reg->getSubRegs();
1368 for (CodeGenRegister::SubRegMap::const_iterator SRI = SRM.begin(),
1369 SRE = SRM.end(); SRI != SRE; ++SRI) {
1370 if (SRI->second == Reg)
1371 continue; // self-cycles happen
1373 Changed |= normalizeWeight(SRI->second, UberSets, RegSets,
1374 NormalRegs, NormalUnits, RegBank);
1376 // Postorder register normalization.
1378 // Inherit register units newly adopted by subregisters.
1379 if (Reg->inheritRegUnits(RegBank))
1380 computeUberWeights(UberSets, RegBank);
1382 // Check if this register is too skinny for its UberRegSet.
1383 UberRegSet *UberSet = RegSets[RegBank.getRegIndex(Reg)];
1385 unsigned RegWeight = Reg->getWeight(RegBank);
1386 if (UberSet->Weight > RegWeight) {
1387 // A register unit's weight can be adjusted only if it is the singular unit
1388 // for this register, has not been used to normalize a subregister's set,
1389 // and has not already been used to singularly determine this UberRegSet.
1390 unsigned AdjustUnit = Reg->getRegUnits().front();
1391 if (Reg->getRegUnits().size() != 1
1392 || hasRegUnit(NormalUnits, AdjustUnit)
1393 || hasRegUnit(UberSet->SingularDeterminants, AdjustUnit)) {
1394 // We don't have an adjustable unit, so adopt a new one.
1395 AdjustUnit = RegBank.newRegUnit(UberSet->Weight - RegWeight);
1396 Reg->adoptRegUnit(AdjustUnit);
1397 // Adopting a unit does not immediately require recomputing set weights.
1400 // Adjust the existing single unit.
1401 RegBank.increaseRegUnitWeight(AdjustUnit, UberSet->Weight - RegWeight);
1402 // The unit may be shared among sets and registers within this set.
1403 computeUberWeights(UberSets, RegBank);
1408 // Mark these units normalized so superregisters can't change their weights.
1409 mergeRegUnits(NormalUnits, Reg->getRegUnits());
1414 // Compute a weight for each register unit created during getSubRegs.
1416 // The goal is that two registers in the same class will have the same weight,
1417 // where each register's weight is defined as sum of its units' weights.
1418 void CodeGenRegBank::computeRegUnitWeights() {
1419 std::vector<UberRegSet> UberSets;
1420 std::vector<UberRegSet*> RegSets(Registers.size());
1421 computeUberSets(UberSets, RegSets, *this);
1422 // UberSets and RegSets are now immutable.
1424 computeUberWeights(UberSets, *this);
1426 // Iterate over each Register, normalizing the unit weights until reaching
1428 unsigned NumIters = 0;
1429 for (bool Changed = true; Changed; ++NumIters) {
1430 assert(NumIters <= NumNativeRegUnits && "Runaway register unit weights");
1432 for (auto &Reg : Registers) {
1433 CodeGenRegister::RegUnitList NormalUnits;
1434 std::set<unsigned> NormalRegs;
1435 Changed |= normalizeWeight(&Reg, UberSets, RegSets, NormalRegs,
1436 NormalUnits, *this);
1441 // Find a set in UniqueSets with the same elements as Set.
1442 // Return an iterator into UniqueSets.
1443 static std::vector<RegUnitSet>::const_iterator
1444 findRegUnitSet(const std::vector<RegUnitSet> &UniqueSets,
1445 const RegUnitSet &Set) {
1446 std::vector<RegUnitSet>::const_iterator
1447 I = UniqueSets.begin(), E = UniqueSets.end();
1449 if (I->Units == Set.Units)
1455 // Return true if the RUSubSet is a subset of RUSuperSet.
1456 static bool isRegUnitSubSet(const std::vector<unsigned> &RUSubSet,
1457 const std::vector<unsigned> &RUSuperSet) {
1458 return std::includes(RUSuperSet.begin(), RUSuperSet.end(),
1459 RUSubSet.begin(), RUSubSet.end());
1462 /// Iteratively prune unit sets. Prune subsets that are close to the superset,
1463 /// but with one or two registers removed. We occasionally have registers like
1464 /// APSR and PC thrown in with the general registers. We also see many
1465 /// special-purpose register subsets, such as tail-call and Thumb
1466 /// encodings. Generating all possible overlapping sets is combinatorial and
1467 /// overkill for modeling pressure. Ideally we could fix this statically in
1468 /// tablegen by (1) having the target define register classes that only include
1469 /// the allocatable registers and marking other classes as non-allocatable and
1470 /// (2) having a way to mark special purpose classes as "don't-care" classes for
1471 /// the purpose of pressure. However, we make an attempt to handle targets that
1472 /// are not nicely defined by merging nearly identical register unit sets
1473 /// statically. This generates smaller tables. Then, dynamically, we adjust the
1474 /// set limit by filtering the reserved registers.
1476 /// Merge sets only if the units have the same weight. For example, on ARM,
1477 /// Q-tuples with ssub index 0 include all S regs but also include D16+. We
1478 /// should not expand the S set to include D regs.
1479 void CodeGenRegBank::pruneUnitSets() {
1480 assert(RegClassUnitSets.empty() && "this invalidates RegClassUnitSets");
1482 // Form an equivalence class of UnitSets with no significant difference.
1483 std::vector<unsigned> SuperSetIDs;
1484 for (unsigned SubIdx = 0, EndIdx = RegUnitSets.size();
1485 SubIdx != EndIdx; ++SubIdx) {
1486 const RegUnitSet &SubSet = RegUnitSets[SubIdx];
1487 unsigned SuperIdx = 0;
1488 for (; SuperIdx != EndIdx; ++SuperIdx) {
1489 if (SuperIdx == SubIdx)
1492 unsigned UnitWeight = RegUnits[SubSet.Units[0]].Weight;
1493 const RegUnitSet &SuperSet = RegUnitSets[SuperIdx];
1494 if (isRegUnitSubSet(SubSet.Units, SuperSet.Units)
1495 && (SubSet.Units.size() + 3 > SuperSet.Units.size())
1496 && UnitWeight == RegUnits[SuperSet.Units[0]].Weight
1497 && UnitWeight == RegUnits[SuperSet.Units.back()].Weight) {
1498 DEBUG(dbgs() << "UnitSet " << SubIdx << " subsumed by " << SuperIdx
1503 if (SuperIdx == EndIdx)
1504 SuperSetIDs.push_back(SubIdx);
1506 // Populate PrunedUnitSets with each equivalence class's superset.
1507 std::vector<RegUnitSet> PrunedUnitSets(SuperSetIDs.size());
1508 for (unsigned i = 0, e = SuperSetIDs.size(); i != e; ++i) {
1509 unsigned SuperIdx = SuperSetIDs[i];
1510 PrunedUnitSets[i].Name = RegUnitSets[SuperIdx].Name;
1511 PrunedUnitSets[i].Units.swap(RegUnitSets[SuperIdx].Units);
1513 RegUnitSets.swap(PrunedUnitSets);
1516 // Create a RegUnitSet for each RegClass that contains all units in the class
1517 // including adopted units that are necessary to model register pressure. Then
1518 // iteratively compute RegUnitSets such that the union of any two overlapping
1519 // RegUnitSets is repreresented.
1521 // RegisterInfoEmitter will map each RegClass to its RegUnitClass and any
1522 // RegUnitSet that is a superset of that RegUnitClass.
1523 void CodeGenRegBank::computeRegUnitSets() {
1524 assert(RegUnitSets.empty() && "dirty RegUnitSets");
1526 // Compute a unique RegUnitSet for each RegClass.
1527 auto &RegClasses = getRegClasses();
1528 for (auto &RC : RegClasses) {
1529 if (!RC.Allocatable)
1532 // Speculatively grow the RegUnitSets to hold the new set.
1533 RegUnitSets.resize(RegUnitSets.size() + 1);
1534 RegUnitSets.back().Name = RC.getName();
1536 // Compute a sorted list of units in this class.
1537 RC.buildRegUnitSet(RegUnitSets.back().Units);
1539 // Find an existing RegUnitSet.
1540 std::vector<RegUnitSet>::const_iterator SetI =
1541 findRegUnitSet(RegUnitSets, RegUnitSets.back());
1542 if (SetI != std::prev(RegUnitSets.end()))
1543 RegUnitSets.pop_back();
1546 DEBUG(dbgs() << "\nBefore pruning:\n";
1547 for (unsigned USIdx = 0, USEnd = RegUnitSets.size();
1548 USIdx < USEnd; ++USIdx) {
1549 dbgs() << "UnitSet " << USIdx << " " << RegUnitSets[USIdx].Name
1551 ArrayRef<unsigned> Units = RegUnitSets[USIdx].Units;
1552 for (unsigned i = 0, e = Units.size(); i < e; ++i)
1553 dbgs() << " " << RegUnits[Units[i]].Roots[0]->getName();
1557 // Iteratively prune unit sets.
1560 DEBUG(dbgs() << "\nBefore union:\n";
1561 for (unsigned USIdx = 0, USEnd = RegUnitSets.size();
1562 USIdx < USEnd; ++USIdx) {
1563 dbgs() << "UnitSet " << USIdx << " " << RegUnitSets[USIdx].Name
1565 ArrayRef<unsigned> Units = RegUnitSets[USIdx].Units;
1566 for (unsigned i = 0, e = Units.size(); i < e; ++i)
1567 dbgs() << " " << RegUnits[Units[i]].Roots[0]->getName();
1570 dbgs() << "\nUnion sets:\n");
1572 // Iterate over all unit sets, including new ones added by this loop.
1573 unsigned NumRegUnitSubSets = RegUnitSets.size();
1574 for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx) {
1575 // In theory, this is combinatorial. In practice, it needs to be bounded
1576 // by a small number of sets for regpressure to be efficient.
1577 // If the assert is hit, we need to implement pruning.
1578 assert(Idx < (2*NumRegUnitSubSets) && "runaway unit set inference");
1580 // Compare new sets with all original classes.
1581 for (unsigned SearchIdx = (Idx >= NumRegUnitSubSets) ? 0 : Idx+1;
1582 SearchIdx != EndIdx; ++SearchIdx) {
1583 std::set<unsigned> Intersection;
1584 std::set_intersection(RegUnitSets[Idx].Units.begin(),
1585 RegUnitSets[Idx].Units.end(),
1586 RegUnitSets[SearchIdx].Units.begin(),
1587 RegUnitSets[SearchIdx].Units.end(),
1588 std::inserter(Intersection, Intersection.begin()));
1589 if (Intersection.empty())
1592 // Speculatively grow the RegUnitSets to hold the new set.
1593 RegUnitSets.resize(RegUnitSets.size() + 1);
1594 RegUnitSets.back().Name =
1595 RegUnitSets[Idx].Name + "+" + RegUnitSets[SearchIdx].Name;
1597 std::set_union(RegUnitSets[Idx].Units.begin(),
1598 RegUnitSets[Idx].Units.end(),
1599 RegUnitSets[SearchIdx].Units.begin(),
1600 RegUnitSets[SearchIdx].Units.end(),
1601 std::inserter(RegUnitSets.back().Units,
1602 RegUnitSets.back().Units.begin()));
1604 // Find an existing RegUnitSet, or add the union to the unique sets.
1605 std::vector<RegUnitSet>::const_iterator SetI =
1606 findRegUnitSet(RegUnitSets, RegUnitSets.back());
1607 if (SetI != std::prev(RegUnitSets.end()))
1608 RegUnitSets.pop_back();
1610 DEBUG(dbgs() << "UnitSet " << RegUnitSets.size()-1
1611 << " " << RegUnitSets.back().Name << ":";
1612 ArrayRef<unsigned> Units = RegUnitSets.back().Units;
1613 for (unsigned i = 0, e = Units.size(); i < e; ++i)
1614 dbgs() << " " << RegUnits[Units[i]].Roots[0]->getName();
1620 // Iteratively prune unit sets after inferring supersets.
1623 DEBUG(dbgs() << "\n";
1624 for (unsigned USIdx = 0, USEnd = RegUnitSets.size();
1625 USIdx < USEnd; ++USIdx) {
1626 dbgs() << "UnitSet " << USIdx << " " << RegUnitSets[USIdx].Name
1628 ArrayRef<unsigned> Units = RegUnitSets[USIdx].Units;
1629 for (unsigned i = 0, e = Units.size(); i < e; ++i)
1630 dbgs() << " " << RegUnits[Units[i]].Roots[0]->getName();
1634 // For each register class, list the UnitSets that are supersets.
1635 RegClassUnitSets.resize(RegClasses.size());
1637 for (auto &RC : RegClasses) {
1639 if (!RC.Allocatable)
1642 // Recompute the sorted list of units in this class.
1643 std::vector<unsigned> RCRegUnits;
1644 RC.buildRegUnitSet(RCRegUnits);
1646 // Don't increase pressure for unallocatable regclasses.
1647 if (RCRegUnits.empty())
1650 DEBUG(dbgs() << "RC " << RC.getName() << " Units: \n";
1651 for (unsigned i = 0, e = RCRegUnits.size(); i < e; ++i) dbgs()
1652 << RegUnits[RCRegUnits[i]].getRoots()[0]->getName() << " ";
1653 dbgs() << "\n UnitSetIDs:");
1655 // Find all supersets.
1656 for (unsigned USIdx = 0, USEnd = RegUnitSets.size();
1657 USIdx != USEnd; ++USIdx) {
1658 if (isRegUnitSubSet(RCRegUnits, RegUnitSets[USIdx].Units)) {
1659 DEBUG(dbgs() << " " << USIdx);
1660 RegClassUnitSets[RCIdx].push_back(USIdx);
1663 DEBUG(dbgs() << "\n");
1664 assert(!RegClassUnitSets[RCIdx].empty() && "missing unit set for regclass");
1667 // For each register unit, ensure that we have the list of UnitSets that
1668 // contain the unit. Normally, this matches an existing list of UnitSets for a
1669 // register class. If not, we create a new entry in RegClassUnitSets as a
1670 // "fake" register class.
1671 for (unsigned UnitIdx = 0, UnitEnd = NumNativeRegUnits;
1672 UnitIdx < UnitEnd; ++UnitIdx) {
1673 std::vector<unsigned> RUSets;
1674 for (unsigned i = 0, e = RegUnitSets.size(); i != e; ++i) {
1675 RegUnitSet &RUSet = RegUnitSets[i];
1676 if (std::find(RUSet.Units.begin(), RUSet.Units.end(), UnitIdx)
1677 == RUSet.Units.end())
1679 RUSets.push_back(i);
1681 unsigned RCUnitSetsIdx = 0;
1682 for (unsigned e = RegClassUnitSets.size();
1683 RCUnitSetsIdx != e; ++RCUnitSetsIdx) {
1684 if (RegClassUnitSets[RCUnitSetsIdx] == RUSets) {
1688 RegUnits[UnitIdx].RegClassUnitSetsIdx = RCUnitSetsIdx;
1689 if (RCUnitSetsIdx == RegClassUnitSets.size()) {
1690 // Create a new list of UnitSets as a "fake" register class.
1691 RegClassUnitSets.resize(RCUnitSetsIdx + 1);
1692 RegClassUnitSets[RCUnitSetsIdx].swap(RUSets);
1697 void CodeGenRegBank::computeDerivedInfo() {
1698 computeComposites();
1699 computeSubRegIndexLaneMasks();
1701 // Compute a weight for each register unit created during getSubRegs.
1702 // This may create adopted register units (with unit # >= NumNativeRegUnits).
1703 computeRegUnitWeights();
1705 // Compute a unique set of RegUnitSets. One for each RegClass and inferred
1706 // supersets for the union of overlapping sets.
1707 computeRegUnitSets();
1709 // Get the weight of each set.
1710 for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx)
1711 RegUnitSets[Idx].Weight = getRegUnitSetWeight(RegUnitSets[Idx].Units);
1713 // Find the order of each set.
1714 RegUnitSetOrder.reserve(RegUnitSets.size());
1715 for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx)
1716 RegUnitSetOrder.push_back(Idx);
1718 std::stable_sort(RegUnitSetOrder.begin(), RegUnitSetOrder.end(),
1719 [this](unsigned ID1, unsigned ID2) {
1720 return getRegPressureSet(ID1).Units.size() <
1721 getRegPressureSet(ID2).Units.size();
1723 for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx) {
1724 RegUnitSets[RegUnitSetOrder[Idx]].Order = Idx;
1729 // Synthesize missing register class intersections.
1731 // Make sure that sub-classes of RC exists such that getCommonSubClass(RC, X)
1732 // returns a maximal register class for all X.
1734 void CodeGenRegBank::inferCommonSubClass(CodeGenRegisterClass *RC) {
1735 assert(!RegClasses.empty());
1736 // Stash the iterator to the last element so that this loop doesn't visit
1737 // elements added by the getOrCreateSubClass call within it.
1738 for (auto I = RegClasses.begin(), E = std::prev(RegClasses.end());
1739 I != std::next(E); ++I) {
1740 CodeGenRegisterClass *RC1 = RC;
1741 CodeGenRegisterClass *RC2 = &*I;
1745 // Compute the set intersection of RC1 and RC2.
1746 const CodeGenRegister::Set &Memb1 = RC1->getMembers();
1747 const CodeGenRegister::Set &Memb2 = RC2->getMembers();
1748 CodeGenRegister::Set Intersection;
1749 std::set_intersection(Memb1.begin(), Memb1.end(),
1750 Memb2.begin(), Memb2.end(),
1751 std::inserter(Intersection, Intersection.begin()),
1752 CodeGenRegister::Less());
1754 // Skip disjoint class pairs.
1755 if (Intersection.empty())
1758 // If RC1 and RC2 have different spill sizes or alignments, use the
1759 // larger size for sub-classing. If they are equal, prefer RC1.
1760 if (RC2->SpillSize > RC1->SpillSize ||
1761 (RC2->SpillSize == RC1->SpillSize &&
1762 RC2->SpillAlignment > RC1->SpillAlignment))
1763 std::swap(RC1, RC2);
1765 getOrCreateSubClass(RC1, &Intersection,
1766 RC1->getName() + "_and_" + RC2->getName());
1771 // Synthesize missing sub-classes for getSubClassWithSubReg().
1773 // Make sure that the set of registers in RC with a given SubIdx sub-register
1774 // form a register class. Update RC->SubClassWithSubReg.
1776 void CodeGenRegBank::inferSubClassWithSubReg(CodeGenRegisterClass *RC) {
1777 // Map SubRegIndex to set of registers in RC supporting that SubRegIndex.
1778 typedef std::map<const CodeGenSubRegIndex *, CodeGenRegister::Set,
1779 CodeGenSubRegIndex::Less> SubReg2SetMap;
1781 // Compute the set of registers supporting each SubRegIndex.
1782 SubReg2SetMap SRSets;
1783 for (CodeGenRegister::Set::const_iterator RI = RC->getMembers().begin(),
1784 RE = RC->getMembers().end(); RI != RE; ++RI) {
1785 const CodeGenRegister::SubRegMap &SRM = (*RI)->getSubRegs();
1786 for (CodeGenRegister::SubRegMap::const_iterator I = SRM.begin(),
1787 E = SRM.end(); I != E; ++I)
1788 SRSets[I->first].insert(*RI);
1791 // Find matching classes for all SRSets entries. Iterate in SubRegIndex
1792 // numerical order to visit synthetic indices last.
1793 for (const auto &SubIdx : SubRegIndices) {
1794 SubReg2SetMap::const_iterator I = SRSets.find(&SubIdx);
1795 // Unsupported SubRegIndex. Skip it.
1796 if (I == SRSets.end())
1798 // In most cases, all RC registers support the SubRegIndex.
1799 if (I->second.size() == RC->getMembers().size()) {
1800 RC->setSubClassWithSubReg(&SubIdx, RC);
1803 // This is a real subset. See if we have a matching class.
1804 CodeGenRegisterClass *SubRC =
1805 getOrCreateSubClass(RC, &I->second,
1806 RC->getName() + "_with_" + I->first->getName());
1807 RC->setSubClassWithSubReg(&SubIdx, SubRC);
1812 // Synthesize missing sub-classes of RC for getMatchingSuperRegClass().
1814 // Create sub-classes of RC such that getMatchingSuperRegClass(RC, SubIdx, X)
1815 // has a maximal result for any SubIdx and any X >= FirstSubRegRC.
1818 void CodeGenRegBank::inferMatchingSuperRegClass(CodeGenRegisterClass *RC,
1819 unsigned FirstSubRegRC) {
1820 SmallVector<std::pair<const CodeGenRegister*,
1821 const CodeGenRegister*>, 16> SSPairs;
1822 BitVector TopoSigs(getNumTopoSigs());
1824 // Iterate in SubRegIndex numerical order to visit synthetic indices last.
1825 for (auto &SubIdx : SubRegIndices) {
1826 // Skip indexes that aren't fully supported by RC's registers. This was
1827 // computed by inferSubClassWithSubReg() above which should have been
1829 if (RC->getSubClassWithSubReg(&SubIdx) != RC)
1832 // Build list of (Super, Sub) pairs for this SubIdx.
1835 for (CodeGenRegister::Set::const_iterator RI = RC->getMembers().begin(),
1836 RE = RC->getMembers().end(); RI != RE; ++RI) {
1837 const CodeGenRegister *Super = *RI;
1838 const CodeGenRegister *Sub = Super->getSubRegs().find(&SubIdx)->second;
1839 assert(Sub && "Missing sub-register");
1840 SSPairs.push_back(std::make_pair(Super, Sub));
1841 TopoSigs.set(Sub->getTopoSig());
1844 // Iterate over sub-register class candidates. Ignore classes created by
1845 // this loop. They will never be useful.
1846 // Careful if trying to transform this loop to use iterators - as this loop
1847 // will add new classes it will invalidate iterators to RegClasses.
1848 assert(!RegClasses.empty());
1849 for (auto I = std::next(RegClasses.begin(), FirstSubRegRC),
1850 E = std::prev(RegClasses.end());
1851 I != std::next(E); ++I) {
1852 CodeGenRegisterClass &SubRC = *I;
1853 // Topological shortcut: SubRC members have the wrong shape.
1854 if (!TopoSigs.anyCommon(SubRC.getTopoSigs()))
1856 // Compute the subset of RC that maps into SubRC.
1857 CodeGenRegister::Set SubSet;
1858 for (unsigned i = 0, e = SSPairs.size(); i != e; ++i)
1859 if (SubRC.contains(SSPairs[i].second))
1860 SubSet.insert(SSPairs[i].first);
1863 // RC injects completely into SubRC.
1864 if (SubSet.size() == SSPairs.size()) {
1865 SubRC.addSuperRegClass(&SubIdx, RC);
1868 // Only a subset of RC maps into SubRC. Make sure it is represented by a
1870 getOrCreateSubClass(RC, &SubSet, RC->getName() + "_with_" +
1871 SubIdx.getName() + "_in_" +
1879 // Infer missing register classes.
1881 void CodeGenRegBank::computeInferredRegisterClasses() {
1882 // When this function is called, the register classes have not been sorted
1883 // and assigned EnumValues yet. That means getSubClasses(),
1884 // getSuperClasses(), and hasSubClass() functions are defunct.
1885 unsigned FirstNewRC = RegClasses.size();
1887 // Visit all register classes, including the ones being added by the loop.
1888 // Watch out for iterator invalidation here.
1890 for (auto &RCR : RegClasses) {
1891 CodeGenRegisterClass *RC = &RCR;
1893 // Synthesize answers for getSubClassWithSubReg().
1894 inferSubClassWithSubReg(RC);
1896 // Synthesize answers for getCommonSubClass().
1897 inferCommonSubClass(RC);
1899 // Synthesize answers for getMatchingSuperRegClass().
1900 inferMatchingSuperRegClass(RC);
1902 // New register classes are created while this loop is running, and we need
1903 // to visit all of them. I particular, inferMatchingSuperRegClass needs
1904 // to match old super-register classes with sub-register classes created
1905 // after inferMatchingSuperRegClass was called. At this point,
1906 // inferMatchingSuperRegClass has checked SuperRC = [0..rci] with SubRC =
1907 // [0..FirstNewRC). We need to cover SubRC = [FirstNewRC..rci].
1908 if (rci + 1 == FirstNewRC) {
1909 unsigned NextNewRC = RegClasses.size();
1910 auto I2 = RegClasses.begin();
1911 for (unsigned rci2 = 0; rci2 != FirstNewRC; ++rci2, ++I2)
1912 // This can add more things to RegClasses, be careful about iterator
1913 // invalidation of outer loop variables.
1914 inferMatchingSuperRegClass(&*I2, FirstNewRC);
1915 FirstNewRC = NextNewRC;
1920 /// getRegisterClassForRegister - Find the register class that contains the
1921 /// specified physical register. If the register is not in a register class,
1922 /// return null. If the register is in multiple classes, and the classes have a
1923 /// superset-subset relationship and the same set of types, return the
1924 /// superclass. Otherwise return null.
1925 const CodeGenRegisterClass*
1926 CodeGenRegBank::getRegClassForRegister(Record *R) {
1927 const CodeGenRegister *Reg = getReg(R);
1928 const CodeGenRegisterClass *FoundRC = nullptr;
1929 for (const auto &RC : getRegClasses()) {
1930 if (!RC.contains(Reg))
1933 // If this is the first class that contains the register,
1934 // make a note of it and go on to the next class.
1940 // If a register's classes have different types, return null.
1941 if (RC.getValueTypes() != FoundRC->getValueTypes())
1944 // Check to see if the previously found class that contains
1945 // the register is a subclass of the current class. If so,
1946 // prefer the superclass.
1947 if (RC.hasSubClass(FoundRC)) {
1952 // Check to see if the previously found class that contains
1953 // the register is a superclass of the current class. If so,
1954 // prefer the superclass.
1955 if (FoundRC->hasSubClass(&RC))
1958 // Multiple classes, and neither is a superclass of the other.
1965 BitVector CodeGenRegBank::computeCoveredRegisters(ArrayRef<Record*> Regs) {
1966 SetVector<const CodeGenRegister*> Set;
1968 // First add Regs with all sub-registers.
1969 for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
1970 CodeGenRegister *Reg = getReg(Regs[i]);
1971 if (Set.insert(Reg))
1972 // Reg is new, add all sub-registers.
1973 // The pre-ordering is not important here.
1974 Reg->addSubRegsPreOrder(Set, *this);
1977 // Second, find all super-registers that are completely covered by the set.
1978 for (unsigned i = 0; i != Set.size(); ++i) {
1979 const CodeGenRegister::SuperRegList &SR = Set[i]->getSuperRegs();
1980 for (unsigned j = 0, e = SR.size(); j != e; ++j) {
1981 const CodeGenRegister *Super = SR[j];
1982 if (!Super->CoveredBySubRegs || Set.count(Super))
1984 // This new super-register is covered by its sub-registers.
1985 bool AllSubsInSet = true;
1986 const CodeGenRegister::SubRegMap &SRM = Super->getSubRegs();
1987 for (CodeGenRegister::SubRegMap::const_iterator I = SRM.begin(),
1988 E = SRM.end(); I != E; ++I)
1989 if (!Set.count(I->second)) {
1990 AllSubsInSet = false;
1993 // All sub-registers in Set, add Super as well.
1994 // We will visit Super later to recheck its super-registers.
2000 // Convert to BitVector.
2001 BitVector BV(Registers.size() + 1);
2002 for (unsigned i = 0, e = Set.size(); i != e; ++i)
2003 BV.set(Set[i]->EnumValue);