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