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