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