a9eed98a5b561ffad28935bf0cacd7a124139f34
[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/IntEqClasses.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/Twine.h"
23
24 using namespace llvm;
25
26 //===----------------------------------------------------------------------===//
27 //                             CodeGenSubRegIndex
28 //===----------------------------------------------------------------------===//
29
30 CodeGenSubRegIndex::CodeGenSubRegIndex(Record *R, unsigned Enum)
31   : TheDef(R),
32     EnumValue(Enum)
33 {}
34
35 std::string CodeGenSubRegIndex::getNamespace() const {
36   if (TheDef->getValue("Namespace"))
37     return TheDef->getValueAsString("Namespace");
38   else
39     return "";
40 }
41
42 const std::string &CodeGenSubRegIndex::getName() const {
43   return TheDef->getName();
44 }
45
46 std::string CodeGenSubRegIndex::getQualifiedName() const {
47   std::string N = getNamespace();
48   if (!N.empty())
49     N += "::";
50   N += getName();
51   return N;
52 }
53
54 void CodeGenSubRegIndex::updateComponents(CodeGenRegBank &RegBank) {
55   std::vector<Record*> Comps = TheDef->getValueAsListOfDefs("ComposedOf");
56   if (Comps.empty())
57     return;
58   if (Comps.size() != 2)
59     throw TGError(TheDef->getLoc(), "ComposedOf must have exactly two entries");
60   CodeGenSubRegIndex *A = RegBank.getSubRegIdx(Comps[0]);
61   CodeGenSubRegIndex *B = RegBank.getSubRegIdx(Comps[1]);
62   CodeGenSubRegIndex *X = A->addComposite(B, this);
63   if (X)
64     throw TGError(TheDef->getLoc(), "Ambiguous ComposedOf entries");
65 }
66
67 void CodeGenSubRegIndex::cleanComposites() {
68   // Clean out redundant mappings of the form this+X -> X.
69   for (CompMap::iterator i = Composed.begin(), e = Composed.end(); i != e;) {
70     CompMap::iterator j = i;
71     ++i;
72     if (j->first == j->second)
73       Composed.erase(j);
74   }
75 }
76
77 //===----------------------------------------------------------------------===//
78 //                              CodeGenRegister
79 //===----------------------------------------------------------------------===//
80
81 CodeGenRegister::CodeGenRegister(Record *R, unsigned Enum)
82   : TheDef(R),
83     EnumValue(Enum),
84     CostPerUse(R->getValueAsInt("CostPerUse")),
85     CoveredBySubRegs(R->getValueAsBit("CoveredBySubRegs")),
86     SubRegsComplete(false)
87 {}
88
89 const std::string &CodeGenRegister::getName() const {
90   return TheDef->getName();
91 }
92
93 namespace {
94 // Iterate over all register units in a set of registers.
95 class RegUnitIterator {
96   CodeGenRegister::Set::const_iterator RegI, RegE;
97   CodeGenRegister::RegUnitList::const_iterator UnitI, UnitE;
98
99 public:
100   RegUnitIterator(const CodeGenRegister::Set &Regs):
101     RegI(Regs.begin()), RegE(Regs.end()), UnitI(), UnitE() {
102
103     if (RegI != RegE) {
104       UnitI = (*RegI)->getRegUnits().begin();
105       UnitE = (*RegI)->getRegUnits().end();
106       advance();
107     }
108   }
109
110   bool isValid() const { return UnitI != UnitE; }
111
112   unsigned operator* () const { assert(isValid()); return *UnitI; };
113
114   const CodeGenRegister *getReg() const { assert(isValid()); return *RegI; }
115
116   /// Preincrement.  Move to the next unit.
117   void operator++() {
118     assert(isValid() && "Cannot advance beyond the last operand");
119     ++UnitI;
120     advance();
121   }
122
123 protected:
124   void advance() {
125     while (UnitI == UnitE) {
126       if (++RegI == RegE)
127         break;
128       UnitI = (*RegI)->getRegUnits().begin();
129       UnitE = (*RegI)->getRegUnits().end();
130     }
131   }
132 };
133 } // namespace
134
135 // Merge two RegUnitLists maintaining the order and removing duplicates.
136 // Overwrites MergedRU in the process.
137 static void mergeRegUnits(CodeGenRegister::RegUnitList &MergedRU,
138                           const CodeGenRegister::RegUnitList &RRU) {
139   CodeGenRegister::RegUnitList LRU = MergedRU;
140   MergedRU.clear();
141   std::set_union(LRU.begin(), LRU.end(), RRU.begin(), RRU.end(),
142                  std::back_inserter(MergedRU));
143 }
144
145 // Return true of this unit appears in RegUnits.
146 static bool hasRegUnit(CodeGenRegister::RegUnitList &RegUnits, unsigned Unit) {
147   return std::count(RegUnits.begin(), RegUnits.end(), Unit);
148 }
149
150 // Inherit register units from subregisters.
151 // Return true if the RegUnits changed.
152 bool CodeGenRegister::inheritRegUnits(CodeGenRegBank &RegBank) {
153   unsigned OldNumUnits = RegUnits.size();
154   for (SubRegMap::const_iterator I = SubRegs.begin(), E = SubRegs.end();
155        I != E; ++I) {
156     // Strangely a register may have itself as a subreg (self-cycle) e.g. XMM.
157     // Only create a unit if no other subregs have units.
158     CodeGenRegister *SR = I->second;
159     if (SR == this) {
160       // RegUnits are only empty during getSubRegs, prior to computing weight.
161       if (RegUnits.empty())
162         RegUnits.push_back(RegBank.newRegUnit(0));
163       continue;
164     }
165     // Merge the subregister's units into this register's RegUnits.
166     mergeRegUnits(RegUnits, SR->RegUnits);
167   }
168   return OldNumUnits != RegUnits.size();
169 }
170
171 const CodeGenRegister::SubRegMap &
172 CodeGenRegister::getSubRegs(CodeGenRegBank &RegBank) {
173   // Only compute this map once.
174   if (SubRegsComplete)
175     return SubRegs;
176   SubRegsComplete = true;
177
178   std::vector<Record*> SubList = TheDef->getValueAsListOfDefs("SubRegs");
179   std::vector<Record*> IdxList = TheDef->getValueAsListOfDefs("SubRegIndices");
180   if (SubList.size() != IdxList.size())
181     throw TGError(TheDef->getLoc(), "Register " + getName() +
182                   " SubRegIndices doesn't match SubRegs");
183
184   // First insert the direct subregs and make sure they are fully indexed.
185   SmallVector<CodeGenSubRegIndex*, 8> Indices;
186   for (unsigned i = 0, e = SubList.size(); i != e; ++i) {
187     CodeGenRegister *SR = RegBank.getReg(SubList[i]);
188     CodeGenSubRegIndex *Idx = RegBank.getSubRegIdx(IdxList[i]);
189     Indices.push_back(Idx);
190     if (!SubRegs.insert(std::make_pair(Idx, SR)).second)
191       throw TGError(TheDef->getLoc(), "SubRegIndex " + Idx->getName() +
192                     " appears twice in Register " + getName());
193   }
194
195   // Keep track of inherited subregs and how they can be reached.
196   SmallPtrSet<CodeGenRegister*, 8> Orphans;
197
198   // Clone inherited subregs and place duplicate entries in Orphans.
199   // Here the order is important - earlier subregs take precedence.
200   for (unsigned i = 0, e = SubList.size(); i != e; ++i) {
201     CodeGenRegister *SR = RegBank.getReg(SubList[i]);
202     const SubRegMap &Map = SR->getSubRegs(RegBank);
203
204     // Add this as a super-register of SR now all sub-registers are in the list.
205     // This creates a topological ordering, the exact order depends on the
206     // order getSubRegs is called on all registers.
207     SR->SuperRegs.push_back(this);
208
209     for (SubRegMap::const_iterator SI = Map.begin(), SE = Map.end(); SI != SE;
210          ++SI) {
211       if (!SubRegs.insert(*SI).second)
212         Orphans.insert(SI->second);
213
214       // Noop sub-register indexes are possible, so avoid duplicates.
215       if (SI->second != SR)
216         SI->second->SuperRegs.push_back(this);
217     }
218   }
219
220   // Expand any composed subreg indices.
221   // If dsub_2 has ComposedOf = [qsub_1, dsub_0], and this register has a
222   // qsub_1 subreg, add a dsub_2 subreg.  Keep growing Indices and process
223   // expanded subreg indices recursively.
224   for (unsigned i = 0; i != Indices.size(); ++i) {
225     CodeGenSubRegIndex *Idx = Indices[i];
226     const CodeGenSubRegIndex::CompMap &Comps = Idx->getComposites();
227     CodeGenRegister *SR = SubRegs[Idx];
228     const SubRegMap &Map = SR->getSubRegs(RegBank);
229
230     // Look at the possible compositions of Idx.
231     // They may not all be supported by SR.
232     for (CodeGenSubRegIndex::CompMap::const_iterator I = Comps.begin(),
233            E = Comps.end(); I != E; ++I) {
234       SubRegMap::const_iterator SRI = Map.find(I->first);
235       if (SRI == Map.end())
236         continue; // Idx + I->first doesn't exist in SR.
237       // Add I->second as a name for the subreg SRI->second, assuming it is
238       // orphaned, and the name isn't already used for something else.
239       if (SubRegs.count(I->second) || !Orphans.erase(SRI->second))
240         continue;
241       // We found a new name for the orphaned sub-register.
242       SubRegs.insert(std::make_pair(I->second, SRI->second));
243       Indices.push_back(I->second);
244     }
245   }
246
247   // Process the composites.
248   ListInit *Comps = TheDef->getValueAsListInit("CompositeIndices");
249   for (unsigned i = 0, e = Comps->size(); i != e; ++i) {
250     DagInit *Pat = dynamic_cast<DagInit*>(Comps->getElement(i));
251     if (!Pat)
252       throw TGError(TheDef->getLoc(), "Invalid dag '" +
253                     Comps->getElement(i)->getAsString() +
254                     "' in CompositeIndices");
255     DefInit *BaseIdxInit = dynamic_cast<DefInit*>(Pat->getOperator());
256     if (!BaseIdxInit || !BaseIdxInit->getDef()->isSubClassOf("SubRegIndex"))
257       throw TGError(TheDef->getLoc(), "Invalid SubClassIndex in " +
258                     Pat->getAsString());
259     CodeGenSubRegIndex *BaseIdx = RegBank.getSubRegIdx(BaseIdxInit->getDef());
260
261     // Resolve list of subreg indices into R2.
262     CodeGenRegister *R2 = this;
263     for (DagInit::const_arg_iterator di = Pat->arg_begin(),
264          de = Pat->arg_end(); di != de; ++di) {
265       DefInit *IdxInit = dynamic_cast<DefInit*>(*di);
266       if (!IdxInit || !IdxInit->getDef()->isSubClassOf("SubRegIndex"))
267         throw TGError(TheDef->getLoc(), "Invalid SubClassIndex in " +
268                       Pat->getAsString());
269       CodeGenSubRegIndex *Idx = RegBank.getSubRegIdx(IdxInit->getDef());
270       const SubRegMap &R2Subs = R2->getSubRegs(RegBank);
271       SubRegMap::const_iterator ni = R2Subs.find(Idx);
272       if (ni == R2Subs.end())
273         throw TGError(TheDef->getLoc(), "Composite " + Pat->getAsString() +
274                       " refers to bad index in " + R2->getName());
275       R2 = ni->second;
276     }
277
278     // Insert composite index. Allow overriding inherited indices etc.
279     SubRegs[BaseIdx] = R2;
280
281     // R2 is no longer an orphan.
282     Orphans.erase(R2);
283   }
284
285   // Now Orphans contains the inherited subregisters without a direct index.
286   // Create inferred indexes for all missing entries.
287   // Work backwards in the Indices vector in order to compose subregs bottom-up.
288   // Consider this subreg sequence:
289   //
290   //   qsub_1 -> dsub_0 -> ssub_0
291   //
292   // The qsub_1 -> dsub_0 composition becomes dsub_2, so the ssub_0 register
293   // can be reached in two different ways:
294   //
295   //   qsub_1 -> ssub_0
296   //   dsub_2 -> ssub_0
297   //
298   // We pick the latter composition because another register may have [dsub_0,
299   // dsub_1, dsub_2] subregs without neccessarily having a qsub_1 subreg.  The
300   // dsub_2 -> ssub_0 composition can be shared.
301   while (!Indices.empty() && !Orphans.empty()) {
302     CodeGenSubRegIndex *Idx = Indices.pop_back_val();
303     CodeGenRegister *SR = SubRegs[Idx];
304     const SubRegMap &Map = SR->getSubRegs(RegBank);
305     for (SubRegMap::const_iterator SI = Map.begin(), SE = Map.end(); SI != SE;
306          ++SI)
307       if (Orphans.erase(SI->second))
308         SubRegs[RegBank.getCompositeSubRegIndex(Idx, SI->first)] = SI->second;
309   }
310
311   // Initialize RegUnitList. A register with no subregisters creates its own
312   // unit. Otherwise, it inherits all its subregister's units. Because
313   // getSubRegs is called recursively, this processes the register hierarchy in
314   // postorder.
315   //
316   // TODO: We currently assume all register units correspond to a named "leaf"
317   // register. We should also unify register units for ad-hoc register
318   // aliases. This can be done by iteratively merging units for aliasing
319   // registers using a worklist.
320   assert(RegUnits.empty() && "Should only initialize RegUnits once");
321   if (SubRegs.empty())
322     RegUnits.push_back(RegBank.newRegUnit(0));
323   else
324     inheritRegUnits(RegBank);
325   return SubRegs;
326 }
327
328 void
329 CodeGenRegister::addSubRegsPreOrder(SetVector<const CodeGenRegister*> &OSet,
330                                     CodeGenRegBank &RegBank) const {
331   assert(SubRegsComplete && "Must precompute sub-registers");
332   std::vector<Record*> Indices = TheDef->getValueAsListOfDefs("SubRegIndices");
333   for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
334     CodeGenSubRegIndex *Idx = RegBank.getSubRegIdx(Indices[i]);
335     CodeGenRegister *SR = SubRegs.find(Idx)->second;
336     if (OSet.insert(SR))
337       SR->addSubRegsPreOrder(OSet, RegBank);
338   }
339 }
340
341 // Get the sum of this register's unit weights.
342 unsigned CodeGenRegister::getWeight(const CodeGenRegBank &RegBank) const {
343   unsigned Weight = 0;
344   for (RegUnitList::const_iterator I = RegUnits.begin(), E = RegUnits.end();
345        I != E; ++I) {
346     Weight += RegBank.getRegUnitWeight(*I);
347   }
348   return Weight;
349 }
350
351 //===----------------------------------------------------------------------===//
352 //                               RegisterTuples
353 //===----------------------------------------------------------------------===//
354
355 // A RegisterTuples def is used to generate pseudo-registers from lists of
356 // sub-registers. We provide a SetTheory expander class that returns the new
357 // registers.
358 namespace {
359 struct TupleExpander : SetTheory::Expander {
360   void expand(SetTheory &ST, Record *Def, SetTheory::RecSet &Elts) {
361     std::vector<Record*> Indices = Def->getValueAsListOfDefs("SubRegIndices");
362     unsigned Dim = Indices.size();
363     ListInit *SubRegs = Def->getValueAsListInit("SubRegs");
364     if (Dim != SubRegs->getSize())
365       throw TGError(Def->getLoc(), "SubRegIndices and SubRegs size mismatch");
366     if (Dim < 2)
367       throw TGError(Def->getLoc(), "Tuples must have at least 2 sub-registers");
368
369     // Evaluate the sub-register lists to be zipped.
370     unsigned Length = ~0u;
371     SmallVector<SetTheory::RecSet, 4> Lists(Dim);
372     for (unsigned i = 0; i != Dim; ++i) {
373       ST.evaluate(SubRegs->getElement(i), Lists[i]);
374       Length = std::min(Length, unsigned(Lists[i].size()));
375     }
376
377     if (Length == 0)
378       return;
379
380     // Precompute some types.
381     Record *RegisterCl = Def->getRecords().getClass("Register");
382     RecTy *RegisterRecTy = RecordRecTy::get(RegisterCl);
383     StringInit *BlankName = StringInit::get("");
384
385     // Zip them up.
386     for (unsigned n = 0; n != Length; ++n) {
387       std::string Name;
388       Record *Proto = Lists[0][n];
389       std::vector<Init*> Tuple;
390       unsigned CostPerUse = 0;
391       for (unsigned i = 0; i != Dim; ++i) {
392         Record *Reg = Lists[i][n];
393         if (i) Name += '_';
394         Name += Reg->getName();
395         Tuple.push_back(DefInit::get(Reg));
396         CostPerUse = std::max(CostPerUse,
397                               unsigned(Reg->getValueAsInt("CostPerUse")));
398       }
399
400       // Create a new Record representing the synthesized register. This record
401       // is only for consumption by CodeGenRegister, it is not added to the
402       // RecordKeeper.
403       Record *NewReg = new Record(Name, Def->getLoc(), Def->getRecords());
404       Elts.insert(NewReg);
405
406       // Copy Proto super-classes.
407       for (unsigned i = 0, e = Proto->getSuperClasses().size(); i != e; ++i)
408         NewReg->addSuperClass(Proto->getSuperClasses()[i]);
409
410       // Copy Proto fields.
411       for (unsigned i = 0, e = Proto->getValues().size(); i != e; ++i) {
412         RecordVal RV = Proto->getValues()[i];
413
414         // Skip existing fields, like NAME.
415         if (NewReg->getValue(RV.getNameInit()))
416           continue;
417
418         StringRef Field = RV.getName();
419
420         // Replace the sub-register list with Tuple.
421         if (Field == "SubRegs")
422           RV.setValue(ListInit::get(Tuple, RegisterRecTy));
423
424         // Provide a blank AsmName. MC hacks are required anyway.
425         if (Field == "AsmName")
426           RV.setValue(BlankName);
427
428         // CostPerUse is aggregated from all Tuple members.
429         if (Field == "CostPerUse")
430           RV.setValue(IntInit::get(CostPerUse));
431
432         // Composite registers are always covered by sub-registers.
433         if (Field == "CoveredBySubRegs")
434           RV.setValue(BitInit::get(true));
435
436         // Copy fields from the RegisterTuples def.
437         if (Field == "SubRegIndices" ||
438             Field == "CompositeIndices") {
439           NewReg->addValue(*Def->getValue(Field));
440           continue;
441         }
442
443         // Some fields get their default uninitialized value.
444         if (Field == "DwarfNumbers" ||
445             Field == "DwarfAlias" ||
446             Field == "Aliases") {
447           if (const RecordVal *DefRV = RegisterCl->getValue(Field))
448             NewReg->addValue(*DefRV);
449           continue;
450         }
451
452         // Everything else is copied from Proto.
453         NewReg->addValue(RV);
454       }
455     }
456   }
457 };
458 }
459
460 //===----------------------------------------------------------------------===//
461 //                            CodeGenRegisterClass
462 //===----------------------------------------------------------------------===//
463
464 CodeGenRegisterClass::CodeGenRegisterClass(CodeGenRegBank &RegBank, Record *R)
465   : TheDef(R), Name(R->getName()), EnumValue(-1) {
466   // Rename anonymous register classes.
467   if (R->getName().size() > 9 && R->getName()[9] == '.') {
468     static unsigned AnonCounter = 0;
469     R->setName("AnonRegClass_"+utostr(AnonCounter++));
470   }
471
472   std::vector<Record*> TypeList = R->getValueAsListOfDefs("RegTypes");
473   for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
474     Record *Type = TypeList[i];
475     if (!Type->isSubClassOf("ValueType"))
476       throw "RegTypes list member '" + Type->getName() +
477         "' does not derive from the ValueType class!";
478     VTs.push_back(getValueType(Type));
479   }
480   assert(!VTs.empty() && "RegisterClass must contain at least one ValueType!");
481
482   // Allocation order 0 is the full set. AltOrders provides others.
483   const SetTheory::RecVec *Elements = RegBank.getSets().expand(R);
484   ListInit *AltOrders = R->getValueAsListInit("AltOrders");
485   Orders.resize(1 + AltOrders->size());
486
487   // Default allocation order always contains all registers.
488   for (unsigned i = 0, e = Elements->size(); i != e; ++i) {
489     Orders[0].push_back((*Elements)[i]);
490     Members.insert(RegBank.getReg((*Elements)[i]));
491   }
492
493   // Alternative allocation orders may be subsets.
494   SetTheory::RecSet Order;
495   for (unsigned i = 0, e = AltOrders->size(); i != e; ++i) {
496     RegBank.getSets().evaluate(AltOrders->getElement(i), Order);
497     Orders[1 + i].append(Order.begin(), Order.end());
498     // Verify that all altorder members are regclass members.
499     while (!Order.empty()) {
500       CodeGenRegister *Reg = RegBank.getReg(Order.back());
501       Order.pop_back();
502       if (!contains(Reg))
503         throw TGError(R->getLoc(), " AltOrder register " + Reg->getName() +
504                       " is not a class member");
505     }
506   }
507
508   // Allow targets to override the size in bits of the RegisterClass.
509   unsigned Size = R->getValueAsInt("Size");
510
511   Namespace = R->getValueAsString("Namespace");
512   SpillSize = Size ? Size : EVT(VTs[0]).getSizeInBits();
513   SpillAlignment = R->getValueAsInt("Alignment");
514   CopyCost = R->getValueAsInt("CopyCost");
515   Allocatable = R->getValueAsBit("isAllocatable");
516   AltOrderSelect = R->getValueAsString("AltOrderSelect");
517 }
518
519 // Create an inferred register class that was missing from the .td files.
520 // Most properties will be inherited from the closest super-class after the
521 // class structure has been computed.
522 CodeGenRegisterClass::CodeGenRegisterClass(StringRef Name, Key Props)
523   : Members(*Props.Members),
524     TheDef(0),
525     Name(Name),
526     EnumValue(-1),
527     SpillSize(Props.SpillSize),
528     SpillAlignment(Props.SpillAlignment),
529     CopyCost(0),
530     Allocatable(true) {
531 }
532
533 // Compute inherited propertied for a synthesized register class.
534 void CodeGenRegisterClass::inheritProperties(CodeGenRegBank &RegBank) {
535   assert(!getDef() && "Only synthesized classes can inherit properties");
536   assert(!SuperClasses.empty() && "Synthesized class without super class");
537
538   // The last super-class is the smallest one.
539   CodeGenRegisterClass &Super = *SuperClasses.back();
540
541   // Most properties are copied directly.
542   // Exceptions are members, size, and alignment
543   Namespace = Super.Namespace;
544   VTs = Super.VTs;
545   CopyCost = Super.CopyCost;
546   Allocatable = Super.Allocatable;
547   AltOrderSelect = Super.AltOrderSelect;
548
549   // Copy all allocation orders, filter out foreign registers from the larger
550   // super-class.
551   Orders.resize(Super.Orders.size());
552   for (unsigned i = 0, ie = Super.Orders.size(); i != ie; ++i)
553     for (unsigned j = 0, je = Super.Orders[i].size(); j != je; ++j)
554       if (contains(RegBank.getReg(Super.Orders[i][j])))
555         Orders[i].push_back(Super.Orders[i][j]);
556 }
557
558 bool CodeGenRegisterClass::contains(const CodeGenRegister *Reg) const {
559   return Members.count(Reg);
560 }
561
562 namespace llvm {
563   raw_ostream &operator<<(raw_ostream &OS, const CodeGenRegisterClass::Key &K) {
564     OS << "{ S=" << K.SpillSize << ", A=" << K.SpillAlignment;
565     for (CodeGenRegister::Set::const_iterator I = K.Members->begin(),
566          E = K.Members->end(); I != E; ++I)
567       OS << ", " << (*I)->getName();
568     return OS << " }";
569   }
570 }
571
572 // This is a simple lexicographical order that can be used to search for sets.
573 // It is not the same as the topological order provided by TopoOrderRC.
574 bool CodeGenRegisterClass::Key::
575 operator<(const CodeGenRegisterClass::Key &B) const {
576   assert(Members && B.Members);
577   if (*Members != *B.Members)
578     return *Members < *B.Members;
579   if (SpillSize != B.SpillSize)
580     return SpillSize < B.SpillSize;
581   return SpillAlignment < B.SpillAlignment;
582 }
583
584 // Returns true if RC is a strict subclass.
585 // RC is a sub-class of this class if it is a valid replacement for any
586 // instruction operand where a register of this classis required. It must
587 // satisfy these conditions:
588 //
589 // 1. All RC registers are also in this.
590 // 2. The RC spill size must not be smaller than our spill size.
591 // 3. RC spill alignment must be compatible with ours.
592 //
593 static bool testSubClass(const CodeGenRegisterClass *A,
594                          const CodeGenRegisterClass *B) {
595   return A->SpillAlignment && B->SpillAlignment % A->SpillAlignment == 0 &&
596     A->SpillSize <= B->SpillSize &&
597     std::includes(A->getMembers().begin(), A->getMembers().end(),
598                   B->getMembers().begin(), B->getMembers().end(),
599                   CodeGenRegister::Less());
600 }
601
602 /// Sorting predicate for register classes.  This provides a topological
603 /// ordering that arranges all register classes before their sub-classes.
604 ///
605 /// Register classes with the same registers, spill size, and alignment form a
606 /// clique.  They will be ordered alphabetically.
607 ///
608 static int TopoOrderRC(const void *PA, const void *PB) {
609   const CodeGenRegisterClass *A = *(const CodeGenRegisterClass* const*)PA;
610   const CodeGenRegisterClass *B = *(const CodeGenRegisterClass* const*)PB;
611   if (A == B)
612     return 0;
613
614   // Order by descending set size.  Note that the classes' allocation order may
615   // not have been computed yet.  The Members set is always vaild.
616   if (A->getMembers().size() > B->getMembers().size())
617     return -1;
618   if (A->getMembers().size() < B->getMembers().size())
619     return 1;
620
621   // Order by ascending spill size.
622   if (A->SpillSize < B->SpillSize)
623     return -1;
624   if (A->SpillSize > B->SpillSize)
625     return 1;
626
627   // Order by ascending spill alignment.
628   if (A->SpillAlignment < B->SpillAlignment)
629     return -1;
630   if (A->SpillAlignment > B->SpillAlignment)
631     return 1;
632
633   // Finally order by name as a tie breaker.
634   return StringRef(A->getName()).compare(B->getName());
635 }
636
637 std::string CodeGenRegisterClass::getQualifiedName() const {
638   if (Namespace.empty())
639     return getName();
640   else
641     return Namespace + "::" + getName();
642 }
643
644 // Compute sub-classes of all register classes.
645 // Assume the classes are ordered topologically.
646 void CodeGenRegisterClass::computeSubClasses(CodeGenRegBank &RegBank) {
647   ArrayRef<CodeGenRegisterClass*> RegClasses = RegBank.getRegClasses();
648
649   // Visit backwards so sub-classes are seen first.
650   for (unsigned rci = RegClasses.size(); rci; --rci) {
651     CodeGenRegisterClass &RC = *RegClasses[rci - 1];
652     RC.SubClasses.resize(RegClasses.size());
653     RC.SubClasses.set(RC.EnumValue);
654
655     // Normally, all subclasses have IDs >= rci, unless RC is part of a clique.
656     for (unsigned s = rci; s != RegClasses.size(); ++s) {
657       if (RC.SubClasses.test(s))
658         continue;
659       CodeGenRegisterClass *SubRC = RegClasses[s];
660       if (!testSubClass(&RC, SubRC))
661         continue;
662       // SubRC is a sub-class. Grap all its sub-classes so we won't have to
663       // check them again.
664       RC.SubClasses |= SubRC->SubClasses;
665     }
666
667     // Sweep up missed clique members.  They will be immediately preceeding RC.
668     for (unsigned s = rci - 1; s && testSubClass(&RC, RegClasses[s - 1]); --s)
669       RC.SubClasses.set(s - 1);
670   }
671
672   // Compute the SuperClasses lists from the SubClasses vectors.
673   for (unsigned rci = 0; rci != RegClasses.size(); ++rci) {
674     const BitVector &SC = RegClasses[rci]->getSubClasses();
675     for (int s = SC.find_first(); s >= 0; s = SC.find_next(s)) {
676       if (unsigned(s) == rci)
677         continue;
678       RegClasses[s]->SuperClasses.push_back(RegClasses[rci]);
679     }
680   }
681
682   // With the class hierarchy in place, let synthesized register classes inherit
683   // properties from their closest super-class. The iteration order here can
684   // propagate properties down multiple levels.
685   for (unsigned rci = 0; rci != RegClasses.size(); ++rci)
686     if (!RegClasses[rci]->getDef())
687       RegClasses[rci]->inheritProperties(RegBank);
688 }
689
690 void
691 CodeGenRegisterClass::getSuperRegClasses(CodeGenSubRegIndex *SubIdx,
692                                          BitVector &Out) const {
693   DenseMap<CodeGenSubRegIndex*,
694            SmallPtrSet<CodeGenRegisterClass*, 8> >::const_iterator
695     FindI = SuperRegClasses.find(SubIdx);
696   if (FindI == SuperRegClasses.end())
697     return;
698   for (SmallPtrSet<CodeGenRegisterClass*, 8>::const_iterator I =
699        FindI->second.begin(), E = FindI->second.end(); I != E; ++I)
700     Out.set((*I)->EnumValue);
701 }
702
703 // Populate a unique sorted list of units from a register set.
704 void CodeGenRegisterClass::buildRegUnitSet(
705   std::vector<unsigned> &RegUnits) const {
706   std::vector<unsigned> TmpUnits;
707   for (RegUnitIterator UnitI(Members); UnitI.isValid(); ++UnitI)
708     TmpUnits.push_back(*UnitI);
709   std::sort(TmpUnits.begin(), TmpUnits.end());
710   std::unique_copy(TmpUnits.begin(), TmpUnits.end(),
711                    std::back_inserter(RegUnits));
712 }
713
714 //===----------------------------------------------------------------------===//
715 //                               CodeGenRegBank
716 //===----------------------------------------------------------------------===//
717
718 CodeGenRegBank::CodeGenRegBank(RecordKeeper &Records) : Records(Records) {
719   // Configure register Sets to understand register classes and tuples.
720   Sets.addFieldExpander("RegisterClass", "MemberList");
721   Sets.addFieldExpander("CalleeSavedRegs", "SaveList");
722   Sets.addExpander("RegisterTuples", new TupleExpander());
723
724   // Read in the user-defined (named) sub-register indices.
725   // More indices will be synthesized later.
726   std::vector<Record*> SRIs = Records.getAllDerivedDefinitions("SubRegIndex");
727   std::sort(SRIs.begin(), SRIs.end(), LessRecord());
728   NumNamedIndices = SRIs.size();
729   for (unsigned i = 0, e = SRIs.size(); i != e; ++i)
730     getSubRegIdx(SRIs[i]);
731   // Build composite maps from ComposedOf fields.
732   for (unsigned i = 0, e = SubRegIndices.size(); i != e; ++i)
733     SubRegIndices[i]->updateComponents(*this);
734
735   // Read in the register definitions.
736   std::vector<Record*> Regs = Records.getAllDerivedDefinitions("Register");
737   std::sort(Regs.begin(), Regs.end(), LessRecord());
738   Registers.reserve(Regs.size());
739   // Assign the enumeration values.
740   for (unsigned i = 0, e = Regs.size(); i != e; ++i)
741     getReg(Regs[i]);
742
743   // Expand tuples and number the new registers.
744   std::vector<Record*> Tups =
745     Records.getAllDerivedDefinitions("RegisterTuples");
746   for (unsigned i = 0, e = Tups.size(); i != e; ++i) {
747     const std::vector<Record*> *TupRegs = Sets.expand(Tups[i]);
748     for (unsigned j = 0, je = TupRegs->size(); j != je; ++j)
749       getReg((*TupRegs)[j]);
750   }
751
752   // Precompute all sub-register maps now all the registers are known.
753   // This will create Composite entries for all inferred sub-register indices.
754   NumRegUnits = 0;
755   for (unsigned i = 0, e = Registers.size(); i != e; ++i)
756     Registers[i]->getSubRegs(*this);
757
758   // Native register units are associated with a leaf register. They've all been
759   // discovered now.
760   NumNativeRegUnits = NumRegUnits;
761
762   // Read in register class definitions.
763   std::vector<Record*> RCs = Records.getAllDerivedDefinitions("RegisterClass");
764   if (RCs.empty())
765     throw std::string("No 'RegisterClass' subclasses defined!");
766
767   // Allocate user-defined register classes.
768   RegClasses.reserve(RCs.size());
769   for (unsigned i = 0, e = RCs.size(); i != e; ++i)
770     addToMaps(new CodeGenRegisterClass(*this, RCs[i]));
771
772   // Infer missing classes to create a full algebra.
773   computeInferredRegisterClasses();
774
775   // Order register classes topologically and assign enum values.
776   array_pod_sort(RegClasses.begin(), RegClasses.end(), TopoOrderRC);
777   for (unsigned i = 0, e = RegClasses.size(); i != e; ++i)
778     RegClasses[i]->EnumValue = i;
779   CodeGenRegisterClass::computeSubClasses(*this);
780 }
781
782 CodeGenSubRegIndex *CodeGenRegBank::getSubRegIdx(Record *Def) {
783   CodeGenSubRegIndex *&Idx = Def2SubRegIdx[Def];
784   if (Idx)
785     return Idx;
786   Idx = new CodeGenSubRegIndex(Def, SubRegIndices.size() + 1);
787   SubRegIndices.push_back(Idx);
788   return Idx;
789 }
790
791 CodeGenRegister *CodeGenRegBank::getReg(Record *Def) {
792   CodeGenRegister *&Reg = Def2Reg[Def];
793   if (Reg)
794     return Reg;
795   Reg = new CodeGenRegister(Def, Registers.size() + 1);
796   Registers.push_back(Reg);
797   return Reg;
798 }
799
800 void CodeGenRegBank::addToMaps(CodeGenRegisterClass *RC) {
801   RegClasses.push_back(RC);
802
803   if (Record *Def = RC->getDef())
804     Def2RC.insert(std::make_pair(Def, RC));
805
806   // Duplicate classes are rejected by insert().
807   // That's OK, we only care about the properties handled by CGRC::Key.
808   CodeGenRegisterClass::Key K(*RC);
809   Key2RC.insert(std::make_pair(K, RC));
810 }
811
812 // Create a synthetic sub-class if it is missing.
813 CodeGenRegisterClass*
814 CodeGenRegBank::getOrCreateSubClass(const CodeGenRegisterClass *RC,
815                                     const CodeGenRegister::Set *Members,
816                                     StringRef Name) {
817   // Synthetic sub-class has the same size and alignment as RC.
818   CodeGenRegisterClass::Key K(Members, RC->SpillSize, RC->SpillAlignment);
819   RCKeyMap::const_iterator FoundI = Key2RC.find(K);
820   if (FoundI != Key2RC.end())
821     return FoundI->second;
822
823   // Sub-class doesn't exist, create a new one.
824   CodeGenRegisterClass *NewRC = new CodeGenRegisterClass(Name, K);
825   addToMaps(NewRC);
826   return NewRC;
827 }
828
829 CodeGenRegisterClass *CodeGenRegBank::getRegClass(Record *Def) {
830   if (CodeGenRegisterClass *RC = Def2RC[Def])
831     return RC;
832
833   throw TGError(Def->getLoc(), "Not a known RegisterClass!");
834 }
835
836 CodeGenSubRegIndex*
837 CodeGenRegBank::getCompositeSubRegIndex(CodeGenSubRegIndex *A,
838                                         CodeGenSubRegIndex *B) {
839   // Look for an existing entry.
840   CodeGenSubRegIndex *Comp = A->compose(B);
841   if (Comp)
842     return Comp;
843
844   // None exists, synthesize one.
845   std::string Name = A->getName() + "_then_" + B->getName();
846   Comp = getSubRegIdx(new Record(Name, SMLoc(), Records));
847   A->addComposite(B, Comp);
848   return Comp;
849 }
850
851 void CodeGenRegBank::computeComposites() {
852   for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
853     CodeGenRegister *Reg1 = Registers[i];
854     const CodeGenRegister::SubRegMap &SRM1 = Reg1->getSubRegs();
855     for (CodeGenRegister::SubRegMap::const_iterator i1 = SRM1.begin(),
856          e1 = SRM1.end(); i1 != e1; ++i1) {
857       CodeGenSubRegIndex *Idx1 = i1->first;
858       CodeGenRegister *Reg2 = i1->second;
859       // Ignore identity compositions.
860       if (Reg1 == Reg2)
861         continue;
862       const CodeGenRegister::SubRegMap &SRM2 = Reg2->getSubRegs();
863       // Try composing Idx1 with another SubRegIndex.
864       for (CodeGenRegister::SubRegMap::const_iterator i2 = SRM2.begin(),
865            e2 = SRM2.end(); i2 != e2; ++i2) {
866       CodeGenSubRegIndex *Idx2 = i2->first;
867         CodeGenRegister *Reg3 = i2->second;
868         // Ignore identity compositions.
869         if (Reg2 == Reg3)
870           continue;
871         // OK Reg1:IdxPair == Reg3. Find the index with Reg:Idx == Reg3.
872         for (CodeGenRegister::SubRegMap::const_iterator i1d = SRM1.begin(),
873              e1d = SRM1.end(); i1d != e1d; ++i1d) {
874           if (i1d->second == Reg3) {
875             // Conflicting composition? Emit a warning but allow it.
876             if (CodeGenSubRegIndex *Prev = Idx1->addComposite(Idx2, i1d->first))
877               PrintWarning(Twine("SubRegIndex") + Idx1->getQualifiedName() +
878                      " and " + Idx2->getQualifiedName() +
879                      " compose ambiguously as " + Prev->getQualifiedName() +
880                      " or " + i1d->first->getQualifiedName());
881           }
882         }
883       }
884     }
885   }
886
887   // We don't care about the difference between (Idx1, Idx2) -> Idx2 and invalid
888   // compositions, so remove any mappings of that form.
889   for (unsigned i = 0, e = SubRegIndices.size(); i != e; ++i)
890     SubRegIndices[i]->cleanComposites();
891 }
892
893 namespace {
894 // UberRegSet is a helper class for computeRegUnitWeights. Each UberRegSet is
895 // the transitive closure of the union of overlapping register
896 // classes. Together, the UberRegSets form a partition of the registers. If we
897 // consider overlapping register classes to be connected, then each UberRegSet
898 // is a set of connected components.
899 //
900 // An UberRegSet will likely be a horizontal slice of register names of
901 // the same width. Nontrivial subregisters should then be in a separate
902 // UberRegSet. But this property isn't required for valid computation of
903 // register unit weights.
904 //
905 // A Weight field caches the max per-register unit weight in each UberRegSet.
906 //
907 // A set of SingularDeterminants flags single units of some register in this set
908 // for which the unit weight equals the set weight. These units should not have
909 // their weight increased.
910 struct UberRegSet {
911   CodeGenRegister::Set Regs;
912   unsigned Weight;
913   CodeGenRegister::RegUnitList SingularDeterminants;
914
915   UberRegSet(): Weight(0) {}
916 };
917 } // namespace
918
919 // Partition registers into UberRegSets, where each set is the transitive
920 // closure of the union of overlapping register classes.
921 //
922 // UberRegSets[0] is a special non-allocatable set.
923 static void computeUberSets(std::vector<UberRegSet> &UberSets,
924                             std::vector<UberRegSet*> &RegSets,
925                             CodeGenRegBank &RegBank) {
926
927   const std::vector<CodeGenRegister*> &Registers = RegBank.getRegisters();
928
929   // The Register EnumValue is one greater than its index into Registers.
930   assert(Registers.size() == Registers[Registers.size()-1]->EnumValue &&
931          "register enum value mismatch");
932
933   // For simplicitly make the SetID the same as EnumValue.
934   IntEqClasses UberSetIDs(Registers.size()+1);
935   std::set<unsigned> AllocatableRegs;
936   for (unsigned i = 0, e = RegBank.getRegClasses().size(); i != e; ++i) {
937
938     CodeGenRegisterClass *RegClass = RegBank.getRegClasses()[i];
939     if (!RegClass->Allocatable)
940       continue;
941
942     const CodeGenRegister::Set &Regs = RegClass->getMembers();
943     if (Regs.empty())
944       continue;
945
946     unsigned USetID = UberSetIDs.findLeader((*Regs.begin())->EnumValue);
947     assert(USetID && "register number 0 is invalid");
948
949     AllocatableRegs.insert((*Regs.begin())->EnumValue);
950     for (CodeGenRegister::Set::const_iterator I = llvm::next(Regs.begin()),
951            E = Regs.end(); I != E; ++I) {
952       AllocatableRegs.insert((*I)->EnumValue);
953       UberSetIDs.join(USetID, (*I)->EnumValue);
954     }
955   }
956   // Combine non-allocatable regs.
957   for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
958     unsigned RegNum = Registers[i]->EnumValue;
959     if (AllocatableRegs.count(RegNum))
960       continue;
961
962     UberSetIDs.join(0, RegNum);
963   }
964   UberSetIDs.compress();
965
966   // Make the first UberSet a special unallocatable set.
967   unsigned ZeroID = UberSetIDs[0];
968
969   // Insert Registers into the UberSets formed by union-find.
970   // Do not resize after this.
971   UberSets.resize(UberSetIDs.getNumClasses());
972   for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
973     const CodeGenRegister *Reg = Registers[i];
974     unsigned USetID = UberSetIDs[Reg->EnumValue];
975     if (!USetID)
976       USetID = ZeroID;
977     else if (USetID == ZeroID)
978       USetID = 0;
979
980     UberRegSet *USet = &UberSets[USetID];
981     USet->Regs.insert(Reg);
982     RegSets[i] = USet;
983   }
984 }
985
986 // Recompute each UberSet weight after changing unit weights.
987 static void computeUberWeights(std::vector<UberRegSet> &UberSets,
988                                CodeGenRegBank &RegBank) {
989   // Skip the first unallocatable set.
990   for (std::vector<UberRegSet>::iterator I = llvm::next(UberSets.begin()),
991          E = UberSets.end(); I != E; ++I) {
992
993     // Initialize all unit weights in this set, and remember the max units/reg.
994     const CodeGenRegister *Reg = 0;
995     unsigned MaxWeight = 0, Weight = 0;
996     for (RegUnitIterator UnitI(I->Regs); UnitI.isValid(); ++UnitI) {
997       if (Reg != UnitI.getReg()) {
998         if (Weight > MaxWeight)
999           MaxWeight = Weight;
1000         Reg = UnitI.getReg();
1001         Weight = 0;
1002       }
1003       unsigned UWeight = RegBank.getRegUnitWeight(*UnitI);
1004       if (!UWeight) {
1005         UWeight = 1;
1006         RegBank.increaseRegUnitWeight(*UnitI, UWeight);
1007       }
1008       Weight += UWeight;
1009     }
1010     if (Weight > MaxWeight)
1011       MaxWeight = Weight;
1012
1013     // Update the set weight.
1014     I->Weight = MaxWeight;
1015
1016     // Find singular determinants.
1017     for (CodeGenRegister::Set::iterator RegI = I->Regs.begin(),
1018            RegE = I->Regs.end(); RegI != RegE; ++RegI) {
1019       if ((*RegI)->getRegUnits().size() == 1
1020           && (*RegI)->getWeight(RegBank) == I->Weight)
1021         mergeRegUnits(I->SingularDeterminants, (*RegI)->getRegUnits());
1022     }
1023   }
1024 }
1025
1026 // normalizeWeight is a computeRegUnitWeights helper that adjusts the weight of
1027 // a register and its subregisters so that they have the same weight as their
1028 // UberSet. Self-recursion processes the subregister tree in postorder so
1029 // subregisters are normalized first.
1030 //
1031 // Side effects:
1032 // - creates new adopted register units
1033 // - causes superregisters to inherit adopted units
1034 // - increases the weight of "singular" units
1035 // - induces recomputation of UberWeights.
1036 static bool normalizeWeight(CodeGenRegister *Reg,
1037                             std::vector<UberRegSet> &UberSets,
1038                             std::vector<UberRegSet*> &RegSets,
1039                             CodeGenRegister::RegUnitList &NormalUnits,
1040                             CodeGenRegBank &RegBank) {
1041   bool Changed = false;
1042   const CodeGenRegister::SubRegMap &SRM = Reg->getSubRegs();
1043   for (CodeGenRegister::SubRegMap::const_iterator SRI = SRM.begin(),
1044          SRE = SRM.end(); SRI != SRE; ++SRI) {
1045     if (SRI->second == Reg)
1046       continue; // self-cycles happen
1047
1048     Changed |=
1049       normalizeWeight(SRI->second, UberSets, RegSets, NormalUnits, RegBank);
1050   }
1051   // Postorder register normalization.
1052
1053   // Inherit register units newly adopted by subregisters.
1054   if (Reg->inheritRegUnits(RegBank))
1055     computeUberWeights(UberSets, RegBank);
1056
1057   // Check if this register is too skinny for its UberRegSet.
1058   UberRegSet *UberSet = RegSets[RegBank.getRegIndex(Reg)];
1059
1060   unsigned RegWeight = Reg->getWeight(RegBank);
1061   if (UberSet->Weight > RegWeight) {
1062     // A register unit's weight can be adjusted only if it is the singular unit
1063     // for this register, has not been used to normalize a subregister's set,
1064     // and has not already been used to singularly determine this UberRegSet.
1065     unsigned AdjustUnit = Reg->getRegUnits().front();
1066     if (Reg->getRegUnits().size() != 1
1067         || hasRegUnit(NormalUnits, AdjustUnit)
1068         || hasRegUnit(UberSet->SingularDeterminants, AdjustUnit)) {
1069       // We don't have an adjustable unit, so adopt a new one.
1070       AdjustUnit = RegBank.newRegUnit(UberSet->Weight - RegWeight);
1071       Reg->adoptRegUnit(AdjustUnit);
1072       // Adopting a unit does not immediately require recomputing set weights.
1073     }
1074     else {
1075       // Adjust the existing single unit.
1076       RegBank.increaseRegUnitWeight(AdjustUnit, UberSet->Weight - RegWeight);
1077       // The unit may be shared among sets and registers within this set.
1078       computeUberWeights(UberSets, RegBank);
1079     }
1080     Changed = true;
1081   }
1082
1083   // Mark these units normalized so superregisters can't change their weights.
1084   mergeRegUnits(NormalUnits, Reg->getRegUnits());
1085
1086   return Changed;
1087 }
1088
1089 // Compute a weight for each register unit created during getSubRegs.
1090 //
1091 // The goal is that two registers in the same class will have the same weight,
1092 // where each register's weight is defined as sum of its units' weights.
1093 void CodeGenRegBank::computeRegUnitWeights() {
1094   assert(RegUnitWeights.empty() && "Only initialize RegUnitWeights once");
1095
1096   // Only allocatable units will be initialized to nonzero weight.
1097   RegUnitWeights.resize(NumRegUnits);
1098
1099   std::vector<UberRegSet> UberSets;
1100   std::vector<UberRegSet*> RegSets(Registers.size());
1101   computeUberSets(UberSets, RegSets, *this);
1102   // UberSets and RegSets are now immutable.
1103
1104   computeUberWeights(UberSets, *this);
1105
1106   // Iterate over each Register, normalizing the unit weights until reaching
1107   // a fix point.
1108   unsigned NumIters = 0;
1109   for (bool Changed = true; Changed; ++NumIters) {
1110     assert(NumIters <= NumNativeRegUnits && "Runaway register unit weights");
1111     Changed = false;
1112     for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
1113       CodeGenRegister::RegUnitList NormalUnits;
1114       Changed |=
1115         normalizeWeight(Registers[i], UberSets, RegSets, NormalUnits, *this);
1116     }
1117   }
1118 }
1119
1120 // Find a set in UniqueSets with the same elements as Set.
1121 // Return an iterator into UniqueSets.
1122 static std::vector<RegUnitSet>::const_iterator
1123 findRegUnitSet(const std::vector<RegUnitSet> &UniqueSets,
1124                const RegUnitSet &Set) {
1125   std::vector<RegUnitSet>::const_iterator
1126     I = UniqueSets.begin(), E = UniqueSets.end();
1127   for(;I != E; ++I) {
1128     if (I->Units == Set.Units)
1129       break;
1130   }
1131   return I;
1132 }
1133
1134 // Return true if the RUSubSet is a subset of RUSuperSet.
1135 static bool isRegUnitSubSet(const std::vector<unsigned> &RUSubSet,
1136                             const std::vector<unsigned> &RUSuperSet) {
1137   return std::includes(RUSuperSet.begin(), RUSuperSet.end(),
1138                        RUSubSet.begin(), RUSubSet.end());
1139 }
1140
1141 // Iteratively prune unit sets.
1142 void CodeGenRegBank::pruneUnitSets() {
1143   assert(RegClassUnitSets.empty() && "this invalidates RegClassUnitSets");
1144
1145   // Form an equivalence class of UnitSets with no significant difference.
1146   std::vector<unsigned> SuperSetIDs;
1147   for (unsigned SubIdx = 0, EndIdx = RegUnitSets.size();
1148        SubIdx != EndIdx; ++SubIdx) {
1149     const RegUnitSet &SubSet = RegUnitSets[SubIdx];
1150     unsigned SuperIdx = 0;
1151     for (; SuperIdx != EndIdx; ++SuperIdx) {
1152       if (SuperIdx == SubIdx)
1153         continue;
1154
1155       const RegUnitSet &SuperSet = RegUnitSets[SuperIdx];
1156       if (isRegUnitSubSet(SubSet.Units, SuperSet.Units)
1157           && (SubSet.Units.size() + 3 > SuperSet.Units.size())) {
1158         break;
1159       }
1160     }
1161     if (SuperIdx == EndIdx)
1162       SuperSetIDs.push_back(SubIdx);
1163   }
1164   // Populate PrunedUnitSets with each equivalence class's superset.
1165   std::vector<RegUnitSet> PrunedUnitSets(SuperSetIDs.size());
1166   for (unsigned i = 0, e = SuperSetIDs.size(); i != e; ++i) {
1167     unsigned SuperIdx = SuperSetIDs[i];
1168     PrunedUnitSets[i].Name = RegUnitSets[SuperIdx].Name;
1169     PrunedUnitSets[i].Units.swap(RegUnitSets[SuperIdx].Units);
1170   }
1171   RegUnitSets.swap(PrunedUnitSets);
1172 }
1173
1174 // Create a RegUnitSet for each RegClass that contains all units in the class
1175 // including adopted units that are necessary to model register pressure. Then
1176 // iteratively compute RegUnitSets such that the union of any two overlapping
1177 // RegUnitSets is repreresented.
1178 //
1179 // RegisterInfoEmitter will map each RegClass to its RegUnitClass and any
1180 // RegUnitSet that is a superset of that RegUnitClass.
1181 void CodeGenRegBank::computeRegUnitSets() {
1182
1183   // Compute a unique RegUnitSet for each RegClass.
1184   const ArrayRef<CodeGenRegisterClass*> &RegClasses = getRegClasses();
1185   unsigned NumRegClasses = RegClasses.size();
1186   for (unsigned RCIdx = 0, RCEnd = NumRegClasses; RCIdx != RCEnd; ++RCIdx) {
1187     if (!RegClasses[RCIdx]->Allocatable)
1188       continue;
1189
1190     // Speculatively grow the RegUnitSets to hold the new set.
1191     RegUnitSets.resize(RegUnitSets.size() + 1);
1192     RegUnitSets.back().Name = RegClasses[RCIdx]->getName();
1193
1194     // Compute a sorted list of units in this class.
1195     RegClasses[RCIdx]->buildRegUnitSet(RegUnitSets.back().Units);
1196
1197     // Find an existing RegUnitSet.
1198     std::vector<RegUnitSet>::const_iterator SetI =
1199       findRegUnitSet(RegUnitSets, RegUnitSets.back());
1200     if (SetI != llvm::prior(RegUnitSets.end()))
1201       RegUnitSets.pop_back();
1202   }
1203
1204   // Iteratively prune unit sets.
1205   pruneUnitSets();
1206
1207   // Iterate over all unit sets, including new ones added by this loop.
1208   unsigned NumRegUnitSubSets = RegUnitSets.size();
1209   for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx) {
1210     // In theory, this is combinatorial. In practice, it needs to be bounded
1211     // by a small number of sets for regpressure to be efficient.
1212     // If the assert is hit, we need to implement pruning.
1213     assert(Idx < (2*NumRegUnitSubSets) && "runaway unit set inference");
1214
1215     // Compare new sets with all original classes.
1216     for (unsigned SearchIdx = (Idx >= NumRegUnitSubSets) ? 0 : Idx+1;
1217          SearchIdx != EndIdx; ++SearchIdx) {
1218       std::set<unsigned> Intersection;
1219       std::set_intersection(RegUnitSets[Idx].Units.begin(),
1220                             RegUnitSets[Idx].Units.end(),
1221                             RegUnitSets[SearchIdx].Units.begin(),
1222                             RegUnitSets[SearchIdx].Units.end(),
1223                             std::inserter(Intersection, Intersection.begin()));
1224       if (Intersection.empty())
1225         continue;
1226
1227       // Speculatively grow the RegUnitSets to hold the new set.
1228       RegUnitSets.resize(RegUnitSets.size() + 1);
1229       RegUnitSets.back().Name =
1230         RegUnitSets[Idx].Name + "+" + RegUnitSets[SearchIdx].Name;
1231
1232       std::set_union(RegUnitSets[Idx].Units.begin(),
1233                      RegUnitSets[Idx].Units.end(),
1234                      RegUnitSets[SearchIdx].Units.begin(),
1235                      RegUnitSets[SearchIdx].Units.end(),
1236                      std::inserter(RegUnitSets.back().Units,
1237                                    RegUnitSets.back().Units.begin()));
1238
1239       // Find an existing RegUnitSet, or add the union to the unique sets.
1240       std::vector<RegUnitSet>::const_iterator SetI =
1241         findRegUnitSet(RegUnitSets, RegUnitSets.back());
1242       if (SetI != llvm::prior(RegUnitSets.end()))
1243         RegUnitSets.pop_back();
1244     }
1245   }
1246
1247   // Iteratively prune unit sets after inferring supersets.
1248   pruneUnitSets();
1249
1250   // For each register class, list the UnitSets that are supersets.
1251   RegClassUnitSets.resize(NumRegClasses);
1252   for (unsigned RCIdx = 0, RCEnd = NumRegClasses; RCIdx != RCEnd; ++RCIdx) {
1253     if (!RegClasses[RCIdx]->Allocatable)
1254       continue;
1255
1256     // Recompute the sorted list of units in this class.
1257     std::vector<unsigned> RegUnits;
1258     RegClasses[RCIdx]->buildRegUnitSet(RegUnits);
1259
1260     // Don't increase pressure for unallocatable regclasses.
1261     if (RegUnits.empty())
1262       continue;
1263
1264     // Find all supersets.
1265     for (unsigned USIdx = 0, USEnd = RegUnitSets.size();
1266          USIdx != USEnd; ++USIdx) {
1267       if (isRegUnitSubSet(RegUnits, RegUnitSets[USIdx].Units))
1268         RegClassUnitSets[RCIdx].push_back(USIdx);
1269     }
1270     assert(!RegClassUnitSets[RCIdx].empty() && "missing unit set for regclass");
1271   }
1272 }
1273
1274 // Compute sets of overlapping registers.
1275 //
1276 // The standard set is all super-registers and all sub-registers, but the
1277 // target description can add arbitrary overlapping registers via the 'Aliases'
1278 // field. This complicates things, but we can compute overlapping sets using
1279 // the following rules:
1280 //
1281 // 1. The relation overlap(A, B) is reflexive and symmetric but not transitive.
1282 //
1283 // 2. overlap(A, B) implies overlap(A, S) for all S in supers(B).
1284 //
1285 // Alternatively:
1286 //
1287 //    overlap(A, B) iff there exists:
1288 //    A' in { A, subregs(A) } and B' in { B, subregs(B) } such that:
1289 //    A' = B' or A' in aliases(B') or B' in aliases(A').
1290 //
1291 // Here subregs(A) is the full flattened sub-register set returned by
1292 // A.getSubRegs() while aliases(A) is simply the special 'Aliases' field in the
1293 // description of register A.
1294 //
1295 // This also implies that registers with a common sub-register are considered
1296 // overlapping. This can happen when forming register pairs:
1297 //
1298 //    P0 = (R0, R1)
1299 //    P1 = (R1, R2)
1300 //    P2 = (R2, R3)
1301 //
1302 // In this case, we will infer an overlap between P0 and P1 because of the
1303 // shared sub-register R1. There is no overlap between P0 and P2.
1304 //
1305 void CodeGenRegBank::
1306 computeOverlaps(std::map<const CodeGenRegister*, CodeGenRegister::Set> &Map) {
1307   assert(Map.empty());
1308
1309   // Collect overlaps that don't follow from rule 2.
1310   for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
1311     CodeGenRegister *Reg = Registers[i];
1312     CodeGenRegister::Set &Overlaps = Map[Reg];
1313
1314     // Reg overlaps itself.
1315     Overlaps.insert(Reg);
1316
1317     // All super-registers overlap.
1318     const CodeGenRegister::SuperRegList &Supers = Reg->getSuperRegs();
1319     Overlaps.insert(Supers.begin(), Supers.end());
1320
1321     // Form symmetrical relations from the special Aliases[] lists.
1322     std::vector<Record*> RegList = Reg->TheDef->getValueAsListOfDefs("Aliases");
1323     for (unsigned i2 = 0, e2 = RegList.size(); i2 != e2; ++i2) {
1324       CodeGenRegister *Reg2 = getReg(RegList[i2]);
1325       CodeGenRegister::Set &Overlaps2 = Map[Reg2];
1326       const CodeGenRegister::SuperRegList &Supers2 = Reg2->getSuperRegs();
1327       // Reg overlaps Reg2 which implies it overlaps supers(Reg2).
1328       Overlaps.insert(Reg2);
1329       Overlaps.insert(Supers2.begin(), Supers2.end());
1330       Overlaps2.insert(Reg);
1331       Overlaps2.insert(Supers.begin(), Supers.end());
1332     }
1333   }
1334
1335   // Apply rule 2. and inherit all sub-register overlaps.
1336   for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
1337     CodeGenRegister *Reg = Registers[i];
1338     CodeGenRegister::Set &Overlaps = Map[Reg];
1339     const CodeGenRegister::SubRegMap &SRM = Reg->getSubRegs();
1340     for (CodeGenRegister::SubRegMap::const_iterator i2 = SRM.begin(),
1341          e2 = SRM.end(); i2 != e2; ++i2) {
1342       CodeGenRegister::Set &Overlaps2 = Map[i2->second];
1343       Overlaps.insert(Overlaps2.begin(), Overlaps2.end());
1344     }
1345   }
1346 }
1347
1348 void CodeGenRegBank::computeDerivedInfo() {
1349   computeComposites();
1350
1351   // Compute a weight for each register unit created during getSubRegs.
1352   // This may create adopted register units (with unit # >= NumNativeRegUnits).
1353   computeRegUnitWeights();
1354
1355   // Compute a unique set of RegUnitSets. One for each RegClass and inferred
1356   // supersets for the union of overlapping sets.
1357   computeRegUnitSets();
1358 }
1359
1360 //
1361 // Synthesize missing register class intersections.
1362 //
1363 // Make sure that sub-classes of RC exists such that getCommonSubClass(RC, X)
1364 // returns a maximal register class for all X.
1365 //
1366 void CodeGenRegBank::inferCommonSubClass(CodeGenRegisterClass *RC) {
1367   for (unsigned rci = 0, rce = RegClasses.size(); rci != rce; ++rci) {
1368     CodeGenRegisterClass *RC1 = RC;
1369     CodeGenRegisterClass *RC2 = RegClasses[rci];
1370     if (RC1 == RC2)
1371       continue;
1372
1373     // Compute the set intersection of RC1 and RC2.
1374     const CodeGenRegister::Set &Memb1 = RC1->getMembers();
1375     const CodeGenRegister::Set &Memb2 = RC2->getMembers();
1376     CodeGenRegister::Set Intersection;
1377     std::set_intersection(Memb1.begin(), Memb1.end(),
1378                           Memb2.begin(), Memb2.end(),
1379                           std::inserter(Intersection, Intersection.begin()),
1380                           CodeGenRegister::Less());
1381
1382     // Skip disjoint class pairs.
1383     if (Intersection.empty())
1384       continue;
1385
1386     // If RC1 and RC2 have different spill sizes or alignments, use the
1387     // larger size for sub-classing.  If they are equal, prefer RC1.
1388     if (RC2->SpillSize > RC1->SpillSize ||
1389         (RC2->SpillSize == RC1->SpillSize &&
1390          RC2->SpillAlignment > RC1->SpillAlignment))
1391       std::swap(RC1, RC2);
1392
1393     getOrCreateSubClass(RC1, &Intersection,
1394                         RC1->getName() + "_and_" + RC2->getName());
1395   }
1396 }
1397
1398 //
1399 // Synthesize missing sub-classes for getSubClassWithSubReg().
1400 //
1401 // Make sure that the set of registers in RC with a given SubIdx sub-register
1402 // form a register class.  Update RC->SubClassWithSubReg.
1403 //
1404 void CodeGenRegBank::inferSubClassWithSubReg(CodeGenRegisterClass *RC) {
1405   // Map SubRegIndex to set of registers in RC supporting that SubRegIndex.
1406   typedef std::map<CodeGenSubRegIndex*, CodeGenRegister::Set,
1407                    CodeGenSubRegIndex::Less> SubReg2SetMap;
1408
1409   // Compute the set of registers supporting each SubRegIndex.
1410   SubReg2SetMap SRSets;
1411   for (CodeGenRegister::Set::const_iterator RI = RC->getMembers().begin(),
1412        RE = RC->getMembers().end(); RI != RE; ++RI) {
1413     const CodeGenRegister::SubRegMap &SRM = (*RI)->getSubRegs();
1414     for (CodeGenRegister::SubRegMap::const_iterator I = SRM.begin(),
1415          E = SRM.end(); I != E; ++I)
1416       SRSets[I->first].insert(*RI);
1417   }
1418
1419   // Find matching classes for all SRSets entries.  Iterate in SubRegIndex
1420   // numerical order to visit synthetic indices last.
1421   for (unsigned sri = 0, sre = SubRegIndices.size(); sri != sre; ++sri) {
1422     CodeGenSubRegIndex *SubIdx = SubRegIndices[sri];
1423     SubReg2SetMap::const_iterator I = SRSets.find(SubIdx);
1424     // Unsupported SubRegIndex. Skip it.
1425     if (I == SRSets.end())
1426       continue;
1427     // In most cases, all RC registers support the SubRegIndex.
1428     if (I->second.size() == RC->getMembers().size()) {
1429       RC->setSubClassWithSubReg(SubIdx, RC);
1430       continue;
1431     }
1432     // This is a real subset.  See if we have a matching class.
1433     CodeGenRegisterClass *SubRC =
1434       getOrCreateSubClass(RC, &I->second,
1435                           RC->getName() + "_with_" + I->first->getName());
1436     RC->setSubClassWithSubReg(SubIdx, SubRC);
1437   }
1438 }
1439
1440 //
1441 // Synthesize missing sub-classes of RC for getMatchingSuperRegClass().
1442 //
1443 // Create sub-classes of RC such that getMatchingSuperRegClass(RC, SubIdx, X)
1444 // has a maximal result for any SubIdx and any X >= FirstSubRegRC.
1445 //
1446
1447 void CodeGenRegBank::inferMatchingSuperRegClass(CodeGenRegisterClass *RC,
1448                                                 unsigned FirstSubRegRC) {
1449   SmallVector<std::pair<const CodeGenRegister*,
1450                         const CodeGenRegister*>, 16> SSPairs;
1451
1452   // Iterate in SubRegIndex numerical order to visit synthetic indices last.
1453   for (unsigned sri = 0, sre = SubRegIndices.size(); sri != sre; ++sri) {
1454     CodeGenSubRegIndex *SubIdx = SubRegIndices[sri];
1455     // Skip indexes that aren't fully supported by RC's registers. This was
1456     // computed by inferSubClassWithSubReg() above which should have been
1457     // called first.
1458     if (RC->getSubClassWithSubReg(SubIdx) != RC)
1459       continue;
1460
1461     // Build list of (Super, Sub) pairs for this SubIdx.
1462     SSPairs.clear();
1463     for (CodeGenRegister::Set::const_iterator RI = RC->getMembers().begin(),
1464          RE = RC->getMembers().end(); RI != RE; ++RI) {
1465       const CodeGenRegister *Super = *RI;
1466       const CodeGenRegister *Sub = Super->getSubRegs().find(SubIdx)->second;
1467       assert(Sub && "Missing sub-register");
1468       SSPairs.push_back(std::make_pair(Super, Sub));
1469     }
1470
1471     // Iterate over sub-register class candidates.  Ignore classes created by
1472     // this loop. They will never be useful.
1473     for (unsigned rci = FirstSubRegRC, rce = RegClasses.size(); rci != rce;
1474          ++rci) {
1475       CodeGenRegisterClass *SubRC = RegClasses[rci];
1476       // Compute the subset of RC that maps into SubRC.
1477       CodeGenRegister::Set SubSet;
1478       for (unsigned i = 0, e = SSPairs.size(); i != e; ++i)
1479         if (SubRC->contains(SSPairs[i].second))
1480           SubSet.insert(SSPairs[i].first);
1481       if (SubSet.empty())
1482         continue;
1483       // RC injects completely into SubRC.
1484       if (SubSet.size() == SSPairs.size()) {
1485         SubRC->addSuperRegClass(SubIdx, RC);
1486         continue;
1487       }
1488       // Only a subset of RC maps into SubRC. Make sure it is represented by a
1489       // class.
1490       getOrCreateSubClass(RC, &SubSet, RC->getName() +
1491                           "_with_" + SubIdx->getName() +
1492                           "_in_" + SubRC->getName());
1493     }
1494   }
1495 }
1496
1497
1498 //
1499 // Infer missing register classes.
1500 //
1501 void CodeGenRegBank::computeInferredRegisterClasses() {
1502   // When this function is called, the register classes have not been sorted
1503   // and assigned EnumValues yet.  That means getSubClasses(),
1504   // getSuperClasses(), and hasSubClass() functions are defunct.
1505   unsigned FirstNewRC = RegClasses.size();
1506
1507   // Visit all register classes, including the ones being added by the loop.
1508   for (unsigned rci = 0; rci != RegClasses.size(); ++rci) {
1509     CodeGenRegisterClass *RC = RegClasses[rci];
1510
1511     // Synthesize answers for getSubClassWithSubReg().
1512     inferSubClassWithSubReg(RC);
1513
1514     // Synthesize answers for getCommonSubClass().
1515     inferCommonSubClass(RC);
1516
1517     // Synthesize answers for getMatchingSuperRegClass().
1518     inferMatchingSuperRegClass(RC);
1519
1520     // New register classes are created while this loop is running, and we need
1521     // to visit all of them.  I  particular, inferMatchingSuperRegClass needs
1522     // to match old super-register classes with sub-register classes created
1523     // after inferMatchingSuperRegClass was called.  At this point,
1524     // inferMatchingSuperRegClass has checked SuperRC = [0..rci] with SubRC =
1525     // [0..FirstNewRC).  We need to cover SubRC = [FirstNewRC..rci].
1526     if (rci + 1 == FirstNewRC) {
1527       unsigned NextNewRC = RegClasses.size();
1528       for (unsigned rci2 = 0; rci2 != FirstNewRC; ++rci2)
1529         inferMatchingSuperRegClass(RegClasses[rci2], FirstNewRC);
1530       FirstNewRC = NextNewRC;
1531     }
1532   }
1533 }
1534
1535 /// getRegisterClassForRegister - Find the register class that contains the
1536 /// specified physical register.  If the register is not in a register class,
1537 /// return null. If the register is in multiple classes, and the classes have a
1538 /// superset-subset relationship and the same set of types, return the
1539 /// superclass.  Otherwise return null.
1540 const CodeGenRegisterClass*
1541 CodeGenRegBank::getRegClassForRegister(Record *R) {
1542   const CodeGenRegister *Reg = getReg(R);
1543   ArrayRef<CodeGenRegisterClass*> RCs = getRegClasses();
1544   const CodeGenRegisterClass *FoundRC = 0;
1545   for (unsigned i = 0, e = RCs.size(); i != e; ++i) {
1546     const CodeGenRegisterClass &RC = *RCs[i];
1547     if (!RC.contains(Reg))
1548       continue;
1549
1550     // If this is the first class that contains the register,
1551     // make a note of it and go on to the next class.
1552     if (!FoundRC) {
1553       FoundRC = &RC;
1554       continue;
1555     }
1556
1557     // If a register's classes have different types, return null.
1558     if (RC.getValueTypes() != FoundRC->getValueTypes())
1559       return 0;
1560
1561     // Check to see if the previously found class that contains
1562     // the register is a subclass of the current class. If so,
1563     // prefer the superclass.
1564     if (RC.hasSubClass(FoundRC)) {
1565       FoundRC = &RC;
1566       continue;
1567     }
1568
1569     // Check to see if the previously found class that contains
1570     // the register is a superclass of the current class. If so,
1571     // prefer the superclass.
1572     if (FoundRC->hasSubClass(&RC))
1573       continue;
1574
1575     // Multiple classes, and neither is a superclass of the other.
1576     // Return null.
1577     return 0;
1578   }
1579   return FoundRC;
1580 }
1581
1582 BitVector CodeGenRegBank::computeCoveredRegisters(ArrayRef<Record*> Regs) {
1583   SetVector<const CodeGenRegister*> Set;
1584
1585   // First add Regs with all sub-registers.
1586   for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
1587     CodeGenRegister *Reg = getReg(Regs[i]);
1588     if (Set.insert(Reg))
1589       // Reg is new, add all sub-registers.
1590       // The pre-ordering is not important here.
1591       Reg->addSubRegsPreOrder(Set, *this);
1592   }
1593
1594   // Second, find all super-registers that are completely covered by the set.
1595   for (unsigned i = 0; i != Set.size(); ++i) {
1596     const CodeGenRegister::SuperRegList &SR = Set[i]->getSuperRegs();
1597     for (unsigned j = 0, e = SR.size(); j != e; ++j) {
1598       const CodeGenRegister *Super = SR[j];
1599       if (!Super->CoveredBySubRegs || Set.count(Super))
1600         continue;
1601       // This new super-register is covered by its sub-registers.
1602       bool AllSubsInSet = true;
1603       const CodeGenRegister::SubRegMap &SRM = Super->getSubRegs();
1604       for (CodeGenRegister::SubRegMap::const_iterator I = SRM.begin(),
1605              E = SRM.end(); I != E; ++I)
1606         if (!Set.count(I->second)) {
1607           AllSubsInSet = false;
1608           break;
1609         }
1610       // All sub-registers in Set, add Super as well.
1611       // We will visit Super later to recheck its super-registers.
1612       if (AllSubsInSet)
1613         Set.insert(Super);
1614     }
1615   }
1616
1617   // Convert to BitVector.
1618   BitVector BV(Registers.size() + 1);
1619   for (unsigned i = 0, e = Set.size(); i != e; ++i)
1620     BV.set(Set[i]->EnumValue);
1621   return BV;
1622 }