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