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/ArrayRef.h"
18 #include "llvm/ADT/BitVector.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/IntEqClasses.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/SparseBitVector.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringRef.h"
28 #include "llvm/ADT/Twine.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/MathExtras.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/TableGen/Error.h"
33 #include "llvm/TableGen/Record.h"
47 #define DEBUG_TYPE "regalloc-emitter"
49 //===----------------------------------------------------------------------===//
51 //===----------------------------------------------------------------------===//
53 CodeGenSubRegIndex::CodeGenSubRegIndex(Record *R, unsigned Enum)
54 : TheDef(R), EnumValue(Enum), AllSuperRegsCovered(true) {
56 if (R->getValue("Namespace"))
57 Namespace = R->getValueAsString("Namespace");
58 Size = R->getValueAsInt("Size");
59 Offset = R->getValueAsInt("Offset");
62 CodeGenSubRegIndex::CodeGenSubRegIndex(StringRef N, StringRef Nspace,
64 : TheDef(nullptr), Name(N), Namespace(Nspace), Size(-1), Offset(-1),
65 EnumValue(Enum), AllSuperRegsCovered(true) {
68 std::string CodeGenSubRegIndex::getQualifiedName() const {
69 std::string N = getNamespace();
76 void CodeGenSubRegIndex::updateComponents(CodeGenRegBank &RegBank) {
80 std::vector<Record*> Comps = TheDef->getValueAsListOfDefs("ComposedOf");
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);
89 PrintFatalError(TheDef->getLoc(), "Ambiguous ComposedOf entries");
92 std::vector<Record*> Parts =
93 TheDef->getValueAsListOfDefs("CoveringSubRegIndices");
96 PrintFatalError(TheDef->getLoc(),
97 "CoveredBySubRegs must have two or more entries");
98 SmallVector<CodeGenSubRegIndex*, 8> IdxParts;
99 for (unsigned i = 0, e = Parts.size(); i != e; ++i)
100 IdxParts.push_back(RegBank.getSubRegIdx(Parts[i]));
101 RegBank.addConcatSubRegIndex(IdxParts, this);
105 LaneBitmask CodeGenSubRegIndex::computeLaneMask() const {
110 // Recursion guard, shouldn't be required.
111 LaneMask = LaneBitmask::getAll();
113 // The lane mask is simply the union of all sub-indices.
115 for (const auto &C : Composed)
116 M |= C.second->computeLaneMask();
117 assert(M.any() && "Missing lane mask, sub-register cycle?");
122 //===----------------------------------------------------------------------===//
124 //===----------------------------------------------------------------------===//
126 CodeGenRegister::CodeGenRegister(Record *R, unsigned Enum)
129 CostPerUse(R->getValueAsInt("CostPerUse")),
130 CoveredBySubRegs(R->getValueAsBit("CoveredBySubRegs")),
131 HasDisjunctSubRegs(false),
132 SubRegsComplete(false),
133 SuperRegsComplete(false),
137 void CodeGenRegister::buildObjectGraph(CodeGenRegBank &RegBank) {
138 std::vector<Record*> SRIs = TheDef->getValueAsListOfDefs("SubRegIndices");
139 std::vector<Record*> SRs = TheDef->getValueAsListOfDefs("SubRegs");
141 if (SRIs.size() != SRs.size())
142 PrintFatalError(TheDef->getLoc(),
143 "SubRegs and SubRegIndices must have the same size");
145 for (unsigned i = 0, e = SRIs.size(); i != e; ++i) {
146 ExplicitSubRegIndices.push_back(RegBank.getSubRegIdx(SRIs[i]));
147 ExplicitSubRegs.push_back(RegBank.getReg(SRs[i]));
150 // Also compute leading super-registers. Each register has a list of
151 // covered-by-subregs super-registers where it appears as the first explicit
154 // This is used by computeSecondarySubRegs() to find candidates.
155 if (CoveredBySubRegs && !ExplicitSubRegs.empty())
156 ExplicitSubRegs.front()->LeadingSuperRegs.push_back(this);
158 // Add ad hoc alias links. This is a symmetric relationship between two
159 // registers, so build a symmetric graph by adding links in both ends.
160 std::vector<Record*> Aliases = TheDef->getValueAsListOfDefs("Aliases");
161 for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
162 CodeGenRegister *Reg = RegBank.getReg(Aliases[i]);
163 ExplicitAliases.push_back(Reg);
164 Reg->ExplicitAliases.push_back(this);
168 const StringRef CodeGenRegister::getName() const {
169 assert(TheDef && "no def");
170 return TheDef->getName();
175 // Iterate over all register units in a set of registers.
176 class RegUnitIterator {
177 CodeGenRegister::Vec::const_iterator RegI, RegE;
178 CodeGenRegister::RegUnitList::iterator UnitI, UnitE;
181 RegUnitIterator(const CodeGenRegister::Vec &Regs):
182 RegI(Regs.begin()), RegE(Regs.end()) {
185 UnitI = (*RegI)->getRegUnits().begin();
186 UnitE = (*RegI)->getRegUnits().end();
191 bool isValid() const { return UnitI != UnitE; }
193 unsigned operator* () const { assert(isValid()); return *UnitI; }
195 const CodeGenRegister *getReg() const { assert(isValid()); return *RegI; }
197 /// Preincrement. Move to the next unit.
199 assert(isValid() && "Cannot advance beyond the last operand");
206 while (UnitI == UnitE) {
209 UnitI = (*RegI)->getRegUnits().begin();
210 UnitE = (*RegI)->getRegUnits().end();
215 } // end anonymous namespace
217 // Return true of this unit appears in RegUnits.
218 static bool hasRegUnit(CodeGenRegister::RegUnitList &RegUnits, unsigned Unit) {
219 return RegUnits.test(Unit);
222 // Inherit register units from subregisters.
223 // Return true if the RegUnits changed.
224 bool CodeGenRegister::inheritRegUnits(CodeGenRegBank &RegBank) {
225 bool changed = false;
226 for (SubRegMap::const_iterator I = SubRegs.begin(), E = SubRegs.end();
228 CodeGenRegister *SR = I->second;
229 // Merge the subregister's units into this register's RegUnits.
230 changed |= (RegUnits |= SR->RegUnits);
236 const CodeGenRegister::SubRegMap &
237 CodeGenRegister::computeSubRegs(CodeGenRegBank &RegBank) {
238 // Only compute this map once.
241 SubRegsComplete = true;
243 HasDisjunctSubRegs = ExplicitSubRegs.size() > 1;
245 // First insert the explicit subregs and make sure they are fully indexed.
246 for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
247 CodeGenRegister *SR = ExplicitSubRegs[i];
248 CodeGenSubRegIndex *Idx = ExplicitSubRegIndices[i];
249 if (!SubRegs.insert(std::make_pair(Idx, SR)).second)
250 PrintFatalError(TheDef->getLoc(), "SubRegIndex " + Idx->getName() +
251 " appears twice in Register " + getName());
252 // Map explicit sub-registers first, so the names take precedence.
253 // The inherited sub-registers are mapped below.
254 SubReg2Idx.insert(std::make_pair(SR, Idx));
257 // Keep track of inherited subregs and how they can be reached.
258 SmallPtrSet<CodeGenRegister*, 8> Orphans;
260 // Clone inherited subregs and place duplicate entries in Orphans.
261 // Here the order is important - earlier subregs take precedence.
262 for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
263 CodeGenRegister *SR = ExplicitSubRegs[i];
264 const SubRegMap &Map = SR->computeSubRegs(RegBank);
265 HasDisjunctSubRegs |= SR->HasDisjunctSubRegs;
267 for (SubRegMap::const_iterator SI = Map.begin(), SE = Map.end(); SI != SE;
269 if (!SubRegs.insert(*SI).second)
270 Orphans.insert(SI->second);
274 // Expand any composed subreg indices.
275 // If dsub_2 has ComposedOf = [qsub_1, dsub_0], and this register has a
276 // qsub_1 subreg, add a dsub_2 subreg. Keep growing Indices and process
277 // expanded subreg indices recursively.
278 SmallVector<CodeGenSubRegIndex*, 8> Indices = ExplicitSubRegIndices;
279 for (unsigned i = 0; i != Indices.size(); ++i) {
280 CodeGenSubRegIndex *Idx = Indices[i];
281 const CodeGenSubRegIndex::CompMap &Comps = Idx->getComposites();
282 CodeGenRegister *SR = SubRegs[Idx];
283 const SubRegMap &Map = SR->computeSubRegs(RegBank);
285 // Look at the possible compositions of Idx.
286 // They may not all be supported by SR.
287 for (CodeGenSubRegIndex::CompMap::const_iterator I = Comps.begin(),
288 E = Comps.end(); I != E; ++I) {
289 SubRegMap::const_iterator SRI = Map.find(I->first);
290 if (SRI == Map.end())
291 continue; // Idx + I->first doesn't exist in SR.
292 // Add I->second as a name for the subreg SRI->second, assuming it is
293 // orphaned, and the name isn't already used for something else.
294 if (SubRegs.count(I->second) || !Orphans.erase(SRI->second))
296 // We found a new name for the orphaned sub-register.
297 SubRegs.insert(std::make_pair(I->second, SRI->second));
298 Indices.push_back(I->second);
302 // Now Orphans contains the inherited subregisters without a direct index.
303 // Create inferred indexes for all missing entries.
304 // Work backwards in the Indices vector in order to compose subregs bottom-up.
305 // Consider this subreg sequence:
307 // qsub_1 -> dsub_0 -> ssub_0
309 // The qsub_1 -> dsub_0 composition becomes dsub_2, so the ssub_0 register
310 // can be reached in two different ways:
315 // We pick the latter composition because another register may have [dsub_0,
316 // dsub_1, dsub_2] subregs without necessarily having a qsub_1 subreg. The
317 // dsub_2 -> ssub_0 composition can be shared.
318 while (!Indices.empty() && !Orphans.empty()) {
319 CodeGenSubRegIndex *Idx = Indices.pop_back_val();
320 CodeGenRegister *SR = SubRegs[Idx];
321 const SubRegMap &Map = SR->computeSubRegs(RegBank);
322 for (SubRegMap::const_iterator SI = Map.begin(), SE = Map.end(); SI != SE;
324 if (Orphans.erase(SI->second))
325 SubRegs[RegBank.getCompositeSubRegIndex(Idx, SI->first)] = SI->second;
328 // Compute the inverse SubReg -> Idx map.
329 for (SubRegMap::const_iterator SI = SubRegs.begin(), SE = SubRegs.end();
331 if (SI->second == this) {
334 Loc = TheDef->getLoc();
335 PrintFatalError(Loc, "Register " + getName() +
336 " has itself as a sub-register");
339 // Compute AllSuperRegsCovered.
340 if (!CoveredBySubRegs)
341 SI->first->AllSuperRegsCovered = false;
343 // Ensure that every sub-register has a unique name.
344 DenseMap<const CodeGenRegister*, CodeGenSubRegIndex*>::iterator Ins =
345 SubReg2Idx.insert(std::make_pair(SI->second, SI->first)).first;
346 if (Ins->second == SI->first)
348 // Trouble: Two different names for SI->second.
351 Loc = TheDef->getLoc();
352 PrintFatalError(Loc, "Sub-register can't have two names: " +
353 SI->second->getName() + " available as " +
354 SI->first->getName() + " and " + Ins->second->getName());
357 // Derive possible names for sub-register concatenations from any explicit
358 // sub-registers. By doing this before computeSecondarySubRegs(), we ensure
359 // that getConcatSubRegIndex() won't invent any concatenated indices that the
360 // user already specified.
361 for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
362 CodeGenRegister *SR = ExplicitSubRegs[i];
363 if (!SR->CoveredBySubRegs || SR->ExplicitSubRegs.size() <= 1)
366 // SR is composed of multiple sub-regs. Find their names in this register.
367 SmallVector<CodeGenSubRegIndex*, 8> Parts;
368 for (unsigned j = 0, e = SR->ExplicitSubRegs.size(); j != e; ++j)
369 Parts.push_back(getSubRegIndex(SR->ExplicitSubRegs[j]));
371 // Offer this as an existing spelling for the concatenation of Parts.
372 RegBank.addConcatSubRegIndex(Parts, ExplicitSubRegIndices[i]);
375 // Initialize RegUnitList. Because getSubRegs is called recursively, this
376 // processes the register hierarchy in postorder.
378 // Inherit all sub-register units. It is good enough to look at the explicit
379 // sub-registers, the other registers won't contribute any more units.
380 for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
381 CodeGenRegister *SR = ExplicitSubRegs[i];
382 RegUnits |= SR->RegUnits;
385 // Absent any ad hoc aliasing, we create one register unit per leaf register.
386 // These units correspond to the maximal cliques in the register overlap
387 // graph which is optimal.
389 // When there is ad hoc aliasing, we simply create one unit per edge in the
390 // undirected ad hoc aliasing graph. Technically, we could do better by
391 // identifying maximal cliques in the ad hoc graph, but cliques larger than 2
392 // are extremely rare anyway (I've never seen one), so we don't bother with
393 // the added complexity.
394 for (unsigned i = 0, e = ExplicitAliases.size(); i != e; ++i) {
395 CodeGenRegister *AR = ExplicitAliases[i];
396 // Only visit each edge once.
397 if (AR->SubRegsComplete)
399 // Create a RegUnit representing this alias edge, and add it to both
401 unsigned Unit = RegBank.newRegUnit(this, AR);
403 AR->RegUnits.set(Unit);
406 // Finally, create units for leaf registers without ad hoc aliases. Note that
407 // a leaf register with ad hoc aliases doesn't get its own unit - it isn't
408 // necessary. This means the aliasing leaf registers can share a single unit.
409 if (RegUnits.empty())
410 RegUnits.set(RegBank.newRegUnit(this));
412 // We have now computed the native register units. More may be adopted later
413 // for balancing purposes.
414 NativeRegUnits = RegUnits;
419 // In a register that is covered by its sub-registers, try to find redundant
420 // sub-registers. For example:
426 // We can infer that D1_D2 is also a sub-register, even if it wasn't named in
427 // the register definition.
429 // The explicitly specified registers form a tree. This function discovers
430 // sub-register relationships that would force a DAG.
432 void CodeGenRegister::computeSecondarySubRegs(CodeGenRegBank &RegBank) {
433 // Collect new sub-registers first, add them later.
434 SmallVector<SubRegMap::value_type, 8> NewSubRegs;
436 // Look at the leading super-registers of each sub-register. Those are the
437 // candidates for new sub-registers, assuming they are fully contained in
439 for (SubRegMap::iterator I = SubRegs.begin(), E = SubRegs.end(); I != E; ++I){
440 const CodeGenRegister *SubReg = I->second;
441 const CodeGenRegister::SuperRegList &Leads = SubReg->LeadingSuperRegs;
442 for (unsigned i = 0, e = Leads.size(); i != e; ++i) {
443 CodeGenRegister *Cand = const_cast<CodeGenRegister*>(Leads[i]);
444 // Already got this sub-register?
445 if (Cand == this || getSubRegIndex(Cand))
447 // Check if each component of Cand is already a sub-register.
448 // We know that the first component is I->second, and is present with the
450 SmallVector<CodeGenSubRegIndex*, 8> Parts(1, I->first);
451 assert(!Cand->ExplicitSubRegs.empty() &&
452 "Super-register has no sub-registers");
453 for (unsigned j = 1, e = Cand->ExplicitSubRegs.size(); j != e; ++j) {
454 if (CodeGenSubRegIndex *Idx = getSubRegIndex(Cand->ExplicitSubRegs[j]))
455 Parts.push_back(Idx);
457 // Sub-register doesn't exist.
462 // If some Cand sub-register is not part of this register, or if Cand only
463 // has one sub-register, there is nothing to do.
464 if (Parts.size() <= 1)
467 // Each part of Cand is a sub-register of this. Make the full Cand also
468 // a sub-register with a concatenated sub-register index.
469 CodeGenSubRegIndex *Concat= RegBank.getConcatSubRegIndex(Parts);
470 NewSubRegs.push_back(std::make_pair(Concat, Cand));
474 // Now add all the new sub-registers.
475 for (unsigned i = 0, e = NewSubRegs.size(); i != e; ++i) {
476 // Don't add Cand if another sub-register is already using the index.
477 if (!SubRegs.insert(NewSubRegs[i]).second)
480 CodeGenSubRegIndex *NewIdx = NewSubRegs[i].first;
481 CodeGenRegister *NewSubReg = NewSubRegs[i].second;
482 SubReg2Idx.insert(std::make_pair(NewSubReg, NewIdx));
485 // Create sub-register index composition maps for the synthesized indices.
486 for (unsigned i = 0, e = NewSubRegs.size(); i != e; ++i) {
487 CodeGenSubRegIndex *NewIdx = NewSubRegs[i].first;
488 CodeGenRegister *NewSubReg = NewSubRegs[i].second;
489 for (SubRegMap::const_iterator SI = NewSubReg->SubRegs.begin(),
490 SE = NewSubReg->SubRegs.end(); SI != SE; ++SI) {
491 CodeGenSubRegIndex *SubIdx = getSubRegIndex(SI->second);
493 PrintFatalError(TheDef->getLoc(), "No SubRegIndex for " +
494 SI->second->getName() + " in " + getName());
495 NewIdx->addComposite(SI->first, SubIdx);
500 void CodeGenRegister::computeSuperRegs(CodeGenRegBank &RegBank) {
501 // Only visit each register once.
502 if (SuperRegsComplete)
504 SuperRegsComplete = true;
506 // Make sure all sub-registers have been visited first, so the super-reg
507 // lists will be topologically ordered.
508 for (SubRegMap::const_iterator I = SubRegs.begin(), E = SubRegs.end();
510 I->second->computeSuperRegs(RegBank);
512 // Now add this as a super-register on all sub-registers.
513 // Also compute the TopoSigId in post-order.
515 for (SubRegMap::const_iterator I = SubRegs.begin(), E = SubRegs.end();
517 // Topological signature computed from SubIdx, TopoId(SubReg).
518 // Loops and idempotent indices have TopoSig = ~0u.
519 Id.push_back(I->first->EnumValue);
520 Id.push_back(I->second->TopoSig);
522 // Don't add duplicate entries.
523 if (!I->second->SuperRegs.empty() && I->second->SuperRegs.back() == this)
525 I->second->SuperRegs.push_back(this);
527 TopoSig = RegBank.getTopoSig(Id);
531 CodeGenRegister::addSubRegsPreOrder(SetVector<const CodeGenRegister*> &OSet,
532 CodeGenRegBank &RegBank) const {
533 assert(SubRegsComplete && "Must precompute sub-registers");
534 for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
535 CodeGenRegister *SR = ExplicitSubRegs[i];
537 SR->addSubRegsPreOrder(OSet, RegBank);
539 // Add any secondary sub-registers that weren't part of the explicit tree.
540 for (SubRegMap::const_iterator I = SubRegs.begin(), E = SubRegs.end();
542 OSet.insert(I->second);
545 // Get the sum of this register's unit weights.
546 unsigned CodeGenRegister::getWeight(const CodeGenRegBank &RegBank) const {
548 for (RegUnitList::iterator I = RegUnits.begin(), E = RegUnits.end();
550 Weight += RegBank.getRegUnit(*I).Weight;
555 //===----------------------------------------------------------------------===//
557 //===----------------------------------------------------------------------===//
559 // A RegisterTuples def is used to generate pseudo-registers from lists of
560 // sub-registers. We provide a SetTheory expander class that returns the new
564 struct TupleExpander : SetTheory::Expander {
565 void expand(SetTheory &ST, Record *Def, SetTheory::RecSet &Elts) override {
566 std::vector<Record*> Indices = Def->getValueAsListOfDefs("SubRegIndices");
567 unsigned Dim = Indices.size();
568 ListInit *SubRegs = Def->getValueAsListInit("SubRegs");
569 if (Dim != SubRegs->size())
570 PrintFatalError(Def->getLoc(), "SubRegIndices and SubRegs size mismatch");
572 PrintFatalError(Def->getLoc(),
573 "Tuples must have at least 2 sub-registers");
575 // Evaluate the sub-register lists to be zipped.
576 unsigned Length = ~0u;
577 SmallVector<SetTheory::RecSet, 4> Lists(Dim);
578 for (unsigned i = 0; i != Dim; ++i) {
579 ST.evaluate(SubRegs->getElement(i), Lists[i], Def->getLoc());
580 Length = std::min(Length, unsigned(Lists[i].size()));
586 // Precompute some types.
587 Record *RegisterCl = Def->getRecords().getClass("Register");
588 RecTy *RegisterRecTy = RecordRecTy::get(RegisterCl);
589 StringInit *BlankName = StringInit::get("");
592 for (unsigned n = 0; n != Length; ++n) {
594 Record *Proto = Lists[0][n];
595 std::vector<Init*> Tuple;
596 unsigned CostPerUse = 0;
597 for (unsigned i = 0; i != Dim; ++i) {
598 Record *Reg = Lists[i][n];
600 Name += Reg->getName();
601 Tuple.push_back(DefInit::get(Reg));
602 CostPerUse = std::max(CostPerUse,
603 unsigned(Reg->getValueAsInt("CostPerUse")));
606 // Create a new Record representing the synthesized register. This record
607 // is only for consumption by CodeGenRegister, it is not added to the
609 Record *NewReg = new Record(Name, Def->getLoc(), Def->getRecords());
612 // Copy Proto super-classes.
613 ArrayRef<std::pair<Record *, SMRange>> Supers = Proto->getSuperClasses();
614 for (const auto &SuperPair : Supers)
615 NewReg->addSuperClass(SuperPair.first, SuperPair.second);
617 // Copy Proto fields.
618 for (unsigned i = 0, e = Proto->getValues().size(); i != e; ++i) {
619 RecordVal RV = Proto->getValues()[i];
621 // Skip existing fields, like NAME.
622 if (NewReg->getValue(RV.getNameInit()))
625 StringRef Field = RV.getName();
627 // Replace the sub-register list with Tuple.
628 if (Field == "SubRegs")
629 RV.setValue(ListInit::get(Tuple, RegisterRecTy));
631 // Provide a blank AsmName. MC hacks are required anyway.
632 if (Field == "AsmName")
633 RV.setValue(BlankName);
635 // CostPerUse is aggregated from all Tuple members.
636 if (Field == "CostPerUse")
637 RV.setValue(IntInit::get(CostPerUse));
639 // Composite registers are always covered by sub-registers.
640 if (Field == "CoveredBySubRegs")
641 RV.setValue(BitInit::get(true));
643 // Copy fields from the RegisterTuples def.
644 if (Field == "SubRegIndices" ||
645 Field == "CompositeIndices") {
646 NewReg->addValue(*Def->getValue(Field));
650 // Some fields get their default uninitialized value.
651 if (Field == "DwarfNumbers" ||
652 Field == "DwarfAlias" ||
653 Field == "Aliases") {
654 if (const RecordVal *DefRV = RegisterCl->getValue(Field))
655 NewReg->addValue(*DefRV);
659 // Everything else is copied from Proto.
660 NewReg->addValue(RV);
666 } // end anonymous namespace
668 //===----------------------------------------------------------------------===//
669 // CodeGenRegisterClass
670 //===----------------------------------------------------------------------===//
672 static void sortAndUniqueRegisters(CodeGenRegister::Vec &M) {
673 std::sort(M.begin(), M.end(), deref<llvm::less>());
674 M.erase(std::unique(M.begin(), M.end(), deref<llvm::equal>()), M.end());
677 CodeGenRegisterClass::CodeGenRegisterClass(CodeGenRegBank &RegBank, Record *R)
680 TopoSigs(RegBank.getNumTopoSigs()),
683 std::vector<Record*> TypeList = R->getValueAsListOfDefs("RegTypes");
684 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
685 Record *Type = TypeList[i];
686 if (!Type->isSubClassOf("ValueType"))
687 PrintFatalError("RegTypes list member '" + Type->getName() +
688 "' does not derive from the ValueType class!");
689 VTs.push_back(getValueType(Type));
691 assert(!VTs.empty() && "RegisterClass must contain at least one ValueType!");
693 // Allocation order 0 is the full set. AltOrders provides others.
694 const SetTheory::RecVec *Elements = RegBank.getSets().expand(R);
695 ListInit *AltOrders = R->getValueAsListInit("AltOrders");
696 Orders.resize(1 + AltOrders->size());
698 // Default allocation order always contains all registers.
699 for (unsigned i = 0, e = Elements->size(); i != e; ++i) {
700 Orders[0].push_back((*Elements)[i]);
701 const CodeGenRegister *Reg = RegBank.getReg((*Elements)[i]);
702 Members.push_back(Reg);
703 TopoSigs.set(Reg->getTopoSig());
705 sortAndUniqueRegisters(Members);
707 // Alternative allocation orders may be subsets.
708 SetTheory::RecSet Order;
709 for (unsigned i = 0, e = AltOrders->size(); i != e; ++i) {
710 RegBank.getSets().evaluate(AltOrders->getElement(i), Order, R->getLoc());
711 Orders[1 + i].append(Order.begin(), Order.end());
712 // Verify that all altorder members are regclass members.
713 while (!Order.empty()) {
714 CodeGenRegister *Reg = RegBank.getReg(Order.back());
717 PrintFatalError(R->getLoc(), " AltOrder register " + Reg->getName() +
718 " is not a class member");
722 // Allow targets to override the size in bits of the RegisterClass.
723 unsigned Size = R->getValueAsInt("Size");
725 Namespace = R->getValueAsString("Namespace");
726 SpillSize = Size ? Size : MVT(VTs[0]).getSizeInBits();
727 SpillAlignment = R->getValueAsInt("Alignment");
728 CopyCost = R->getValueAsInt("CopyCost");
729 Allocatable = R->getValueAsBit("isAllocatable");
730 AltOrderSelect = R->getValueAsString("AltOrderSelect");
731 int AllocationPriority = R->getValueAsInt("AllocationPriority");
732 if (AllocationPriority < 0 || AllocationPriority > 63)
733 PrintFatalError(R->getLoc(), "AllocationPriority out of range [0,63]");
734 this->AllocationPriority = AllocationPriority;
737 // Create an inferred register class that was missing from the .td files.
738 // Most properties will be inherited from the closest super-class after the
739 // class structure has been computed.
740 CodeGenRegisterClass::CodeGenRegisterClass(CodeGenRegBank &RegBank,
741 StringRef Name, Key Props)
742 : Members(*Props.Members),
745 TopoSigs(RegBank.getNumTopoSigs()),
747 SpillSize(Props.SpillSize),
748 SpillAlignment(Props.SpillAlignment),
751 AllocationPriority(0) {
752 for (const auto R : Members)
753 TopoSigs.set(R->getTopoSig());
756 // Compute inherited propertied for a synthesized register class.
757 void CodeGenRegisterClass::inheritProperties(CodeGenRegBank &RegBank) {
758 assert(!getDef() && "Only synthesized classes can inherit properties");
759 assert(!SuperClasses.empty() && "Synthesized class without super class");
761 // The last super-class is the smallest one.
762 CodeGenRegisterClass &Super = *SuperClasses.back();
764 // Most properties are copied directly.
765 // Exceptions are members, size, and alignment
766 Namespace = Super.Namespace;
768 CopyCost = Super.CopyCost;
769 Allocatable = Super.Allocatable;
770 AltOrderSelect = Super.AltOrderSelect;
771 AllocationPriority = Super.AllocationPriority;
773 // Copy all allocation orders, filter out foreign registers from the larger
775 Orders.resize(Super.Orders.size());
776 for (unsigned i = 0, ie = Super.Orders.size(); i != ie; ++i)
777 for (unsigned j = 0, je = Super.Orders[i].size(); j != je; ++j)
778 if (contains(RegBank.getReg(Super.Orders[i][j])))
779 Orders[i].push_back(Super.Orders[i][j]);
782 bool CodeGenRegisterClass::contains(const CodeGenRegister *Reg) const {
783 return std::binary_search(Members.begin(), Members.end(), Reg,
784 deref<llvm::less>());
789 raw_ostream &operator<<(raw_ostream &OS, const CodeGenRegisterClass::Key &K) {
790 OS << "{ S=" << K.SpillSize << ", A=" << K.SpillAlignment;
791 for (const auto R : *K.Members)
792 OS << ", " << R->getName();
796 } // end namespace llvm
798 // This is a simple lexicographical order that can be used to search for sets.
799 // It is not the same as the topological order provided by TopoOrderRC.
800 bool CodeGenRegisterClass::Key::
801 operator<(const CodeGenRegisterClass::Key &B) const {
802 assert(Members && B.Members);
803 return std::tie(*Members, SpillSize, SpillAlignment) <
804 std::tie(*B.Members, B.SpillSize, B.SpillAlignment);
807 // Returns true if RC is a strict subclass.
808 // RC is a sub-class of this class if it is a valid replacement for any
809 // instruction operand where a register of this classis required. It must
810 // satisfy these conditions:
812 // 1. All RC registers are also in this.
813 // 2. The RC spill size must not be smaller than our spill size.
814 // 3. RC spill alignment must be compatible with ours.
816 static bool testSubClass(const CodeGenRegisterClass *A,
817 const CodeGenRegisterClass *B) {
818 return A->SpillAlignment && B->SpillAlignment % A->SpillAlignment == 0 &&
819 A->SpillSize <= B->SpillSize &&
820 std::includes(A->getMembers().begin(), A->getMembers().end(),
821 B->getMembers().begin(), B->getMembers().end(),
822 deref<llvm::less>());
825 /// Sorting predicate for register classes. This provides a topological
826 /// ordering that arranges all register classes before their sub-classes.
828 /// Register classes with the same registers, spill size, and alignment form a
829 /// clique. They will be ordered alphabetically.
831 static bool TopoOrderRC(const CodeGenRegisterClass &PA,
832 const CodeGenRegisterClass &PB) {
838 // Order by ascending spill size.
839 if (A->SpillSize < B->SpillSize)
841 if (A->SpillSize > B->SpillSize)
844 // Order by ascending spill alignment.
845 if (A->SpillAlignment < B->SpillAlignment)
847 if (A->SpillAlignment > B->SpillAlignment)
850 // Order by descending set size. Note that the classes' allocation order may
851 // not have been computed yet. The Members set is always vaild.
852 if (A->getMembers().size() > B->getMembers().size())
854 if (A->getMembers().size() < B->getMembers().size())
857 // Finally order by name as a tie breaker.
858 return StringRef(A->getName()) < B->getName();
861 std::string CodeGenRegisterClass::getQualifiedName() const {
862 if (Namespace.empty())
865 return (Namespace + "::" + getName()).str();
868 // Compute sub-classes of all register classes.
869 // Assume the classes are ordered topologically.
870 void CodeGenRegisterClass::computeSubClasses(CodeGenRegBank &RegBank) {
871 auto &RegClasses = RegBank.getRegClasses();
873 // Visit backwards so sub-classes are seen first.
874 for (auto I = RegClasses.rbegin(), E = RegClasses.rend(); I != E; ++I) {
875 CodeGenRegisterClass &RC = *I;
876 RC.SubClasses.resize(RegClasses.size());
877 RC.SubClasses.set(RC.EnumValue);
879 // Normally, all subclasses have IDs >= rci, unless RC is part of a clique.
880 for (auto I2 = I.base(), E2 = RegClasses.end(); I2 != E2; ++I2) {
881 CodeGenRegisterClass &SubRC = *I2;
882 if (RC.SubClasses.test(SubRC.EnumValue))
884 if (!testSubClass(&RC, &SubRC))
886 // SubRC is a sub-class. Grap all its sub-classes so we won't have to
888 RC.SubClasses |= SubRC.SubClasses;
891 // Sweep up missed clique members. They will be immediately preceding RC.
892 for (auto I2 = std::next(I); I2 != E && testSubClass(&RC, &*I2); ++I2)
893 RC.SubClasses.set(I2->EnumValue);
896 // Compute the SuperClasses lists from the SubClasses vectors.
897 for (auto &RC : RegClasses) {
898 const BitVector &SC = RC.getSubClasses();
899 auto I = RegClasses.begin();
900 for (int s = 0, next_s = SC.find_first(); next_s != -1;
901 next_s = SC.find_next(s)) {
902 std::advance(I, next_s - s);
906 I->SuperClasses.push_back(&RC);
910 // With the class hierarchy in place, let synthesized register classes inherit
911 // properties from their closest super-class. The iteration order here can
912 // propagate properties down multiple levels.
913 for (auto &RC : RegClasses)
915 RC.inheritProperties(RegBank);
918 Optional<std::pair<CodeGenRegisterClass *, CodeGenRegisterClass *>>
919 CodeGenRegisterClass::getMatchingSubClassWithSubRegs(
920 CodeGenRegBank &RegBank, const CodeGenSubRegIndex *SubIdx) const {
921 auto SizeOrder = [](const CodeGenRegisterClass *A,
922 const CodeGenRegisterClass *B) {
923 return A->getMembers().size() > B->getMembers().size();
926 auto &RegClasses = RegBank.getRegClasses();
928 // Find all the subclasses of this one that fully support the sub-register
929 // index and order them by size. BiggestSuperRC should always be first.
930 CodeGenRegisterClass *BiggestSuperRegRC = getSubClassWithSubReg(SubIdx);
931 if (!BiggestSuperRegRC)
933 BitVector SuperRegRCsBV = BiggestSuperRegRC->getSubClasses();
934 std::vector<CodeGenRegisterClass *> SuperRegRCs;
935 for (auto &RC : RegClasses)
936 if (SuperRegRCsBV[RC.EnumValue])
937 SuperRegRCs.emplace_back(&RC);
938 std::sort(SuperRegRCs.begin(), SuperRegRCs.end(), SizeOrder);
939 assert(SuperRegRCs.front() == BiggestSuperRegRC && "Biggest class wasn't first");
941 // Find all the subreg classes and order them by size too.
942 std::vector<std::pair<CodeGenRegisterClass *, BitVector>> SuperRegClasses;
943 for (auto &RC: RegClasses) {
944 BitVector SuperRegClassesBV(RegClasses.size());
945 RC.getSuperRegClasses(SubIdx, SuperRegClassesBV);
946 if (SuperRegClassesBV.any())
947 SuperRegClasses.push_back(std::make_pair(&RC, SuperRegClassesBV));
949 std::sort(SuperRegClasses.begin(), SuperRegClasses.end(),
950 [&](const std::pair<CodeGenRegisterClass *, BitVector> &A,
951 const std::pair<CodeGenRegisterClass *, BitVector> &B) {
952 return SizeOrder(A.first, B.first);
955 // Find the biggest subclass and subreg class such that R:subidx is in the
956 // subreg class for all R in subclass.
959 // All registers in X86's GR64 have a sub_32bit subregister but no class
960 // exists that contains all the 32-bit subregisters because GR64 contains RIP
961 // but GR32 does not contain EIP. Instead, we constrain SuperRegRC to
962 // GR32_with_sub_8bit (which is identical to GR32_with_sub_32bit) and then,
963 // having excluded RIP, we are able to find a SubRegRC (GR32).
964 CodeGenRegisterClass *ChosenSuperRegClass = nullptr;
965 CodeGenRegisterClass *SubRegRC = nullptr;
966 for (auto *SuperRegRC : SuperRegRCs) {
967 for (const auto &SuperRegClassPair : SuperRegClasses) {
968 const BitVector &SuperRegClassBV = SuperRegClassPair.second;
969 if (SuperRegClassBV[SuperRegRC->EnumValue]) {
970 SubRegRC = SuperRegClassPair.first;
971 ChosenSuperRegClass = SuperRegRC;
973 // If SubRegRC is bigger than SuperRegRC then there are members of
974 // SubRegRC that don't have super registers via SubIdx. Keep looking to
975 // find a better fit and fall back on this one if there isn't one.
977 // This is intended to prevent X86 from making odd choices such as
978 // picking LOW32_ADDR_ACCESS_RBP instead of GR32 in the example above.
979 // LOW32_ADDR_ACCESS_RBP is a valid choice but contains registers that
980 // aren't subregisters of SuperRegRC whereas GR32 has a direct 1:1
982 if (SuperRegRC->getMembers().size() >= SubRegRC->getMembers().size())
983 return std::make_pair(ChosenSuperRegClass, SubRegRC);
987 // If we found a fit but it wasn't quite ideal because SubRegRC had excess
988 // registers, then we're done.
989 if (ChosenSuperRegClass)
990 return std::make_pair(ChosenSuperRegClass, SubRegRC);
996 void CodeGenRegisterClass::getSuperRegClasses(const CodeGenSubRegIndex *SubIdx,
997 BitVector &Out) const {
998 auto FindI = SuperRegClasses.find(SubIdx);
999 if (FindI == SuperRegClasses.end())
1001 for (CodeGenRegisterClass *RC : FindI->second)
1002 Out.set(RC->EnumValue);
1005 // Populate a unique sorted list of units from a register set.
1006 void CodeGenRegisterClass::buildRegUnitSet(
1007 std::vector<unsigned> &RegUnits) const {
1008 std::vector<unsigned> TmpUnits;
1009 for (RegUnitIterator UnitI(Members); UnitI.isValid(); ++UnitI)
1010 TmpUnits.push_back(*UnitI);
1011 std::sort(TmpUnits.begin(), TmpUnits.end());
1012 std::unique_copy(TmpUnits.begin(), TmpUnits.end(),
1013 std::back_inserter(RegUnits));
1016 //===----------------------------------------------------------------------===//
1018 //===----------------------------------------------------------------------===//
1020 CodeGenRegBank::CodeGenRegBank(RecordKeeper &Records) {
1021 // Configure register Sets to understand register classes and tuples.
1022 Sets.addFieldExpander("RegisterClass", "MemberList");
1023 Sets.addFieldExpander("CalleeSavedRegs", "SaveList");
1024 Sets.addExpander("RegisterTuples", llvm::make_unique<TupleExpander>());
1026 // Read in the user-defined (named) sub-register indices.
1027 // More indices will be synthesized later.
1028 std::vector<Record*> SRIs = Records.getAllDerivedDefinitions("SubRegIndex");
1029 std::sort(SRIs.begin(), SRIs.end(), LessRecord());
1030 for (unsigned i = 0, e = SRIs.size(); i != e; ++i)
1031 getSubRegIdx(SRIs[i]);
1032 // Build composite maps from ComposedOf fields.
1033 for (auto &Idx : SubRegIndices)
1034 Idx.updateComponents(*this);
1036 // Read in the register definitions.
1037 std::vector<Record*> Regs = Records.getAllDerivedDefinitions("Register");
1038 std::sort(Regs.begin(), Regs.end(), LessRecordRegister());
1039 // Assign the enumeration values.
1040 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
1043 // Expand tuples and number the new registers.
1044 std::vector<Record*> Tups =
1045 Records.getAllDerivedDefinitions("RegisterTuples");
1047 for (Record *R : Tups) {
1048 std::vector<Record *> TupRegs = *Sets.expand(R);
1049 std::sort(TupRegs.begin(), TupRegs.end(), LessRecordRegister());
1050 for (Record *RC : TupRegs)
1054 // Now all the registers are known. Build the object graph of explicit
1055 // register-register references.
1056 for (auto &Reg : Registers)
1057 Reg.buildObjectGraph(*this);
1059 // Compute register name map.
1060 for (auto &Reg : Registers)
1061 // FIXME: This could just be RegistersByName[name] = register, except that
1062 // causes some failures in MIPS - perhaps they have duplicate register name
1063 // entries? (or maybe there's a reason for it - I don't know much about this
1064 // code, just drive-by refactoring)
1065 RegistersByName.insert(
1066 std::make_pair(Reg.TheDef->getValueAsString("AsmName"), &Reg));
1068 // Precompute all sub-register maps.
1069 // This will create Composite entries for all inferred sub-register indices.
1070 for (auto &Reg : Registers)
1071 Reg.computeSubRegs(*this);
1073 // Infer even more sub-registers by combining leading super-registers.
1074 for (auto &Reg : Registers)
1075 if (Reg.CoveredBySubRegs)
1076 Reg.computeSecondarySubRegs(*this);
1078 // After the sub-register graph is complete, compute the topologically
1079 // ordered SuperRegs list.
1080 for (auto &Reg : Registers)
1081 Reg.computeSuperRegs(*this);
1083 // Native register units are associated with a leaf register. They've all been
1085 NumNativeRegUnits = RegUnits.size();
1087 // Read in register class definitions.
1088 std::vector<Record*> RCs = Records.getAllDerivedDefinitions("RegisterClass");
1090 PrintFatalError("No 'RegisterClass' subclasses defined!");
1092 // Allocate user-defined register classes.
1093 for (auto *RC : RCs) {
1094 RegClasses.emplace_back(*this, RC);
1095 addToMaps(&RegClasses.back());
1098 // Infer missing classes to create a full algebra.
1099 computeInferredRegisterClasses();
1101 // Order register classes topologically and assign enum values.
1102 RegClasses.sort(TopoOrderRC);
1104 for (auto &RC : RegClasses)
1106 CodeGenRegisterClass::computeSubClasses(*this);
1109 // Create a synthetic CodeGenSubRegIndex without a corresponding Record.
1111 CodeGenRegBank::createSubRegIndex(StringRef Name, StringRef Namespace) {
1112 SubRegIndices.emplace_back(Name, Namespace, SubRegIndices.size() + 1);
1113 return &SubRegIndices.back();
1116 CodeGenSubRegIndex *CodeGenRegBank::getSubRegIdx(Record *Def) {
1117 CodeGenSubRegIndex *&Idx = Def2SubRegIdx[Def];
1120 SubRegIndices.emplace_back(Def, SubRegIndices.size() + 1);
1121 Idx = &SubRegIndices.back();
1125 CodeGenRegister *CodeGenRegBank::getReg(Record *Def) {
1126 CodeGenRegister *&Reg = Def2Reg[Def];
1129 Registers.emplace_back(Def, Registers.size() + 1);
1130 Reg = &Registers.back();
1134 void CodeGenRegBank::addToMaps(CodeGenRegisterClass *RC) {
1135 if (Record *Def = RC->getDef())
1136 Def2RC.insert(std::make_pair(Def, RC));
1138 // Duplicate classes are rejected by insert().
1139 // That's OK, we only care about the properties handled by CGRC::Key.
1140 CodeGenRegisterClass::Key K(*RC);
1141 Key2RC.insert(std::make_pair(K, RC));
1144 // Create a synthetic sub-class if it is missing.
1145 CodeGenRegisterClass*
1146 CodeGenRegBank::getOrCreateSubClass(const CodeGenRegisterClass *RC,
1147 const CodeGenRegister::Vec *Members,
1149 // Synthetic sub-class has the same size and alignment as RC.
1150 CodeGenRegisterClass::Key K(Members, RC->SpillSize, RC->SpillAlignment);
1151 RCKeyMap::const_iterator FoundI = Key2RC.find(K);
1152 if (FoundI != Key2RC.end())
1153 return FoundI->second;
1155 // Sub-class doesn't exist, create a new one.
1156 RegClasses.emplace_back(*this, Name, K);
1157 addToMaps(&RegClasses.back());
1158 return &RegClasses.back();
1161 CodeGenRegisterClass *CodeGenRegBank::getRegClass(Record *Def) {
1162 if (CodeGenRegisterClass *RC = Def2RC[Def])
1165 PrintFatalError(Def->getLoc(), "Not a known RegisterClass!");
1169 CodeGenRegBank::getCompositeSubRegIndex(CodeGenSubRegIndex *A,
1170 CodeGenSubRegIndex *B) {
1171 // Look for an existing entry.
1172 CodeGenSubRegIndex *Comp = A->compose(B);
1176 // None exists, synthesize one.
1177 std::string Name = A->getName() + "_then_" + B->getName();
1178 Comp = createSubRegIndex(Name, A->getNamespace());
1179 A->addComposite(B, Comp);
1183 CodeGenSubRegIndex *CodeGenRegBank::
1184 getConcatSubRegIndex(const SmallVector<CodeGenSubRegIndex *, 8> &Parts) {
1185 assert(Parts.size() > 1 && "Need two parts to concatenate");
1187 // Look for an existing entry.
1188 CodeGenSubRegIndex *&Idx = ConcatIdx[Parts];
1192 // None exists, synthesize one.
1193 std::string Name = Parts.front()->getName();
1194 // Determine whether all parts are contiguous.
1195 bool isContinuous = true;
1196 unsigned Size = Parts.front()->Size;
1197 unsigned LastOffset = Parts.front()->Offset;
1198 unsigned LastSize = Parts.front()->Size;
1199 for (unsigned i = 1, e = Parts.size(); i != e; ++i) {
1201 Name += Parts[i]->getName();
1202 Size += Parts[i]->Size;
1203 if (Parts[i]->Offset != (LastOffset + LastSize))
1204 isContinuous = false;
1205 LastOffset = Parts[i]->Offset;
1206 LastSize = Parts[i]->Size;
1208 Idx = createSubRegIndex(Name, Parts.front()->getNamespace());
1210 Idx->Offset = isContinuous ? Parts.front()->Offset : -1;
1214 void CodeGenRegBank::computeComposites() {
1215 // Keep track of TopoSigs visited. We only need to visit each TopoSig once,
1216 // and many registers will share TopoSigs on regular architectures.
1217 BitVector TopoSigs(getNumTopoSigs());
1219 for (const auto &Reg1 : Registers) {
1220 // Skip identical subreg structures already processed.
1221 if (TopoSigs.test(Reg1.getTopoSig()))
1223 TopoSigs.set(Reg1.getTopoSig());
1225 const CodeGenRegister::SubRegMap &SRM1 = Reg1.getSubRegs();
1226 for (CodeGenRegister::SubRegMap::const_iterator i1 = SRM1.begin(),
1227 e1 = SRM1.end(); i1 != e1; ++i1) {
1228 CodeGenSubRegIndex *Idx1 = i1->first;
1229 CodeGenRegister *Reg2 = i1->second;
1230 // Ignore identity compositions.
1233 const CodeGenRegister::SubRegMap &SRM2 = Reg2->getSubRegs();
1234 // Try composing Idx1 with another SubRegIndex.
1235 for (CodeGenRegister::SubRegMap::const_iterator i2 = SRM2.begin(),
1236 e2 = SRM2.end(); i2 != e2; ++i2) {
1237 CodeGenSubRegIndex *Idx2 = i2->first;
1238 CodeGenRegister *Reg3 = i2->second;
1239 // Ignore identity compositions.
1242 // OK Reg1:IdxPair == Reg3. Find the index with Reg:Idx == Reg3.
1243 CodeGenSubRegIndex *Idx3 = Reg1.getSubRegIndex(Reg3);
1244 assert(Idx3 && "Sub-register doesn't have an index");
1246 // Conflicting composition? Emit a warning but allow it.
1247 if (CodeGenSubRegIndex *Prev = Idx1->addComposite(Idx2, Idx3))
1248 PrintWarning(Twine("SubRegIndex ") + Idx1->getQualifiedName() +
1249 " and " + Idx2->getQualifiedName() +
1250 " compose ambiguously as " + Prev->getQualifiedName() +
1251 " or " + Idx3->getQualifiedName());
1257 // Compute lane masks. This is similar to register units, but at the
1258 // sub-register index level. Each bit in the lane mask is like a register unit
1259 // class, and two lane masks will have a bit in common if two sub-register
1260 // indices overlap in some register.
1262 // Conservatively share a lane mask bit if two sub-register indices overlap in
1263 // some registers, but not in others. That shouldn't happen a lot.
1264 void CodeGenRegBank::computeSubRegLaneMasks() {
1265 // First assign individual bits to all the leaf indices.
1267 // Determine mask of lanes that cover their registers.
1268 CoveringLanes = LaneBitmask::getAll();
1269 for (auto &Idx : SubRegIndices) {
1270 if (Idx.getComposites().empty()) {
1271 if (Bit > LaneBitmask::BitWidth) {
1273 Twine("Ran out of lanemask bits to represent subregister ")
1276 Idx.LaneMask = LaneBitmask::getLane(Bit);
1279 Idx.LaneMask = LaneBitmask::getNone();
1283 // Compute transformation sequences for composeSubRegIndexLaneMask. The idea
1284 // here is that for each possible target subregister we look at the leafs
1285 // in the subregister graph that compose for this target and create
1286 // transformation sequences for the lanemasks. Each step in the sequence
1287 // consists of a bitmask and a bitrotate operation. As the rotation amounts
1288 // are usually the same for many subregisters we can easily combine the steps
1289 // by combining the masks.
1290 for (const auto &Idx : SubRegIndices) {
1291 const auto &Composites = Idx.getComposites();
1292 auto &LaneTransforms = Idx.CompositionLaneMaskTransform;
1294 if (Composites.empty()) {
1295 // Moving from a class with no subregisters we just had a single lane:
1296 // The subregister must be a leaf subregister and only occupies 1 bit.
1297 // Move the bit from the class without subregisters into that position.
1298 static_assert(sizeof(Idx.LaneMask.getAsInteger()) == 4,
1299 "Change Log2_32 to a proper one");
1300 unsigned DstBit = Log2_32(Idx.LaneMask.getAsInteger());
1301 assert(Idx.LaneMask == LaneBitmask::getLane(DstBit) &&
1302 "Must be a leaf subregister");
1303 MaskRolPair MaskRol = { LaneBitmask::getLane(0), (uint8_t)DstBit };
1304 LaneTransforms.push_back(MaskRol);
1306 // Go through all leaf subregisters and find the ones that compose with
1307 // Idx. These make out all possible valid bits in the lane mask we want to
1308 // transform. Looking only at the leafs ensure that only a single bit in
1310 unsigned NextBit = 0;
1311 for (auto &Idx2 : SubRegIndices) {
1312 // Skip non-leaf subregisters.
1313 if (!Idx2.getComposites().empty())
1315 // Replicate the behaviour from the lane mask generation loop above.
1316 unsigned SrcBit = NextBit;
1317 LaneBitmask SrcMask = LaneBitmask::getLane(SrcBit);
1318 if (NextBit < LaneBitmask::BitWidth-1)
1320 assert(Idx2.LaneMask == SrcMask);
1322 // Get the composed subregister if there is any.
1323 auto C = Composites.find(&Idx2);
1324 if (C == Composites.end())
1326 const CodeGenSubRegIndex *Composite = C->second;
1327 // The Composed subreg should be a leaf subreg too
1328 assert(Composite->getComposites().empty());
1330 // Create Mask+Rotate operation and merge with existing ops if possible.
1331 static_assert(sizeof(Composite->LaneMask.getAsInteger()) == 4,
1332 "Change Log2_32 to a proper one");
1333 unsigned DstBit = Log2_32(Composite->LaneMask.getAsInteger());
1334 int Shift = DstBit - SrcBit;
1335 uint8_t RotateLeft = Shift >= 0 ? (uint8_t)Shift
1336 : LaneBitmask::BitWidth + Shift;
1337 for (auto &I : LaneTransforms) {
1338 if (I.RotateLeft == RotateLeft) {
1340 SrcMask = LaneBitmask::getNone();
1343 if (SrcMask.any()) {
1344 MaskRolPair MaskRol = { SrcMask, RotateLeft };
1345 LaneTransforms.push_back(MaskRol);
1350 // Optimize if the transformation consists of one step only: Set mask to
1351 // 0xffffffff (including some irrelevant invalid bits) so that it should
1352 // merge with more entries later while compressing the table.
1353 if (LaneTransforms.size() == 1)
1354 LaneTransforms[0].Mask = LaneBitmask::getAll();
1356 // Further compression optimization: For invalid compositions resulting
1357 // in a sequence with 0 entries we can just pick any other. Choose
1358 // Mask 0xffffffff with Rotation 0.
1359 if (LaneTransforms.size() == 0) {
1360 MaskRolPair P = { LaneBitmask::getAll(), 0 };
1361 LaneTransforms.push_back(P);
1365 // FIXME: What if ad-hoc aliasing introduces overlaps that aren't represented
1366 // by the sub-register graph? This doesn't occur in any known targets.
1368 // Inherit lanes from composites.
1369 for (const auto &Idx : SubRegIndices) {
1370 LaneBitmask Mask = Idx.computeLaneMask();
1371 // If some super-registers without CoveredBySubRegs use this index, we can
1372 // no longer assume that the lanes are covering their registers.
1373 if (!Idx.AllSuperRegsCovered)
1374 CoveringLanes &= ~Mask;
1377 // Compute lane mask combinations for register classes.
1378 for (auto &RegClass : RegClasses) {
1379 LaneBitmask LaneMask;
1380 for (const auto &SubRegIndex : SubRegIndices) {
1381 if (RegClass.getSubClassWithSubReg(&SubRegIndex) == nullptr)
1383 LaneMask |= SubRegIndex.LaneMask;
1386 // For classes without any subregisters set LaneMask to 1 instead of 0.
1387 // This makes it easier for client code to handle classes uniformly.
1388 if (LaneMask.none())
1389 LaneMask = LaneBitmask::getLane(0);
1391 RegClass.LaneMask = LaneMask;
1397 // UberRegSet is a helper class for computeRegUnitWeights. Each UberRegSet is
1398 // the transitive closure of the union of overlapping register
1399 // classes. Together, the UberRegSets form a partition of the registers. If we
1400 // consider overlapping register classes to be connected, then each UberRegSet
1401 // is a set of connected components.
1403 // An UberRegSet will likely be a horizontal slice of register names of
1404 // the same width. Nontrivial subregisters should then be in a separate
1405 // UberRegSet. But this property isn't required for valid computation of
1406 // register unit weights.
1408 // A Weight field caches the max per-register unit weight in each UberRegSet.
1410 // A set of SingularDeterminants flags single units of some register in this set
1411 // for which the unit weight equals the set weight. These units should not have
1412 // their weight increased.
1414 CodeGenRegister::Vec Regs;
1415 unsigned Weight = 0;
1416 CodeGenRegister::RegUnitList SingularDeterminants;
1418 UberRegSet() = default;
1421 } // end anonymous namespace
1423 // Partition registers into UberRegSets, where each set is the transitive
1424 // closure of the union of overlapping register classes.
1426 // UberRegSets[0] is a special non-allocatable set.
1427 static void computeUberSets(std::vector<UberRegSet> &UberSets,
1428 std::vector<UberRegSet*> &RegSets,
1429 CodeGenRegBank &RegBank) {
1430 const auto &Registers = RegBank.getRegisters();
1432 // The Register EnumValue is one greater than its index into Registers.
1433 assert(Registers.size() == Registers.back().EnumValue &&
1434 "register enum value mismatch");
1436 // For simplicitly make the SetID the same as EnumValue.
1437 IntEqClasses UberSetIDs(Registers.size()+1);
1438 std::set<unsigned> AllocatableRegs;
1439 for (auto &RegClass : RegBank.getRegClasses()) {
1440 if (!RegClass.Allocatable)
1443 const CodeGenRegister::Vec &Regs = RegClass.getMembers();
1447 unsigned USetID = UberSetIDs.findLeader((*Regs.begin())->EnumValue);
1448 assert(USetID && "register number 0 is invalid");
1450 AllocatableRegs.insert((*Regs.begin())->EnumValue);
1451 for (auto I = std::next(Regs.begin()), E = Regs.end(); I != E; ++I) {
1452 AllocatableRegs.insert((*I)->EnumValue);
1453 UberSetIDs.join(USetID, (*I)->EnumValue);
1456 // Combine non-allocatable regs.
1457 for (const auto &Reg : Registers) {
1458 unsigned RegNum = Reg.EnumValue;
1459 if (AllocatableRegs.count(RegNum))
1462 UberSetIDs.join(0, RegNum);
1464 UberSetIDs.compress();
1466 // Make the first UberSet a special unallocatable set.
1467 unsigned ZeroID = UberSetIDs[0];
1469 // Insert Registers into the UberSets formed by union-find.
1470 // Do not resize after this.
1471 UberSets.resize(UberSetIDs.getNumClasses());
1473 for (const CodeGenRegister &Reg : Registers) {
1474 unsigned USetID = UberSetIDs[Reg.EnumValue];
1477 else if (USetID == ZeroID)
1480 UberRegSet *USet = &UberSets[USetID];
1481 USet->Regs.push_back(&Reg);
1482 sortAndUniqueRegisters(USet->Regs);
1483 RegSets[i++] = USet;
1487 // Recompute each UberSet weight after changing unit weights.
1488 static void computeUberWeights(std::vector<UberRegSet> &UberSets,
1489 CodeGenRegBank &RegBank) {
1490 // Skip the first unallocatable set.
1491 for (std::vector<UberRegSet>::iterator I = std::next(UberSets.begin()),
1492 E = UberSets.end(); I != E; ++I) {
1494 // Initialize all unit weights in this set, and remember the max units/reg.
1495 const CodeGenRegister *Reg = nullptr;
1496 unsigned MaxWeight = 0, Weight = 0;
1497 for (RegUnitIterator UnitI(I->Regs); UnitI.isValid(); ++UnitI) {
1498 if (Reg != UnitI.getReg()) {
1499 if (Weight > MaxWeight)
1501 Reg = UnitI.getReg();
1504 unsigned UWeight = RegBank.getRegUnit(*UnitI).Weight;
1507 RegBank.increaseRegUnitWeight(*UnitI, UWeight);
1511 if (Weight > MaxWeight)
1513 if (I->Weight != MaxWeight) {
1515 dbgs() << "UberSet " << I - UberSets.begin() << " Weight " << MaxWeight;
1516 for (auto &Unit : I->Regs)
1517 dbgs() << " " << Unit->getName();
1519 // Update the set weight.
1520 I->Weight = MaxWeight;
1523 // Find singular determinants.
1524 for (const auto R : I->Regs) {
1525 if (R->getRegUnits().count() == 1 && R->getWeight(RegBank) == I->Weight) {
1526 I->SingularDeterminants |= R->getRegUnits();
1532 // normalizeWeight is a computeRegUnitWeights helper that adjusts the weight of
1533 // a register and its subregisters so that they have the same weight as their
1534 // UberSet. Self-recursion processes the subregister tree in postorder so
1535 // subregisters are normalized first.
1538 // - creates new adopted register units
1539 // - causes superregisters to inherit adopted units
1540 // - increases the weight of "singular" units
1541 // - induces recomputation of UberWeights.
1542 static bool normalizeWeight(CodeGenRegister *Reg,
1543 std::vector<UberRegSet> &UberSets,
1544 std::vector<UberRegSet*> &RegSets,
1545 SparseBitVector<> &NormalRegs,
1546 CodeGenRegister::RegUnitList &NormalUnits,
1547 CodeGenRegBank &RegBank) {
1548 if (NormalRegs.test(Reg->EnumValue))
1550 NormalRegs.set(Reg->EnumValue);
1552 bool Changed = false;
1553 const CodeGenRegister::SubRegMap &SRM = Reg->getSubRegs();
1554 for (CodeGenRegister::SubRegMap::const_iterator SRI = SRM.begin(),
1555 SRE = SRM.end(); SRI != SRE; ++SRI) {
1556 if (SRI->second == Reg)
1557 continue; // self-cycles happen
1559 Changed |= normalizeWeight(SRI->second, UberSets, RegSets,
1560 NormalRegs, NormalUnits, RegBank);
1562 // Postorder register normalization.
1564 // Inherit register units newly adopted by subregisters.
1565 if (Reg->inheritRegUnits(RegBank))
1566 computeUberWeights(UberSets, RegBank);
1568 // Check if this register is too skinny for its UberRegSet.
1569 UberRegSet *UberSet = RegSets[RegBank.getRegIndex(Reg)];
1571 unsigned RegWeight = Reg->getWeight(RegBank);
1572 if (UberSet->Weight > RegWeight) {
1573 // A register unit's weight can be adjusted only if it is the singular unit
1574 // for this register, has not been used to normalize a subregister's set,
1575 // and has not already been used to singularly determine this UberRegSet.
1576 unsigned AdjustUnit = *Reg->getRegUnits().begin();
1577 if (Reg->getRegUnits().count() != 1
1578 || hasRegUnit(NormalUnits, AdjustUnit)
1579 || hasRegUnit(UberSet->SingularDeterminants, AdjustUnit)) {
1580 // We don't have an adjustable unit, so adopt a new one.
1581 AdjustUnit = RegBank.newRegUnit(UberSet->Weight - RegWeight);
1582 Reg->adoptRegUnit(AdjustUnit);
1583 // Adopting a unit does not immediately require recomputing set weights.
1586 // Adjust the existing single unit.
1587 RegBank.increaseRegUnitWeight(AdjustUnit, UberSet->Weight - RegWeight);
1588 // The unit may be shared among sets and registers within this set.
1589 computeUberWeights(UberSets, RegBank);
1594 // Mark these units normalized so superregisters can't change their weights.
1595 NormalUnits |= Reg->getRegUnits();
1600 // Compute a weight for each register unit created during getSubRegs.
1602 // The goal is that two registers in the same class will have the same weight,
1603 // where each register's weight is defined as sum of its units' weights.
1604 void CodeGenRegBank::computeRegUnitWeights() {
1605 std::vector<UberRegSet> UberSets;
1606 std::vector<UberRegSet*> RegSets(Registers.size());
1607 computeUberSets(UberSets, RegSets, *this);
1608 // UberSets and RegSets are now immutable.
1610 computeUberWeights(UberSets, *this);
1612 // Iterate over each Register, normalizing the unit weights until reaching
1614 unsigned NumIters = 0;
1615 for (bool Changed = true; Changed; ++NumIters) {
1616 assert(NumIters <= NumNativeRegUnits && "Runaway register unit weights");
1618 for (auto &Reg : Registers) {
1619 CodeGenRegister::RegUnitList NormalUnits;
1620 SparseBitVector<> NormalRegs;
1621 Changed |= normalizeWeight(&Reg, UberSets, RegSets, NormalRegs,
1622 NormalUnits, *this);
1627 // Find a set in UniqueSets with the same elements as Set.
1628 // Return an iterator into UniqueSets.
1629 static std::vector<RegUnitSet>::const_iterator
1630 findRegUnitSet(const std::vector<RegUnitSet> &UniqueSets,
1631 const RegUnitSet &Set) {
1632 std::vector<RegUnitSet>::const_iterator
1633 I = UniqueSets.begin(), E = UniqueSets.end();
1635 if (I->Units == Set.Units)
1641 // Return true if the RUSubSet is a subset of RUSuperSet.
1642 static bool isRegUnitSubSet(const std::vector<unsigned> &RUSubSet,
1643 const std::vector<unsigned> &RUSuperSet) {
1644 return std::includes(RUSuperSet.begin(), RUSuperSet.end(),
1645 RUSubSet.begin(), RUSubSet.end());
1648 /// Iteratively prune unit sets. Prune subsets that are close to the superset,
1649 /// but with one or two registers removed. We occasionally have registers like
1650 /// APSR and PC thrown in with the general registers. We also see many
1651 /// special-purpose register subsets, such as tail-call and Thumb
1652 /// encodings. Generating all possible overlapping sets is combinatorial and
1653 /// overkill for modeling pressure. Ideally we could fix this statically in
1654 /// tablegen by (1) having the target define register classes that only include
1655 /// the allocatable registers and marking other classes as non-allocatable and
1656 /// (2) having a way to mark special purpose classes as "don't-care" classes for
1657 /// the purpose of pressure. However, we make an attempt to handle targets that
1658 /// are not nicely defined by merging nearly identical register unit sets
1659 /// statically. This generates smaller tables. Then, dynamically, we adjust the
1660 /// set limit by filtering the reserved registers.
1662 /// Merge sets only if the units have the same weight. For example, on ARM,
1663 /// Q-tuples with ssub index 0 include all S regs but also include D16+. We
1664 /// should not expand the S set to include D regs.
1665 void CodeGenRegBank::pruneUnitSets() {
1666 assert(RegClassUnitSets.empty() && "this invalidates RegClassUnitSets");
1668 // Form an equivalence class of UnitSets with no significant difference.
1669 std::vector<unsigned> SuperSetIDs;
1670 for (unsigned SubIdx = 0, EndIdx = RegUnitSets.size();
1671 SubIdx != EndIdx; ++SubIdx) {
1672 const RegUnitSet &SubSet = RegUnitSets[SubIdx];
1673 unsigned SuperIdx = 0;
1674 for (; SuperIdx != EndIdx; ++SuperIdx) {
1675 if (SuperIdx == SubIdx)
1678 unsigned UnitWeight = RegUnits[SubSet.Units[0]].Weight;
1679 const RegUnitSet &SuperSet = RegUnitSets[SuperIdx];
1680 if (isRegUnitSubSet(SubSet.Units, SuperSet.Units)
1681 && (SubSet.Units.size() + 3 > SuperSet.Units.size())
1682 && UnitWeight == RegUnits[SuperSet.Units[0]].Weight
1683 && UnitWeight == RegUnits[SuperSet.Units.back()].Weight) {
1684 DEBUG(dbgs() << "UnitSet " << SubIdx << " subsumed by " << SuperIdx
1686 // We can pick any of the set names for the merged set. Go for the
1687 // shortest one to avoid picking the name of one of the classes that are
1688 // artificially created by tablegen. So "FPR128_lo" instead of
1689 // "QQQQ_with_qsub3_in_FPR128_lo".
1690 if (RegUnitSets[SubIdx].Name.size() < RegUnitSets[SuperIdx].Name.size())
1691 RegUnitSets[SuperIdx].Name = RegUnitSets[SubIdx].Name;
1695 if (SuperIdx == EndIdx)
1696 SuperSetIDs.push_back(SubIdx);
1698 // Populate PrunedUnitSets with each equivalence class's superset.
1699 std::vector<RegUnitSet> PrunedUnitSets(SuperSetIDs.size());
1700 for (unsigned i = 0, e = SuperSetIDs.size(); i != e; ++i) {
1701 unsigned SuperIdx = SuperSetIDs[i];
1702 PrunedUnitSets[i].Name = RegUnitSets[SuperIdx].Name;
1703 PrunedUnitSets[i].Units.swap(RegUnitSets[SuperIdx].Units);
1705 RegUnitSets.swap(PrunedUnitSets);
1708 // Create a RegUnitSet for each RegClass that contains all units in the class
1709 // including adopted units that are necessary to model register pressure. Then
1710 // iteratively compute RegUnitSets such that the union of any two overlapping
1711 // RegUnitSets is repreresented.
1713 // RegisterInfoEmitter will map each RegClass to its RegUnitClass and any
1714 // RegUnitSet that is a superset of that RegUnitClass.
1715 void CodeGenRegBank::computeRegUnitSets() {
1716 assert(RegUnitSets.empty() && "dirty RegUnitSets");
1718 // Compute a unique RegUnitSet for each RegClass.
1719 auto &RegClasses = getRegClasses();
1720 for (auto &RC : RegClasses) {
1721 if (!RC.Allocatable)
1724 // Speculatively grow the RegUnitSets to hold the new set.
1725 RegUnitSets.resize(RegUnitSets.size() + 1);
1726 RegUnitSets.back().Name = RC.getName();
1728 // Compute a sorted list of units in this class.
1729 RC.buildRegUnitSet(RegUnitSets.back().Units);
1731 // Find an existing RegUnitSet.
1732 std::vector<RegUnitSet>::const_iterator SetI =
1733 findRegUnitSet(RegUnitSets, RegUnitSets.back());
1734 if (SetI != std::prev(RegUnitSets.end()))
1735 RegUnitSets.pop_back();
1738 DEBUG(dbgs() << "\nBefore pruning:\n";
1739 for (unsigned USIdx = 0, USEnd = RegUnitSets.size();
1740 USIdx < USEnd; ++USIdx) {
1741 dbgs() << "UnitSet " << USIdx << " " << RegUnitSets[USIdx].Name
1743 for (auto &U : RegUnitSets[USIdx].Units)
1744 printRegUnitName(U);
1748 // Iteratively prune unit sets.
1751 DEBUG(dbgs() << "\nBefore union:\n";
1752 for (unsigned USIdx = 0, USEnd = RegUnitSets.size();
1753 USIdx < USEnd; ++USIdx) {
1754 dbgs() << "UnitSet " << USIdx << " " << RegUnitSets[USIdx].Name
1756 for (auto &U : RegUnitSets[USIdx].Units)
1757 printRegUnitName(U);
1760 dbgs() << "\nUnion sets:\n");
1762 // Iterate over all unit sets, including new ones added by this loop.
1763 unsigned NumRegUnitSubSets = RegUnitSets.size();
1764 for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx) {
1765 // In theory, this is combinatorial. In practice, it needs to be bounded
1766 // by a small number of sets for regpressure to be efficient.
1767 // If the assert is hit, we need to implement pruning.
1768 assert(Idx < (2*NumRegUnitSubSets) && "runaway unit set inference");
1770 // Compare new sets with all original classes.
1771 for (unsigned SearchIdx = (Idx >= NumRegUnitSubSets) ? 0 : Idx+1;
1772 SearchIdx != EndIdx; ++SearchIdx) {
1773 std::set<unsigned> Intersection;
1774 std::set_intersection(RegUnitSets[Idx].Units.begin(),
1775 RegUnitSets[Idx].Units.end(),
1776 RegUnitSets[SearchIdx].Units.begin(),
1777 RegUnitSets[SearchIdx].Units.end(),
1778 std::inserter(Intersection, Intersection.begin()));
1779 if (Intersection.empty())
1782 // Speculatively grow the RegUnitSets to hold the new set.
1783 RegUnitSets.resize(RegUnitSets.size() + 1);
1784 RegUnitSets.back().Name =
1785 RegUnitSets[Idx].Name + "+" + RegUnitSets[SearchIdx].Name;
1787 std::set_union(RegUnitSets[Idx].Units.begin(),
1788 RegUnitSets[Idx].Units.end(),
1789 RegUnitSets[SearchIdx].Units.begin(),
1790 RegUnitSets[SearchIdx].Units.end(),
1791 std::inserter(RegUnitSets.back().Units,
1792 RegUnitSets.back().Units.begin()));
1794 // Find an existing RegUnitSet, or add the union to the unique sets.
1795 std::vector<RegUnitSet>::const_iterator SetI =
1796 findRegUnitSet(RegUnitSets, RegUnitSets.back());
1797 if (SetI != std::prev(RegUnitSets.end()))
1798 RegUnitSets.pop_back();
1800 DEBUG(dbgs() << "UnitSet " << RegUnitSets.size()-1
1801 << " " << RegUnitSets.back().Name << ":";
1802 for (auto &U : RegUnitSets.back().Units)
1803 printRegUnitName(U);
1809 // Iteratively prune unit sets after inferring supersets.
1812 DEBUG(dbgs() << "\n";
1813 for (unsigned USIdx = 0, USEnd = RegUnitSets.size();
1814 USIdx < USEnd; ++USIdx) {
1815 dbgs() << "UnitSet " << USIdx << " " << RegUnitSets[USIdx].Name
1817 for (auto &U : RegUnitSets[USIdx].Units)
1818 printRegUnitName(U);
1822 // For each register class, list the UnitSets that are supersets.
1823 RegClassUnitSets.resize(RegClasses.size());
1825 for (auto &RC : RegClasses) {
1827 if (!RC.Allocatable)
1830 // Recompute the sorted list of units in this class.
1831 std::vector<unsigned> RCRegUnits;
1832 RC.buildRegUnitSet(RCRegUnits);
1834 // Don't increase pressure for unallocatable regclasses.
1835 if (RCRegUnits.empty())
1838 DEBUG(dbgs() << "RC " << RC.getName() << " Units: \n";
1839 for (auto U : RCRegUnits)
1840 printRegUnitName(U);
1841 dbgs() << "\n UnitSetIDs:");
1843 // Find all supersets.
1844 for (unsigned USIdx = 0, USEnd = RegUnitSets.size();
1845 USIdx != USEnd; ++USIdx) {
1846 if (isRegUnitSubSet(RCRegUnits, RegUnitSets[USIdx].Units)) {
1847 DEBUG(dbgs() << " " << USIdx);
1848 RegClassUnitSets[RCIdx].push_back(USIdx);
1851 DEBUG(dbgs() << "\n");
1852 assert(!RegClassUnitSets[RCIdx].empty() && "missing unit set for regclass");
1855 // For each register unit, ensure that we have the list of UnitSets that
1856 // contain the unit. Normally, this matches an existing list of UnitSets for a
1857 // register class. If not, we create a new entry in RegClassUnitSets as a
1858 // "fake" register class.
1859 for (unsigned UnitIdx = 0, UnitEnd = NumNativeRegUnits;
1860 UnitIdx < UnitEnd; ++UnitIdx) {
1861 std::vector<unsigned> RUSets;
1862 for (unsigned i = 0, e = RegUnitSets.size(); i != e; ++i) {
1863 RegUnitSet &RUSet = RegUnitSets[i];
1864 if (!is_contained(RUSet.Units, UnitIdx))
1866 RUSets.push_back(i);
1868 unsigned RCUnitSetsIdx = 0;
1869 for (unsigned e = RegClassUnitSets.size();
1870 RCUnitSetsIdx != e; ++RCUnitSetsIdx) {
1871 if (RegClassUnitSets[RCUnitSetsIdx] == RUSets) {
1875 RegUnits[UnitIdx].RegClassUnitSetsIdx = RCUnitSetsIdx;
1876 if (RCUnitSetsIdx == RegClassUnitSets.size()) {
1877 // Create a new list of UnitSets as a "fake" register class.
1878 RegClassUnitSets.resize(RCUnitSetsIdx + 1);
1879 RegClassUnitSets[RCUnitSetsIdx].swap(RUSets);
1884 void CodeGenRegBank::computeRegUnitLaneMasks() {
1885 for (auto &Register : Registers) {
1886 // Create an initial lane mask for all register units.
1887 const auto &RegUnits = Register.getRegUnits();
1888 CodeGenRegister::RegUnitLaneMaskList
1889 RegUnitLaneMasks(RegUnits.count(), LaneBitmask::getNone());
1890 // Iterate through SubRegisters.
1891 typedef CodeGenRegister::SubRegMap SubRegMap;
1892 const SubRegMap &SubRegs = Register.getSubRegs();
1893 for (SubRegMap::const_iterator S = SubRegs.begin(),
1894 SE = SubRegs.end(); S != SE; ++S) {
1895 CodeGenRegister *SubReg = S->second;
1896 // Ignore non-leaf subregisters, their lane masks are fully covered by
1897 // the leaf subregisters anyway.
1898 if (!SubReg->getSubRegs().empty())
1900 CodeGenSubRegIndex *SubRegIndex = S->first;
1901 const CodeGenRegister *SubRegister = S->second;
1902 LaneBitmask LaneMask = SubRegIndex->LaneMask;
1903 // Distribute LaneMask to Register Units touched.
1904 for (unsigned SUI : SubRegister->getRegUnits()) {
1907 for (unsigned RU : RegUnits) {
1909 RegUnitLaneMasks[u] |= LaneMask;
1919 Register.setRegUnitLaneMasks(RegUnitLaneMasks);
1923 void CodeGenRegBank::computeDerivedInfo() {
1924 computeComposites();
1925 computeSubRegLaneMasks();
1927 // Compute a weight for each register unit created during getSubRegs.
1928 // This may create adopted register units (with unit # >= NumNativeRegUnits).
1929 computeRegUnitWeights();
1931 // Compute a unique set of RegUnitSets. One for each RegClass and inferred
1932 // supersets for the union of overlapping sets.
1933 computeRegUnitSets();
1935 computeRegUnitLaneMasks();
1937 // Compute register class HasDisjunctSubRegs/CoveredBySubRegs flag.
1938 for (CodeGenRegisterClass &RC : RegClasses) {
1939 RC.HasDisjunctSubRegs = false;
1940 RC.CoveredBySubRegs = true;
1941 for (const CodeGenRegister *Reg : RC.getMembers()) {
1942 RC.HasDisjunctSubRegs |= Reg->HasDisjunctSubRegs;
1943 RC.CoveredBySubRegs &= Reg->CoveredBySubRegs;
1947 // Get the weight of each set.
1948 for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx)
1949 RegUnitSets[Idx].Weight = getRegUnitSetWeight(RegUnitSets[Idx].Units);
1951 // Find the order of each set.
1952 RegUnitSetOrder.reserve(RegUnitSets.size());
1953 for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx)
1954 RegUnitSetOrder.push_back(Idx);
1956 std::stable_sort(RegUnitSetOrder.begin(), RegUnitSetOrder.end(),
1957 [this](unsigned ID1, unsigned ID2) {
1958 return getRegPressureSet(ID1).Units.size() <
1959 getRegPressureSet(ID2).Units.size();
1961 for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx) {
1962 RegUnitSets[RegUnitSetOrder[Idx]].Order = Idx;
1967 // Synthesize missing register class intersections.
1969 // Make sure that sub-classes of RC exists such that getCommonSubClass(RC, X)
1970 // returns a maximal register class for all X.
1972 void CodeGenRegBank::inferCommonSubClass(CodeGenRegisterClass *RC) {
1973 assert(!RegClasses.empty());
1974 // Stash the iterator to the last element so that this loop doesn't visit
1975 // elements added by the getOrCreateSubClass call within it.
1976 for (auto I = RegClasses.begin(), E = std::prev(RegClasses.end());
1977 I != std::next(E); ++I) {
1978 CodeGenRegisterClass *RC1 = RC;
1979 CodeGenRegisterClass *RC2 = &*I;
1983 // Compute the set intersection of RC1 and RC2.
1984 const CodeGenRegister::Vec &Memb1 = RC1->getMembers();
1985 const CodeGenRegister::Vec &Memb2 = RC2->getMembers();
1986 CodeGenRegister::Vec Intersection;
1987 std::set_intersection(
1988 Memb1.begin(), Memb1.end(), Memb2.begin(), Memb2.end(),
1989 std::inserter(Intersection, Intersection.begin()), deref<llvm::less>());
1991 // Skip disjoint class pairs.
1992 if (Intersection.empty())
1995 // If RC1 and RC2 have different spill sizes or alignments, use the
1996 // larger size for sub-classing. If they are equal, prefer RC1.
1997 if (RC2->SpillSize > RC1->SpillSize ||
1998 (RC2->SpillSize == RC1->SpillSize &&
1999 RC2->SpillAlignment > RC1->SpillAlignment))
2000 std::swap(RC1, RC2);
2002 getOrCreateSubClass(RC1, &Intersection,
2003 RC1->getName() + "_and_" + RC2->getName());
2008 // Synthesize missing sub-classes for getSubClassWithSubReg().
2010 // Make sure that the set of registers in RC with a given SubIdx sub-register
2011 // form a register class. Update RC->SubClassWithSubReg.
2013 void CodeGenRegBank::inferSubClassWithSubReg(CodeGenRegisterClass *RC) {
2014 // Map SubRegIndex to set of registers in RC supporting that SubRegIndex.
2015 typedef std::map<const CodeGenSubRegIndex *, CodeGenRegister::Vec,
2016 deref<llvm::less>> SubReg2SetMap;
2018 // Compute the set of registers supporting each SubRegIndex.
2019 SubReg2SetMap SRSets;
2020 for (const auto R : RC->getMembers()) {
2021 const CodeGenRegister::SubRegMap &SRM = R->getSubRegs();
2022 for (CodeGenRegister::SubRegMap::const_iterator I = SRM.begin(),
2023 E = SRM.end(); I != E; ++I)
2024 SRSets[I->first].push_back(R);
2027 for (auto I : SRSets)
2028 sortAndUniqueRegisters(I.second);
2030 // Find matching classes for all SRSets entries. Iterate in SubRegIndex
2031 // numerical order to visit synthetic indices last.
2032 for (const auto &SubIdx : SubRegIndices) {
2033 SubReg2SetMap::const_iterator I = SRSets.find(&SubIdx);
2034 // Unsupported SubRegIndex. Skip it.
2035 if (I == SRSets.end())
2037 // In most cases, all RC registers support the SubRegIndex.
2038 if (I->second.size() == RC->getMembers().size()) {
2039 RC->setSubClassWithSubReg(&SubIdx, RC);
2042 // This is a real subset. See if we have a matching class.
2043 CodeGenRegisterClass *SubRC =
2044 getOrCreateSubClass(RC, &I->second,
2045 RC->getName() + "_with_" + I->first->getName());
2046 RC->setSubClassWithSubReg(&SubIdx, SubRC);
2051 // Synthesize missing sub-classes of RC for getMatchingSuperRegClass().
2053 // Create sub-classes of RC such that getMatchingSuperRegClass(RC, SubIdx, X)
2054 // has a maximal result for any SubIdx and any X >= FirstSubRegRC.
2057 void CodeGenRegBank::inferMatchingSuperRegClass(CodeGenRegisterClass *RC,
2058 std::list<CodeGenRegisterClass>::iterator FirstSubRegRC) {
2059 SmallVector<std::pair<const CodeGenRegister*,
2060 const CodeGenRegister*>, 16> SSPairs;
2061 BitVector TopoSigs(getNumTopoSigs());
2063 // Iterate in SubRegIndex numerical order to visit synthetic indices last.
2064 for (auto &SubIdx : SubRegIndices) {
2065 // Skip indexes that aren't fully supported by RC's registers. This was
2066 // computed by inferSubClassWithSubReg() above which should have been
2068 if (RC->getSubClassWithSubReg(&SubIdx) != RC)
2071 // Build list of (Super, Sub) pairs for this SubIdx.
2074 for (const auto Super : RC->getMembers()) {
2075 const CodeGenRegister *Sub = Super->getSubRegs().find(&SubIdx)->second;
2076 assert(Sub && "Missing sub-register");
2077 SSPairs.push_back(std::make_pair(Super, Sub));
2078 TopoSigs.set(Sub->getTopoSig());
2081 // Iterate over sub-register class candidates. Ignore classes created by
2082 // this loop. They will never be useful.
2083 // Store an iterator to the last element (not end) so that this loop doesn't
2084 // visit newly inserted elements.
2085 assert(!RegClasses.empty());
2086 for (auto I = FirstSubRegRC, E = std::prev(RegClasses.end());
2087 I != std::next(E); ++I) {
2088 CodeGenRegisterClass &SubRC = *I;
2089 // Topological shortcut: SubRC members have the wrong shape.
2090 if (!TopoSigs.anyCommon(SubRC.getTopoSigs()))
2092 // Compute the subset of RC that maps into SubRC.
2093 CodeGenRegister::Vec SubSetVec;
2094 for (unsigned i = 0, e = SSPairs.size(); i != e; ++i)
2095 if (SubRC.contains(SSPairs[i].second))
2096 SubSetVec.push_back(SSPairs[i].first);
2098 if (SubSetVec.empty())
2101 // RC injects completely into SubRC.
2102 sortAndUniqueRegisters(SubSetVec);
2103 if (SubSetVec.size() == SSPairs.size()) {
2104 SubRC.addSuperRegClass(&SubIdx, RC);
2108 // Only a subset of RC maps into SubRC. Make sure it is represented by a
2110 getOrCreateSubClass(RC, &SubSetVec, RC->getName() + "_with_" +
2111 SubIdx.getName() + "_in_" +
2118 // Infer missing register classes.
2120 void CodeGenRegBank::computeInferredRegisterClasses() {
2121 assert(!RegClasses.empty());
2122 // When this function is called, the register classes have not been sorted
2123 // and assigned EnumValues yet. That means getSubClasses(),
2124 // getSuperClasses(), and hasSubClass() functions are defunct.
2126 // Use one-before-the-end so it doesn't move forward when new elements are
2128 auto FirstNewRC = std::prev(RegClasses.end());
2130 // Visit all register classes, including the ones being added by the loop.
2131 // Watch out for iterator invalidation here.
2132 for (auto I = RegClasses.begin(), E = RegClasses.end(); I != E; ++I) {
2133 CodeGenRegisterClass *RC = &*I;
2135 // Synthesize answers for getSubClassWithSubReg().
2136 inferSubClassWithSubReg(RC);
2138 // Synthesize answers for getCommonSubClass().
2139 inferCommonSubClass(RC);
2141 // Synthesize answers for getMatchingSuperRegClass().
2142 inferMatchingSuperRegClass(RC);
2144 // New register classes are created while this loop is running, and we need
2145 // to visit all of them. I particular, inferMatchingSuperRegClass needs
2146 // to match old super-register classes with sub-register classes created
2147 // after inferMatchingSuperRegClass was called. At this point,
2148 // inferMatchingSuperRegClass has checked SuperRC = [0..rci] with SubRC =
2149 // [0..FirstNewRC). We need to cover SubRC = [FirstNewRC..rci].
2150 if (I == FirstNewRC) {
2151 auto NextNewRC = std::prev(RegClasses.end());
2152 for (auto I2 = RegClasses.begin(), E2 = std::next(FirstNewRC); I2 != E2;
2154 inferMatchingSuperRegClass(&*I2, E2);
2155 FirstNewRC = NextNewRC;
2160 /// getRegisterClassForRegister - Find the register class that contains the
2161 /// specified physical register. If the register is not in a register class,
2162 /// return null. If the register is in multiple classes, and the classes have a
2163 /// superset-subset relationship and the same set of types, return the
2164 /// superclass. Otherwise return null.
2165 const CodeGenRegisterClass*
2166 CodeGenRegBank::getRegClassForRegister(Record *R) {
2167 const CodeGenRegister *Reg = getReg(R);
2168 const CodeGenRegisterClass *FoundRC = nullptr;
2169 for (const auto &RC : getRegClasses()) {
2170 if (!RC.contains(Reg))
2173 // If this is the first class that contains the register,
2174 // make a note of it and go on to the next class.
2180 // If a register's classes have different types, return null.
2181 if (RC.getValueTypes() != FoundRC->getValueTypes())
2184 // Check to see if the previously found class that contains
2185 // the register is a subclass of the current class. If so,
2186 // prefer the superclass.
2187 if (RC.hasSubClass(FoundRC)) {
2192 // Check to see if the previously found class that contains
2193 // the register is a superclass of the current class. If so,
2194 // prefer the superclass.
2195 if (FoundRC->hasSubClass(&RC))
2198 // Multiple classes, and neither is a superclass of the other.
2205 BitVector CodeGenRegBank::computeCoveredRegisters(ArrayRef<Record*> Regs) {
2206 SetVector<const CodeGenRegister*> Set;
2208 // First add Regs with all sub-registers.
2209 for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
2210 CodeGenRegister *Reg = getReg(Regs[i]);
2211 if (Set.insert(Reg))
2212 // Reg is new, add all sub-registers.
2213 // The pre-ordering is not important here.
2214 Reg->addSubRegsPreOrder(Set, *this);
2217 // Second, find all super-registers that are completely covered by the set.
2218 for (unsigned i = 0; i != Set.size(); ++i) {
2219 const CodeGenRegister::SuperRegList &SR = Set[i]->getSuperRegs();
2220 for (unsigned j = 0, e = SR.size(); j != e; ++j) {
2221 const CodeGenRegister *Super = SR[j];
2222 if (!Super->CoveredBySubRegs || Set.count(Super))
2224 // This new super-register is covered by its sub-registers.
2225 bool AllSubsInSet = true;
2226 const CodeGenRegister::SubRegMap &SRM = Super->getSubRegs();
2227 for (CodeGenRegister::SubRegMap::const_iterator I = SRM.begin(),
2228 E = SRM.end(); I != E; ++I)
2229 if (!Set.count(I->second)) {
2230 AllSubsInSet = false;
2233 // All sub-registers in Set, add Super as well.
2234 // We will visit Super later to recheck its super-registers.
2240 // Convert to BitVector.
2241 BitVector BV(Registers.size() + 1);
2242 for (unsigned i = 0, e = Set.size(); i != e; ++i)
2243 BV.set(Set[i]->EnumValue);
2247 void CodeGenRegBank::printRegUnitName(unsigned Unit) const {
2248 if (Unit < NumNativeRegUnits)
2249 dbgs() << ' ' << RegUnits[Unit].Roots[0]->getName();
2251 dbgs() << " #" << Unit;