7c6661742aacc13e90639e2db7d83929b7b15de7
[oota-llvm.git] / utils / TableGen / CodeGenRegisters.cpp
1 //===- CodeGenRegisters.cpp - Register and RegisterClass Info -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines structures to encapsulate information gleaned from the
11 // target register and register class definitions.
12 //
13 //===----------------------------------------------------------------------===//
14
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"
21
22 using namespace llvm;
23
24 //===----------------------------------------------------------------------===//
25 //                             CodeGenSubRegIndex
26 //===----------------------------------------------------------------------===//
27
28 CodeGenSubRegIndex::CodeGenSubRegIndex(Record *R, unsigned Enum)
29   : TheDef(R),
30     EnumValue(Enum)
31 {}
32
33 std::string CodeGenSubRegIndex::getNamespace() const {
34   if (TheDef->getValue("Namespace"))
35     return TheDef->getValueAsString("Namespace");
36   else
37     return "";
38 }
39
40 const std::string &CodeGenSubRegIndex::getName() const {
41   return TheDef->getName();
42 }
43
44 std::string CodeGenSubRegIndex::getQualifiedName() const {
45   std::string N = getNamespace();
46   if (!N.empty())
47     N += "::";
48   N += getName();
49   return N;
50 }
51
52 void CodeGenSubRegIndex::cleanComposites() {
53   // Clean out redundant mappings of the form this+X -> X.
54   for (CompMap::iterator i = Composed.begin(), e = Composed.end(); i != e;) {
55     CompMap::iterator j = i;
56     ++i;
57     if (j->first == j->second)
58       Composed.erase(j);
59   }
60 }
61
62 //===----------------------------------------------------------------------===//
63 //                              CodeGenRegister
64 //===----------------------------------------------------------------------===//
65
66 CodeGenRegister::CodeGenRegister(Record *R, unsigned Enum)
67   : TheDef(R),
68     EnumValue(Enum),
69     CostPerUse(R->getValueAsInt("CostPerUse")),
70     CoveredBySubRegs(R->getValueAsBit("CoveredBySubRegs")),
71     SubRegsComplete(false)
72 {}
73
74 const std::string &CodeGenRegister::getName() const {
75   return TheDef->getName();
76 }
77
78 namespace {
79   struct Orphan {
80     CodeGenRegister *SubReg;
81     CodeGenSubRegIndex *First, *Second;
82     Orphan(CodeGenRegister *r, CodeGenSubRegIndex *a, CodeGenSubRegIndex *b)
83       : SubReg(r), First(a), Second(b) {}
84   };
85 }
86
87 const CodeGenRegister::SubRegMap &
88 CodeGenRegister::getSubRegs(CodeGenRegBank &RegBank) {
89   // Only compute this map once.
90   if (SubRegsComplete)
91     return SubRegs;
92   SubRegsComplete = true;
93
94   std::vector<Record*> SubList = TheDef->getValueAsListOfDefs("SubRegs");
95   std::vector<Record*> Indices = TheDef->getValueAsListOfDefs("SubRegIndices");
96   if (SubList.size() != Indices.size())
97     throw TGError(TheDef->getLoc(), "Register " + getName() +
98                   " SubRegIndices doesn't match SubRegs");
99
100   // First insert the direct subregs and make sure they are fully indexed.
101   for (unsigned i = 0, e = SubList.size(); i != e; ++i) {
102     CodeGenRegister *SR = RegBank.getReg(SubList[i]);
103     CodeGenSubRegIndex *Idx = RegBank.getSubRegIdx(Indices[i]);
104     if (!SubRegs.insert(std::make_pair(Idx, SR)).second)
105       throw TGError(TheDef->getLoc(), "SubRegIndex " + Idx->getName() +
106                     " appears twice in Register " + getName());
107   }
108
109   // Keep track of inherited subregs and how they can be reached.
110   SmallVector<Orphan, 8> Orphans;
111
112   // Clone inherited subregs and place duplicate entries on Orphans.
113   // Here the order is important - earlier subregs take precedence.
114   for (unsigned i = 0, e = SubList.size(); i != e; ++i) {
115     CodeGenRegister *SR = RegBank.getReg(SubList[i]);
116     CodeGenSubRegIndex *Idx = RegBank.getSubRegIdx(Indices[i]);
117     const SubRegMap &Map = SR->getSubRegs(RegBank);
118
119     // Add this as a super-register of SR now all sub-registers are in the list.
120     // This creates a topological ordering, the exact order depends on the
121     // order getSubRegs is called on all registers.
122     SR->SuperRegs.push_back(this);
123
124     for (SubRegMap::const_iterator SI = Map.begin(), SE = Map.end(); SI != SE;
125          ++SI) {
126       if (!SubRegs.insert(*SI).second)
127         Orphans.push_back(Orphan(SI->second, Idx, SI->first));
128
129       // Noop sub-register indexes are possible, so avoid duplicates.
130       if (SI->second != SR)
131         SI->second->SuperRegs.push_back(this);
132     }
133   }
134
135   // Process the composites.
136   ListInit *Comps = TheDef->getValueAsListInit("CompositeIndices");
137   for (unsigned i = 0, e = Comps->size(); i != e; ++i) {
138     DagInit *Pat = dynamic_cast<DagInit*>(Comps->getElement(i));
139     if (!Pat)
140       throw TGError(TheDef->getLoc(), "Invalid dag '" +
141                     Comps->getElement(i)->getAsString() +
142                     "' in CompositeIndices");
143     DefInit *BaseIdxInit = dynamic_cast<DefInit*>(Pat->getOperator());
144     if (!BaseIdxInit || !BaseIdxInit->getDef()->isSubClassOf("SubRegIndex"))
145       throw TGError(TheDef->getLoc(), "Invalid SubClassIndex in " +
146                     Pat->getAsString());
147     CodeGenSubRegIndex *BaseIdx = RegBank.getSubRegIdx(BaseIdxInit->getDef());
148
149     // Resolve list of subreg indices into R2.
150     CodeGenRegister *R2 = this;
151     for (DagInit::const_arg_iterator di = Pat->arg_begin(),
152          de = Pat->arg_end(); di != de; ++di) {
153       DefInit *IdxInit = dynamic_cast<DefInit*>(*di);
154       if (!IdxInit || !IdxInit->getDef()->isSubClassOf("SubRegIndex"))
155         throw TGError(TheDef->getLoc(), "Invalid SubClassIndex in " +
156                       Pat->getAsString());
157       CodeGenSubRegIndex *Idx = RegBank.getSubRegIdx(IdxInit->getDef());
158       const SubRegMap &R2Subs = R2->getSubRegs(RegBank);
159       SubRegMap::const_iterator ni = R2Subs.find(Idx);
160       if (ni == R2Subs.end())
161         throw TGError(TheDef->getLoc(), "Composite " + Pat->getAsString() +
162                       " refers to bad index in " + R2->getName());
163       R2 = ni->second;
164     }
165
166     // Insert composite index. Allow overriding inherited indices etc.
167     SubRegs[BaseIdx] = R2;
168
169     // R2 is no longer an orphan.
170     for (unsigned j = 0, je = Orphans.size(); j != je; ++j)
171       if (Orphans[j].SubReg == R2)
172           Orphans[j].SubReg = 0;
173   }
174
175   // Now Orphans contains the inherited subregisters without a direct index.
176   // Create inferred indexes for all missing entries.
177   for (unsigned i = 0, e = Orphans.size(); i != e; ++i) {
178     Orphan &O = Orphans[i];
179     if (!O.SubReg)
180       continue;
181     SubRegs[RegBank.getCompositeSubRegIndex(O.First, O.Second)] =
182       O.SubReg;
183   }
184   return SubRegs;
185 }
186
187 void
188 CodeGenRegister::addSubRegsPreOrder(SetVector<CodeGenRegister*> &OSet,
189                                     CodeGenRegBank &RegBank) const {
190   assert(SubRegsComplete && "Must precompute sub-registers");
191   std::vector<Record*> Indices = TheDef->getValueAsListOfDefs("SubRegIndices");
192   for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
193     CodeGenSubRegIndex *Idx = RegBank.getSubRegIdx(Indices[i]);
194     CodeGenRegister *SR = SubRegs.find(Idx)->second;
195     if (OSet.insert(SR))
196       SR->addSubRegsPreOrder(OSet, RegBank);
197   }
198 }
199
200 //===----------------------------------------------------------------------===//
201 //                               RegisterTuples
202 //===----------------------------------------------------------------------===//
203
204 // A RegisterTuples def is used to generate pseudo-registers from lists of
205 // sub-registers. We provide a SetTheory expander class that returns the new
206 // registers.
207 namespace {
208 struct TupleExpander : SetTheory::Expander {
209   void expand(SetTheory &ST, Record *Def, SetTheory::RecSet &Elts) {
210     std::vector<Record*> Indices = Def->getValueAsListOfDefs("SubRegIndices");
211     unsigned Dim = Indices.size();
212     ListInit *SubRegs = Def->getValueAsListInit("SubRegs");
213     if (Dim != SubRegs->getSize())
214       throw TGError(Def->getLoc(), "SubRegIndices and SubRegs size mismatch");
215     if (Dim < 2)
216       throw TGError(Def->getLoc(), "Tuples must have at least 2 sub-registers");
217
218     // Evaluate the sub-register lists to be zipped.
219     unsigned Length = ~0u;
220     SmallVector<SetTheory::RecSet, 4> Lists(Dim);
221     for (unsigned i = 0; i != Dim; ++i) {
222       ST.evaluate(SubRegs->getElement(i), Lists[i]);
223       Length = std::min(Length, unsigned(Lists[i].size()));
224     }
225
226     if (Length == 0)
227       return;
228
229     // Precompute some types.
230     Record *RegisterCl = Def->getRecords().getClass("Register");
231     RecTy *RegisterRecTy = RecordRecTy::get(RegisterCl);
232     StringInit *BlankName = StringInit::get("");
233
234     // Zip them up.
235     for (unsigned n = 0; n != Length; ++n) {
236       std::string Name;
237       Record *Proto = Lists[0][n];
238       std::vector<Init*> Tuple;
239       unsigned CostPerUse = 0;
240       for (unsigned i = 0; i != Dim; ++i) {
241         Record *Reg = Lists[i][n];
242         if (i) Name += '_';
243         Name += Reg->getName();
244         Tuple.push_back(DefInit::get(Reg));
245         CostPerUse = std::max(CostPerUse,
246                               unsigned(Reg->getValueAsInt("CostPerUse")));
247       }
248
249       // Create a new Record representing the synthesized register. This record
250       // is only for consumption by CodeGenRegister, it is not added to the
251       // RecordKeeper.
252       Record *NewReg = new Record(Name, Def->getLoc(), Def->getRecords());
253       Elts.insert(NewReg);
254
255       // Copy Proto super-classes.
256       for (unsigned i = 0, e = Proto->getSuperClasses().size(); i != e; ++i)
257         NewReg->addSuperClass(Proto->getSuperClasses()[i]);
258
259       // Copy Proto fields.
260       for (unsigned i = 0, e = Proto->getValues().size(); i != e; ++i) {
261         RecordVal RV = Proto->getValues()[i];
262
263         // Skip existing fields, like NAME.
264         if (NewReg->getValue(RV.getNameInit()))
265           continue;
266
267         StringRef Field = RV.getName();
268
269         // Replace the sub-register list with Tuple.
270         if (Field == "SubRegs")
271           RV.setValue(ListInit::get(Tuple, RegisterRecTy));
272
273         // Provide a blank AsmName. MC hacks are required anyway.
274         if (Field == "AsmName")
275           RV.setValue(BlankName);
276
277         // CostPerUse is aggregated from all Tuple members.
278         if (Field == "CostPerUse")
279           RV.setValue(IntInit::get(CostPerUse));
280
281         // Composite registers are always covered by sub-registers.
282         if (Field == "CoveredBySubRegs")
283           RV.setValue(BitInit::get(true));
284
285         // Copy fields from the RegisterTuples def.
286         if (Field == "SubRegIndices" ||
287             Field == "CompositeIndices") {
288           NewReg->addValue(*Def->getValue(Field));
289           continue;
290         }
291
292         // Some fields get their default uninitialized value.
293         if (Field == "DwarfNumbers" ||
294             Field == "DwarfAlias" ||
295             Field == "Aliases") {
296           if (const RecordVal *DefRV = RegisterCl->getValue(Field))
297             NewReg->addValue(*DefRV);
298           continue;
299         }
300
301         // Everything else is copied from Proto.
302         NewReg->addValue(RV);
303       }
304     }
305   }
306 };
307 }
308
309 //===----------------------------------------------------------------------===//
310 //                            CodeGenRegisterClass
311 //===----------------------------------------------------------------------===//
312
313 CodeGenRegisterClass::CodeGenRegisterClass(CodeGenRegBank &RegBank, Record *R)
314   : TheDef(R), Name(R->getName()), EnumValue(-1) {
315   // Rename anonymous register classes.
316   if (R->getName().size() > 9 && R->getName()[9] == '.') {
317     static unsigned AnonCounter = 0;
318     R->setName("AnonRegClass_"+utostr(AnonCounter++));
319   }
320
321   std::vector<Record*> TypeList = R->getValueAsListOfDefs("RegTypes");
322   for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
323     Record *Type = TypeList[i];
324     if (!Type->isSubClassOf("ValueType"))
325       throw "RegTypes list member '" + Type->getName() +
326         "' does not derive from the ValueType class!";
327     VTs.push_back(getValueType(Type));
328   }
329   assert(!VTs.empty() && "RegisterClass must contain at least one ValueType!");
330
331   // Allocation order 0 is the full set. AltOrders provides others.
332   const SetTheory::RecVec *Elements = RegBank.getSets().expand(R);
333   ListInit *AltOrders = R->getValueAsListInit("AltOrders");
334   Orders.resize(1 + AltOrders->size());
335
336   // Default allocation order always contains all registers.
337   for (unsigned i = 0, e = Elements->size(); i != e; ++i) {
338     Orders[0].push_back((*Elements)[i]);
339     Members.insert(RegBank.getReg((*Elements)[i]));
340   }
341
342   // Alternative allocation orders may be subsets.
343   SetTheory::RecSet Order;
344   for (unsigned i = 0, e = AltOrders->size(); i != e; ++i) {
345     RegBank.getSets().evaluate(AltOrders->getElement(i), Order);
346     Orders[1 + i].append(Order.begin(), Order.end());
347     // Verify that all altorder members are regclass members.
348     while (!Order.empty()) {
349       CodeGenRegister *Reg = RegBank.getReg(Order.back());
350       Order.pop_back();
351       if (!contains(Reg))
352         throw TGError(R->getLoc(), " AltOrder register " + Reg->getName() +
353                       " is not a class member");
354     }
355   }
356
357   // SubRegClasses is a list<dag> containing (RC, subregindex, ...) dags.
358   ListInit *SRC = R->getValueAsListInit("SubRegClasses");
359   for (ListInit::const_iterator i = SRC->begin(), e = SRC->end(); i != e; ++i) {
360     DagInit *DAG = dynamic_cast<DagInit*>(*i);
361     if (!DAG) throw "SubRegClasses must contain DAGs";
362     DefInit *DAGOp = dynamic_cast<DefInit*>(DAG->getOperator());
363     Record *RCRec;
364     if (!DAGOp || !(RCRec = DAGOp->getDef())->isSubClassOf("RegisterClass"))
365       throw "Operator '" + DAG->getOperator()->getAsString() +
366         "' in SubRegClasses is not a RegisterClass";
367     // Iterate over args, all SubRegIndex instances.
368     for (DagInit::const_arg_iterator ai = DAG->arg_begin(), ae = DAG->arg_end();
369          ai != ae; ++ai) {
370       DefInit *Idx = dynamic_cast<DefInit*>(*ai);
371       Record *IdxRec;
372       if (!Idx || !(IdxRec = Idx->getDef())->isSubClassOf("SubRegIndex"))
373         throw "Argument '" + (*ai)->getAsString() +
374           "' in SubRegClasses is not a SubRegIndex";
375       if (!SubRegClasses.insert(std::make_pair(IdxRec, RCRec)).second)
376         throw "SubRegIndex '" + IdxRec->getName() + "' mentioned twice";
377     }
378   }
379
380   // Allow targets to override the size in bits of the RegisterClass.
381   unsigned Size = R->getValueAsInt("Size");
382
383   Namespace = R->getValueAsString("Namespace");
384   SpillSize = Size ? Size : EVT(VTs[0]).getSizeInBits();
385   SpillAlignment = R->getValueAsInt("Alignment");
386   CopyCost = R->getValueAsInt("CopyCost");
387   Allocatable = R->getValueAsBit("isAllocatable");
388   AltOrderSelect = R->getValueAsString("AltOrderSelect");
389 }
390
391 // Create an inferred register class that was missing from the .td files.
392 // Most properties will be inherited from the closest super-class after the
393 // class structure has been computed.
394 CodeGenRegisterClass::CodeGenRegisterClass(StringRef Name, Key Props)
395   : Members(*Props.Members),
396     TheDef(0),
397     Name(Name),
398     EnumValue(-1),
399     SpillSize(Props.SpillSize),
400     SpillAlignment(Props.SpillAlignment),
401     CopyCost(0),
402     Allocatable(true) {
403 }
404
405 // Compute inherited propertied for a synthesized register class.
406 void CodeGenRegisterClass::inheritProperties(CodeGenRegBank &RegBank) {
407   assert(!getDef() && "Only synthesized classes can inherit properties");
408   assert(!SuperClasses.empty() && "Synthesized class without super class");
409
410   // The last super-class is the smallest one.
411   CodeGenRegisterClass &Super = *SuperClasses.back();
412
413   // Most properties are copied directly.
414   // Exceptions are members, size, and alignment
415   Namespace = Super.Namespace;
416   VTs = Super.VTs;
417   CopyCost = Super.CopyCost;
418   Allocatable = Super.Allocatable;
419   AltOrderSelect = Super.AltOrderSelect;
420
421   // Copy all allocation orders, filter out foreign registers from the larger
422   // super-class.
423   Orders.resize(Super.Orders.size());
424   for (unsigned i = 0, ie = Super.Orders.size(); i != ie; ++i)
425     for (unsigned j = 0, je = Super.Orders[i].size(); j != je; ++j)
426       if (contains(RegBank.getReg(Super.Orders[i][j])))
427         Orders[i].push_back(Super.Orders[i][j]);
428 }
429
430 bool CodeGenRegisterClass::contains(const CodeGenRegister *Reg) const {
431   return Members.count(Reg);
432 }
433
434 namespace llvm {
435   raw_ostream &operator<<(raw_ostream &OS, const CodeGenRegisterClass::Key &K) {
436     OS << "{ S=" << K.SpillSize << ", A=" << K.SpillAlignment;
437     for (CodeGenRegister::Set::const_iterator I = K.Members->begin(),
438          E = K.Members->end(); I != E; ++I)
439       OS << ", " << (*I)->getName();
440     return OS << " }";
441   }
442 }
443
444 // This is a simple lexicographical order that can be used to search for sets.
445 // It is not the same as the topological order provided by TopoOrderRC.
446 bool CodeGenRegisterClass::Key::
447 operator<(const CodeGenRegisterClass::Key &B) const {
448   assert(Members && B.Members);
449   if (*Members != *B.Members)
450     return *Members < *B.Members;
451   if (SpillSize != B.SpillSize)
452     return SpillSize < B.SpillSize;
453   return SpillAlignment < B.SpillAlignment;
454 }
455
456 // Returns true if RC is a strict subclass.
457 // RC is a sub-class of this class if it is a valid replacement for any
458 // instruction operand where a register of this classis required. It must
459 // satisfy these conditions:
460 //
461 // 1. All RC registers are also in this.
462 // 2. The RC spill size must not be smaller than our spill size.
463 // 3. RC spill alignment must be compatible with ours.
464 //
465 static bool testSubClass(const CodeGenRegisterClass *A,
466                          const CodeGenRegisterClass *B) {
467   return A->SpillAlignment && B->SpillAlignment % A->SpillAlignment == 0 &&
468     A->SpillSize <= B->SpillSize &&
469     std::includes(A->getMembers().begin(), A->getMembers().end(),
470                   B->getMembers().begin(), B->getMembers().end(),
471                   CodeGenRegister::Less());
472 }
473
474 /// Sorting predicate for register classes.  This provides a topological
475 /// ordering that arranges all register classes before their sub-classes.
476 ///
477 /// Register classes with the same registers, spill size, and alignment form a
478 /// clique.  They will be ordered alphabetically.
479 ///
480 static int TopoOrderRC(const void *PA, const void *PB) {
481   const CodeGenRegisterClass *A = *(const CodeGenRegisterClass* const*)PA;
482   const CodeGenRegisterClass *B = *(const CodeGenRegisterClass* const*)PB;
483   if (A == B)
484     return 0;
485
486   // Order by descending set size.  Note that the classes' allocation order may
487   // not have been computed yet.  The Members set is always vaild.
488   if (A->getMembers().size() > B->getMembers().size())
489     return -1;
490   if (A->getMembers().size() < B->getMembers().size())
491     return 1;
492
493   // Order by ascending spill size.
494   if (A->SpillSize < B->SpillSize)
495     return -1;
496   if (A->SpillSize > B->SpillSize)
497     return 1;
498
499   // Order by ascending spill alignment.
500   if (A->SpillAlignment < B->SpillAlignment)
501     return -1;
502   if (A->SpillAlignment > B->SpillAlignment)
503     return 1;
504
505   // Finally order by name as a tie breaker.
506   return A->getName() < B->getName();
507 }
508
509 std::string CodeGenRegisterClass::getQualifiedName() const {
510   if (Namespace.empty())
511     return getName();
512   else
513     return Namespace + "::" + getName();
514 }
515
516 // Compute sub-classes of all register classes.
517 // Assume the classes are ordered topologically.
518 void CodeGenRegisterClass::computeSubClasses(CodeGenRegBank &RegBank) {
519   ArrayRef<CodeGenRegisterClass*> RegClasses = RegBank.getRegClasses();
520
521   // Visit backwards so sub-classes are seen first.
522   for (unsigned rci = RegClasses.size(); rci; --rci) {
523     CodeGenRegisterClass &RC = *RegClasses[rci - 1];
524     RC.SubClasses.resize(RegClasses.size());
525     RC.SubClasses.set(RC.EnumValue);
526
527     // Normally, all subclasses have IDs >= rci, unless RC is part of a clique.
528     for (unsigned s = rci; s != RegClasses.size(); ++s) {
529       if (RC.SubClasses.test(s))
530         continue;
531       CodeGenRegisterClass *SubRC = RegClasses[s];
532       if (!testSubClass(&RC, SubRC))
533         continue;
534       // SubRC is a sub-class. Grap all its sub-classes so we won't have to
535       // check them again.
536       RC.SubClasses |= SubRC->SubClasses;
537     }
538
539     // Sweep up missed clique members.  They will be immediately preceeding RC.
540     for (unsigned s = rci - 1; s && testSubClass(&RC, RegClasses[s - 1]); --s)
541       RC.SubClasses.set(s - 1);
542   }
543
544   // Compute the SuperClasses lists from the SubClasses vectors.
545   for (unsigned rci = 0; rci != RegClasses.size(); ++rci) {
546     const BitVector &SC = RegClasses[rci]->getSubClasses();
547     for (int s = SC.find_first(); s >= 0; s = SC.find_next(s)) {
548       if (unsigned(s) == rci)
549         continue;
550       RegClasses[s]->SuperClasses.push_back(RegClasses[rci]);
551     }
552   }
553
554   // With the class hierarchy in place, let synthesized register classes inherit
555   // properties from their closest super-class. The iteration order here can
556   // propagate properties down multiple levels.
557   for (unsigned rci = 0; rci != RegClasses.size(); ++rci)
558     if (!RegClasses[rci]->getDef())
559       RegClasses[rci]->inheritProperties(RegBank);
560 }
561
562 void
563 CodeGenRegisterClass::getSuperRegClasses(CodeGenSubRegIndex *SubIdx,
564                                          BitVector &Out) const {
565   DenseMap<CodeGenSubRegIndex*,
566            SmallPtrSet<CodeGenRegisterClass*, 8> >::const_iterator
567     FindI = SuperRegClasses.find(SubIdx);
568   if (FindI == SuperRegClasses.end())
569     return;
570   for (SmallPtrSet<CodeGenRegisterClass*, 8>::const_iterator I =
571        FindI->second.begin(), E = FindI->second.end(); I != E; ++I)
572     Out.set((*I)->EnumValue);
573 }
574
575
576 //===----------------------------------------------------------------------===//
577 //                               CodeGenRegBank
578 //===----------------------------------------------------------------------===//
579
580 CodeGenRegBank::CodeGenRegBank(RecordKeeper &Records) : Records(Records) {
581   // Configure register Sets to understand register classes and tuples.
582   Sets.addFieldExpander("RegisterClass", "MemberList");
583   Sets.addFieldExpander("CalleeSavedRegs", "SaveList");
584   Sets.addExpander("RegisterTuples", new TupleExpander());
585
586   // Read in the user-defined (named) sub-register indices.
587   // More indices will be synthesized later.
588   std::vector<Record*> SRIs = Records.getAllDerivedDefinitions("SubRegIndex");
589   std::sort(SRIs.begin(), SRIs.end(), LessRecord());
590   NumNamedIndices = SRIs.size();
591   for (unsigned i = 0, e = SRIs.size(); i != e; ++i)
592     getSubRegIdx(SRIs[i]);
593
594   // Read in the register definitions.
595   std::vector<Record*> Regs = Records.getAllDerivedDefinitions("Register");
596   std::sort(Regs.begin(), Regs.end(), LessRecord());
597   Registers.reserve(Regs.size());
598   // Assign the enumeration values.
599   for (unsigned i = 0, e = Regs.size(); i != e; ++i)
600     getReg(Regs[i]);
601
602   // Expand tuples and number the new registers.
603   std::vector<Record*> Tups =
604     Records.getAllDerivedDefinitions("RegisterTuples");
605   for (unsigned i = 0, e = Tups.size(); i != e; ++i) {
606     const std::vector<Record*> *TupRegs = Sets.expand(Tups[i]);
607     for (unsigned j = 0, je = TupRegs->size(); j != je; ++j)
608       getReg((*TupRegs)[j]);
609   }
610
611   // Precompute all sub-register maps now all the registers are known.
612   // This will create Composite entries for all inferred sub-register indices.
613   for (unsigned i = 0, e = Registers.size(); i != e; ++i)
614     Registers[i]->getSubRegs(*this);
615
616   // Read in register class definitions.
617   std::vector<Record*> RCs = Records.getAllDerivedDefinitions("RegisterClass");
618   if (RCs.empty())
619     throw std::string("No 'RegisterClass' subclasses defined!");
620
621   // Allocate user-defined register classes.
622   RegClasses.reserve(RCs.size());
623   for (unsigned i = 0, e = RCs.size(); i != e; ++i)
624     addToMaps(new CodeGenRegisterClass(*this, RCs[i]));
625
626   // Infer missing classes to create a full algebra.
627   computeInferredRegisterClasses();
628
629   // Order register classes topologically and assign enum values.
630   array_pod_sort(RegClasses.begin(), RegClasses.end(), TopoOrderRC);
631   for (unsigned i = 0, e = RegClasses.size(); i != e; ++i)
632     RegClasses[i]->EnumValue = i;
633   CodeGenRegisterClass::computeSubClasses(*this);
634 }
635
636 CodeGenSubRegIndex *CodeGenRegBank::getSubRegIdx(Record *Def) {
637   CodeGenSubRegIndex *&Idx = Def2SubRegIdx[Def];
638   if (Idx)
639     return Idx;
640   Idx = new CodeGenSubRegIndex(Def, SubRegIndices.size() + 1);
641   SubRegIndices.push_back(Idx);
642   return Idx;
643 }
644
645 CodeGenRegister *CodeGenRegBank::getReg(Record *Def) {
646   CodeGenRegister *&Reg = Def2Reg[Def];
647   if (Reg)
648     return Reg;
649   Reg = new CodeGenRegister(Def, Registers.size() + 1);
650   Registers.push_back(Reg);
651   return Reg;
652 }
653
654 void CodeGenRegBank::addToMaps(CodeGenRegisterClass *RC) {
655   RegClasses.push_back(RC);
656
657   if (Record *Def = RC->getDef())
658     Def2RC.insert(std::make_pair(Def, RC));
659
660   // Duplicate classes are rejected by insert().
661   // That's OK, we only care about the properties handled by CGRC::Key.
662   CodeGenRegisterClass::Key K(*RC);
663   Key2RC.insert(std::make_pair(K, RC));
664 }
665
666 // Create a synthetic sub-class if it is missing.
667 CodeGenRegisterClass*
668 CodeGenRegBank::getOrCreateSubClass(const CodeGenRegisterClass *RC,
669                                     const CodeGenRegister::Set *Members,
670                                     StringRef Name) {
671   // Synthetic sub-class has the same size and alignment as RC.
672   CodeGenRegisterClass::Key K(Members, RC->SpillSize, RC->SpillAlignment);
673   RCKeyMap::const_iterator FoundI = Key2RC.find(K);
674   if (FoundI != Key2RC.end())
675     return FoundI->second;
676
677   // Sub-class doesn't exist, create a new one.
678   CodeGenRegisterClass *NewRC = new CodeGenRegisterClass(Name, K);
679   addToMaps(NewRC);
680   return NewRC;
681 }
682
683 CodeGenRegisterClass *CodeGenRegBank::getRegClass(Record *Def) {
684   if (CodeGenRegisterClass *RC = Def2RC[Def])
685     return RC;
686
687   throw TGError(Def->getLoc(), "Not a known RegisterClass!");
688 }
689
690 CodeGenSubRegIndex*
691 CodeGenRegBank::getCompositeSubRegIndex(CodeGenSubRegIndex *A,
692                                         CodeGenSubRegIndex *B) {
693   // Look for an existing entry.
694   CodeGenSubRegIndex *Comp = A->compose(B);
695   if (Comp)
696     return Comp;
697
698   // None exists, synthesize one.
699   std::string Name = A->getName() + "_then_" + B->getName();
700   Comp = getSubRegIdx(new Record(Name, SMLoc(), Records));
701   A->addComposite(B, Comp);
702   return Comp;
703 }
704
705 void CodeGenRegBank::computeComposites() {
706   for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
707     CodeGenRegister *Reg1 = Registers[i];
708     const CodeGenRegister::SubRegMap &SRM1 = Reg1->getSubRegs();
709     for (CodeGenRegister::SubRegMap::const_iterator i1 = SRM1.begin(),
710          e1 = SRM1.end(); i1 != e1; ++i1) {
711       CodeGenSubRegIndex *Idx1 = i1->first;
712       CodeGenRegister *Reg2 = i1->second;
713       // Ignore identity compositions.
714       if (Reg1 == Reg2)
715         continue;
716       const CodeGenRegister::SubRegMap &SRM2 = Reg2->getSubRegs();
717       // Try composing Idx1 with another SubRegIndex.
718       for (CodeGenRegister::SubRegMap::const_iterator i2 = SRM2.begin(),
719            e2 = SRM2.end(); i2 != e2; ++i2) {
720       CodeGenSubRegIndex *Idx2 = i2->first;
721         CodeGenRegister *Reg3 = i2->second;
722         // Ignore identity compositions.
723         if (Reg2 == Reg3)
724           continue;
725         // OK Reg1:IdxPair == Reg3. Find the index with Reg:Idx == Reg3.
726         for (CodeGenRegister::SubRegMap::const_iterator i1d = SRM1.begin(),
727              e1d = SRM1.end(); i1d != e1d; ++i1d) {
728           if (i1d->second == Reg3) {
729             // Conflicting composition? Emit a warning but allow it.
730             if (CodeGenSubRegIndex *Prev = Idx1->addComposite(Idx2, i1d->first))
731               errs() << "Warning: SubRegIndex " << Idx1->getQualifiedName()
732                      << " and " << Idx2->getQualifiedName()
733                      << " compose ambiguously as "
734                      << Prev->getQualifiedName() << " or "
735                      << i1d->first->getQualifiedName() << "\n";
736           }
737         }
738       }
739     }
740   }
741
742   // We don't care about the difference between (Idx1, Idx2) -> Idx2 and invalid
743   // compositions, so remove any mappings of that form.
744   for (unsigned i = 0, e = SubRegIndices.size(); i != e; ++i)
745     SubRegIndices[i]->cleanComposites();
746 }
747
748 // Compute sets of overlapping registers.
749 //
750 // The standard set is all super-registers and all sub-registers, but the
751 // target description can add arbitrary overlapping registers via the 'Aliases'
752 // field. This complicates things, but we can compute overlapping sets using
753 // the following rules:
754 //
755 // 1. The relation overlap(A, B) is reflexive and symmetric but not transitive.
756 //
757 // 2. overlap(A, B) implies overlap(A, S) for all S in supers(B).
758 //
759 // Alternatively:
760 //
761 //    overlap(A, B) iff there exists:
762 //    A' in { A, subregs(A) } and B' in { B, subregs(B) } such that:
763 //    A' = B' or A' in aliases(B') or B' in aliases(A').
764 //
765 // Here subregs(A) is the full flattened sub-register set returned by
766 // A.getSubRegs() while aliases(A) is simply the special 'Aliases' field in the
767 // description of register A.
768 //
769 // This also implies that registers with a common sub-register are considered
770 // overlapping. This can happen when forming register pairs:
771 //
772 //    P0 = (R0, R1)
773 //    P1 = (R1, R2)
774 //    P2 = (R2, R3)
775 //
776 // In this case, we will infer an overlap between P0 and P1 because of the
777 // shared sub-register R1. There is no overlap between P0 and P2.
778 //
779 void CodeGenRegBank::
780 computeOverlaps(std::map<const CodeGenRegister*, CodeGenRegister::Set> &Map) {
781   assert(Map.empty());
782
783   // Collect overlaps that don't follow from rule 2.
784   for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
785     CodeGenRegister *Reg = Registers[i];
786     CodeGenRegister::Set &Overlaps = Map[Reg];
787
788     // Reg overlaps itself.
789     Overlaps.insert(Reg);
790
791     // All super-registers overlap.
792     const CodeGenRegister::SuperRegList &Supers = Reg->getSuperRegs();
793     Overlaps.insert(Supers.begin(), Supers.end());
794
795     // Form symmetrical relations from the special Aliases[] lists.
796     std::vector<Record*> RegList = Reg->TheDef->getValueAsListOfDefs("Aliases");
797     for (unsigned i2 = 0, e2 = RegList.size(); i2 != e2; ++i2) {
798       CodeGenRegister *Reg2 = getReg(RegList[i2]);
799       CodeGenRegister::Set &Overlaps2 = Map[Reg2];
800       const CodeGenRegister::SuperRegList &Supers2 = Reg2->getSuperRegs();
801       // Reg overlaps Reg2 which implies it overlaps supers(Reg2).
802       Overlaps.insert(Reg2);
803       Overlaps.insert(Supers2.begin(), Supers2.end());
804       Overlaps2.insert(Reg);
805       Overlaps2.insert(Supers.begin(), Supers.end());
806     }
807   }
808
809   // Apply rule 2. and inherit all sub-register overlaps.
810   for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
811     CodeGenRegister *Reg = Registers[i];
812     CodeGenRegister::Set &Overlaps = Map[Reg];
813     const CodeGenRegister::SubRegMap &SRM = Reg->getSubRegs();
814     for (CodeGenRegister::SubRegMap::const_iterator i2 = SRM.begin(),
815          e2 = SRM.end(); i2 != e2; ++i2) {
816       CodeGenRegister::Set &Overlaps2 = Map[i2->second];
817       Overlaps.insert(Overlaps2.begin(), Overlaps2.end());
818     }
819   }
820 }
821
822 void CodeGenRegBank::computeDerivedInfo() {
823   computeComposites();
824 }
825
826 //
827 // Synthesize missing register class intersections.
828 //
829 // Make sure that sub-classes of RC exists such that getCommonSubClass(RC, X)
830 // returns a maximal register class for all X.
831 //
832 void CodeGenRegBank::inferCommonSubClass(CodeGenRegisterClass *RC) {
833   for (unsigned rci = 0, rce = RegClasses.size(); rci != rce; ++rci) {
834     CodeGenRegisterClass *RC1 = RC;
835     CodeGenRegisterClass *RC2 = RegClasses[rci];
836     if (RC1 == RC2)
837       continue;
838
839     // Compute the set intersection of RC1 and RC2.
840     const CodeGenRegister::Set &Memb1 = RC1->getMembers();
841     const CodeGenRegister::Set &Memb2 = RC2->getMembers();
842     CodeGenRegister::Set Intersection;
843     std::set_intersection(Memb1.begin(), Memb1.end(),
844                           Memb2.begin(), Memb2.end(),
845                           std::inserter(Intersection, Intersection.begin()),
846                           CodeGenRegister::Less());
847
848     // Skip disjoint class pairs.
849     if (Intersection.empty())
850       continue;
851
852     // If RC1 and RC2 have different spill sizes or alignments, use the
853     // larger size for sub-classing.  If they are equal, prefer RC1.
854     if (RC2->SpillSize > RC1->SpillSize ||
855         (RC2->SpillSize == RC1->SpillSize &&
856          RC2->SpillAlignment > RC1->SpillAlignment))
857       std::swap(RC1, RC2);
858
859     getOrCreateSubClass(RC1, &Intersection,
860                         RC1->getName() + "_and_" + RC2->getName());
861   }
862 }
863
864 //
865 // Synthesize missing sub-classes for getSubClassWithSubReg().
866 //
867 // Make sure that the set of registers in RC with a given SubIdx sub-register
868 // form a register class.  Update RC->SubClassWithSubReg.
869 //
870 void CodeGenRegBank::inferSubClassWithSubReg(CodeGenRegisterClass *RC) {
871   // Map SubRegIndex to set of registers in RC supporting that SubRegIndex.
872   typedef std::map<CodeGenSubRegIndex*, CodeGenRegister::Set,
873                    CodeGenSubRegIndex::Less> SubReg2SetMap;
874
875   // Compute the set of registers supporting each SubRegIndex.
876   SubReg2SetMap SRSets;
877   for (CodeGenRegister::Set::const_iterator RI = RC->getMembers().begin(),
878        RE = RC->getMembers().end(); RI != RE; ++RI) {
879     const CodeGenRegister::SubRegMap &SRM = (*RI)->getSubRegs();
880     for (CodeGenRegister::SubRegMap::const_iterator I = SRM.begin(),
881          E = SRM.end(); I != E; ++I)
882       SRSets[I->first].insert(*RI);
883   }
884
885   // Find matching classes for all SRSets entries.  Iterate in SubRegIndex
886   // numerical order to visit synthetic indices last.
887   for (unsigned sri = 0, sre = SubRegIndices.size(); sri != sre; ++sri) {
888     CodeGenSubRegIndex *SubIdx = SubRegIndices[sri];
889     SubReg2SetMap::const_iterator I = SRSets.find(SubIdx);
890     // Unsupported SubRegIndex. Skip it.
891     if (I == SRSets.end())
892       continue;
893     // In most cases, all RC registers support the SubRegIndex.
894     if (I->second.size() == RC->getMembers().size()) {
895       RC->setSubClassWithSubReg(SubIdx, RC);
896       continue;
897     }
898     // This is a real subset.  See if we have a matching class.
899     CodeGenRegisterClass *SubRC =
900       getOrCreateSubClass(RC, &I->second,
901                           RC->getName() + "_with_" + I->first->getName());
902     RC->setSubClassWithSubReg(SubIdx, SubRC);
903   }
904 }
905
906 //
907 // Synthesize missing sub-classes of RC for getMatchingSuperRegClass().
908 //
909 // Create sub-classes of RC such that getMatchingSuperRegClass(RC, SubIdx, X)
910 // has a maximal result for any SubIdx and any X >= FirstSubRegRC.
911 //
912
913 void CodeGenRegBank::inferMatchingSuperRegClass(CodeGenRegisterClass *RC,
914                                                 unsigned FirstSubRegRC) {
915   SmallVector<std::pair<const CodeGenRegister*,
916                         const CodeGenRegister*>, 16> SSPairs;
917
918   // Iterate in SubRegIndex numerical order to visit synthetic indices last.
919   for (unsigned sri = 0, sre = SubRegIndices.size(); sri != sre; ++sri) {
920     CodeGenSubRegIndex *SubIdx = SubRegIndices[sri];
921     // Skip indexes that aren't fully supported by RC's registers. This was
922     // computed by inferSubClassWithSubReg() above which should have been
923     // called first.
924     if (RC->getSubClassWithSubReg(SubIdx) != RC)
925       continue;
926
927     // Build list of (Super, Sub) pairs for this SubIdx.
928     SSPairs.clear();
929     for (CodeGenRegister::Set::const_iterator RI = RC->getMembers().begin(),
930          RE = RC->getMembers().end(); RI != RE; ++RI) {
931       const CodeGenRegister *Super = *RI;
932       const CodeGenRegister *Sub = Super->getSubRegs().find(SubIdx)->second;
933       assert(Sub && "Missing sub-register");
934       SSPairs.push_back(std::make_pair(Super, Sub));
935     }
936
937     // Iterate over sub-register class candidates.  Ignore classes created by
938     // this loop. They will never be useful.
939     for (unsigned rci = FirstSubRegRC, rce = RegClasses.size(); rci != rce;
940          ++rci) {
941       CodeGenRegisterClass *SubRC = RegClasses[rci];
942       // Compute the subset of RC that maps into SubRC.
943       CodeGenRegister::Set SubSet;
944       for (unsigned i = 0, e = SSPairs.size(); i != e; ++i)
945         if (SubRC->contains(SSPairs[i].second))
946           SubSet.insert(SSPairs[i].first);
947       if (SubSet.empty())
948         continue;
949       // RC injects completely into SubRC.
950       if (SubSet.size() == SSPairs.size()) {
951         SubRC->addSuperRegClass(SubIdx, RC);
952         continue;
953       }
954       // Only a subset of RC maps into SubRC. Make sure it is represented by a
955       // class.
956       getOrCreateSubClass(RC, &SubSet, RC->getName() +
957                           "_with_" + SubIdx->getName() +
958                           "_in_" + SubRC->getName());
959     }
960   }
961 }
962
963
964 //
965 // Infer missing register classes.
966 //
967 void CodeGenRegBank::computeInferredRegisterClasses() {
968   // When this function is called, the register classes have not been sorted
969   // and assigned EnumValues yet.  That means getSubClasses(),
970   // getSuperClasses(), and hasSubClass() functions are defunct.
971   unsigned FirstNewRC = RegClasses.size();
972
973   // Visit all register classes, including the ones being added by the loop.
974   for (unsigned rci = 0; rci != RegClasses.size(); ++rci) {
975     CodeGenRegisterClass *RC = RegClasses[rci];
976
977     // Synthesize answers for getSubClassWithSubReg().
978     inferSubClassWithSubReg(RC);
979
980     // Synthesize answers for getCommonSubClass().
981     inferCommonSubClass(RC);
982
983     // Synthesize answers for getMatchingSuperRegClass().
984     inferMatchingSuperRegClass(RC);
985
986     // New register classes are created while this loop is running, and we need
987     // to visit all of them.  I  particular, inferMatchingSuperRegClass needs
988     // to match old super-register classes with sub-register classes created
989     // after inferMatchingSuperRegClass was called.  At this point,
990     // inferMatchingSuperRegClass has checked SuperRC = [0..rci] with SubRC =
991     // [0..FirstNewRC).  We need to cover SubRC = [FirstNewRC..rci].
992     if (rci + 1 == FirstNewRC) {
993       unsigned NextNewRC = RegClasses.size();
994       for (unsigned rci2 = 0; rci2 != FirstNewRC; ++rci2)
995         inferMatchingSuperRegClass(RegClasses[rci2], FirstNewRC);
996       FirstNewRC = NextNewRC;
997     }
998   }
999 }
1000
1001 /// getRegisterClassForRegister - Find the register class that contains the
1002 /// specified physical register.  If the register is not in a register class,
1003 /// return null. If the register is in multiple classes, and the classes have a
1004 /// superset-subset relationship and the same set of types, return the
1005 /// superclass.  Otherwise return null.
1006 const CodeGenRegisterClass*
1007 CodeGenRegBank::getRegClassForRegister(Record *R) {
1008   const CodeGenRegister *Reg = getReg(R);
1009   ArrayRef<CodeGenRegisterClass*> RCs = getRegClasses();
1010   const CodeGenRegisterClass *FoundRC = 0;
1011   for (unsigned i = 0, e = RCs.size(); i != e; ++i) {
1012     const CodeGenRegisterClass &RC = *RCs[i];
1013     if (!RC.contains(Reg))
1014       continue;
1015
1016     // If this is the first class that contains the register,
1017     // make a note of it and go on to the next class.
1018     if (!FoundRC) {
1019       FoundRC = &RC;
1020       continue;
1021     }
1022
1023     // If a register's classes have different types, return null.
1024     if (RC.getValueTypes() != FoundRC->getValueTypes())
1025       return 0;
1026
1027     // Check to see if the previously found class that contains
1028     // the register is a subclass of the current class. If so,
1029     // prefer the superclass.
1030     if (RC.hasSubClass(FoundRC)) {
1031       FoundRC = &RC;
1032       continue;
1033     }
1034
1035     // Check to see if the previously found class that contains
1036     // the register is a superclass of the current class. If so,
1037     // prefer the superclass.
1038     if (FoundRC->hasSubClass(&RC))
1039       continue;
1040
1041     // Multiple classes, and neither is a superclass of the other.
1042     // Return null.
1043     return 0;
1044   }
1045   return FoundRC;
1046 }
1047
1048 BitVector CodeGenRegBank::computeCoveredRegisters(ArrayRef<Record*> Regs) {
1049   SetVector<CodeGenRegister*> Set;
1050
1051   // First add Regs with all sub-registers.
1052   for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
1053     CodeGenRegister *Reg = getReg(Regs[i]);
1054     if (Set.insert(Reg))
1055       // Reg is new, add all sub-registers.
1056       // The pre-ordering is not important here.
1057       Reg->addSubRegsPreOrder(Set, *this);
1058   }
1059
1060   // Second, find all super-registers that are completely covered by the set.
1061   for (unsigned i = 0; i != Set.size(); ++i) {
1062     const CodeGenRegister::SuperRegList &SR = Set[i]->getSuperRegs();
1063     for (unsigned j = 0, e = SR.size(); j != e; ++j) {
1064       CodeGenRegister *Super = SR[j];
1065       if (!Super->CoveredBySubRegs || Set.count(Super))
1066         continue;
1067       // This new super-register is covered by its sub-registers.
1068       bool AllSubsInSet = true;
1069       const CodeGenRegister::SubRegMap &SRM = Super->getSubRegs();
1070       for (CodeGenRegister::SubRegMap::const_iterator I = SRM.begin(),
1071              E = SRM.end(); I != E; ++I)
1072         if (!Set.count(I->second)) {
1073           AllSubsInSet = false;
1074           break;
1075         }
1076       // All sub-registers in Set, add Super as well.
1077       // We will visit Super later to recheck its super-registers.
1078       if (AllSubsInSet)
1079         Set.insert(Super);
1080     }
1081   }
1082
1083   // Convert to BitVector.
1084   BitVector BV(Registers.size() + 1);
1085   for (unsigned i = 0, e = Set.size(); i != e; ++i)
1086     BV.set(Set[i]->EnumValue);
1087   return BV;
1088 }