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 if (RV.getName() == "NAME")
221 // Replace the sub-register list with Tuple.
222 if (RV.getName() == "SubRegs")
223 RV.setValue(ListInit::get(Tuple, RegisterRecTy));
225 // Provide a blank AsmName. MC hacks are required anyway.
226 if (RV.getName() == "AsmName")
227 RV.setValue(BlankName);
229 // CostPerUse is aggregated from all Tuple members.
230 if (RV.getName() == "CostPerUse")
231 RV.setValue(IntInit::get(CostPerUse));
233 // Copy fields from the RegisterTuples def.
234 if (RV.getName() == "SubRegIndices" ||
235 RV.getName() == "CompositeIndices") {
236 NewReg->addValue(*Def->getValue(RV.getName()));
240 // Some fields get their default uninitialized value.
241 if (RV.getName() == "DwarfNumbers" ||
242 RV.getName() == "DwarfAlias" ||
243 RV.getName() == "Aliases") {
244 if (const RecordVal *DefRV = RegisterCl->getValue(RV.getName()))
245 NewReg->addValue(*DefRV);
249 // Everything else is copied from Proto.
250 NewReg->addValue(RV);
257 //===----------------------------------------------------------------------===//
258 // CodeGenRegisterClass
259 //===----------------------------------------------------------------------===//
261 CodeGenRegisterClass::CodeGenRegisterClass(CodeGenRegBank &RegBank, Record *R)
262 : TheDef(R), Name(R->getName()), EnumValue(-1) {
263 // Rename anonymous register classes.
264 if (R->getName().size() > 9 && R->getName()[9] == '.') {
265 static unsigned AnonCounter = 0;
266 R->setName("AnonRegClass_"+utostr(AnonCounter++));
269 std::vector<Record*> TypeList = R->getValueAsListOfDefs("RegTypes");
270 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
271 Record *Type = TypeList[i];
272 if (!Type->isSubClassOf("ValueType"))
273 throw "RegTypes list member '" + Type->getName() +
274 "' does not derive from the ValueType class!";
275 VTs.push_back(getValueType(Type));
277 assert(!VTs.empty() && "RegisterClass must contain at least one ValueType!");
279 // Allocation order 0 is the full set. AltOrders provides others.
280 const SetTheory::RecVec *Elements = RegBank.getSets().expand(R);
281 ListInit *AltOrders = R->getValueAsListInit("AltOrders");
282 Orders.resize(1 + AltOrders->size());
284 // Default allocation order always contains all registers.
285 for (unsigned i = 0, e = Elements->size(); i != e; ++i) {
286 Orders[0].push_back((*Elements)[i]);
287 Members.insert(RegBank.getReg((*Elements)[i]));
290 // Alternative allocation orders may be subsets.
291 SetTheory::RecSet Order;
292 for (unsigned i = 0, e = AltOrders->size(); i != e; ++i) {
293 RegBank.getSets().evaluate(AltOrders->getElement(i), Order);
294 Orders[1 + i].append(Order.begin(), Order.end());
295 // Verify that all altorder members are regclass members.
296 while (!Order.empty()) {
297 CodeGenRegister *Reg = RegBank.getReg(Order.back());
300 throw TGError(R->getLoc(), " AltOrder register " + Reg->getName() +
301 " is not a class member");
305 // SubRegClasses is a list<dag> containing (RC, subregindex, ...) dags.
306 ListInit *SRC = R->getValueAsListInit("SubRegClasses");
307 for (ListInit::const_iterator i = SRC->begin(), e = SRC->end(); i != e; ++i) {
308 DagInit *DAG = dynamic_cast<DagInit*>(*i);
309 if (!DAG) throw "SubRegClasses must contain DAGs";
310 DefInit *DAGOp = dynamic_cast<DefInit*>(DAG->getOperator());
312 if (!DAGOp || !(RCRec = DAGOp->getDef())->isSubClassOf("RegisterClass"))
313 throw "Operator '" + DAG->getOperator()->getAsString() +
314 "' in SubRegClasses is not a RegisterClass";
315 // Iterate over args, all SubRegIndex instances.
316 for (DagInit::const_arg_iterator ai = DAG->arg_begin(), ae = DAG->arg_end();
318 DefInit *Idx = dynamic_cast<DefInit*>(*ai);
320 if (!Idx || !(IdxRec = Idx->getDef())->isSubClassOf("SubRegIndex"))
321 throw "Argument '" + (*ai)->getAsString() +
322 "' in SubRegClasses is not a SubRegIndex";
323 if (!SubRegClasses.insert(std::make_pair(IdxRec, RCRec)).second)
324 throw "SubRegIndex '" + IdxRec->getName() + "' mentioned twice";
328 // Allow targets to override the size in bits of the RegisterClass.
329 unsigned Size = R->getValueAsInt("Size");
331 Namespace = R->getValueAsString("Namespace");
332 SpillSize = Size ? Size : EVT(VTs[0]).getSizeInBits();
333 SpillAlignment = R->getValueAsInt("Alignment");
334 CopyCost = R->getValueAsInt("CopyCost");
335 Allocatable = R->getValueAsBit("isAllocatable");
336 AltOrderSelect = R->getValueAsString("AltOrderSelect");
339 // Create an inferred register class that was missing from the .td files.
340 // Most properties will be inherited from the closest super-class after the
341 // class structure has been computed.
342 CodeGenRegisterClass::CodeGenRegisterClass(StringRef Name, Key Props)
343 : Members(*Props.Members),
347 SpillSize(Props.SpillSize),
348 SpillAlignment(Props.SpillAlignment),
353 // Compute inherited propertied for a synthesized register class.
354 void CodeGenRegisterClass::inheritProperties(CodeGenRegBank &RegBank) {
355 assert(!getDef() && "Only synthesized classes can inherit properties");
356 assert(!SuperClasses.empty() && "Synthesized class without super class");
358 // The last super-class is the smallest one.
359 CodeGenRegisterClass &Super = *SuperClasses.back();
361 // Most properties are copied directly.
362 // Exceptions are members, size, and alignment
363 Namespace = Super.Namespace;
365 CopyCost = Super.CopyCost;
366 Allocatable = Super.Allocatable;
367 AltOrderSelect = Super.AltOrderSelect;
369 // Copy all allocation orders, filter out foreign registers from the larger
371 Orders.resize(Super.Orders.size());
372 for (unsigned i = 0, ie = Super.Orders.size(); i != ie; ++i)
373 for (unsigned j = 0, je = Super.Orders[i].size(); j != je; ++j)
374 if (contains(RegBank.getReg(Super.Orders[i][j])))
375 Orders[i].push_back(Super.Orders[i][j]);
378 bool CodeGenRegisterClass::contains(const CodeGenRegister *Reg) const {
379 return Members.count(Reg);
383 raw_ostream &operator<<(raw_ostream &OS, const CodeGenRegisterClass::Key &K) {
384 OS << "{ S=" << K.SpillSize << ", A=" << K.SpillAlignment;
385 for (CodeGenRegister::Set::const_iterator I = K.Members->begin(),
386 E = K.Members->end(); I != E; ++I)
387 OS << ", " << (*I)->getName();
392 // This is a simple lexicographical order that can be used to search for sets.
393 // It is not the same as the topological order provided by TopoOrderRC.
394 bool CodeGenRegisterClass::Key::
395 operator<(const CodeGenRegisterClass::Key &B) const {
396 assert(Members && B.Members);
397 if (*Members != *B.Members)
398 return *Members < *B.Members;
399 if (SpillSize != B.SpillSize)
400 return SpillSize < B.SpillSize;
401 return SpillAlignment < B.SpillAlignment;
404 // Returns true if RC is a strict subclass.
405 // RC is a sub-class of this class if it is a valid replacement for any
406 // instruction operand where a register of this classis required. It must
407 // satisfy these conditions:
409 // 1. All RC registers are also in this.
410 // 2. The RC spill size must not be smaller than our spill size.
411 // 3. RC spill alignment must be compatible with ours.
413 static bool testSubClass(const CodeGenRegisterClass *A,
414 const CodeGenRegisterClass *B) {
415 return A->SpillAlignment && B->SpillAlignment % A->SpillAlignment == 0 &&
416 A->SpillSize <= B->SpillSize &&
417 std::includes(A->getMembers().begin(), A->getMembers().end(),
418 B->getMembers().begin(), B->getMembers().end(),
419 CodeGenRegister::Less());
422 /// Sorting predicate for register classes. This provides a topological
423 /// ordering that arranges all register classes before their sub-classes.
425 /// Register classes with the same registers, spill size, and alignment form a
426 /// clique. They will be ordered alphabetically.
428 static int TopoOrderRC(const void *PA, const void *PB) {
429 const CodeGenRegisterClass *A = *(const CodeGenRegisterClass* const*)PA;
430 const CodeGenRegisterClass *B = *(const CodeGenRegisterClass* const*)PB;
434 // Order by descending set size. Note that the classes' allocation order may
435 // not have been computed yet. The Members set is always vaild.
436 if (A->getMembers().size() > B->getMembers().size())
438 if (A->getMembers().size() < B->getMembers().size())
441 // Order by ascending spill size.
442 if (A->SpillSize < B->SpillSize)
444 if (A->SpillSize > B->SpillSize)
447 // Order by ascending spill alignment.
448 if (A->SpillAlignment < B->SpillAlignment)
450 if (A->SpillAlignment > B->SpillAlignment)
453 // Finally order by name as a tie breaker.
454 return A->getName() < B->getName();
457 std::string CodeGenRegisterClass::getQualifiedName() const {
458 if (Namespace.empty())
461 return Namespace + "::" + getName();
464 // Compute sub-classes of all register classes.
465 // Assume the classes are ordered topologically.
466 void CodeGenRegisterClass::computeSubClasses(CodeGenRegBank &RegBank) {
467 ArrayRef<CodeGenRegisterClass*> RegClasses = RegBank.getRegClasses();
469 // Visit backwards so sub-classes are seen first.
470 for (unsigned rci = RegClasses.size(); rci; --rci) {
471 CodeGenRegisterClass &RC = *RegClasses[rci - 1];
472 RC.SubClasses.resize(RegClasses.size());
473 RC.SubClasses.set(RC.EnumValue);
475 // Normally, all subclasses have IDs >= rci, unless RC is part of a clique.
476 for (unsigned s = rci; s != RegClasses.size(); ++s) {
477 if (RC.SubClasses.test(s))
479 CodeGenRegisterClass *SubRC = RegClasses[s];
480 if (!testSubClass(&RC, SubRC))
482 // SubRC is a sub-class. Grap all its sub-classes so we won't have to
484 RC.SubClasses |= SubRC->SubClasses;
487 // Sweep up missed clique members. They will be immediately preceeding RC.
488 for (unsigned s = rci - 1; s && testSubClass(&RC, RegClasses[s - 1]); --s)
489 RC.SubClasses.set(s - 1);
492 // Compute the SuperClasses lists from the SubClasses vectors.
493 for (unsigned rci = 0; rci != RegClasses.size(); ++rci) {
494 const BitVector &SC = RegClasses[rci]->getSubClasses();
495 for (int s = SC.find_first(); s >= 0; s = SC.find_next(s)) {
496 if (unsigned(s) == rci)
498 RegClasses[s]->SuperClasses.push_back(RegClasses[rci]);
502 // With the class hierarchy in place, let synthesized register classes inherit
503 // properties from their closest super-class. The iteration order here can
504 // propagate properties down multiple levels.
505 for (unsigned rci = 0; rci != RegClasses.size(); ++rci)
506 if (!RegClasses[rci]->getDef())
507 RegClasses[rci]->inheritProperties(RegBank);
511 CodeGenRegisterClass::getSuperRegClasses(Record *SubIdx, BitVector &Out) const {
512 DenseMap<Record*, SmallPtrSet<CodeGenRegisterClass*, 8> >::const_iterator
513 FindI = SuperRegClasses.find(SubIdx);
514 if (FindI == SuperRegClasses.end())
516 for (SmallPtrSet<CodeGenRegisterClass*, 8>::const_iterator I =
517 FindI->second.begin(), E = FindI->second.end(); I != E; ++I)
518 Out.set((*I)->EnumValue);
522 //===----------------------------------------------------------------------===//
524 //===----------------------------------------------------------------------===//
526 CodeGenRegBank::CodeGenRegBank(RecordKeeper &Records) : Records(Records) {
527 // Configure register Sets to understand register classes and tuples.
528 Sets.addFieldExpander("RegisterClass", "MemberList");
529 Sets.addExpander("RegisterTuples", new TupleExpander());
531 // Read in the user-defined (named) sub-register indices.
532 // More indices will be synthesized later.
533 SubRegIndices = Records.getAllDerivedDefinitions("SubRegIndex");
534 std::sort(SubRegIndices.begin(), SubRegIndices.end(), LessRecord());
535 NumNamedIndices = SubRegIndices.size();
537 // Read in the register definitions.
538 std::vector<Record*> Regs = Records.getAllDerivedDefinitions("Register");
539 std::sort(Regs.begin(), Regs.end(), LessRecord());
540 Registers.reserve(Regs.size());
541 // Assign the enumeration values.
542 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
545 // Expand tuples and number the new registers.
546 std::vector<Record*> Tups =
547 Records.getAllDerivedDefinitions("RegisterTuples");
548 for (unsigned i = 0, e = Tups.size(); i != e; ++i) {
549 const std::vector<Record*> *TupRegs = Sets.expand(Tups[i]);
550 for (unsigned j = 0, je = TupRegs->size(); j != je; ++j)
551 getReg((*TupRegs)[j]);
554 // Precompute all sub-register maps now all the registers are known.
555 // This will create Composite entries for all inferred sub-register indices.
556 for (unsigned i = 0, e = Registers.size(); i != e; ++i)
557 Registers[i]->getSubRegs(*this);
559 // Read in register class definitions.
560 std::vector<Record*> RCs = Records.getAllDerivedDefinitions("RegisterClass");
562 throw std::string("No 'RegisterClass' subclasses defined!");
564 // Allocate user-defined register classes.
565 RegClasses.reserve(RCs.size());
566 for (unsigned i = 0, e = RCs.size(); i != e; ++i)
567 addToMaps(new CodeGenRegisterClass(*this, RCs[i]));
569 // Infer missing classes to create a full algebra.
570 computeInferredRegisterClasses();
572 // Order register classes topologically and assign enum values.
573 array_pod_sort(RegClasses.begin(), RegClasses.end(), TopoOrderRC);
574 for (unsigned i = 0, e = RegClasses.size(); i != e; ++i)
575 RegClasses[i]->EnumValue = i;
576 CodeGenRegisterClass::computeSubClasses(*this);
579 CodeGenRegister *CodeGenRegBank::getReg(Record *Def) {
580 CodeGenRegister *&Reg = Def2Reg[Def];
583 Reg = new CodeGenRegister(Def, Registers.size() + 1);
584 Registers.push_back(Reg);
588 void CodeGenRegBank::addToMaps(CodeGenRegisterClass *RC) {
589 RegClasses.push_back(RC);
591 if (Record *Def = RC->getDef())
592 Def2RC.insert(std::make_pair(Def, RC));
594 // Duplicate classes are rejected by insert().
595 // That's OK, we only care about the properties handled by CGRC::Key.
596 CodeGenRegisterClass::Key K(*RC);
597 Key2RC.insert(std::make_pair(K, RC));
600 // Create a synthetic sub-class if it is missing.
601 CodeGenRegisterClass*
602 CodeGenRegBank::getOrCreateSubClass(const CodeGenRegisterClass *RC,
603 const CodeGenRegister::Set *Members,
605 // Synthetic sub-class has the same size and alignment as RC.
606 CodeGenRegisterClass::Key K(Members, RC->SpillSize, RC->SpillAlignment);
607 RCKeyMap::const_iterator FoundI = Key2RC.find(K);
608 if (FoundI != Key2RC.end())
609 return FoundI->second;
611 // Sub-class doesn't exist, create a new one.
612 CodeGenRegisterClass *NewRC = new CodeGenRegisterClass(Name, K);
617 CodeGenRegisterClass *CodeGenRegBank::getRegClass(Record *Def) {
618 if (CodeGenRegisterClass *RC = Def2RC[Def])
621 throw TGError(Def->getLoc(), "Not a known RegisterClass!");
624 Record *CodeGenRegBank::getCompositeSubRegIndex(Record *A, Record *B,
626 // Look for an existing entry.
627 Record *&Comp = Composite[std::make_pair(A, B)];
631 // None exists, synthesize one.
632 std::string Name = A->getName() + "_then_" + B->getName();
633 Comp = new Record(Name, SMLoc(), Records);
634 SubRegIndices.push_back(Comp);
638 unsigned CodeGenRegBank::getSubRegIndexNo(Record *idx) {
639 std::vector<Record*>::const_iterator i =
640 std::find(SubRegIndices.begin(), SubRegIndices.end(), idx);
641 assert(i != SubRegIndices.end() && "Not a SubRegIndex");
642 return (i - SubRegIndices.begin()) + 1;
645 void CodeGenRegBank::computeComposites() {
646 for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
647 CodeGenRegister *Reg1 = Registers[i];
648 const CodeGenRegister::SubRegMap &SRM1 = Reg1->getSubRegs();
649 for (CodeGenRegister::SubRegMap::const_iterator i1 = SRM1.begin(),
650 e1 = SRM1.end(); i1 != e1; ++i1) {
651 Record *Idx1 = i1->first;
652 CodeGenRegister *Reg2 = i1->second;
653 // Ignore identity compositions.
656 const CodeGenRegister::SubRegMap &SRM2 = Reg2->getSubRegs();
657 // Try composing Idx1 with another SubRegIndex.
658 for (CodeGenRegister::SubRegMap::const_iterator i2 = SRM2.begin(),
659 e2 = SRM2.end(); i2 != e2; ++i2) {
660 std::pair<Record*, Record*> IdxPair(Idx1, i2->first);
661 CodeGenRegister *Reg3 = i2->second;
662 // Ignore identity compositions.
665 // OK Reg1:IdxPair == Reg3. Find the index with Reg:Idx == Reg3.
666 for (CodeGenRegister::SubRegMap::const_iterator i1d = SRM1.begin(),
667 e1d = SRM1.end(); i1d != e1d; ++i1d) {
668 if (i1d->second == Reg3) {
669 std::pair<CompositeMap::iterator, bool> Ins =
670 Composite.insert(std::make_pair(IdxPair, i1d->first));
671 // Conflicting composition? Emit a warning but allow it.
672 if (!Ins.second && Ins.first->second != i1d->first) {
673 errs() << "Warning: SubRegIndex " << getQualifiedName(Idx1)
674 << " and " << getQualifiedName(IdxPair.second)
675 << " compose ambiguously as "
676 << getQualifiedName(Ins.first->second) << " or "
677 << getQualifiedName(i1d->first) << "\n";
685 // We don't care about the difference between (Idx1, Idx2) -> Idx2 and invalid
686 // compositions, so remove any mappings of that form.
687 for (CompositeMap::iterator i = Composite.begin(), e = Composite.end();
689 CompositeMap::iterator j = i;
691 if (j->first.second == j->second)
696 // Compute sets of overlapping registers.
698 // The standard set is all super-registers and all sub-registers, but the
699 // target description can add arbitrary overlapping registers via the 'Aliases'
700 // field. This complicates things, but we can compute overlapping sets using
701 // the following rules:
703 // 1. The relation overlap(A, B) is reflexive and symmetric but not transitive.
705 // 2. overlap(A, B) implies overlap(A, S) for all S in supers(B).
709 // overlap(A, B) iff there exists:
710 // A' in { A, subregs(A) } and B' in { B, subregs(B) } such that:
711 // A' = B' or A' in aliases(B') or B' in aliases(A').
713 // Here subregs(A) is the full flattened sub-register set returned by
714 // A.getSubRegs() while aliases(A) is simply the special 'Aliases' field in the
715 // description of register A.
717 // This also implies that registers with a common sub-register are considered
718 // overlapping. This can happen when forming register pairs:
724 // In this case, we will infer an overlap between P0 and P1 because of the
725 // shared sub-register R1. There is no overlap between P0 and P2.
727 void CodeGenRegBank::
728 computeOverlaps(std::map<const CodeGenRegister*, CodeGenRegister::Set> &Map) {
731 // Collect overlaps that don't follow from rule 2.
732 for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
733 CodeGenRegister *Reg = Registers[i];
734 CodeGenRegister::Set &Overlaps = Map[Reg];
736 // Reg overlaps itself.
737 Overlaps.insert(Reg);
739 // All super-registers overlap.
740 const CodeGenRegister::SuperRegList &Supers = Reg->getSuperRegs();
741 Overlaps.insert(Supers.begin(), Supers.end());
743 // Form symmetrical relations from the special Aliases[] lists.
744 std::vector<Record*> RegList = Reg->TheDef->getValueAsListOfDefs("Aliases");
745 for (unsigned i2 = 0, e2 = RegList.size(); i2 != e2; ++i2) {
746 CodeGenRegister *Reg2 = getReg(RegList[i2]);
747 CodeGenRegister::Set &Overlaps2 = Map[Reg2];
748 const CodeGenRegister::SuperRegList &Supers2 = Reg2->getSuperRegs();
749 // Reg overlaps Reg2 which implies it overlaps supers(Reg2).
750 Overlaps.insert(Reg2);
751 Overlaps.insert(Supers2.begin(), Supers2.end());
752 Overlaps2.insert(Reg);
753 Overlaps2.insert(Supers.begin(), Supers.end());
757 // Apply rule 2. and inherit all sub-register overlaps.
758 for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
759 CodeGenRegister *Reg = Registers[i];
760 CodeGenRegister::Set &Overlaps = Map[Reg];
761 const CodeGenRegister::SubRegMap &SRM = Reg->getSubRegs();
762 for (CodeGenRegister::SubRegMap::const_iterator i2 = SRM.begin(),
763 e2 = SRM.end(); i2 != e2; ++i2) {
764 CodeGenRegister::Set &Overlaps2 = Map[i2->second];
765 Overlaps.insert(Overlaps2.begin(), Overlaps2.end());
770 void CodeGenRegBank::computeDerivedInfo() {
775 // Synthesize missing register class intersections.
777 // Make sure that sub-classes of RC exists such that getCommonSubClass(RC, X)
778 // returns a maximal register class for all X.
780 void CodeGenRegBank::inferCommonSubClass(CodeGenRegisterClass *RC) {
781 for (unsigned rci = 0, rce = RegClasses.size(); rci != rce; ++rci) {
782 CodeGenRegisterClass *RC1 = RC;
783 CodeGenRegisterClass *RC2 = RegClasses[rci];
787 // Compute the set intersection of RC1 and RC2.
788 const CodeGenRegister::Set &Memb1 = RC1->getMembers();
789 const CodeGenRegister::Set &Memb2 = RC2->getMembers();
790 CodeGenRegister::Set Intersection;
791 std::set_intersection(Memb1.begin(), Memb1.end(),
792 Memb2.begin(), Memb2.end(),
793 std::inserter(Intersection, Intersection.begin()),
794 CodeGenRegister::Less());
796 // Skip disjoint class pairs.
797 if (Intersection.empty())
800 // If RC1 and RC2 have different spill sizes or alignments, use the
801 // larger size for sub-classing. If they are equal, prefer RC1.
802 if (RC2->SpillSize > RC1->SpillSize ||
803 (RC2->SpillSize == RC1->SpillSize &&
804 RC2->SpillAlignment > RC1->SpillAlignment))
807 getOrCreateSubClass(RC1, &Intersection,
808 RC1->getName() + "_and_" + RC2->getName());
813 // Synthesize missing sub-classes for getSubClassWithSubReg().
815 // Make sure that the set of registers in RC with a given SubIdx sub-register
816 // form a register class. Update RC->SubClassWithSubReg.
818 void CodeGenRegBank::inferSubClassWithSubReg(CodeGenRegisterClass *RC) {
819 // Map SubRegIndex to set of registers in RC supporting that SubRegIndex.
820 typedef std::map<Record*, CodeGenRegister::Set, LessRecord> SubReg2SetMap;
822 // Compute the set of registers supporting each SubRegIndex.
823 SubReg2SetMap SRSets;
824 for (CodeGenRegister::Set::const_iterator RI = RC->getMembers().begin(),
825 RE = RC->getMembers().end(); RI != RE; ++RI) {
826 const CodeGenRegister::SubRegMap &SRM = (*RI)->getSubRegs();
827 for (CodeGenRegister::SubRegMap::const_iterator I = SRM.begin(),
828 E = SRM.end(); I != E; ++I)
829 SRSets[I->first].insert(*RI);
832 // Find matching classes for all SRSets entries. Iterate in SubRegIndex
833 // numerical order to visit synthetic indices last.
834 for (unsigned sri = 0, sre = SubRegIndices.size(); sri != sre; ++sri) {
835 Record *SubIdx = SubRegIndices[sri];
836 SubReg2SetMap::const_iterator I = SRSets.find(SubIdx);
837 // Unsupported SubRegIndex. Skip it.
838 if (I == SRSets.end())
840 // In most cases, all RC registers support the SubRegIndex.
841 if (I->second.size() == RC->getMembers().size()) {
842 RC->setSubClassWithSubReg(SubIdx, RC);
845 // This is a real subset. See if we have a matching class.
846 CodeGenRegisterClass *SubRC =
847 getOrCreateSubClass(RC, &I->second,
848 RC->getName() + "_with_" + I->first->getName());
849 RC->setSubClassWithSubReg(SubIdx, SubRC);
854 // Synthesize missing sub-classes of RC for getMatchingSuperRegClass().
856 // Create sub-classes of RC such that getMatchingSuperRegClass(RC, SubIdx, X)
857 // has a maximal result for any SubIdx and any X >= FirstSubRegRC.
860 void CodeGenRegBank::inferMatchingSuperRegClass(CodeGenRegisterClass *RC,
861 unsigned FirstSubRegRC) {
862 SmallVector<std::pair<const CodeGenRegister*,
863 const CodeGenRegister*>, 16> SSPairs;
865 // Iterate in SubRegIndex numerical order to visit synthetic indices last.
866 for (unsigned sri = 0, sre = SubRegIndices.size(); sri != sre; ++sri) {
867 Record *SubIdx = SubRegIndices[sri];
868 // Skip indexes that aren't fully supported by RC's registers. This was
869 // computed by inferSubClassWithSubReg() above which should have been
871 if (RC->getSubClassWithSubReg(SubIdx) != RC)
874 // Build list of (Super, Sub) pairs for this SubIdx.
876 for (CodeGenRegister::Set::const_iterator RI = RC->getMembers().begin(),
877 RE = RC->getMembers().end(); RI != RE; ++RI) {
878 const CodeGenRegister *Super = *RI;
879 const CodeGenRegister *Sub = Super->getSubRegs().find(SubIdx)->second;
880 assert(Sub && "Missing sub-register");
881 SSPairs.push_back(std::make_pair(Super, Sub));
884 // Iterate over sub-register class candidates. Ignore classes created by
885 // this loop. They will never be useful.
886 for (unsigned rci = FirstSubRegRC, rce = RegClasses.size(); rci != rce;
888 CodeGenRegisterClass *SubRC = RegClasses[rci];
889 // Compute the subset of RC that maps into SubRC.
890 CodeGenRegister::Set SubSet;
891 for (unsigned i = 0, e = SSPairs.size(); i != e; ++i)
892 if (SubRC->contains(SSPairs[i].second))
893 SubSet.insert(SSPairs[i].first);
896 // RC injects completely into SubRC.
897 if (SubSet.size() == SSPairs.size()) {
898 SubRC->addSuperRegClass(SubIdx, RC);
901 // Only a subset of RC maps into SubRC. Make sure it is represented by a
903 getOrCreateSubClass(RC, &SubSet, RC->getName() +
904 "_with_" + SubIdx->getName() +
905 "_in_" + SubRC->getName());
912 // Infer missing register classes.
914 void CodeGenRegBank::computeInferredRegisterClasses() {
915 // When this function is called, the register classes have not been sorted
916 // and assigned EnumValues yet. That means getSubClasses(),
917 // getSuperClasses(), and hasSubClass() functions are defunct.
918 unsigned FirstNewRC = RegClasses.size();
920 // Visit all register classes, including the ones being added by the loop.
921 for (unsigned rci = 0; rci != RegClasses.size(); ++rci) {
922 CodeGenRegisterClass *RC = RegClasses[rci];
924 // Synthesize answers for getSubClassWithSubReg().
925 inferSubClassWithSubReg(RC);
927 // Synthesize answers for getCommonSubClass().
928 inferCommonSubClass(RC);
930 // Synthesize answers for getMatchingSuperRegClass().
931 inferMatchingSuperRegClass(RC);
933 // New register classes are created while this loop is running, and we need
934 // to visit all of them. I particular, inferMatchingSuperRegClass needs
935 // to match old super-register classes with sub-register classes created
936 // after inferMatchingSuperRegClass was called. At this point,
937 // inferMatchingSuperRegClass has checked SuperRC = [0..rci] with SubRC =
938 // [0..FirstNewRC). We need to cover SubRC = [FirstNewRC..rci].
939 if (rci + 1 == FirstNewRC) {
940 unsigned NextNewRC = RegClasses.size();
941 for (unsigned rci2 = 0; rci2 != FirstNewRC; ++rci2)
942 inferMatchingSuperRegClass(RegClasses[rci2], FirstNewRC);
943 FirstNewRC = NextNewRC;
948 /// getRegisterClassForRegister - Find the register class that contains the
949 /// specified physical register. If the register is not in a register class,
950 /// return null. If the register is in multiple classes, and the classes have a
951 /// superset-subset relationship and the same set of types, return the
952 /// superclass. Otherwise return null.
953 const CodeGenRegisterClass*
954 CodeGenRegBank::getRegClassForRegister(Record *R) {
955 const CodeGenRegister *Reg = getReg(R);
956 ArrayRef<CodeGenRegisterClass*> RCs = getRegClasses();
957 const CodeGenRegisterClass *FoundRC = 0;
958 for (unsigned i = 0, e = RCs.size(); i != e; ++i) {
959 const CodeGenRegisterClass &RC = *RCs[i];
960 if (!RC.contains(Reg))
963 // If this is the first class that contains the register,
964 // make a note of it and go on to the next class.
970 // If a register's classes have different types, return null.
971 if (RC.getValueTypes() != FoundRC->getValueTypes())
974 // Check to see if the previously found class that contains
975 // the register is a subclass of the current class. If so,
976 // prefer the superclass.
977 if (RC.hasSubClass(FoundRC)) {
982 // Check to see if the previously found class that contains
983 // the register is a superclass of the current class. If so,
984 // prefer the superclass.
985 if (FoundRC->hasSubClass(&RC))
988 // Multiple classes, and neither is a superclass of the other.