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