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/SmallVector.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/StringExtras.h"
24 //===----------------------------------------------------------------------===//
26 //===----------------------------------------------------------------------===//
28 CodeGenRegister::CodeGenRegister(Record *R, unsigned Enum)
31 CostPerUse(R->getValueAsInt("CostPerUse")),
32 SubRegsComplete(false)
35 const std::string &CodeGenRegister::getName() const {
36 return TheDef->getName();
41 CodeGenRegister *SubReg;
42 Record *First, *Second;
43 Orphan(CodeGenRegister *r, Record *a, Record *b)
44 : SubReg(r), First(a), Second(b) {}
48 const CodeGenRegister::SubRegMap &
49 CodeGenRegister::getSubRegs(CodeGenRegBank &RegBank) {
50 // Only compute this map once.
53 SubRegsComplete = true;
55 std::vector<Record*> SubList = TheDef->getValueAsListOfDefs("SubRegs");
56 std::vector<Record*> Indices = TheDef->getValueAsListOfDefs("SubRegIndices");
57 if (SubList.size() != Indices.size())
58 throw TGError(TheDef->getLoc(), "Register " + getName() +
59 " SubRegIndices doesn't match SubRegs");
61 // First insert the direct subregs and make sure they are fully indexed.
62 for (unsigned i = 0, e = SubList.size(); i != e; ++i) {
63 CodeGenRegister *SR = RegBank.getReg(SubList[i]);
64 if (!SubRegs.insert(std::make_pair(Indices[i], SR)).second)
65 throw TGError(TheDef->getLoc(), "SubRegIndex " + Indices[i]->getName() +
66 " appears twice in Register " + getName());
69 // Keep track of inherited subregs and how they can be reached.
70 SmallVector<Orphan, 8> Orphans;
72 // Clone inherited subregs and place duplicate entries on Orphans.
73 // Here the order is important - earlier subregs take precedence.
74 for (unsigned i = 0, e = SubList.size(); i != e; ++i) {
75 CodeGenRegister *SR = RegBank.getReg(SubList[i]);
76 const SubRegMap &Map = SR->getSubRegs(RegBank);
78 // Add this as a super-register of SR now all sub-registers are in the list.
79 // This creates a topological ordering, the exact order depends on the
80 // order getSubRegs is called on all registers.
81 SR->SuperRegs.push_back(this);
83 for (SubRegMap::const_iterator SI = Map.begin(), SE = Map.end(); SI != SE;
85 if (!SubRegs.insert(*SI).second)
86 Orphans.push_back(Orphan(SI->second, Indices[i], SI->first));
88 // Noop sub-register indexes are possible, so avoid duplicates.
90 SI->second->SuperRegs.push_back(this);
94 // Process the composites.
95 ListInit *Comps = TheDef->getValueAsListInit("CompositeIndices");
96 for (unsigned i = 0, e = Comps->size(); i != e; ++i) {
97 DagInit *Pat = dynamic_cast<DagInit*>(Comps->getElement(i));
99 throw TGError(TheDef->getLoc(), "Invalid dag '" +
100 Comps->getElement(i)->getAsString() +
101 "' in CompositeIndices");
102 DefInit *BaseIdxInit = dynamic_cast<DefInit*>(Pat->getOperator());
103 if (!BaseIdxInit || !BaseIdxInit->getDef()->isSubClassOf("SubRegIndex"))
104 throw TGError(TheDef->getLoc(), "Invalid SubClassIndex in " +
107 // Resolve list of subreg indices into R2.
108 CodeGenRegister *R2 = this;
109 for (DagInit::const_arg_iterator di = Pat->arg_begin(),
110 de = Pat->arg_end(); di != de; ++di) {
111 DefInit *IdxInit = dynamic_cast<DefInit*>(*di);
112 if (!IdxInit || !IdxInit->getDef()->isSubClassOf("SubRegIndex"))
113 throw TGError(TheDef->getLoc(), "Invalid SubClassIndex in " +
115 const SubRegMap &R2Subs = R2->getSubRegs(RegBank);
116 SubRegMap::const_iterator ni = R2Subs.find(IdxInit->getDef());
117 if (ni == R2Subs.end())
118 throw TGError(TheDef->getLoc(), "Composite " + Pat->getAsString() +
119 " refers to bad index in " + R2->getName());
123 // Insert composite index. Allow overriding inherited indices etc.
124 SubRegs[BaseIdxInit->getDef()] = R2;
126 // R2 is no longer an orphan.
127 for (unsigned j = 0, je = Orphans.size(); j != je; ++j)
128 if (Orphans[j].SubReg == R2)
129 Orphans[j].SubReg = 0;
132 // Now Orphans contains the inherited subregisters without a direct index.
133 // Create inferred indexes for all missing entries.
134 for (unsigned i = 0, e = Orphans.size(); i != e; ++i) {
135 Orphan &O = Orphans[i];
138 SubRegs[RegBank.getCompositeSubRegIndex(O.First, O.Second, true)] =
145 CodeGenRegister::addSubRegsPreOrder(SetVector<CodeGenRegister*> &OSet) const {
146 assert(SubRegsComplete && "Must precompute sub-registers");
147 std::vector<Record*> Indices = TheDef->getValueAsListOfDefs("SubRegIndices");
148 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
149 CodeGenRegister *SR = SubRegs.find(Indices[i])->second;
151 SR->addSubRegsPreOrder(OSet);
155 //===----------------------------------------------------------------------===//
157 //===----------------------------------------------------------------------===//
159 // A RegisterTuples def is used to generate pseudo-registers from lists of
160 // sub-registers. We provide a SetTheory expander class that returns the new
163 struct TupleExpander : SetTheory::Expander {
164 void expand(SetTheory &ST, Record *Def, SetTheory::RecSet &Elts) {
165 std::vector<Record*> Indices = Def->getValueAsListOfDefs("SubRegIndices");
166 unsigned Dim = Indices.size();
167 ListInit *SubRegs = Def->getValueAsListInit("SubRegs");
168 if (Dim != SubRegs->getSize())
169 throw TGError(Def->getLoc(), "SubRegIndices and SubRegs size mismatch");
171 throw TGError(Def->getLoc(), "Tuples must have at least 2 sub-registers");
173 // Evaluate the sub-register lists to be zipped.
174 unsigned Length = ~0u;
175 SmallVector<SetTheory::RecSet, 4> Lists(Dim);
176 for (unsigned i = 0; i != Dim; ++i) {
177 ST.evaluate(SubRegs->getElement(i), Lists[i]);
178 Length = std::min(Length, unsigned(Lists[i].size()));
184 // Precompute some types.
185 Record *RegisterCl = Def->getRecords().getClass("Register");
186 RecTy *RegisterRecTy = RecordRecTy::get(RegisterCl);
187 StringInit *BlankName = StringInit::get("");
190 for (unsigned n = 0; n != Length; ++n) {
192 Record *Proto = Lists[0][n];
193 std::vector<Init*> Tuple;
194 unsigned CostPerUse = 0;
195 for (unsigned i = 0; i != Dim; ++i) {
196 Record *Reg = Lists[i][n];
198 Name += Reg->getName();
199 Tuple.push_back(DefInit::get(Reg));
200 CostPerUse = std::max(CostPerUse,
201 unsigned(Reg->getValueAsInt("CostPerUse")));
204 // Create a new Record representing the synthesized register. This record
205 // is only for consumption by CodeGenRegister, it is not added to the
207 Record *NewReg = new Record(Name, Def->getLoc(), Def->getRecords());
210 // Copy Proto super-classes.
211 for (unsigned i = 0, e = Proto->getSuperClasses().size(); i != e; ++i)
212 NewReg->addSuperClass(Proto->getSuperClasses()[i]);
214 // Copy Proto fields.
215 for (unsigned i = 0, e = Proto->getValues().size(); i != e; ++i) {
216 RecordVal RV = Proto->getValues()[i];
218 // Replace the sub-register list with Tuple.
219 if (RV.getName() == "SubRegs")
220 RV.setValue(ListInit::get(Tuple, RegisterRecTy));
222 // Provide a blank AsmName. MC hacks are required anyway.
223 if (RV.getName() == "AsmName")
224 RV.setValue(BlankName);
226 // CostPerUse is aggregated from all Tuple members.
227 if (RV.getName() == "CostPerUse")
228 RV.setValue(IntInit::get(CostPerUse));
230 // Copy fields from the RegisterTuples def.
231 if (RV.getName() == "SubRegIndices" ||
232 RV.getName() == "CompositeIndices") {
233 NewReg->addValue(*Def->getValue(RV.getName()));
237 // Some fields get their default uninitialized value.
238 if (RV.getName() == "DwarfNumbers" ||
239 RV.getName() == "DwarfAlias" ||
240 RV.getName() == "Aliases") {
241 if (const RecordVal *DefRV = RegisterCl->getValue(RV.getName()))
242 NewReg->addValue(*DefRV);
246 // Everything else is copied from Proto.
247 NewReg->addValue(RV);
254 //===----------------------------------------------------------------------===//
255 // CodeGenRegisterClass
256 //===----------------------------------------------------------------------===//
258 CodeGenRegisterClass::CodeGenRegisterClass(CodeGenRegBank &RegBank, Record *R)
259 : TheDef(R), Name(R->getName()), EnumValue(-1) {
260 // Rename anonymous register classes.
261 if (R->getName().size() > 9 && R->getName()[9] == '.') {
262 static unsigned AnonCounter = 0;
263 R->setName("AnonRegClass_"+utostr(AnonCounter++));
266 std::vector<Record*> TypeList = R->getValueAsListOfDefs("RegTypes");
267 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
268 Record *Type = TypeList[i];
269 if (!Type->isSubClassOf("ValueType"))
270 throw "RegTypes list member '" + Type->getName() +
271 "' does not derive from the ValueType class!";
272 VTs.push_back(getValueType(Type));
274 assert(!VTs.empty() && "RegisterClass must contain at least one ValueType!");
276 // Allocation order 0 is the full set. AltOrders provides others.
277 const SetTheory::RecVec *Elements = RegBank.getSets().expand(R);
278 ListInit *AltOrders = R->getValueAsListInit("AltOrders");
279 Orders.resize(1 + AltOrders->size());
281 // Default allocation order always contains all registers.
282 for (unsigned i = 0, e = Elements->size(); i != e; ++i) {
283 Orders[0].push_back((*Elements)[i]);
284 Members.insert(RegBank.getReg((*Elements)[i]));
287 // Alternative allocation orders may be subsets.
288 SetTheory::RecSet Order;
289 for (unsigned i = 0, e = AltOrders->size(); i != e; ++i) {
290 RegBank.getSets().evaluate(AltOrders->getElement(i), Order);
291 Orders[1 + i].append(Order.begin(), Order.end());
292 // Verify that all altorder members are regclass members.
293 while (!Order.empty()) {
294 CodeGenRegister *Reg = RegBank.getReg(Order.back());
297 throw TGError(R->getLoc(), " AltOrder register " + Reg->getName() +
298 " is not a class member");
302 // SubRegClasses is a list<dag> containing (RC, subregindex, ...) dags.
303 ListInit *SRC = R->getValueAsListInit("SubRegClasses");
304 for (ListInit::const_iterator i = SRC->begin(), e = SRC->end(); i != e; ++i) {
305 DagInit *DAG = dynamic_cast<DagInit*>(*i);
306 if (!DAG) throw "SubRegClasses must contain DAGs";
307 DefInit *DAGOp = dynamic_cast<DefInit*>(DAG->getOperator());
309 if (!DAGOp || !(RCRec = DAGOp->getDef())->isSubClassOf("RegisterClass"))
310 throw "Operator '" + DAG->getOperator()->getAsString() +
311 "' in SubRegClasses is not a RegisterClass";
312 // Iterate over args, all SubRegIndex instances.
313 for (DagInit::const_arg_iterator ai = DAG->arg_begin(), ae = DAG->arg_end();
315 DefInit *Idx = dynamic_cast<DefInit*>(*ai);
317 if (!Idx || !(IdxRec = Idx->getDef())->isSubClassOf("SubRegIndex"))
318 throw "Argument '" + (*ai)->getAsString() +
319 "' in SubRegClasses is not a SubRegIndex";
320 if (!SubRegClasses.insert(std::make_pair(IdxRec, RCRec)).second)
321 throw "SubRegIndex '" + IdxRec->getName() + "' mentioned twice";
325 // Allow targets to override the size in bits of the RegisterClass.
326 unsigned Size = R->getValueAsInt("Size");
328 Namespace = R->getValueAsString("Namespace");
329 SpillSize = Size ? Size : EVT(VTs[0]).getSizeInBits();
330 SpillAlignment = R->getValueAsInt("Alignment");
331 CopyCost = R->getValueAsInt("CopyCost");
332 Allocatable = R->getValueAsBit("isAllocatable");
333 AltOrderSelect = R->getValueAsCode("AltOrderSelect");
336 // Create an inferred register class that was missing from the .td files.
337 // Most properties will be inherited from the closest super-class after the
338 // class structure has been computed.
339 CodeGenRegisterClass::CodeGenRegisterClass(StringRef Name, Key Props)
340 : Members(*Props.Members),
344 SpillSize(Props.SpillSize),
345 SpillAlignment(Props.SpillAlignment),
350 // Compute inherited propertied for a synthesized register class.
351 void CodeGenRegisterClass::inheritProperties(CodeGenRegBank &RegBank) {
352 assert(!getDef() && "Only synthesized classes can inherit properties");
353 assert(!SuperClasses.empty() && "Synthesized class without super class");
355 // The last super-class is the smallest one.
356 CodeGenRegisterClass &Super = *SuperClasses.back();
358 // Most properties are copied directly.
359 // Exceptions are members, size, and alignment
360 Namespace = Super.Namespace;
362 CopyCost = Super.CopyCost;
363 Allocatable = Super.Allocatable;
364 AltOrderSelect = Super.AltOrderSelect;
366 // Copy all allocation orders, filter out foreign registers from the larger
368 Orders.resize(Super.Orders.size());
369 for (unsigned i = 0, ie = Super.Orders.size(); i != ie; ++i)
370 for (unsigned j = 0, je = Super.Orders[i].size(); j != je; ++j)
371 if (contains(RegBank.getReg(Super.Orders[i][j])))
372 Orders[i].push_back(Super.Orders[i][j]);
375 bool CodeGenRegisterClass::contains(const CodeGenRegister *Reg) const {
376 return Members.count(Reg);
380 raw_ostream &operator<<(raw_ostream &OS, const CodeGenRegisterClass::Key &K) {
381 OS << "{ S=" << K.SpillSize << ", A=" << K.SpillAlignment;
382 for (CodeGenRegister::Set::const_iterator I = K.Members->begin(),
383 E = K.Members->end(); I != E; ++I)
384 OS << ", " << (*I)->getName();
389 // This is a simple lexicographical order that can be used to search for sets.
390 // It is not the same as the topological order provided by TopoOrderRC.
391 bool CodeGenRegisterClass::Key::
392 operator<(const CodeGenRegisterClass::Key &B) const {
393 assert(Members && B.Members);
394 if (*Members != *B.Members)
395 return *Members < *B.Members;
396 if (SpillSize != B.SpillSize)
397 return SpillSize < B.SpillSize;
398 return SpillAlignment < B.SpillAlignment;
401 // Returns true if RC is a strict subclass.
402 // RC is a sub-class of this class if it is a valid replacement for any
403 // instruction operand where a register of this classis required. It must
404 // satisfy these conditions:
406 // 1. All RC registers are also in this.
407 // 2. The RC spill size must not be smaller than our spill size.
408 // 3. RC spill alignment must be compatible with ours.
410 static bool testSubClass(const CodeGenRegisterClass *A,
411 const CodeGenRegisterClass *B) {
412 return A->SpillAlignment && B->SpillAlignment % A->SpillAlignment == 0 &&
413 A->SpillSize <= B->SpillSize &&
414 std::includes(A->getMembers().begin(), A->getMembers().end(),
415 B->getMembers().begin(), B->getMembers().end(),
416 CodeGenRegister::Less());
419 /// Sorting predicate for register classes. This provides a topological
420 /// ordering that arranges all register classes before their sub-classes.
422 /// Register classes with the same registers, spill size, and alignment form a
423 /// clique. They will be ordered alphabetically.
425 static int TopoOrderRC(const void *PA, const void *PB) {
426 const CodeGenRegisterClass *A = *(const CodeGenRegisterClass* const*)PA;
427 const CodeGenRegisterClass *B = *(const CodeGenRegisterClass* const*)PB;
431 // Order by descending set size. Note that the classes' allocation order may
432 // not have been computed yet. The Members set is always vaild.
433 if (A->getMembers().size() > B->getMembers().size())
435 if (A->getMembers().size() < B->getMembers().size())
438 // Order by ascending spill size.
439 if (A->SpillSize < B->SpillSize)
441 if (A->SpillSize > B->SpillSize)
444 // Order by ascending spill alignment.
445 if (A->SpillAlignment < B->SpillAlignment)
447 if (A->SpillAlignment > B->SpillAlignment)
450 // Finally order by name as a tie breaker.
451 return A->getName() < B->getName();
454 std::string CodeGenRegisterClass::getQualifiedName() const {
455 if (Namespace.empty())
458 return Namespace + "::" + getName();
461 // Compute sub-classes of all register classes.
462 // Assume the classes are ordered topologically.
463 void CodeGenRegisterClass::computeSubClasses(CodeGenRegBank &RegBank) {
464 ArrayRef<CodeGenRegisterClass*> RegClasses = RegBank.getRegClasses();
466 // Visit backwards so sub-classes are seen first.
467 for (unsigned rci = RegClasses.size(); rci; --rci) {
468 CodeGenRegisterClass &RC = *RegClasses[rci - 1];
469 RC.SubClasses.resize(RegClasses.size());
470 RC.SubClasses.set(RC.EnumValue);
472 // Normally, all subclasses have IDs >= rci, unless RC is part of a clique.
473 for (unsigned s = rci; s != RegClasses.size(); ++s) {
474 if (RC.SubClasses.test(s))
476 CodeGenRegisterClass *SubRC = RegClasses[s];
477 if (!testSubClass(&RC, SubRC))
479 // SubRC is a sub-class. Grap all its sub-classes so we won't have to
481 RC.SubClasses |= SubRC->SubClasses;
484 // Sweep up missed clique members. They will be immediately preceeding RC.
485 for (unsigned s = rci - 1; s && testSubClass(&RC, RegClasses[s - 1]); --s)
486 RC.SubClasses.set(s - 1);
489 // Compute the SuperClasses lists from the SubClasses vectors.
490 for (unsigned rci = 0; rci != RegClasses.size(); ++rci) {
491 const BitVector &SC = RegClasses[rci]->getSubClasses();
492 for (int s = SC.find_first(); s >= 0; s = SC.find_next(s)) {
493 if (unsigned(s) == rci)
495 RegClasses[s]->SuperClasses.push_back(RegClasses[rci]);
499 // With the class hierarchy in place, let synthesized register classes inherit
500 // properties from their closest super-class. The iteration order here can
501 // propagate properties down multiple levels.
502 for (unsigned rci = 0; rci != RegClasses.size(); ++rci)
503 if (!RegClasses[rci]->getDef())
504 RegClasses[rci]->inheritProperties(RegBank);
507 //===----------------------------------------------------------------------===//
509 //===----------------------------------------------------------------------===//
511 CodeGenRegBank::CodeGenRegBank(RecordKeeper &Records) : Records(Records) {
512 // Configure register Sets to understand register classes and tuples.
513 Sets.addFieldExpander("RegisterClass", "MemberList");
514 Sets.addExpander("RegisterTuples", new TupleExpander());
516 // Read in the user-defined (named) sub-register indices.
517 // More indices will be synthesized later.
518 SubRegIndices = Records.getAllDerivedDefinitions("SubRegIndex");
519 std::sort(SubRegIndices.begin(), SubRegIndices.end(), LessRecord());
520 NumNamedIndices = SubRegIndices.size();
522 // Read in the register definitions.
523 std::vector<Record*> Regs = Records.getAllDerivedDefinitions("Register");
524 std::sort(Regs.begin(), Regs.end(), LessRecord());
525 Registers.reserve(Regs.size());
526 // Assign the enumeration values.
527 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
530 // Expand tuples and number the new registers.
531 std::vector<Record*> Tups =
532 Records.getAllDerivedDefinitions("RegisterTuples");
533 for (unsigned i = 0, e = Tups.size(); i != e; ++i) {
534 const std::vector<Record*> *TupRegs = Sets.expand(Tups[i]);
535 for (unsigned j = 0, je = TupRegs->size(); j != je; ++j)
536 getReg((*TupRegs)[j]);
539 // Precompute all sub-register maps now all the registers are known.
540 // This will create Composite entries for all inferred sub-register indices.
541 for (unsigned i = 0, e = Registers.size(); i != e; ++i)
542 Registers[i]->getSubRegs(*this);
544 // Read in register class definitions.
545 std::vector<Record*> RCs = Records.getAllDerivedDefinitions("RegisterClass");
547 throw std::string("No 'RegisterClass' subclasses defined!");
549 // Allocate user-defined register classes.
550 RegClasses.reserve(RCs.size());
551 for (unsigned i = 0, e = RCs.size(); i != e; ++i)
552 addToMaps(new CodeGenRegisterClass(*this, RCs[i]));
554 // Infer missing classes to create a full algebra.
555 computeInferredRegisterClasses();
557 // Order register classes topologically and assign enum values.
558 array_pod_sort(RegClasses.begin(), RegClasses.end(), TopoOrderRC);
559 for (unsigned i = 0, e = RegClasses.size(); i != e; ++i)
560 RegClasses[i]->EnumValue = i;
561 CodeGenRegisterClass::computeSubClasses(*this);
564 CodeGenRegister *CodeGenRegBank::getReg(Record *Def) {
565 CodeGenRegister *&Reg = Def2Reg[Def];
568 Reg = new CodeGenRegister(Def, Registers.size() + 1);
569 Registers.push_back(Reg);
573 void CodeGenRegBank::addToMaps(CodeGenRegisterClass *RC) {
574 RegClasses.push_back(RC);
576 if (Record *Def = RC->getDef())
577 Def2RC.insert(std::make_pair(Def, RC));
579 // Duplicate classes are rejected by insert().
580 // That's OK, we only care about the properties handled by CGRC::Key.
581 CodeGenRegisterClass::Key K(*RC);
582 Key2RC.insert(std::make_pair(K, RC));
585 // Create a synthetic sub-class if it is missing.
586 CodeGenRegisterClass*
587 CodeGenRegBank::getOrCreateSubClass(const CodeGenRegisterClass *RC,
588 const CodeGenRegister::Set *Members,
590 // Synthetic sub-class has the same size and alignment as RC.
591 CodeGenRegisterClass::Key K(Members, RC->SpillSize, RC->SpillAlignment);
592 RCKeyMap::const_iterator FoundI = Key2RC.find(K);
593 if (FoundI != Key2RC.end())
594 return FoundI->second;
596 // Sub-class doesn't exist, create a new one.
597 CodeGenRegisterClass *NewRC = new CodeGenRegisterClass(Name, K);
602 CodeGenRegisterClass *CodeGenRegBank::getRegClass(Record *Def) {
603 if (CodeGenRegisterClass *RC = Def2RC[Def])
606 throw TGError(Def->getLoc(), "Not a known RegisterClass!");
609 Record *CodeGenRegBank::getCompositeSubRegIndex(Record *A, Record *B,
611 // Look for an existing entry.
612 Record *&Comp = Composite[std::make_pair(A, B)];
616 // None exists, synthesize one.
617 std::string Name = A->getName() + "_then_" + B->getName();
618 Comp = new Record(Name, SMLoc(), Records);
619 SubRegIndices.push_back(Comp);
623 unsigned CodeGenRegBank::getSubRegIndexNo(Record *idx) {
624 std::vector<Record*>::const_iterator i =
625 std::find(SubRegIndices.begin(), SubRegIndices.end(), idx);
626 assert(i != SubRegIndices.end() && "Not a SubRegIndex");
627 return (i - SubRegIndices.begin()) + 1;
630 void CodeGenRegBank::computeComposites() {
631 for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
632 CodeGenRegister *Reg1 = Registers[i];
633 const CodeGenRegister::SubRegMap &SRM1 = Reg1->getSubRegs();
634 for (CodeGenRegister::SubRegMap::const_iterator i1 = SRM1.begin(),
635 e1 = SRM1.end(); i1 != e1; ++i1) {
636 Record *Idx1 = i1->first;
637 CodeGenRegister *Reg2 = i1->second;
638 // Ignore identity compositions.
641 const CodeGenRegister::SubRegMap &SRM2 = Reg2->getSubRegs();
642 // Try composing Idx1 with another SubRegIndex.
643 for (CodeGenRegister::SubRegMap::const_iterator i2 = SRM2.begin(),
644 e2 = SRM2.end(); i2 != e2; ++i2) {
645 std::pair<Record*, Record*> IdxPair(Idx1, i2->first);
646 CodeGenRegister *Reg3 = i2->second;
647 // Ignore identity compositions.
650 // OK Reg1:IdxPair == Reg3. Find the index with Reg:Idx == Reg3.
651 for (CodeGenRegister::SubRegMap::const_iterator i1d = SRM1.begin(),
652 e1d = SRM1.end(); i1d != e1d; ++i1d) {
653 if (i1d->second == Reg3) {
654 std::pair<CompositeMap::iterator, bool> Ins =
655 Composite.insert(std::make_pair(IdxPair, i1d->first));
656 // Conflicting composition? Emit a warning but allow it.
657 if (!Ins.second && Ins.first->second != i1d->first) {
658 errs() << "Warning: SubRegIndex " << getQualifiedName(Idx1)
659 << " and " << getQualifiedName(IdxPair.second)
660 << " compose ambiguously as "
661 << getQualifiedName(Ins.first->second) << " or "
662 << getQualifiedName(i1d->first) << "\n";
670 // We don't care about the difference between (Idx1, Idx2) -> Idx2 and invalid
671 // compositions, so remove any mappings of that form.
672 for (CompositeMap::iterator i = Composite.begin(), e = Composite.end();
674 CompositeMap::iterator j = i;
676 if (j->first.second == j->second)
681 // Compute sets of overlapping registers.
683 // The standard set is all super-registers and all sub-registers, but the
684 // target description can add arbitrary overlapping registers via the 'Aliases'
685 // field. This complicates things, but we can compute overlapping sets using
686 // the following rules:
688 // 1. The relation overlap(A, B) is reflexive and symmetric but not transitive.
690 // 2. overlap(A, B) implies overlap(A, S) for all S in supers(B).
694 // overlap(A, B) iff there exists:
695 // A' in { A, subregs(A) } and B' in { B, subregs(B) } such that:
696 // A' = B' or A' in aliases(B') or B' in aliases(A').
698 // Here subregs(A) is the full flattened sub-register set returned by
699 // A.getSubRegs() while aliases(A) is simply the special 'Aliases' field in the
700 // description of register A.
702 // This also implies that registers with a common sub-register are considered
703 // overlapping. This can happen when forming register pairs:
709 // In this case, we will infer an overlap between P0 and P1 because of the
710 // shared sub-register R1. There is no overlap between P0 and P2.
712 void CodeGenRegBank::
713 computeOverlaps(std::map<const CodeGenRegister*, CodeGenRegister::Set> &Map) {
716 // Collect overlaps that don't follow from rule 2.
717 for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
718 CodeGenRegister *Reg = Registers[i];
719 CodeGenRegister::Set &Overlaps = Map[Reg];
721 // Reg overlaps itself.
722 Overlaps.insert(Reg);
724 // All super-registers overlap.
725 const CodeGenRegister::SuperRegList &Supers = Reg->getSuperRegs();
726 Overlaps.insert(Supers.begin(), Supers.end());
728 // Form symmetrical relations from the special Aliases[] lists.
729 std::vector<Record*> RegList = Reg->TheDef->getValueAsListOfDefs("Aliases");
730 for (unsigned i2 = 0, e2 = RegList.size(); i2 != e2; ++i2) {
731 CodeGenRegister *Reg2 = getReg(RegList[i2]);
732 CodeGenRegister::Set &Overlaps2 = Map[Reg2];
733 const CodeGenRegister::SuperRegList &Supers2 = Reg2->getSuperRegs();
734 // Reg overlaps Reg2 which implies it overlaps supers(Reg2).
735 Overlaps.insert(Reg2);
736 Overlaps.insert(Supers2.begin(), Supers2.end());
737 Overlaps2.insert(Reg);
738 Overlaps2.insert(Supers.begin(), Supers.end());
742 // Apply rule 2. and inherit all sub-register overlaps.
743 for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
744 CodeGenRegister *Reg = Registers[i];
745 CodeGenRegister::Set &Overlaps = Map[Reg];
746 const CodeGenRegister::SubRegMap &SRM = Reg->getSubRegs();
747 for (CodeGenRegister::SubRegMap::const_iterator i2 = SRM.begin(),
748 e2 = SRM.end(); i2 != e2; ++i2) {
749 CodeGenRegister::Set &Overlaps2 = Map[i2->second];
750 Overlaps.insert(Overlaps2.begin(), Overlaps2.end());
755 void CodeGenRegBank::computeDerivedInfo() {
760 // Synthesize missing register class intersections.
762 // Make sure that sub-classes of RC exists such that getCommonSubClass(RC, X)
763 // returns a maximal register class for all X.
765 void CodeGenRegBank::inferCommonSubClass(CodeGenRegisterClass *RC) {
766 for (unsigned rci = 0, rce = RegClasses.size(); rci != rce; ++rci) {
767 CodeGenRegisterClass *RC1 = RC;
768 CodeGenRegisterClass *RC2 = RegClasses[rci];
772 // Compute the set intersection of RC1 and RC2.
773 const CodeGenRegister::Set &Memb1 = RC1->getMembers();
774 const CodeGenRegister::Set &Memb2 = RC2->getMembers();
775 CodeGenRegister::Set Intersection;
776 std::set_intersection(Memb1.begin(), Memb1.end(),
777 Memb2.begin(), Memb2.end(),
778 std::inserter(Intersection, Intersection.begin()),
779 CodeGenRegister::Less());
781 // Skip disjoint class pairs.
782 if (Intersection.empty())
785 // If RC1 and RC2 have different spill sizes or alignments, use the
786 // larger size for sub-classing. If they are equal, prefer RC1.
787 if (RC2->SpillSize > RC1->SpillSize ||
788 (RC2->SpillSize == RC1->SpillSize &&
789 RC2->SpillAlignment > RC1->SpillAlignment))
792 getOrCreateSubClass(RC1, &Intersection,
793 RC1->getName() + "_and_" + RC2->getName());
798 // Synthesize missing sub-classes for getSubClassWithSubReg().
800 // Make sure that the set of registers in RC with a given SubIdx sub-register
801 // form a register class. Update RC->SubClassWithSubReg.
803 void CodeGenRegBank::inferSubClassWithSubReg(CodeGenRegisterClass *RC) {
804 // Map SubRegIndex to set of registers in RC supporting that SubRegIndex.
805 typedef std::map<Record*, CodeGenRegister::Set, LessRecord> SubReg2SetMap;
807 // Compute the set of registers supporting each SubRegIndex.
808 SubReg2SetMap SRSets;
809 for (CodeGenRegister::Set::const_iterator RI = RC->getMembers().begin(),
810 RE = RC->getMembers().end(); RI != RE; ++RI) {
811 const CodeGenRegister::SubRegMap &SRM = (*RI)->getSubRegs();
812 for (CodeGenRegister::SubRegMap::const_iterator I = SRM.begin(),
813 E = SRM.end(); I != E; ++I)
814 SRSets[I->first].insert(*RI);
817 // Find matching classes for all SRSets entries. Iterate in SubRegIndex
818 // numerical order to visit synthetic indices last.
819 for (unsigned sri = 0, sre = SubRegIndices.size(); sri != sre; ++sri) {
820 Record *SubIdx = SubRegIndices[sri];
821 SubReg2SetMap::const_iterator I = SRSets.find(SubIdx);
822 // Unsupported SubRegIndex. Skip it.
823 if (I == SRSets.end())
825 // In most cases, all RC registers support the SubRegIndex.
826 if (I->second.size() == RC->getMembers().size()) {
827 RC->setSubClassWithSubReg(SubIdx, RC);
830 // This is a real subset. See if we have a matching class.
831 CodeGenRegisterClass *SubRC =
832 getOrCreateSubClass(RC, &I->second,
833 RC->getName() + "_with_" + I->first->getName());
834 RC->setSubClassWithSubReg(SubIdx, SubRC);
839 // Synthesize missing sub-classes of RC for getMatchingSuperRegClass().
841 // Create sub-classes of RC such that getMatchingSuperRegClass(RC, SubIdx, X)
842 // has a maximal result for any SubIdx and any X >= FirstSubRegRC.
845 void CodeGenRegBank::inferMatchingSuperRegClass(CodeGenRegisterClass *RC,
846 unsigned FirstSubRegRC) {
847 SmallVector<std::pair<const CodeGenRegister*,
848 const CodeGenRegister*>, 16> SSPairs;
850 // Iterate in SubRegIndex numerical order to visit synthetic indices last.
851 for (unsigned sri = 0, sre = SubRegIndices.size(); sri != sre; ++sri) {
852 Record *SubIdx = SubRegIndices[sri];
853 // Skip indexes that aren't fully supported by RC's registers. This was
854 // computed by inferSubClassWithSubReg() above which should have been
856 if (RC->getSubClassWithSubReg(SubIdx) != RC)
859 // Build list of (Super, Sub) pairs for this SubIdx.
861 for (CodeGenRegister::Set::const_iterator RI = RC->getMembers().begin(),
862 RE = RC->getMembers().end(); RI != RE; ++RI) {
863 const CodeGenRegister *Super = *RI;
864 const CodeGenRegister *Sub = Super->getSubRegs().find(SubIdx)->second;
865 assert(Sub && "Missing sub-register");
866 SSPairs.push_back(std::make_pair(Super, Sub));
869 // Iterate over sub-register class candidates. Ignore classes created by
870 // this loop. They will never be useful.
871 for (unsigned rci = FirstSubRegRC, rce = RegClasses.size(); rci != rce;
873 CodeGenRegisterClass *SubRC = RegClasses[rci];
874 // Compute the subset of RC that maps into SubRC.
875 CodeGenRegister::Set SubSet;
876 for (unsigned i = 0, e = SSPairs.size(); i != e; ++i)
877 if (SubRC->contains(SSPairs[i].second))
878 SubSet.insert(SSPairs[i].first);
881 // RC injects completely into SubRC.
882 if (SubSet.size() == SSPairs.size())
884 // Only a subset of RC maps into SubRC. Make sure it is represented by a
886 getOrCreateSubClass(RC, &SubSet, RC->getName() +
887 "_with_" + SubIdx->getName() +
888 "_in_" + SubRC->getName());
895 // Infer missing register classes.
897 void CodeGenRegBank::computeInferredRegisterClasses() {
898 // When this function is called, the register classes have not been sorted
899 // and assigned EnumValues yet. That means getSubClasses(),
900 // getSuperClasses(), and hasSubClass() functions are defunct.
901 unsigned FirstNewRC = RegClasses.size();
903 // Visit all register classes, including the ones being added by the loop.
904 for (unsigned rci = 0; rci != RegClasses.size(); ++rci) {
905 CodeGenRegisterClass *RC = RegClasses[rci];
907 // Synthesize answers for getSubClassWithSubReg().
908 inferSubClassWithSubReg(RC);
910 // Synthesize answers for getCommonSubClass().
911 inferCommonSubClass(RC);
913 // Synthesize answers for getMatchingSuperRegClass().
914 inferMatchingSuperRegClass(RC);
916 // New register classes are created while this loop is running, and we need
917 // to visit all of them. I particular, inferMatchingSuperRegClass needs
918 // to match old super-register classes with sub-register classes created
919 // after inferMatchingSuperRegClass was called. At this point,
920 // inferMatchingSuperRegClass has checked SuperRC = [0..rci] with SubRC =
921 // [0..FirstNewRC). We need to cover SubRC = [FirstNewRC..rci].
922 if (rci + 1 == FirstNewRC) {
923 unsigned NextNewRC = RegClasses.size();
924 for (unsigned rci2 = 0; rci2 != FirstNewRC; ++rci2)
925 inferMatchingSuperRegClass(RegClasses[rci2], FirstNewRC);
926 FirstNewRC = NextNewRC;
931 /// getRegisterClassForRegister - Find the register class that contains the
932 /// specified physical register. If the register is not in a register class,
933 /// return null. If the register is in multiple classes, and the classes have a
934 /// superset-subset relationship and the same set of types, return the
935 /// superclass. Otherwise return null.
936 const CodeGenRegisterClass*
937 CodeGenRegBank::getRegClassForRegister(Record *R) {
938 const CodeGenRegister *Reg = getReg(R);
939 ArrayRef<CodeGenRegisterClass*> RCs = getRegClasses();
940 const CodeGenRegisterClass *FoundRC = 0;
941 for (unsigned i = 0, e = RCs.size(); i != e; ++i) {
942 const CodeGenRegisterClass &RC = *RCs[i];
943 if (!RC.contains(Reg))
946 // If this is the first class that contains the register,
947 // make a note of it and go on to the next class.
953 // If a register's classes have different types, return null.
954 if (RC.getValueTypes() != FoundRC->getValueTypes())
957 // Check to see if the previously found class that contains
958 // the register is a subclass of the current class. If so,
959 // prefer the superclass.
960 if (RC.hasSubClass(FoundRC)) {
965 // Check to see if the previously found class that contains
966 // the register is a superclass of the current class. If so,
967 // prefer the superclass.
968 if (FoundRC->hasSubClass(&RC))
971 // Multiple classes, and neither is a superclass of the other.