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/TableGen/Error.h"
18 #include "llvm/ADT/IntEqClasses.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/Twine.h"
26 //===----------------------------------------------------------------------===//
28 //===----------------------------------------------------------------------===//
30 CodeGenSubRegIndex::CodeGenSubRegIndex(Record *R, unsigned Enum)
35 std::string CodeGenSubRegIndex::getNamespace() const {
36 if (TheDef->getValue("Namespace"))
37 return TheDef->getValueAsString("Namespace");
42 const std::string &CodeGenSubRegIndex::getName() const {
43 return TheDef->getName();
46 std::string CodeGenSubRegIndex::getQualifiedName() const {
47 std::string N = getNamespace();
54 void CodeGenSubRegIndex::updateComponents(CodeGenRegBank &RegBank) {
55 std::vector<Record*> Comps = TheDef->getValueAsListOfDefs("ComposedOf");
58 if (Comps.size() != 2)
59 throw TGError(TheDef->getLoc(), "ComposedOf must have exactly two entries");
60 CodeGenSubRegIndex *A = RegBank.getSubRegIdx(Comps[0]);
61 CodeGenSubRegIndex *B = RegBank.getSubRegIdx(Comps[1]);
62 CodeGenSubRegIndex *X = A->addComposite(B, this);
64 throw TGError(TheDef->getLoc(), "Ambiguous ComposedOf entries");
67 void CodeGenSubRegIndex::cleanComposites() {
68 // Clean out redundant mappings of the form this+X -> X.
69 for (CompMap::iterator i = Composed.begin(), e = Composed.end(); i != e;) {
70 CompMap::iterator j = i;
72 if (j->first == j->second)
77 //===----------------------------------------------------------------------===//
79 //===----------------------------------------------------------------------===//
81 CodeGenRegister::CodeGenRegister(Record *R, unsigned Enum)
84 CostPerUse(R->getValueAsInt("CostPerUse")),
85 CoveredBySubRegs(R->getValueAsBit("CoveredBySubRegs")),
86 SubRegsComplete(false)
89 const std::string &CodeGenRegister::getName() const {
90 return TheDef->getName();
94 // Iterate over all register units in a set of registers.
95 class RegUnitIterator {
96 CodeGenRegister::Set::const_iterator RegI, RegE;
97 CodeGenRegister::RegUnitList::const_iterator UnitI, UnitE;
100 RegUnitIterator(const CodeGenRegister::Set &Regs):
101 RegI(Regs.begin()), RegE(Regs.end()), UnitI(), UnitE() {
104 UnitI = (*RegI)->getRegUnits().begin();
105 UnitE = (*RegI)->getRegUnits().end();
110 bool isValid() const { return UnitI != UnitE; }
112 unsigned operator* () const { assert(isValid()); return *UnitI; };
114 const CodeGenRegister *getReg() const { assert(isValid()); return *RegI; }
116 /// Preincrement. Move to the next unit.
118 assert(isValid() && "Cannot advance beyond the last operand");
125 while (UnitI == UnitE) {
128 UnitI = (*RegI)->getRegUnits().begin();
129 UnitE = (*RegI)->getRegUnits().end();
135 // Merge two RegUnitLists maintaining the order and removing duplicates.
136 // Overwrites MergedRU in the process.
137 static void mergeRegUnits(CodeGenRegister::RegUnitList &MergedRU,
138 const CodeGenRegister::RegUnitList &RRU) {
139 CodeGenRegister::RegUnitList LRU = MergedRU;
141 std::set_union(LRU.begin(), LRU.end(), RRU.begin(), RRU.end(),
142 std::back_inserter(MergedRU));
145 // Return true of this unit appears in RegUnits.
146 static bool hasRegUnit(CodeGenRegister::RegUnitList &RegUnits, unsigned Unit) {
147 return std::count(RegUnits.begin(), RegUnits.end(), Unit);
150 // Inherit register units from subregisters.
151 // Return true if the RegUnits changed.
152 bool CodeGenRegister::inheritRegUnits(CodeGenRegBank &RegBank) {
153 unsigned OldNumUnits = RegUnits.size();
154 for (SubRegMap::const_iterator I = SubRegs.begin(), E = SubRegs.end();
156 // Strangely a register may have itself as a subreg (self-cycle) e.g. XMM.
157 // Only create a unit if no other subregs have units.
158 CodeGenRegister *SR = I->second;
160 // RegUnits are only empty during computeSubRegs, prior to computing
162 if (RegUnits.empty())
163 RegUnits.push_back(RegBank.newRegUnit(0));
166 // Merge the subregister's units into this register's RegUnits.
167 mergeRegUnits(RegUnits, SR->RegUnits);
169 return OldNumUnits != RegUnits.size();
172 const CodeGenRegister::SubRegMap &
173 CodeGenRegister::computeSubRegs(CodeGenRegBank &RegBank) {
174 // Only compute this map once.
177 SubRegsComplete = true;
179 std::vector<Record*> SubList = TheDef->getValueAsListOfDefs("SubRegs");
180 std::vector<Record*> IdxList = TheDef->getValueAsListOfDefs("SubRegIndices");
181 if (SubList.size() != IdxList.size())
182 throw TGError(TheDef->getLoc(), "Register " + getName() +
183 " SubRegIndices doesn't match SubRegs");
185 // First insert the direct subregs and make sure they are fully indexed.
186 SmallVector<CodeGenSubRegIndex*, 8> Indices;
187 for (unsigned i = 0, e = SubList.size(); i != e; ++i) {
188 CodeGenRegister *SR = RegBank.getReg(SubList[i]);
189 CodeGenSubRegIndex *Idx = RegBank.getSubRegIdx(IdxList[i]);
190 Indices.push_back(Idx);
191 if (!SubRegs.insert(std::make_pair(Idx, SR)).second)
192 throw TGError(TheDef->getLoc(), "SubRegIndex " + Idx->getName() +
193 " appears twice in Register " + getName());
194 // Map explicit sub-registers first, so the names take precedence.
195 // The inherited sub-registers are mapped below.
196 SubReg2Idx.insert(std::make_pair(SR, Idx));
199 // Keep track of inherited subregs and how they can be reached.
200 SmallPtrSet<CodeGenRegister*, 8> Orphans;
202 // Clone inherited subregs and place duplicate entries in Orphans.
203 // Here the order is important - earlier subregs take precedence.
204 for (unsigned i = 0, e = SubList.size(); i != e; ++i) {
205 CodeGenRegister *SR = RegBank.getReg(SubList[i]);
206 const SubRegMap &Map = SR->computeSubRegs(RegBank);
208 // Add this as a super-register of SR now all sub-registers are in the list.
209 // This creates a topological ordering, the exact order depends on the
210 // order computeSubRegs is called on all registers.
211 SR->SuperRegs.push_back(this);
213 for (SubRegMap::const_iterator SI = Map.begin(), SE = Map.end(); SI != SE;
215 if (!SubRegs.insert(*SI).second)
216 Orphans.insert(SI->second);
218 // Noop sub-register indexes are possible, so avoid duplicates.
219 if (SI->second != SR)
220 SI->second->SuperRegs.push_back(this);
224 // Expand any composed subreg indices.
225 // If dsub_2 has ComposedOf = [qsub_1, dsub_0], and this register has a
226 // qsub_1 subreg, add a dsub_2 subreg. Keep growing Indices and process
227 // expanded subreg indices recursively.
228 for (unsigned i = 0; i != Indices.size(); ++i) {
229 CodeGenSubRegIndex *Idx = Indices[i];
230 const CodeGenSubRegIndex::CompMap &Comps = Idx->getComposites();
231 CodeGenRegister *SR = SubRegs[Idx];
232 const SubRegMap &Map = SR->computeSubRegs(RegBank);
234 // Look at the possible compositions of Idx.
235 // They may not all be supported by SR.
236 for (CodeGenSubRegIndex::CompMap::const_iterator I = Comps.begin(),
237 E = Comps.end(); I != E; ++I) {
238 SubRegMap::const_iterator SRI = Map.find(I->first);
239 if (SRI == Map.end())
240 continue; // Idx + I->first doesn't exist in SR.
241 // Add I->second as a name for the subreg SRI->second, assuming it is
242 // orphaned, and the name isn't already used for something else.
243 if (SubRegs.count(I->second) || !Orphans.erase(SRI->second))
245 // We found a new name for the orphaned sub-register.
246 SubRegs.insert(std::make_pair(I->second, SRI->second));
247 Indices.push_back(I->second);
251 // Process the composites.
252 ListInit *Comps = TheDef->getValueAsListInit("CompositeIndices");
253 for (unsigned i = 0, e = Comps->size(); i != e; ++i) {
254 DagInit *Pat = dynamic_cast<DagInit*>(Comps->getElement(i));
256 throw TGError(TheDef->getLoc(), "Invalid dag '" +
257 Comps->getElement(i)->getAsString() +
258 "' in CompositeIndices");
259 DefInit *BaseIdxInit = dynamic_cast<DefInit*>(Pat->getOperator());
260 if (!BaseIdxInit || !BaseIdxInit->getDef()->isSubClassOf("SubRegIndex"))
261 throw TGError(TheDef->getLoc(), "Invalid SubClassIndex in " +
263 CodeGenSubRegIndex *BaseIdx = RegBank.getSubRegIdx(BaseIdxInit->getDef());
265 // Resolve list of subreg indices into R2.
266 CodeGenRegister *R2 = this;
267 for (DagInit::const_arg_iterator di = Pat->arg_begin(),
268 de = Pat->arg_end(); di != de; ++di) {
269 DefInit *IdxInit = dynamic_cast<DefInit*>(*di);
270 if (!IdxInit || !IdxInit->getDef()->isSubClassOf("SubRegIndex"))
271 throw TGError(TheDef->getLoc(), "Invalid SubClassIndex in " +
273 CodeGenSubRegIndex *Idx = RegBank.getSubRegIdx(IdxInit->getDef());
274 const SubRegMap &R2Subs = R2->computeSubRegs(RegBank);
275 SubRegMap::const_iterator ni = R2Subs.find(Idx);
276 if (ni == R2Subs.end())
277 throw TGError(TheDef->getLoc(), "Composite " + Pat->getAsString() +
278 " refers to bad index in " + R2->getName());
282 // Insert composite index. Allow overriding inherited indices etc.
283 SubRegs[BaseIdx] = R2;
285 // R2 is no longer an orphan.
289 // Now Orphans contains the inherited subregisters without a direct index.
290 // Create inferred indexes for all missing entries.
291 // Work backwards in the Indices vector in order to compose subregs bottom-up.
292 // Consider this subreg sequence:
294 // qsub_1 -> dsub_0 -> ssub_0
296 // The qsub_1 -> dsub_0 composition becomes dsub_2, so the ssub_0 register
297 // can be reached in two different ways:
302 // We pick the latter composition because another register may have [dsub_0,
303 // dsub_1, dsub_2] subregs without neccessarily having a qsub_1 subreg. The
304 // dsub_2 -> ssub_0 composition can be shared.
305 while (!Indices.empty() && !Orphans.empty()) {
306 CodeGenSubRegIndex *Idx = Indices.pop_back_val();
307 CodeGenRegister *SR = SubRegs[Idx];
308 const SubRegMap &Map = SR->computeSubRegs(RegBank);
309 for (SubRegMap::const_iterator SI = Map.begin(), SE = Map.end(); SI != SE;
311 if (Orphans.erase(SI->second))
312 SubRegs[RegBank.getCompositeSubRegIndex(Idx, SI->first)] = SI->second;
315 // Compute the inverse SubReg -> Idx map.
316 for (SubRegMap::const_iterator SI = SubRegs.begin(), SE = SubRegs.end();
318 // Ignore idempotent sub-register indices.
319 if (SI->second == this)
321 // Is is possible to have multiple names for the same sub-register.
322 // For example, XMM0 appears as sub_xmm, sub_sd, and sub_ss in YMM0.
323 // Eventually, this degeneration should go away, but for now we simply give
324 // precedence to the explicit sub-register index over the inherited ones.
325 SubReg2Idx.insert(std::make_pair(SI->second, SI->first));
328 // Initialize RegUnitList. A register with no subregisters creates its own
329 // unit. Otherwise, it inherits all its subregister's units. Because
330 // getSubRegs is called recursively, this processes the register hierarchy in
333 // TODO: We currently assume all register units correspond to a named "leaf"
334 // register. We should also unify register units for ad-hoc register
335 // aliases. This can be done by iteratively merging units for aliasing
336 // registers using a worklist.
337 assert(RegUnits.empty() && "Should only initialize RegUnits once");
339 RegUnits.push_back(RegBank.newRegUnit(0));
341 inheritRegUnits(RegBank);
346 CodeGenRegister::addSubRegsPreOrder(SetVector<const CodeGenRegister*> &OSet,
347 CodeGenRegBank &RegBank) const {
348 assert(SubRegsComplete && "Must precompute sub-registers");
349 std::vector<Record*> Indices = TheDef->getValueAsListOfDefs("SubRegIndices");
350 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
351 CodeGenSubRegIndex *Idx = RegBank.getSubRegIdx(Indices[i]);
352 CodeGenRegister *SR = SubRegs.find(Idx)->second;
354 SR->addSubRegsPreOrder(OSet, RegBank);
358 // Get the sum of this register's unit weights.
359 unsigned CodeGenRegister::getWeight(const CodeGenRegBank &RegBank) const {
361 for (RegUnitList::const_iterator I = RegUnits.begin(), E = RegUnits.end();
363 Weight += RegBank.getRegUnitWeight(*I);
368 //===----------------------------------------------------------------------===//
370 //===----------------------------------------------------------------------===//
372 // A RegisterTuples def is used to generate pseudo-registers from lists of
373 // sub-registers. We provide a SetTheory expander class that returns the new
376 struct TupleExpander : SetTheory::Expander {
377 void expand(SetTheory &ST, Record *Def, SetTheory::RecSet &Elts) {
378 std::vector<Record*> Indices = Def->getValueAsListOfDefs("SubRegIndices");
379 unsigned Dim = Indices.size();
380 ListInit *SubRegs = Def->getValueAsListInit("SubRegs");
381 if (Dim != SubRegs->getSize())
382 throw TGError(Def->getLoc(), "SubRegIndices and SubRegs size mismatch");
384 throw TGError(Def->getLoc(), "Tuples must have at least 2 sub-registers");
386 // Evaluate the sub-register lists to be zipped.
387 unsigned Length = ~0u;
388 SmallVector<SetTheory::RecSet, 4> Lists(Dim);
389 for (unsigned i = 0; i != Dim; ++i) {
390 ST.evaluate(SubRegs->getElement(i), Lists[i]);
391 Length = std::min(Length, unsigned(Lists[i].size()));
397 // Precompute some types.
398 Record *RegisterCl = Def->getRecords().getClass("Register");
399 RecTy *RegisterRecTy = RecordRecTy::get(RegisterCl);
400 StringInit *BlankName = StringInit::get("");
403 for (unsigned n = 0; n != Length; ++n) {
405 Record *Proto = Lists[0][n];
406 std::vector<Init*> Tuple;
407 unsigned CostPerUse = 0;
408 for (unsigned i = 0; i != Dim; ++i) {
409 Record *Reg = Lists[i][n];
411 Name += Reg->getName();
412 Tuple.push_back(DefInit::get(Reg));
413 CostPerUse = std::max(CostPerUse,
414 unsigned(Reg->getValueAsInt("CostPerUse")));
417 // Create a new Record representing the synthesized register. This record
418 // is only for consumption by CodeGenRegister, it is not added to the
420 Record *NewReg = new Record(Name, Def->getLoc(), Def->getRecords());
423 // Copy Proto super-classes.
424 for (unsigned i = 0, e = Proto->getSuperClasses().size(); i != e; ++i)
425 NewReg->addSuperClass(Proto->getSuperClasses()[i]);
427 // Copy Proto fields.
428 for (unsigned i = 0, e = Proto->getValues().size(); i != e; ++i) {
429 RecordVal RV = Proto->getValues()[i];
431 // Skip existing fields, like NAME.
432 if (NewReg->getValue(RV.getNameInit()))
435 StringRef Field = RV.getName();
437 // Replace the sub-register list with Tuple.
438 if (Field == "SubRegs")
439 RV.setValue(ListInit::get(Tuple, RegisterRecTy));
441 // Provide a blank AsmName. MC hacks are required anyway.
442 if (Field == "AsmName")
443 RV.setValue(BlankName);
445 // CostPerUse is aggregated from all Tuple members.
446 if (Field == "CostPerUse")
447 RV.setValue(IntInit::get(CostPerUse));
449 // Composite registers are always covered by sub-registers.
450 if (Field == "CoveredBySubRegs")
451 RV.setValue(BitInit::get(true));
453 // Copy fields from the RegisterTuples def.
454 if (Field == "SubRegIndices" ||
455 Field == "CompositeIndices") {
456 NewReg->addValue(*Def->getValue(Field));
460 // Some fields get their default uninitialized value.
461 if (Field == "DwarfNumbers" ||
462 Field == "DwarfAlias" ||
463 Field == "Aliases") {
464 if (const RecordVal *DefRV = RegisterCl->getValue(Field))
465 NewReg->addValue(*DefRV);
469 // Everything else is copied from Proto.
470 NewReg->addValue(RV);
477 //===----------------------------------------------------------------------===//
478 // CodeGenRegisterClass
479 //===----------------------------------------------------------------------===//
481 CodeGenRegisterClass::CodeGenRegisterClass(CodeGenRegBank &RegBank, Record *R)
482 : TheDef(R), Name(R->getName()), EnumValue(-1) {
483 // Rename anonymous register classes.
484 if (R->getName().size() > 9 && R->getName()[9] == '.') {
485 static unsigned AnonCounter = 0;
486 R->setName("AnonRegClass_"+utostr(AnonCounter++));
489 std::vector<Record*> TypeList = R->getValueAsListOfDefs("RegTypes");
490 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
491 Record *Type = TypeList[i];
492 if (!Type->isSubClassOf("ValueType"))
493 throw "RegTypes list member '" + Type->getName() +
494 "' does not derive from the ValueType class!";
495 VTs.push_back(getValueType(Type));
497 assert(!VTs.empty() && "RegisterClass must contain at least one ValueType!");
499 // Allocation order 0 is the full set. AltOrders provides others.
500 const SetTheory::RecVec *Elements = RegBank.getSets().expand(R);
501 ListInit *AltOrders = R->getValueAsListInit("AltOrders");
502 Orders.resize(1 + AltOrders->size());
504 // Default allocation order always contains all registers.
505 for (unsigned i = 0, e = Elements->size(); i != e; ++i) {
506 Orders[0].push_back((*Elements)[i]);
507 Members.insert(RegBank.getReg((*Elements)[i]));
510 // Alternative allocation orders may be subsets.
511 SetTheory::RecSet Order;
512 for (unsigned i = 0, e = AltOrders->size(); i != e; ++i) {
513 RegBank.getSets().evaluate(AltOrders->getElement(i), Order);
514 Orders[1 + i].append(Order.begin(), Order.end());
515 // Verify that all altorder members are regclass members.
516 while (!Order.empty()) {
517 CodeGenRegister *Reg = RegBank.getReg(Order.back());
520 throw TGError(R->getLoc(), " AltOrder register " + Reg->getName() +
521 " is not a class member");
525 // Allow targets to override the size in bits of the RegisterClass.
526 unsigned Size = R->getValueAsInt("Size");
528 Namespace = R->getValueAsString("Namespace");
529 SpillSize = Size ? Size : EVT(VTs[0]).getSizeInBits();
530 SpillAlignment = R->getValueAsInt("Alignment");
531 CopyCost = R->getValueAsInt("CopyCost");
532 Allocatable = R->getValueAsBit("isAllocatable");
533 AltOrderSelect = R->getValueAsString("AltOrderSelect");
536 // Create an inferred register class that was missing from the .td files.
537 // Most properties will be inherited from the closest super-class after the
538 // class structure has been computed.
539 CodeGenRegisterClass::CodeGenRegisterClass(StringRef Name, Key Props)
540 : Members(*Props.Members),
544 SpillSize(Props.SpillSize),
545 SpillAlignment(Props.SpillAlignment),
550 // Compute inherited propertied for a synthesized register class.
551 void CodeGenRegisterClass::inheritProperties(CodeGenRegBank &RegBank) {
552 assert(!getDef() && "Only synthesized classes can inherit properties");
553 assert(!SuperClasses.empty() && "Synthesized class without super class");
555 // The last super-class is the smallest one.
556 CodeGenRegisterClass &Super = *SuperClasses.back();
558 // Most properties are copied directly.
559 // Exceptions are members, size, and alignment
560 Namespace = Super.Namespace;
562 CopyCost = Super.CopyCost;
563 Allocatable = Super.Allocatable;
564 AltOrderSelect = Super.AltOrderSelect;
566 // Copy all allocation orders, filter out foreign registers from the larger
568 Orders.resize(Super.Orders.size());
569 for (unsigned i = 0, ie = Super.Orders.size(); i != ie; ++i)
570 for (unsigned j = 0, je = Super.Orders[i].size(); j != je; ++j)
571 if (contains(RegBank.getReg(Super.Orders[i][j])))
572 Orders[i].push_back(Super.Orders[i][j]);
575 bool CodeGenRegisterClass::contains(const CodeGenRegister *Reg) const {
576 return Members.count(Reg);
580 raw_ostream &operator<<(raw_ostream &OS, const CodeGenRegisterClass::Key &K) {
581 OS << "{ S=" << K.SpillSize << ", A=" << K.SpillAlignment;
582 for (CodeGenRegister::Set::const_iterator I = K.Members->begin(),
583 E = K.Members->end(); I != E; ++I)
584 OS << ", " << (*I)->getName();
589 // This is a simple lexicographical order that can be used to search for sets.
590 // It is not the same as the topological order provided by TopoOrderRC.
591 bool CodeGenRegisterClass::Key::
592 operator<(const CodeGenRegisterClass::Key &B) const {
593 assert(Members && B.Members);
594 if (*Members != *B.Members)
595 return *Members < *B.Members;
596 if (SpillSize != B.SpillSize)
597 return SpillSize < B.SpillSize;
598 return SpillAlignment < B.SpillAlignment;
601 // Returns true if RC is a strict subclass.
602 // RC is a sub-class of this class if it is a valid replacement for any
603 // instruction operand where a register of this classis required. It must
604 // satisfy these conditions:
606 // 1. All RC registers are also in this.
607 // 2. The RC spill size must not be smaller than our spill size.
608 // 3. RC spill alignment must be compatible with ours.
610 static bool testSubClass(const CodeGenRegisterClass *A,
611 const CodeGenRegisterClass *B) {
612 return A->SpillAlignment && B->SpillAlignment % A->SpillAlignment == 0 &&
613 A->SpillSize <= B->SpillSize &&
614 std::includes(A->getMembers().begin(), A->getMembers().end(),
615 B->getMembers().begin(), B->getMembers().end(),
616 CodeGenRegister::Less());
619 /// Sorting predicate for register classes. This provides a topological
620 /// ordering that arranges all register classes before their sub-classes.
622 /// Register classes with the same registers, spill size, and alignment form a
623 /// clique. They will be ordered alphabetically.
625 static int TopoOrderRC(const void *PA, const void *PB) {
626 const CodeGenRegisterClass *A = *(const CodeGenRegisterClass* const*)PA;
627 const CodeGenRegisterClass *B = *(const CodeGenRegisterClass* const*)PB;
631 // Order by ascending spill size.
632 if (A->SpillSize < B->SpillSize)
634 if (A->SpillSize > B->SpillSize)
637 // Order by ascending spill alignment.
638 if (A->SpillAlignment < B->SpillAlignment)
640 if (A->SpillAlignment > B->SpillAlignment)
643 // Order by descending set size. Note that the classes' allocation order may
644 // not have been computed yet. The Members set is always vaild.
645 if (A->getMembers().size() > B->getMembers().size())
647 if (A->getMembers().size() < B->getMembers().size())
650 // Finally order by name as a tie breaker.
651 return StringRef(A->getName()).compare(B->getName());
654 std::string CodeGenRegisterClass::getQualifiedName() const {
655 if (Namespace.empty())
658 return Namespace + "::" + getName();
661 // Compute sub-classes of all register classes.
662 // Assume the classes are ordered topologically.
663 void CodeGenRegisterClass::computeSubClasses(CodeGenRegBank &RegBank) {
664 ArrayRef<CodeGenRegisterClass*> RegClasses = RegBank.getRegClasses();
666 // Visit backwards so sub-classes are seen first.
667 for (unsigned rci = RegClasses.size(); rci; --rci) {
668 CodeGenRegisterClass &RC = *RegClasses[rci - 1];
669 RC.SubClasses.resize(RegClasses.size());
670 RC.SubClasses.set(RC.EnumValue);
672 // Normally, all subclasses have IDs >= rci, unless RC is part of a clique.
673 for (unsigned s = rci; s != RegClasses.size(); ++s) {
674 if (RC.SubClasses.test(s))
676 CodeGenRegisterClass *SubRC = RegClasses[s];
677 if (!testSubClass(&RC, SubRC))
679 // SubRC is a sub-class. Grap all its sub-classes so we won't have to
681 RC.SubClasses |= SubRC->SubClasses;
684 // Sweep up missed clique members. They will be immediately preceeding RC.
685 for (unsigned s = rci - 1; s && testSubClass(&RC, RegClasses[s - 1]); --s)
686 RC.SubClasses.set(s - 1);
689 // Compute the SuperClasses lists from the SubClasses vectors.
690 for (unsigned rci = 0; rci != RegClasses.size(); ++rci) {
691 const BitVector &SC = RegClasses[rci]->getSubClasses();
692 for (int s = SC.find_first(); s >= 0; s = SC.find_next(s)) {
693 if (unsigned(s) == rci)
695 RegClasses[s]->SuperClasses.push_back(RegClasses[rci]);
699 // With the class hierarchy in place, let synthesized register classes inherit
700 // properties from their closest super-class. The iteration order here can
701 // propagate properties down multiple levels.
702 for (unsigned rci = 0; rci != RegClasses.size(); ++rci)
703 if (!RegClasses[rci]->getDef())
704 RegClasses[rci]->inheritProperties(RegBank);
708 CodeGenRegisterClass::getSuperRegClasses(CodeGenSubRegIndex *SubIdx,
709 BitVector &Out) const {
710 DenseMap<CodeGenSubRegIndex*,
711 SmallPtrSet<CodeGenRegisterClass*, 8> >::const_iterator
712 FindI = SuperRegClasses.find(SubIdx);
713 if (FindI == SuperRegClasses.end())
715 for (SmallPtrSet<CodeGenRegisterClass*, 8>::const_iterator I =
716 FindI->second.begin(), E = FindI->second.end(); I != E; ++I)
717 Out.set((*I)->EnumValue);
720 // Populate a unique sorted list of units from a register set.
721 void CodeGenRegisterClass::buildRegUnitSet(
722 std::vector<unsigned> &RegUnits) const {
723 std::vector<unsigned> TmpUnits;
724 for (RegUnitIterator UnitI(Members); UnitI.isValid(); ++UnitI)
725 TmpUnits.push_back(*UnitI);
726 std::sort(TmpUnits.begin(), TmpUnits.end());
727 std::unique_copy(TmpUnits.begin(), TmpUnits.end(),
728 std::back_inserter(RegUnits));
731 //===----------------------------------------------------------------------===//
733 //===----------------------------------------------------------------------===//
735 CodeGenRegBank::CodeGenRegBank(RecordKeeper &Records) : Records(Records) {
736 // Configure register Sets to understand register classes and tuples.
737 Sets.addFieldExpander("RegisterClass", "MemberList");
738 Sets.addFieldExpander("CalleeSavedRegs", "SaveList");
739 Sets.addExpander("RegisterTuples", new TupleExpander());
741 // Read in the user-defined (named) sub-register indices.
742 // More indices will be synthesized later.
743 std::vector<Record*> SRIs = Records.getAllDerivedDefinitions("SubRegIndex");
744 std::sort(SRIs.begin(), SRIs.end(), LessRecord());
745 NumNamedIndices = SRIs.size();
746 for (unsigned i = 0, e = SRIs.size(); i != e; ++i)
747 getSubRegIdx(SRIs[i]);
748 // Build composite maps from ComposedOf fields.
749 for (unsigned i = 0, e = SubRegIndices.size(); i != e; ++i)
750 SubRegIndices[i]->updateComponents(*this);
752 // Read in the register definitions.
753 std::vector<Record*> Regs = Records.getAllDerivedDefinitions("Register");
754 std::sort(Regs.begin(), Regs.end(), LessRecord());
755 Registers.reserve(Regs.size());
756 // Assign the enumeration values.
757 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
760 // Expand tuples and number the new registers.
761 std::vector<Record*> Tups =
762 Records.getAllDerivedDefinitions("RegisterTuples");
763 for (unsigned i = 0, e = Tups.size(); i != e; ++i) {
764 const std::vector<Record*> *TupRegs = Sets.expand(Tups[i]);
765 for (unsigned j = 0, je = TupRegs->size(); j != je; ++j)
766 getReg((*TupRegs)[j]);
769 // Precompute all sub-register maps now all the registers are known.
770 // This will create Composite entries for all inferred sub-register indices.
772 for (unsigned i = 0, e = Registers.size(); i != e; ++i)
773 Registers[i]->computeSubRegs(*this);
775 // Native register units are associated with a leaf register. They've all been
777 NumNativeRegUnits = NumRegUnits;
779 // Read in register class definitions.
780 std::vector<Record*> RCs = Records.getAllDerivedDefinitions("RegisterClass");
782 throw std::string("No 'RegisterClass' subclasses defined!");
784 // Allocate user-defined register classes.
785 RegClasses.reserve(RCs.size());
786 for (unsigned i = 0, e = RCs.size(); i != e; ++i)
787 addToMaps(new CodeGenRegisterClass(*this, RCs[i]));
789 // Infer missing classes to create a full algebra.
790 computeInferredRegisterClasses();
792 // Order register classes topologically and assign enum values.
793 array_pod_sort(RegClasses.begin(), RegClasses.end(), TopoOrderRC);
794 for (unsigned i = 0, e = RegClasses.size(); i != e; ++i)
795 RegClasses[i]->EnumValue = i;
796 CodeGenRegisterClass::computeSubClasses(*this);
799 CodeGenSubRegIndex *CodeGenRegBank::getSubRegIdx(Record *Def) {
800 CodeGenSubRegIndex *&Idx = Def2SubRegIdx[Def];
803 Idx = new CodeGenSubRegIndex(Def, SubRegIndices.size() + 1);
804 SubRegIndices.push_back(Idx);
808 CodeGenRegister *CodeGenRegBank::getReg(Record *Def) {
809 CodeGenRegister *&Reg = Def2Reg[Def];
812 Reg = new CodeGenRegister(Def, Registers.size() + 1);
813 Registers.push_back(Reg);
817 void CodeGenRegBank::addToMaps(CodeGenRegisterClass *RC) {
818 RegClasses.push_back(RC);
820 if (Record *Def = RC->getDef())
821 Def2RC.insert(std::make_pair(Def, RC));
823 // Duplicate classes are rejected by insert().
824 // That's OK, we only care about the properties handled by CGRC::Key.
825 CodeGenRegisterClass::Key K(*RC);
826 Key2RC.insert(std::make_pair(K, RC));
829 // Create a synthetic sub-class if it is missing.
830 CodeGenRegisterClass*
831 CodeGenRegBank::getOrCreateSubClass(const CodeGenRegisterClass *RC,
832 const CodeGenRegister::Set *Members,
834 // Synthetic sub-class has the same size and alignment as RC.
835 CodeGenRegisterClass::Key K(Members, RC->SpillSize, RC->SpillAlignment);
836 RCKeyMap::const_iterator FoundI = Key2RC.find(K);
837 if (FoundI != Key2RC.end())
838 return FoundI->second;
840 // Sub-class doesn't exist, create a new one.
841 CodeGenRegisterClass *NewRC = new CodeGenRegisterClass(Name, K);
846 CodeGenRegisterClass *CodeGenRegBank::getRegClass(Record *Def) {
847 if (CodeGenRegisterClass *RC = Def2RC[Def])
850 throw TGError(Def->getLoc(), "Not a known RegisterClass!");
854 CodeGenRegBank::getCompositeSubRegIndex(CodeGenSubRegIndex *A,
855 CodeGenSubRegIndex *B) {
856 // Look for an existing entry.
857 CodeGenSubRegIndex *Comp = A->compose(B);
861 // None exists, synthesize one.
862 std::string Name = A->getName() + "_then_" + B->getName();
863 Comp = getSubRegIdx(new Record(Name, SMLoc(), Records));
864 A->addComposite(B, Comp);
868 void CodeGenRegBank::computeComposites() {
869 for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
870 CodeGenRegister *Reg1 = Registers[i];
871 const CodeGenRegister::SubRegMap &SRM1 = Reg1->getSubRegs();
872 for (CodeGenRegister::SubRegMap::const_iterator i1 = SRM1.begin(),
873 e1 = SRM1.end(); i1 != e1; ++i1) {
874 CodeGenSubRegIndex *Idx1 = i1->first;
875 CodeGenRegister *Reg2 = i1->second;
876 // Ignore identity compositions.
879 const CodeGenRegister::SubRegMap &SRM2 = Reg2->getSubRegs();
880 // Try composing Idx1 with another SubRegIndex.
881 for (CodeGenRegister::SubRegMap::const_iterator i2 = SRM2.begin(),
882 e2 = SRM2.end(); i2 != e2; ++i2) {
883 CodeGenSubRegIndex *Idx2 = i2->first;
884 CodeGenRegister *Reg3 = i2->second;
885 // Ignore identity compositions.
888 // OK Reg1:IdxPair == Reg3. Find the index with Reg:Idx == Reg3.
889 for (CodeGenRegister::SubRegMap::const_iterator i1d = SRM1.begin(),
890 e1d = SRM1.end(); i1d != e1d; ++i1d) {
891 if (i1d->second == Reg3) {
892 // Conflicting composition? Emit a warning but allow it.
893 if (CodeGenSubRegIndex *Prev = Idx1->addComposite(Idx2, i1d->first))
894 PrintWarning(Twine("SubRegIndex ") + Idx1->getQualifiedName() +
895 " and " + Idx2->getQualifiedName() +
896 " compose ambiguously as " + Prev->getQualifiedName() +
897 " or " + i1d->first->getQualifiedName());
904 // We don't care about the difference between (Idx1, Idx2) -> Idx2 and invalid
905 // compositions, so remove any mappings of that form.
906 for (unsigned i = 0, e = SubRegIndices.size(); i != e; ++i)
907 SubRegIndices[i]->cleanComposites();
911 // UberRegSet is a helper class for computeRegUnitWeights. Each UberRegSet is
912 // the transitive closure of the union of overlapping register
913 // classes. Together, the UberRegSets form a partition of the registers. If we
914 // consider overlapping register classes to be connected, then each UberRegSet
915 // is a set of connected components.
917 // An UberRegSet will likely be a horizontal slice of register names of
918 // the same width. Nontrivial subregisters should then be in a separate
919 // UberRegSet. But this property isn't required for valid computation of
920 // register unit weights.
922 // A Weight field caches the max per-register unit weight in each UberRegSet.
924 // A set of SingularDeterminants flags single units of some register in this set
925 // for which the unit weight equals the set weight. These units should not have
926 // their weight increased.
928 CodeGenRegister::Set Regs;
930 CodeGenRegister::RegUnitList SingularDeterminants;
932 UberRegSet(): Weight(0) {}
936 // Partition registers into UberRegSets, where each set is the transitive
937 // closure of the union of overlapping register classes.
939 // UberRegSets[0] is a special non-allocatable set.
940 static void computeUberSets(std::vector<UberRegSet> &UberSets,
941 std::vector<UberRegSet*> &RegSets,
942 CodeGenRegBank &RegBank) {
944 const std::vector<CodeGenRegister*> &Registers = RegBank.getRegisters();
946 // The Register EnumValue is one greater than its index into Registers.
947 assert(Registers.size() == Registers[Registers.size()-1]->EnumValue &&
948 "register enum value mismatch");
950 // For simplicitly make the SetID the same as EnumValue.
951 IntEqClasses UberSetIDs(Registers.size()+1);
952 std::set<unsigned> AllocatableRegs;
953 for (unsigned i = 0, e = RegBank.getRegClasses().size(); i != e; ++i) {
955 CodeGenRegisterClass *RegClass = RegBank.getRegClasses()[i];
956 if (!RegClass->Allocatable)
959 const CodeGenRegister::Set &Regs = RegClass->getMembers();
963 unsigned USetID = UberSetIDs.findLeader((*Regs.begin())->EnumValue);
964 assert(USetID && "register number 0 is invalid");
966 AllocatableRegs.insert((*Regs.begin())->EnumValue);
967 for (CodeGenRegister::Set::const_iterator I = llvm::next(Regs.begin()),
968 E = Regs.end(); I != E; ++I) {
969 AllocatableRegs.insert((*I)->EnumValue);
970 UberSetIDs.join(USetID, (*I)->EnumValue);
973 // Combine non-allocatable regs.
974 for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
975 unsigned RegNum = Registers[i]->EnumValue;
976 if (AllocatableRegs.count(RegNum))
979 UberSetIDs.join(0, RegNum);
981 UberSetIDs.compress();
983 // Make the first UberSet a special unallocatable set.
984 unsigned ZeroID = UberSetIDs[0];
986 // Insert Registers into the UberSets formed by union-find.
987 // Do not resize after this.
988 UberSets.resize(UberSetIDs.getNumClasses());
989 for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
990 const CodeGenRegister *Reg = Registers[i];
991 unsigned USetID = UberSetIDs[Reg->EnumValue];
994 else if (USetID == ZeroID)
997 UberRegSet *USet = &UberSets[USetID];
998 USet->Regs.insert(Reg);
1003 // Recompute each UberSet weight after changing unit weights.
1004 static void computeUberWeights(std::vector<UberRegSet> &UberSets,
1005 CodeGenRegBank &RegBank) {
1006 // Skip the first unallocatable set.
1007 for (std::vector<UberRegSet>::iterator I = llvm::next(UberSets.begin()),
1008 E = UberSets.end(); I != E; ++I) {
1010 // Initialize all unit weights in this set, and remember the max units/reg.
1011 const CodeGenRegister *Reg = 0;
1012 unsigned MaxWeight = 0, Weight = 0;
1013 for (RegUnitIterator UnitI(I->Regs); UnitI.isValid(); ++UnitI) {
1014 if (Reg != UnitI.getReg()) {
1015 if (Weight > MaxWeight)
1017 Reg = UnitI.getReg();
1020 unsigned UWeight = RegBank.getRegUnitWeight(*UnitI);
1023 RegBank.increaseRegUnitWeight(*UnitI, UWeight);
1027 if (Weight > MaxWeight)
1030 // Update the set weight.
1031 I->Weight = MaxWeight;
1033 // Find singular determinants.
1034 for (CodeGenRegister::Set::iterator RegI = I->Regs.begin(),
1035 RegE = I->Regs.end(); RegI != RegE; ++RegI) {
1036 if ((*RegI)->getRegUnits().size() == 1
1037 && (*RegI)->getWeight(RegBank) == I->Weight)
1038 mergeRegUnits(I->SingularDeterminants, (*RegI)->getRegUnits());
1043 // normalizeWeight is a computeRegUnitWeights helper that adjusts the weight of
1044 // a register and its subregisters so that they have the same weight as their
1045 // UberSet. Self-recursion processes the subregister tree in postorder so
1046 // subregisters are normalized first.
1049 // - creates new adopted register units
1050 // - causes superregisters to inherit adopted units
1051 // - increases the weight of "singular" units
1052 // - induces recomputation of UberWeights.
1053 static bool normalizeWeight(CodeGenRegister *Reg,
1054 std::vector<UberRegSet> &UberSets,
1055 std::vector<UberRegSet*> &RegSets,
1056 CodeGenRegister::RegUnitList &NormalUnits,
1057 CodeGenRegBank &RegBank) {
1058 bool Changed = false;
1059 const CodeGenRegister::SubRegMap &SRM = Reg->getSubRegs();
1060 for (CodeGenRegister::SubRegMap::const_iterator SRI = SRM.begin(),
1061 SRE = SRM.end(); SRI != SRE; ++SRI) {
1062 if (SRI->second == Reg)
1063 continue; // self-cycles happen
1066 normalizeWeight(SRI->second, UberSets, RegSets, NormalUnits, RegBank);
1068 // Postorder register normalization.
1070 // Inherit register units newly adopted by subregisters.
1071 if (Reg->inheritRegUnits(RegBank))
1072 computeUberWeights(UberSets, RegBank);
1074 // Check if this register is too skinny for its UberRegSet.
1075 UberRegSet *UberSet = RegSets[RegBank.getRegIndex(Reg)];
1077 unsigned RegWeight = Reg->getWeight(RegBank);
1078 if (UberSet->Weight > RegWeight) {
1079 // A register unit's weight can be adjusted only if it is the singular unit
1080 // for this register, has not been used to normalize a subregister's set,
1081 // and has not already been used to singularly determine this UberRegSet.
1082 unsigned AdjustUnit = Reg->getRegUnits().front();
1083 if (Reg->getRegUnits().size() != 1
1084 || hasRegUnit(NormalUnits, AdjustUnit)
1085 || hasRegUnit(UberSet->SingularDeterminants, AdjustUnit)) {
1086 // We don't have an adjustable unit, so adopt a new one.
1087 AdjustUnit = RegBank.newRegUnit(UberSet->Weight - RegWeight);
1088 Reg->adoptRegUnit(AdjustUnit);
1089 // Adopting a unit does not immediately require recomputing set weights.
1092 // Adjust the existing single unit.
1093 RegBank.increaseRegUnitWeight(AdjustUnit, UberSet->Weight - RegWeight);
1094 // The unit may be shared among sets and registers within this set.
1095 computeUberWeights(UberSets, RegBank);
1100 // Mark these units normalized so superregisters can't change their weights.
1101 mergeRegUnits(NormalUnits, Reg->getRegUnits());
1106 // Compute a weight for each register unit created during getSubRegs.
1108 // The goal is that two registers in the same class will have the same weight,
1109 // where each register's weight is defined as sum of its units' weights.
1110 void CodeGenRegBank::computeRegUnitWeights() {
1111 assert(RegUnitWeights.empty() && "Only initialize RegUnitWeights once");
1113 // Only allocatable units will be initialized to nonzero weight.
1114 RegUnitWeights.resize(NumRegUnits);
1116 std::vector<UberRegSet> UberSets;
1117 std::vector<UberRegSet*> RegSets(Registers.size());
1118 computeUberSets(UberSets, RegSets, *this);
1119 // UberSets and RegSets are now immutable.
1121 computeUberWeights(UberSets, *this);
1123 // Iterate over each Register, normalizing the unit weights until reaching
1125 unsigned NumIters = 0;
1126 for (bool Changed = true; Changed; ++NumIters) {
1127 assert(NumIters <= NumNativeRegUnits && "Runaway register unit weights");
1129 for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
1130 CodeGenRegister::RegUnitList NormalUnits;
1132 normalizeWeight(Registers[i], UberSets, RegSets, NormalUnits, *this);
1137 // Find a set in UniqueSets with the same elements as Set.
1138 // Return an iterator into UniqueSets.
1139 static std::vector<RegUnitSet>::const_iterator
1140 findRegUnitSet(const std::vector<RegUnitSet> &UniqueSets,
1141 const RegUnitSet &Set) {
1142 std::vector<RegUnitSet>::const_iterator
1143 I = UniqueSets.begin(), E = UniqueSets.end();
1145 if (I->Units == Set.Units)
1151 // Return true if the RUSubSet is a subset of RUSuperSet.
1152 static bool isRegUnitSubSet(const std::vector<unsigned> &RUSubSet,
1153 const std::vector<unsigned> &RUSuperSet) {
1154 return std::includes(RUSuperSet.begin(), RUSuperSet.end(),
1155 RUSubSet.begin(), RUSubSet.end());
1158 // Iteratively prune unit sets.
1159 void CodeGenRegBank::pruneUnitSets() {
1160 assert(RegClassUnitSets.empty() && "this invalidates RegClassUnitSets");
1162 // Form an equivalence class of UnitSets with no significant difference.
1163 std::vector<unsigned> SuperSetIDs;
1164 for (unsigned SubIdx = 0, EndIdx = RegUnitSets.size();
1165 SubIdx != EndIdx; ++SubIdx) {
1166 const RegUnitSet &SubSet = RegUnitSets[SubIdx];
1167 unsigned SuperIdx = 0;
1168 for (; SuperIdx != EndIdx; ++SuperIdx) {
1169 if (SuperIdx == SubIdx)
1172 const RegUnitSet &SuperSet = RegUnitSets[SuperIdx];
1173 if (isRegUnitSubSet(SubSet.Units, SuperSet.Units)
1174 && (SubSet.Units.size() + 3 > SuperSet.Units.size())) {
1178 if (SuperIdx == EndIdx)
1179 SuperSetIDs.push_back(SubIdx);
1181 // Populate PrunedUnitSets with each equivalence class's superset.
1182 std::vector<RegUnitSet> PrunedUnitSets(SuperSetIDs.size());
1183 for (unsigned i = 0, e = SuperSetIDs.size(); i != e; ++i) {
1184 unsigned SuperIdx = SuperSetIDs[i];
1185 PrunedUnitSets[i].Name = RegUnitSets[SuperIdx].Name;
1186 PrunedUnitSets[i].Units.swap(RegUnitSets[SuperIdx].Units);
1188 RegUnitSets.swap(PrunedUnitSets);
1191 // Create a RegUnitSet for each RegClass that contains all units in the class
1192 // including adopted units that are necessary to model register pressure. Then
1193 // iteratively compute RegUnitSets such that the union of any two overlapping
1194 // RegUnitSets is repreresented.
1196 // RegisterInfoEmitter will map each RegClass to its RegUnitClass and any
1197 // RegUnitSet that is a superset of that RegUnitClass.
1198 void CodeGenRegBank::computeRegUnitSets() {
1200 // Compute a unique RegUnitSet for each RegClass.
1201 const ArrayRef<CodeGenRegisterClass*> &RegClasses = getRegClasses();
1202 unsigned NumRegClasses = RegClasses.size();
1203 for (unsigned RCIdx = 0, RCEnd = NumRegClasses; RCIdx != RCEnd; ++RCIdx) {
1204 if (!RegClasses[RCIdx]->Allocatable)
1207 // Speculatively grow the RegUnitSets to hold the new set.
1208 RegUnitSets.resize(RegUnitSets.size() + 1);
1209 RegUnitSets.back().Name = RegClasses[RCIdx]->getName();
1211 // Compute a sorted list of units in this class.
1212 RegClasses[RCIdx]->buildRegUnitSet(RegUnitSets.back().Units);
1214 // Find an existing RegUnitSet.
1215 std::vector<RegUnitSet>::const_iterator SetI =
1216 findRegUnitSet(RegUnitSets, RegUnitSets.back());
1217 if (SetI != llvm::prior(RegUnitSets.end()))
1218 RegUnitSets.pop_back();
1221 // Iteratively prune unit sets.
1224 // Iterate over all unit sets, including new ones added by this loop.
1225 unsigned NumRegUnitSubSets = RegUnitSets.size();
1226 for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx) {
1227 // In theory, this is combinatorial. In practice, it needs to be bounded
1228 // by a small number of sets for regpressure to be efficient.
1229 // If the assert is hit, we need to implement pruning.
1230 assert(Idx < (2*NumRegUnitSubSets) && "runaway unit set inference");
1232 // Compare new sets with all original classes.
1233 for (unsigned SearchIdx = (Idx >= NumRegUnitSubSets) ? 0 : Idx+1;
1234 SearchIdx != EndIdx; ++SearchIdx) {
1235 std::set<unsigned> Intersection;
1236 std::set_intersection(RegUnitSets[Idx].Units.begin(),
1237 RegUnitSets[Idx].Units.end(),
1238 RegUnitSets[SearchIdx].Units.begin(),
1239 RegUnitSets[SearchIdx].Units.end(),
1240 std::inserter(Intersection, Intersection.begin()));
1241 if (Intersection.empty())
1244 // Speculatively grow the RegUnitSets to hold the new set.
1245 RegUnitSets.resize(RegUnitSets.size() + 1);
1246 RegUnitSets.back().Name =
1247 RegUnitSets[Idx].Name + "+" + RegUnitSets[SearchIdx].Name;
1249 std::set_union(RegUnitSets[Idx].Units.begin(),
1250 RegUnitSets[Idx].Units.end(),
1251 RegUnitSets[SearchIdx].Units.begin(),
1252 RegUnitSets[SearchIdx].Units.end(),
1253 std::inserter(RegUnitSets.back().Units,
1254 RegUnitSets.back().Units.begin()));
1256 // Find an existing RegUnitSet, or add the union to the unique sets.
1257 std::vector<RegUnitSet>::const_iterator SetI =
1258 findRegUnitSet(RegUnitSets, RegUnitSets.back());
1259 if (SetI != llvm::prior(RegUnitSets.end()))
1260 RegUnitSets.pop_back();
1264 // Iteratively prune unit sets after inferring supersets.
1267 // For each register class, list the UnitSets that are supersets.
1268 RegClassUnitSets.resize(NumRegClasses);
1269 for (unsigned RCIdx = 0, RCEnd = NumRegClasses; RCIdx != RCEnd; ++RCIdx) {
1270 if (!RegClasses[RCIdx]->Allocatable)
1273 // Recompute the sorted list of units in this class.
1274 std::vector<unsigned> RegUnits;
1275 RegClasses[RCIdx]->buildRegUnitSet(RegUnits);
1277 // Don't increase pressure for unallocatable regclasses.
1278 if (RegUnits.empty())
1281 // Find all supersets.
1282 for (unsigned USIdx = 0, USEnd = RegUnitSets.size();
1283 USIdx != USEnd; ++USIdx) {
1284 if (isRegUnitSubSet(RegUnits, RegUnitSets[USIdx].Units))
1285 RegClassUnitSets[RCIdx].push_back(USIdx);
1287 assert(!RegClassUnitSets[RCIdx].empty() && "missing unit set for regclass");
1291 // Compute sets of overlapping registers.
1293 // The standard set is all super-registers and all sub-registers, but the
1294 // target description can add arbitrary overlapping registers via the 'Aliases'
1295 // field. This complicates things, but we can compute overlapping sets using
1296 // the following rules:
1298 // 1. The relation overlap(A, B) is reflexive and symmetric but not transitive.
1300 // 2. overlap(A, B) implies overlap(A, S) for all S in supers(B).
1304 // overlap(A, B) iff there exists:
1305 // A' in { A, subregs(A) } and B' in { B, subregs(B) } such that:
1306 // A' = B' or A' in aliases(B') or B' in aliases(A').
1308 // Here subregs(A) is the full flattened sub-register set returned by
1309 // A.getSubRegs() while aliases(A) is simply the special 'Aliases' field in the
1310 // description of register A.
1312 // This also implies that registers with a common sub-register are considered
1313 // overlapping. This can happen when forming register pairs:
1319 // In this case, we will infer an overlap between P0 and P1 because of the
1320 // shared sub-register R1. There is no overlap between P0 and P2.
1322 void CodeGenRegBank::
1323 computeOverlaps(std::map<const CodeGenRegister*, CodeGenRegister::Set> &Map) {
1324 assert(Map.empty());
1326 // Collect overlaps that don't follow from rule 2.
1327 for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
1328 CodeGenRegister *Reg = Registers[i];
1329 CodeGenRegister::Set &Overlaps = Map[Reg];
1331 // Reg overlaps itself.
1332 Overlaps.insert(Reg);
1334 // All super-registers overlap.
1335 const CodeGenRegister::SuperRegList &Supers = Reg->getSuperRegs();
1336 Overlaps.insert(Supers.begin(), Supers.end());
1338 // Form symmetrical relations from the special Aliases[] lists.
1339 std::vector<Record*> RegList = Reg->TheDef->getValueAsListOfDefs("Aliases");
1340 for (unsigned i2 = 0, e2 = RegList.size(); i2 != e2; ++i2) {
1341 CodeGenRegister *Reg2 = getReg(RegList[i2]);
1342 CodeGenRegister::Set &Overlaps2 = Map[Reg2];
1343 const CodeGenRegister::SuperRegList &Supers2 = Reg2->getSuperRegs();
1344 // Reg overlaps Reg2 which implies it overlaps supers(Reg2).
1345 Overlaps.insert(Reg2);
1346 Overlaps.insert(Supers2.begin(), Supers2.end());
1347 Overlaps2.insert(Reg);
1348 Overlaps2.insert(Supers.begin(), Supers.end());
1352 // Apply rule 2. and inherit all sub-register overlaps.
1353 for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
1354 CodeGenRegister *Reg = Registers[i];
1355 CodeGenRegister::Set &Overlaps = Map[Reg];
1356 const CodeGenRegister::SubRegMap &SRM = Reg->getSubRegs();
1357 for (CodeGenRegister::SubRegMap::const_iterator i2 = SRM.begin(),
1358 e2 = SRM.end(); i2 != e2; ++i2) {
1359 CodeGenRegister::Set &Overlaps2 = Map[i2->second];
1360 Overlaps.insert(Overlaps2.begin(), Overlaps2.end());
1365 void CodeGenRegBank::computeDerivedInfo() {
1366 computeComposites();
1368 // Compute a weight for each register unit created during getSubRegs.
1369 // This may create adopted register units (with unit # >= NumNativeRegUnits).
1370 computeRegUnitWeights();
1372 // Compute a unique set of RegUnitSets. One for each RegClass and inferred
1373 // supersets for the union of overlapping sets.
1374 computeRegUnitSets();
1378 // Synthesize missing register class intersections.
1380 // Make sure that sub-classes of RC exists such that getCommonSubClass(RC, X)
1381 // returns a maximal register class for all X.
1383 void CodeGenRegBank::inferCommonSubClass(CodeGenRegisterClass *RC) {
1384 for (unsigned rci = 0, rce = RegClasses.size(); rci != rce; ++rci) {
1385 CodeGenRegisterClass *RC1 = RC;
1386 CodeGenRegisterClass *RC2 = RegClasses[rci];
1390 // Compute the set intersection of RC1 and RC2.
1391 const CodeGenRegister::Set &Memb1 = RC1->getMembers();
1392 const CodeGenRegister::Set &Memb2 = RC2->getMembers();
1393 CodeGenRegister::Set Intersection;
1394 std::set_intersection(Memb1.begin(), Memb1.end(),
1395 Memb2.begin(), Memb2.end(),
1396 std::inserter(Intersection, Intersection.begin()),
1397 CodeGenRegister::Less());
1399 // Skip disjoint class pairs.
1400 if (Intersection.empty())
1403 // If RC1 and RC2 have different spill sizes or alignments, use the
1404 // larger size for sub-classing. If they are equal, prefer RC1.
1405 if (RC2->SpillSize > RC1->SpillSize ||
1406 (RC2->SpillSize == RC1->SpillSize &&
1407 RC2->SpillAlignment > RC1->SpillAlignment))
1408 std::swap(RC1, RC2);
1410 getOrCreateSubClass(RC1, &Intersection,
1411 RC1->getName() + "_and_" + RC2->getName());
1416 // Synthesize missing sub-classes for getSubClassWithSubReg().
1418 // Make sure that the set of registers in RC with a given SubIdx sub-register
1419 // form a register class. Update RC->SubClassWithSubReg.
1421 void CodeGenRegBank::inferSubClassWithSubReg(CodeGenRegisterClass *RC) {
1422 // Map SubRegIndex to set of registers in RC supporting that SubRegIndex.
1423 typedef std::map<CodeGenSubRegIndex*, CodeGenRegister::Set,
1424 CodeGenSubRegIndex::Less> SubReg2SetMap;
1426 // Compute the set of registers supporting each SubRegIndex.
1427 SubReg2SetMap SRSets;
1428 for (CodeGenRegister::Set::const_iterator RI = RC->getMembers().begin(),
1429 RE = RC->getMembers().end(); RI != RE; ++RI) {
1430 const CodeGenRegister::SubRegMap &SRM = (*RI)->getSubRegs();
1431 for (CodeGenRegister::SubRegMap::const_iterator I = SRM.begin(),
1432 E = SRM.end(); I != E; ++I)
1433 SRSets[I->first].insert(*RI);
1436 // Find matching classes for all SRSets entries. Iterate in SubRegIndex
1437 // numerical order to visit synthetic indices last.
1438 for (unsigned sri = 0, sre = SubRegIndices.size(); sri != sre; ++sri) {
1439 CodeGenSubRegIndex *SubIdx = SubRegIndices[sri];
1440 SubReg2SetMap::const_iterator I = SRSets.find(SubIdx);
1441 // Unsupported SubRegIndex. Skip it.
1442 if (I == SRSets.end())
1444 // In most cases, all RC registers support the SubRegIndex.
1445 if (I->second.size() == RC->getMembers().size()) {
1446 RC->setSubClassWithSubReg(SubIdx, RC);
1449 // This is a real subset. See if we have a matching class.
1450 CodeGenRegisterClass *SubRC =
1451 getOrCreateSubClass(RC, &I->second,
1452 RC->getName() + "_with_" + I->first->getName());
1453 RC->setSubClassWithSubReg(SubIdx, SubRC);
1458 // Synthesize missing sub-classes of RC for getMatchingSuperRegClass().
1460 // Create sub-classes of RC such that getMatchingSuperRegClass(RC, SubIdx, X)
1461 // has a maximal result for any SubIdx and any X >= FirstSubRegRC.
1464 void CodeGenRegBank::inferMatchingSuperRegClass(CodeGenRegisterClass *RC,
1465 unsigned FirstSubRegRC) {
1466 SmallVector<std::pair<const CodeGenRegister*,
1467 const CodeGenRegister*>, 16> SSPairs;
1469 // Iterate in SubRegIndex numerical order to visit synthetic indices last.
1470 for (unsigned sri = 0, sre = SubRegIndices.size(); sri != sre; ++sri) {
1471 CodeGenSubRegIndex *SubIdx = SubRegIndices[sri];
1472 // Skip indexes that aren't fully supported by RC's registers. This was
1473 // computed by inferSubClassWithSubReg() above which should have been
1475 if (RC->getSubClassWithSubReg(SubIdx) != RC)
1478 // Build list of (Super, Sub) pairs for this SubIdx.
1480 for (CodeGenRegister::Set::const_iterator RI = RC->getMembers().begin(),
1481 RE = RC->getMembers().end(); RI != RE; ++RI) {
1482 const CodeGenRegister *Super = *RI;
1483 const CodeGenRegister *Sub = Super->getSubRegs().find(SubIdx)->second;
1484 assert(Sub && "Missing sub-register");
1485 SSPairs.push_back(std::make_pair(Super, Sub));
1488 // Iterate over sub-register class candidates. Ignore classes created by
1489 // this loop. They will never be useful.
1490 for (unsigned rci = FirstSubRegRC, rce = RegClasses.size(); rci != rce;
1492 CodeGenRegisterClass *SubRC = RegClasses[rci];
1493 // Compute the subset of RC that maps into SubRC.
1494 CodeGenRegister::Set SubSet;
1495 for (unsigned i = 0, e = SSPairs.size(); i != e; ++i)
1496 if (SubRC->contains(SSPairs[i].second))
1497 SubSet.insert(SSPairs[i].first);
1500 // RC injects completely into SubRC.
1501 if (SubSet.size() == SSPairs.size()) {
1502 SubRC->addSuperRegClass(SubIdx, RC);
1505 // Only a subset of RC maps into SubRC. Make sure it is represented by a
1507 getOrCreateSubClass(RC, &SubSet, RC->getName() +
1508 "_with_" + SubIdx->getName() +
1509 "_in_" + SubRC->getName());
1516 // Infer missing register classes.
1518 void CodeGenRegBank::computeInferredRegisterClasses() {
1519 // When this function is called, the register classes have not been sorted
1520 // and assigned EnumValues yet. That means getSubClasses(),
1521 // getSuperClasses(), and hasSubClass() functions are defunct.
1522 unsigned FirstNewRC = RegClasses.size();
1524 // Visit all register classes, including the ones being added by the loop.
1525 for (unsigned rci = 0; rci != RegClasses.size(); ++rci) {
1526 CodeGenRegisterClass *RC = RegClasses[rci];
1528 // Synthesize answers for getSubClassWithSubReg().
1529 inferSubClassWithSubReg(RC);
1531 // Synthesize answers for getCommonSubClass().
1532 inferCommonSubClass(RC);
1534 // Synthesize answers for getMatchingSuperRegClass().
1535 inferMatchingSuperRegClass(RC);
1537 // New register classes are created while this loop is running, and we need
1538 // to visit all of them. I particular, inferMatchingSuperRegClass needs
1539 // to match old super-register classes with sub-register classes created
1540 // after inferMatchingSuperRegClass was called. At this point,
1541 // inferMatchingSuperRegClass has checked SuperRC = [0..rci] with SubRC =
1542 // [0..FirstNewRC). We need to cover SubRC = [FirstNewRC..rci].
1543 if (rci + 1 == FirstNewRC) {
1544 unsigned NextNewRC = RegClasses.size();
1545 for (unsigned rci2 = 0; rci2 != FirstNewRC; ++rci2)
1546 inferMatchingSuperRegClass(RegClasses[rci2], FirstNewRC);
1547 FirstNewRC = NextNewRC;
1552 /// getRegisterClassForRegister - Find the register class that contains the
1553 /// specified physical register. If the register is not in a register class,
1554 /// return null. If the register is in multiple classes, and the classes have a
1555 /// superset-subset relationship and the same set of types, return the
1556 /// superclass. Otherwise return null.
1557 const CodeGenRegisterClass*
1558 CodeGenRegBank::getRegClassForRegister(Record *R) {
1559 const CodeGenRegister *Reg = getReg(R);
1560 ArrayRef<CodeGenRegisterClass*> RCs = getRegClasses();
1561 const CodeGenRegisterClass *FoundRC = 0;
1562 for (unsigned i = 0, e = RCs.size(); i != e; ++i) {
1563 const CodeGenRegisterClass &RC = *RCs[i];
1564 if (!RC.contains(Reg))
1567 // If this is the first class that contains the register,
1568 // make a note of it and go on to the next class.
1574 // If a register's classes have different types, return null.
1575 if (RC.getValueTypes() != FoundRC->getValueTypes())
1578 // Check to see if the previously found class that contains
1579 // the register is a subclass of the current class. If so,
1580 // prefer the superclass.
1581 if (RC.hasSubClass(FoundRC)) {
1586 // Check to see if the previously found class that contains
1587 // the register is a superclass of the current class. If so,
1588 // prefer the superclass.
1589 if (FoundRC->hasSubClass(&RC))
1592 // Multiple classes, and neither is a superclass of the other.
1599 BitVector CodeGenRegBank::computeCoveredRegisters(ArrayRef<Record*> Regs) {
1600 SetVector<const CodeGenRegister*> Set;
1602 // First add Regs with all sub-registers.
1603 for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
1604 CodeGenRegister *Reg = getReg(Regs[i]);
1605 if (Set.insert(Reg))
1606 // Reg is new, add all sub-registers.
1607 // The pre-ordering is not important here.
1608 Reg->addSubRegsPreOrder(Set, *this);
1611 // Second, find all super-registers that are completely covered by the set.
1612 for (unsigned i = 0; i != Set.size(); ++i) {
1613 const CodeGenRegister::SuperRegList &SR = Set[i]->getSuperRegs();
1614 for (unsigned j = 0, e = SR.size(); j != e; ++j) {
1615 const CodeGenRegister *Super = SR[j];
1616 if (!Super->CoveredBySubRegs || Set.count(Super))
1618 // This new super-register is covered by its sub-registers.
1619 bool AllSubsInSet = true;
1620 const CodeGenRegister::SubRegMap &SRM = Super->getSubRegs();
1621 for (CodeGenRegister::SubRegMap::const_iterator I = SRM.begin(),
1622 E = SRM.end(); I != E; ++I)
1623 if (!Set.count(I->second)) {
1624 AllSubsInSet = false;
1627 // All sub-registers in Set, add Super as well.
1628 // We will visit Super later to recheck its super-registers.
1634 // Convert to BitVector.
1635 BitVector BV(Registers.size() + 1);
1636 for (unsigned i = 0, e = Set.size(); i != e; ++i)
1637 BV.set(Set[i]->EnumValue);