1//===- CodeGenRegisters.cpp - Register and RegisterClass Info -------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines structures to encapsulate information gleaned from the
10// target register and register class definitions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenRegisters.h"
15#include "llvm/ADT/ArrayRef.h"
16#include "llvm/ADT/BitVector.h"
17#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/IntEqClasses.h"
19#include "llvm/ADT/PointerUnion.h"
20#include "llvm/ADT/PostOrderIterator.h"
21#include "llvm/ADT/STLExtras.h"
22#include "llvm/ADT/SetVector.h"
23#include "llvm/ADT/SmallPtrSet.h"
24#include "llvm/ADT/SmallSet.h"
25#include "llvm/ADT/SmallVector.h"
26#include "llvm/ADT/StringRef.h"
27#include "llvm/ADT/StringSet.h"
28#include "llvm/ADT/Twine.h"
29#include "llvm/Support/Debug.h"
30#include "llvm/Support/FormatVariadic.h"
31#include "llvm/Support/raw_ostream.h"
32#include "llvm/TableGen/Error.h"
33#include "llvm/TableGen/Record.h"
34#include "llvm/TableGen/TGTimer.h"
35#include <algorithm>
36#include <cassert>
37#include <cstdint>
38#include <iterator>
39#include <map>
40#include <queue>
41#include <string>
42#include <tuple>
43#include <utility>
44#include <vector>
45
46using namespace llvm;
47
48#define DEBUG_TYPE "regalloc-emitter"
49
50//===----------------------------------------------------------------------===//
51// CodeGenSubRegIndex
52//===----------------------------------------------------------------------===//
53
54CodeGenSubRegIndex::CodeGenSubRegIndex(const Record *R, unsigned Enum,
55 const CodeGenHwModes &CGH)
56 : TheDef(R), Name(R->getName().str()), EnumValue(Enum),
57 AllSuperRegsCovered(true), Artificial(true) {
58 if (R->getValue(Name: "Namespace"))
59 Namespace = R->getValueAsString(FieldName: "Namespace").str();
60
61 if (const Record *RV = R->getValueAsOptionalDef(FieldName: "SubRegRanges"))
62 Range = SubRegRangeByHwMode(RV, CGH);
63 if (!Range.hasDefault())
64 Range.insertSubRegRangeForMode(Mode: DefaultMode, Info: SubRegRange(R));
65}
66
67CodeGenSubRegIndex::CodeGenSubRegIndex(StringRef N, StringRef Nspace,
68 unsigned Enum)
69 : TheDef(nullptr), Name(N.str()), Namespace(Nspace.str()),
70 Range(SubRegRange(-1, -1)), EnumValue(Enum), AllSuperRegsCovered(true),
71 Artificial(true) {}
72
73std::string CodeGenSubRegIndex::getQualifiedName() const {
74 std::string N = getNamespace();
75 if (!N.empty())
76 N += "::";
77 N += getName();
78 return N;
79}
80
81void CodeGenSubRegIndex::updateComponents(CodeGenRegBank &RegBank) {
82 if (!TheDef)
83 return;
84
85 std::vector<const Record *> Comps =
86 TheDef->getValueAsListOfDefs(FieldName: "ComposedOf");
87 if (!Comps.empty()) {
88 if (Comps.size() != 2)
89 PrintFatalError(ErrorLoc: TheDef->getLoc(),
90 Msg: "ComposedOf must have exactly two entries");
91 CodeGenSubRegIndex *A = RegBank.getSubRegIdx(Comps[0]);
92 CodeGenSubRegIndex *B = RegBank.getSubRegIdx(Comps[1]);
93 CodeGenSubRegIndex *X = A->addComposite(A: B, B: this, CGH: RegBank.getHwModes());
94 if (X)
95 PrintFatalError(ErrorLoc: TheDef->getLoc(), Msg: "Ambiguous ComposedOf entries");
96 }
97
98 std::vector<const Record *> Parts =
99 TheDef->getValueAsListOfDefs(FieldName: "CoveringSubRegIndices");
100 if (!Parts.empty()) {
101 if (Parts.size() < 2)
102 PrintFatalError(ErrorLoc: TheDef->getLoc(),
103 Msg: "CoveringSubRegIndices must have two or more entries");
104 SmallVector<CodeGenSubRegIndex *, 8> IdxParts;
105 for (const Record *Part : Parts)
106 IdxParts.push_back(Elt: RegBank.getSubRegIdx(Part));
107 setConcatenationOf(IdxParts);
108 }
109}
110
111LaneBitmask CodeGenSubRegIndex::computeLaneMask() const {
112 // Already computed?
113 if (LaneMask.any())
114 return LaneMask;
115
116 // Recursion guard, shouldn't be required.
117 LaneMask = LaneBitmask::getAll();
118
119 // The lane mask is simply the union of all sub-indices.
120 LaneBitmask M;
121 for (const auto &C : Composed)
122 M |= C.second->computeLaneMask();
123 assert(M.any() && "Missing lane mask, sub-register cycle?");
124 LaneMask = M;
125 return LaneMask;
126}
127
128void CodeGenSubRegIndex::setConcatenationOf(
129 ArrayRef<CodeGenSubRegIndex *> Parts) {
130 if (ConcatenationOf.empty()) {
131 ConcatenationOf.assign(in_start: Parts.begin(), in_end: Parts.end());
132 return;
133 }
134 assert(llvm::equal(Parts, ConcatenationOf) && "parts consistent");
135}
136
137void CodeGenSubRegIndex::computeConcatTransitiveClosure() {
138 for (SmallVectorImpl<CodeGenSubRegIndex *>::iterator I =
139 ConcatenationOf.begin();
140 I != ConcatenationOf.end();
141 /*empty*/) {
142 CodeGenSubRegIndex *SubIdx = *I;
143 SubIdx->computeConcatTransitiveClosure();
144#ifndef NDEBUG
145 for (CodeGenSubRegIndex *SRI : SubIdx->ConcatenationOf)
146 assert(SRI->ConcatenationOf.empty() && "No transitive closure?");
147#endif
148
149 if (SubIdx->ConcatenationOf.empty()) {
150 ++I;
151 } else {
152 I = ConcatenationOf.erase(CI: I);
153 I = ConcatenationOf.insert(I, From: SubIdx->ConcatenationOf.begin(),
154 To: SubIdx->ConcatenationOf.end());
155 I += SubIdx->ConcatenationOf.size();
156 }
157 }
158}
159
160//===----------------------------------------------------------------------===//
161// CodeGenRegister
162//===----------------------------------------------------------------------===//
163
164CodeGenRegister::CodeGenRegister(const Record *R, unsigned Enum)
165 : TheDef(R), EnumValue(Enum),
166 CostPerUse(R->getValueAsListOfInts(FieldName: "CostPerUse")),
167 CoveredBySubRegs(R->getValueAsBit(FieldName: "CoveredBySubRegs")),
168 Constant(R->getValueAsBit(FieldName: "isConstant")), SubRegsComplete(false),
169 SuperRegsComplete(false), TopoSig(~0u) {
170 Artificial = R->getValueAsBit(FieldName: "isArtificial");
171}
172
173void CodeGenRegister::buildObjectGraph(CodeGenRegBank &RegBank) {
174 std::vector<const Record *> SRIs =
175 TheDef->getValueAsListOfDefs(FieldName: "SubRegIndices");
176 std::vector<const Record *> SRs = TheDef->getValueAsListOfDefs(FieldName: "SubRegs");
177
178 for (const auto &[SRI, SR] : zip_equal(t&: SRIs, u&: SRs)) {
179 ExplicitSubRegIndices.push_back(Elt: RegBank.getSubRegIdx(SRI));
180 ExplicitSubRegs.push_back(Elt: RegBank.getReg(SR));
181 }
182
183 // Also compute leading super-registers. Each register has a list of
184 // covered-by-subregs super-registers where it appears as the first explicit
185 // sub-register.
186 //
187 // This is used by computeSecondarySubRegs() to find candidates.
188 if (CoveredBySubRegs && !ExplicitSubRegs.empty())
189 ExplicitSubRegs.front()->LeadingSuperRegs.push_back(x: this);
190
191 // Add ad hoc alias links. This is a symmetric relationship between two
192 // registers, so build a symmetric graph by adding links in both ends.
193 for (const Record *Alias : TheDef->getValueAsListOfDefs(FieldName: "Aliases")) {
194 CodeGenRegister *Reg = RegBank.getReg(Alias);
195 ExplicitAliases.push_back(Elt: Reg);
196 Reg->ExplicitAliases.push_back(Elt: this);
197 }
198}
199
200// Inherit register units from subregisters.
201// Return true if the RegUnits changed.
202bool CodeGenRegister::inheritRegUnits(CodeGenRegBank &RegBank) {
203 bool changed = false;
204 for (const auto &[_, SR] : SubRegs) {
205 // Merge the subregister's units into this register's RegUnits.
206 changed |= (RegUnits |= SR->RegUnits);
207 }
208
209 return changed;
210}
211
212const CodeGenRegister::SubRegMap &
213CodeGenRegister::computeSubRegs(CodeGenRegBank &RegBank) {
214 // Only compute this map once.
215 if (SubRegsComplete)
216 return SubRegs;
217 SubRegsComplete = true;
218
219 HasDisjunctSubRegs = ExplicitSubRegs.size() > 1;
220
221 // First insert the explicit subregs and make sure they are fully indexed.
222 for (auto [SR, Idx] : zip_equal(t&: ExplicitSubRegs, u&: ExplicitSubRegIndices)) {
223 if (!SR->Artificial)
224 Idx->Artificial = false;
225 if (!SubRegs.try_emplace(k: Idx, args&: SR).second)
226 PrintFatalError(ErrorLoc: TheDef->getLoc(), Msg: "SubRegIndex " + Idx->getName() +
227 " appears twice in Register " +
228 getName());
229 // Map explicit sub-registers first, so the names take precedence.
230 // The inherited sub-registers are mapped below.
231 SubReg2Idx.try_emplace(Key: SR, Args&: Idx);
232 }
233
234 // Keep track of inherited subregs and how they can be reached.
235 SmallPtrSet<CodeGenRegister *, 8> Orphans;
236
237 // Clone inherited subregs and place duplicate entries in Orphans.
238 // Here the order is important - earlier subregs take precedence.
239 for (CodeGenRegister *ESR : ExplicitSubRegs) {
240 const SubRegMap &Map = ESR->computeSubRegs(RegBank);
241 HasDisjunctSubRegs |= ESR->HasDisjunctSubRegs;
242
243 for (const auto &SR : Map) {
244 if (!SubRegs.insert(x: SR).second)
245 Orphans.insert(Ptr: SR.second);
246 }
247 }
248
249 // Expand any composed subreg indices.
250 // If dsub_2 has ComposedOf = [qsub_1, dsub_0], and this register has a
251 // qsub_1 subreg, add a dsub_2 subreg. Keep growing Indices and process
252 // expanded subreg indices recursively.
253 SmallVector<CodeGenSubRegIndex *, 8> Indices = ExplicitSubRegIndices;
254 for (unsigned i = 0; i != Indices.size(); ++i) {
255 CodeGenSubRegIndex *Idx = Indices[i];
256 const CodeGenSubRegIndex::CompMap &Comps = Idx->getComposites();
257 CodeGenRegister *SR = SubRegs[Idx];
258 const SubRegMap &Map = SR->computeSubRegs(RegBank);
259
260 // Look at the possible compositions of Idx.
261 // They may not all be supported by SR.
262 for (auto [Key, Val] : Comps) {
263 SubRegMap::const_iterator SRI = Map.find(x: Key);
264 if (SRI == Map.end())
265 continue; // Idx + I->first doesn't exist in SR.
266 // Add `Val` as a name for the subreg SRI->second, assuming it is
267 // orphaned, and the name isn't already used for something else.
268 if (SubRegs.count(x: Val) || !Orphans.erase(Ptr: SRI->second))
269 continue;
270 // We found a new name for the orphaned sub-register.
271 SubRegs.try_emplace(k: Val, args: SRI->second);
272 Indices.push_back(Elt: Val);
273 }
274 }
275
276 // Now Orphans contains the inherited subregisters without a direct index.
277 // Create inferred indexes for all missing entries.
278 // Work backwards in the Indices vector in order to compose subregs bottom-up.
279 // Consider this subreg sequence:
280 //
281 // qsub_1 -> dsub_0 -> ssub_0
282 //
283 // The qsub_1 -> dsub_0 composition becomes dsub_2, so the ssub_0 register
284 // can be reached in two different ways:
285 //
286 // qsub_1 -> ssub_0
287 // dsub_2 -> ssub_0
288 //
289 // We pick the latter composition because another register may have [dsub_0,
290 // dsub_1, dsub_2] subregs without necessarily having a qsub_1 subreg. The
291 // dsub_2 -> ssub_0 composition can be shared.
292 while (!Indices.empty() && !Orphans.empty()) {
293 CodeGenSubRegIndex *Idx = Indices.pop_back_val();
294 CodeGenRegister *SR = SubRegs[Idx];
295 const SubRegMap &Map = SR->computeSubRegs(RegBank);
296 for (const auto &[SRI, SubReg] : Map)
297 if (Orphans.erase(Ptr: SubReg))
298 SubRegs[RegBank.getCompositeSubRegIndex(A: Idx, B: SRI)] = SubReg;
299 }
300
301 // Compute the inverse SubReg -> Idx map.
302 for (auto &[SRI, SubReg] : SubRegs) {
303 if (SubReg == this) {
304 ArrayRef<SMLoc> Loc;
305 if (TheDef)
306 Loc = TheDef->getLoc();
307 PrintFatalError(ErrorLoc: Loc, Msg: "Register " + getName() +
308 " has itself as a sub-register");
309 }
310
311 // Compute AllSuperRegsCovered.
312 if (!CoveredBySubRegs)
313 SRI->AllSuperRegsCovered = false;
314
315 // Ensure that every sub-register has a unique name.
316 DenseMap<const CodeGenRegister *, CodeGenSubRegIndex *>::iterator Ins =
317 SubReg2Idx.try_emplace(Key: SubReg, Args: SRI).first;
318 if (Ins->second == SRI)
319 continue;
320 // Trouble: Two different names for SubReg.second.
321 ArrayRef<SMLoc> Loc;
322 if (TheDef)
323 Loc = TheDef->getLoc();
324 PrintFatalError(ErrorLoc: Loc, Msg: "Sub-register can't have two names: " +
325 SubReg->getName() + " available as " +
326 SRI->getName() + " and " + Ins->second->getName());
327 }
328
329 // Derive possible names for sub-register concatenations from any explicit
330 // sub-registers. By doing this before computeSecondarySubRegs(), we ensure
331 // that getConcatSubRegIndex() won't invent any concatenated indices that the
332 // user already specified.
333 for (auto [Idx, SR] : enumerate(First&: ExplicitSubRegs)) {
334 if (!SR->CoveredBySubRegs || SR->Artificial)
335 continue;
336
337 // SR is composed of multiple sub-regs. Find their names in this register.
338 bool AnyArtificial = false;
339 SmallVector<CodeGenSubRegIndex *, 8> Parts;
340 for (unsigned j = 0, e = SR->ExplicitSubRegs.size(); j != e; ++j) {
341 CodeGenSubRegIndex &I = *SR->ExplicitSubRegIndices[j];
342 if (I.Artificial) {
343 AnyArtificial = true;
344 break;
345 }
346 Parts.push_back(Elt: getSubRegIndex(Reg: SR->ExplicitSubRegs[j]));
347 }
348
349 if (AnyArtificial)
350 continue;
351
352 // Offer this as an existing spelling for the concatenation of Parts.
353 ExplicitSubRegIndices[Idx]->setConcatenationOf(Parts);
354 }
355
356 // Initialize RegUnitList. Because getSubRegs is called recursively, this
357 // processes the register hierarchy in postorder.
358 if (ExplicitSubRegs.empty()) {
359 // Create one register unit per leaf register. These units correspond to the
360 // maximal cliques in the register overlap graph which is optimal.
361 RegUnits.set(RegBank.newRegUnit(R0: this));
362 } else {
363 // Inherit all sub-register units. It is good enough to look at the explicit
364 // sub-registers, the other registers won't contribute any more units.
365 for (const CodeGenRegister *SR : ExplicitSubRegs)
366 RegUnits |= SR->RegUnits;
367 }
368
369 // When there is ad hoc aliasing, we simply create one unit per edge in the
370 // undirected ad hoc aliasing graph. Technically, we could do better by
371 // identifying maximal cliques in the ad hoc graph, but cliques larger than 2
372 // are extremely rare anyway (I've never seen one), so we don't bother with
373 // the added complexity.
374 for (CodeGenRegister *AR : ExplicitAliases) {
375 // Only visit each edge once.
376 if (AR->SubRegsComplete)
377 continue;
378 // Create a RegUnit representing this alias edge, and add it to both
379 // registers.
380 unsigned Unit = RegBank.newRegUnit(R0: this, R1: AR);
381 RegUnits.set(Unit);
382 AR->RegUnits.set(Unit);
383 }
384
385 // We have now computed the native register units. More may be adopted later
386 // for balancing purposes.
387 NativeRegUnits = RegUnits;
388
389 return SubRegs;
390}
391
392// Verify that a register's explicit sub-registers fit within it. A SubRegIndex
393// whose offset+size runs past the register's own size gives that sub-register
394// an oversized lane mask, which silently corrupts sub-register liveness and
395// spilling and is not otherwise diagnosed. (This was found via a real
396// wrong-code bug in a downstream target, where a 64-bit exponent sub-register
397// index was mistakenly declared with size 576.) The check is limited to
398// registers whose explicit sub-registers tile a contiguous bit range:
399// strided/spaced register tuples (e.g. ARM's Tuples3DSpc,
400// [dsub_0, dsub_2, dsub_4]) deliberately place sub-registers at non-adjacent
401// offsets that extend past the nominal size, and are not bugs.
402void CodeGenRegister::checkSubRegIndexSizes(CodeGenRegBank &RegBank) const {
403 // Only registers that are covered by their sub-registers promise to be fully
404 // tiled by them; for those an explicit SubRegIndex extending past the
405 // register is a genuine bug. A register that is not covered by its
406 // sub-registers makes no such promise, so don't second-guess its layout.
407 if (!CoveredBySubRegs)
408 return;
409
410 // This register's own bit size is the largest register class containing it.
411 unsigned ParentSize = 0;
412 for (const auto &RC : RegBank.getRegClasses()) {
413 if (!RC.contains(this) || !RC.RSI.hasDefault())
414 continue;
415 // Only trust a register-class size that is backed by a real value type.
416 // An 'untyped' class carries a placeholder size, not the register's bit
417 // width, so its size cannot be compared against sub-register extents.
418 // getValueTypes() is indexed by HwMode; DefaultMode is the first entry.
419 ArrayRef<ValueTypeByHwMode> VTs = RC.getValueTypes();
420 if (VTs.empty())
421 continue;
422 const ValueTypeByHwMode &VT = VTs[DefaultMode];
423 if (!VT.isSimple() || VT.getSimple() == MVT::Untyped)
424 continue;
425 ParentSize = std::max(a: ParentSize, b: RC.RSI.get(Mode: DefaultMode).RegSize);
426 }
427 if (!ParentSize)
428 return;
429
430 // Collect the explicit sub-register (offset, size) ranges. Bail on any
431 // register with incomplete or non-contiguous range info.
432 SmallVector<std::pair<unsigned, unsigned>> Ranges;
433 for (const CodeGenSubRegIndex *Idx : ExplicitSubRegIndices) {
434 if (!Idx->Range.hasDefault())
435 return;
436 const SubRegRange &R = Idx->Range.get(Mode: DefaultMode);
437 if (R.Size == static_cast<uint32_t>(-1) ||
438 R.Offset == static_cast<uint32_t>(-1))
439 return; // tuple sub-index with no contiguous bit range (e.g. X86 KPAIRS,
440 // ARM strided NEON tuples)
441 Ranges.emplace_back(Args: R.Offset, Args: R.Size);
442 }
443 if (Ranges.empty())
444 return;
445
446 // ExplicitSubRegIndices is in .td declaration order, not offset order, so
447 // sort by offset before scanning. Only a contiguous tiling is a dense bit
448 // container; anything left with a gap or overlap is a strided/spaced tuple
449 // (also covered-by-subregs), which is allowed to exceed the nominal size.
450 llvm::sort(C&: Ranges);
451 unsigned Pos = 0;
452 for (auto [Off, Sz] : Ranges) {
453 if (Off != Pos)
454 return; // gap or overlap -> strided/sparse, skip
455 Pos += Sz;
456 }
457
458 if (Pos > ParentSize)
459 PrintFatalError(Rec: TheDef,
460 Msg: formatv(Fmt: "register '{}' has size {} but its explicit "
461 "sub-registers cover {} bits",
462 Vals: getName(), Vals&: ParentSize, Vals&: Pos));
463}
464
465// In a register that is covered by its sub-registers, try to find redundant
466// sub-registers. For example:
467//
468// QQ0 = {Q0, Q1}
469// Q0 = {D0, D1}
470// Q1 = {D2, D3}
471//
472// We can infer that D1_D2 is also a sub-register, even if it wasn't named in
473// the register definition.
474//
475// The explicitly specified registers form a tree. This function discovers
476// sub-register relationships that would force a DAG.
477//
478void CodeGenRegister::computeSecondarySubRegs(CodeGenRegBank &RegBank) {
479 SmallVector<SubRegMap::value_type, 8> NewSubRegs;
480
481 std::queue<std::pair<CodeGenSubRegIndex *, CodeGenRegister *>> SubRegQueue;
482 for (auto [SRI, SubReg] : SubRegs)
483 SubRegQueue.emplace(args: SRI, args&: SubReg);
484
485 // Look at the leading super-registers of each sub-register. Those are the
486 // candidates for new sub-registers, assuming they are fully contained in
487 // this register.
488 while (!SubRegQueue.empty()) {
489 auto [SubRegIdx, SubReg] = SubRegQueue.front();
490 SubRegQueue.pop();
491
492 const CodeGenRegister::SuperRegList &Leads = SubReg->LeadingSuperRegs;
493 for (const CodeGenRegister *Cand : Leads) {
494 // Already got this sub-register?
495 if (Cand == this || getSubRegIndex(Reg: Cand))
496 continue;
497 // Check if each component of Cand is already a sub-register.
498 assert(!Cand->ExplicitSubRegs.empty() &&
499 "Super-register has no sub-registers");
500 if (Cand->ExplicitSubRegs.size() == 1)
501 continue;
502 SmallVector<CodeGenSubRegIndex *, 8> Parts;
503 // We know that the first component is (SubRegIdx,SubReg). However we
504 // may still need to split it into smaller subregister parts.
505 assert(Cand->ExplicitSubRegs[0] == SubReg && "LeadingSuperRegs correct");
506 assert(getSubRegIndex(SubReg) == SubRegIdx && "LeadingSuperRegs correct");
507 for (CodeGenRegister *SubReg : Cand->ExplicitSubRegs) {
508 if (CodeGenSubRegIndex *SubRegIdx = getSubRegIndex(Reg: SubReg)) {
509 if (SubRegIdx->ConcatenationOf.empty())
510 Parts.push_back(Elt: SubRegIdx);
511 else
512 append_range(C&: Parts, R&: SubRegIdx->ConcatenationOf);
513 } else {
514 // Sub-register doesn't exist.
515 Parts.clear();
516 break;
517 }
518 }
519 // There is nothing to do if some Cand sub-register is not part of this
520 // register.
521 if (Parts.empty())
522 continue;
523
524 // Each part of Cand is a sub-register of this. Make the full Cand also
525 // a sub-register with a concatenated sub-register index.
526 CodeGenSubRegIndex *Concat =
527 RegBank.getConcatSubRegIndex(Parts, CGH: RegBank.getHwModes());
528 std::pair<CodeGenSubRegIndex *, CodeGenRegister *> NewSubReg = {
529 Concat, const_cast<CodeGenRegister *>(Cand)};
530
531 if (!SubRegs.insert(x&: NewSubReg).second)
532 continue;
533
534 // We inserted a new subregister.
535 NewSubRegs.push_back(Elt: NewSubReg);
536 SubRegQueue.push(x: NewSubReg);
537 SubReg2Idx.try_emplace(Key: Cand, Args&: Concat);
538 }
539 }
540
541 // Create sub-register index composition maps for the synthesized indices.
542 for (auto [NewIdx, NewSubReg] : NewSubRegs) {
543 for (auto [SRI, SubReg] : NewSubReg->SubRegs) {
544 CodeGenSubRegIndex *SubIdx = getSubRegIndex(Reg: SubReg);
545 if (!SubIdx)
546 PrintFatalError(ErrorLoc: TheDef->getLoc(), Msg: "No SubRegIndex for " +
547 SubReg->getName() + " in " +
548 getName());
549 NewIdx->addComposite(A: SRI, B: SubIdx, CGH: RegBank.getHwModes());
550 }
551 }
552}
553
554void CodeGenRegister::computeSuperRegs(CodeGenRegBank &RegBank) {
555 // Only visit each register once.
556 if (SuperRegsComplete)
557 return;
558 SuperRegsComplete = true;
559
560 // Make sure all sub-registers have been visited first, so the super-reg
561 // lists will be topologically ordered.
562 for (auto SubReg : SubRegs)
563 SubReg.second->computeSuperRegs(RegBank);
564
565 // Now add this as a super-register on all sub-registers.
566 // Also compute the TopoSigId in post-order.
567 TopoSigId Id;
568 for (auto SubReg : SubRegs) {
569 // Topological signature computed from SubIdx, TopoId(SubReg).
570 // Loops and idempotent indices have TopoSig = ~0u.
571 Id.push_back(Elt: SubReg.first->EnumValue);
572 Id.push_back(Elt: SubReg.second->TopoSig);
573
574 // Don't add duplicate entries.
575 if (!SubReg.second->SuperRegs.empty() &&
576 SubReg.second->SuperRegs.back() == this)
577 continue;
578 SubReg.second->SuperRegs.push_back(x: this);
579 }
580 TopoSig = RegBank.getTopoSig(Id);
581}
582
583void CodeGenRegister::addSubRegsPreOrder(
584 SetVector<const CodeGenRegister *> &OSet, CodeGenRegBank &RegBank) const {
585 assert(SubRegsComplete && "Must precompute sub-registers");
586 for (CodeGenRegister *SR : ExplicitSubRegs) {
587 if (OSet.insert(X: SR))
588 SR->addSubRegsPreOrder(OSet, RegBank);
589 }
590 // Add any secondary sub-registers that weren't part of the explicit tree.
591 OSet.insert_range(R: llvm::make_second_range(c: SubRegs));
592}
593
594// Get the sum of this register's unit weights.
595unsigned CodeGenRegister::getWeight(const CodeGenRegBank &RegBank) const {
596 unsigned Weight = 0;
597 for (unsigned RegUnit : RegUnits)
598 Weight += RegBank.getRegUnit(RUID: RegUnit).Weight;
599 return Weight;
600}
601
602//===----------------------------------------------------------------------===//
603// RegisterTuples
604//===----------------------------------------------------------------------===//
605
606// A RegisterTuples def is used to generate pseudo-registers from lists of
607// sub-registers. We provide a SetTheory expander class that returns the new
608// registers.
609namespace {
610
611struct TupleExpander : SetTheory::Expander {
612 // Reference to SynthDefs in the containing CodeGenRegBank, to keep track of
613 // the synthesized definitions for their lifetime.
614 std::vector<std::unique_ptr<Record>> &SynthDefs;
615
616 // Track all synthesized tuple names in order to detect duplicate definitions.
617 llvm::StringSet<> TupleNames;
618
619 TupleExpander(std::vector<std::unique_ptr<Record>> &SynthDefs)
620 : SynthDefs(SynthDefs) {}
621
622 void expand(SetTheory &ST, const Record *Def,
623 SetTheory::RecSet &Elts) override {
624 std::vector<const Record *> Indices =
625 Def->getValueAsListOfDefs(FieldName: "SubRegIndices");
626 unsigned Dim = Indices.size();
627 const ListInit *SubRegs = Def->getValueAsListInit(FieldName: "SubRegs");
628
629 // Evaluate the sub-register lists to be zipped.
630 unsigned Length = ~0u;
631 SmallVector<SetTheory::RecSet, 4> Lists(Dim);
632 for (unsigned i = 0; i != Dim; ++i) {
633 ST.evaluate(Expr: SubRegs->getElement(Idx: i), Elts&: Lists[i], Loc: Def->getLoc());
634 Length = std::min(a: Length, b: unsigned(Lists[i].size()));
635 }
636
637 if (Length == 0)
638 return;
639
640 // Precompute some types.
641 const Record *RegisterCl = Def->getRecords().getClass(Name: "Register");
642 const RecTy *RegisterRecTy = RecordRecTy::get(Class: RegisterCl);
643 std::vector<StringRef> RegNames =
644 Def->getValueAsListOfStrings(FieldName: "RegAsmNames");
645
646 // Zip them up.
647 RecordKeeper &RK = Def->getRecords();
648 for (unsigned n = 0; n != Length; ++n) {
649 std::string Name;
650 const Record *Proto = Lists[0][n];
651 std::vector<Init *> Tuple;
652 for (unsigned i = 0; i != Dim; ++i) {
653 const Record *Reg = Lists[i][n];
654 if (i)
655 Name += '_';
656 Name += Reg->getName();
657 Tuple.push_back(x: Reg->getDefInit());
658 }
659
660 // Take the cost list of the first register in the tuple.
661 const ListInit *CostList = Proto->getValueAsListInit(FieldName: "CostPerUse");
662 SmallVector<const Init *, 2> CostPerUse(CostList->getElements());
663
664 const StringInit *AsmName = StringInit::get(RK, "");
665 if (!RegNames.empty()) {
666 if (RegNames.size() <= n)
667 PrintFatalError(ErrorLoc: Def->getLoc(),
668 Msg: "Register tuple definition missing name for '" +
669 Name + "'.");
670 AsmName = StringInit::get(RK, RegNames[n]);
671 }
672
673 // Create a new Record representing the synthesized register. This record
674 // is only for consumption by CodeGenRegister, it is not added to the
675 // RecordKeeper.
676 SynthDefs.emplace_back(
677 args: std::make_unique<Record>(args&: Name, args: Def->getLoc(), args&: Def->getRecords()));
678 Record *NewReg = SynthDefs.back().get();
679 Elts.insert(X: NewReg);
680
681 // Detect duplicates among synthesized registers.
682 const auto Res = TupleNames.insert(key: NewReg->getName());
683 if (!Res.second)
684 PrintFatalError(ErrorLoc: Def->getLoc(),
685 Msg: "Register tuple redefines register '" + Name + "'.");
686
687 // Copy Proto super-classes.
688 for (const auto &[Super, Loc] : Proto->getDirectSuperClasses())
689 NewReg->addDirectSuperClass(R: Super, Range: Loc);
690
691 // Copy Proto fields.
692 for (RecordVal RV : Proto->getValues()) {
693 // Skip existing fields, like NAME.
694 if (NewReg->getValue(Name: RV.getNameInit()))
695 continue;
696
697 StringRef Field = RV.getName();
698
699 // Replace the sub-register list with Tuple.
700 if (Field == "SubRegs")
701 RV.setValue(ListInit::get(Range: Tuple, EltTy: RegisterRecTy));
702
703 if (Field == "AsmName")
704 RV.setValue(AsmName);
705
706 // CostPerUse is aggregated from all Tuple members.
707 if (Field == "CostPerUse")
708 RV.setValue(ListInit::get(Range: CostPerUse, EltTy: CostList->getElementType()));
709
710 // Composite registers are always covered by sub-registers.
711 if (Field == "CoveredBySubRegs")
712 RV.setValue(BitInit::get(RK, V: true));
713
714 // Copy fields from the RegisterTuples def.
715 if (Field == "SubRegIndices") {
716 NewReg->addValue(RV: *Def->getValue(Name: Field));
717 continue;
718 }
719
720 // Some fields get their default uninitialized value.
721 if (Field == "DwarfNumbers" || Field == "DwarfAlias" ||
722 Field == "Aliases") {
723 if (const RecordVal *DefRV = RegisterCl->getValue(Name: Field))
724 NewReg->addValue(RV: *DefRV);
725 continue;
726 }
727
728 // Everything else is copied from Proto.
729 NewReg->addValue(RV);
730 }
731 }
732 }
733};
734
735} // end anonymous namespace
736
737//===----------------------------------------------------------------------===//
738// CodeGenRegisterClass
739//===----------------------------------------------------------------------===//
740
741static void sortAndUniqueRegisters(CodeGenRegister::Vec &M) {
742 llvm::sort(C&: M, Comp: deref<std::less<>>());
743 M.erase(first: llvm::unique(R&: M, P: deref<std::equal_to<>>()), last: M.end());
744}
745
746CodeGenRegisterClass::CodeGenRegisterClass(CodeGenRegBank &RegBank,
747 const Record *R)
748 : TheDef(R), Name(R->getName().str()),
749 RegsWithSuperRegsTopoSigs(RegBank.getNumTopoSigs()), EnumValue(-1),
750 TSFlags(0) {
751 GeneratePressureSet = R->getValueAsBit(FieldName: "GeneratePressureSet");
752 for (const Record *Type : R->getValueAsListOfDefs(FieldName: "RegTypes"))
753 VTs.push_back(Elt: getValueTypeByHwMode(Rec: Type, CGH: RegBank.getHwModes()));
754
755 // Allocation order 0 is the full set. AltOrders provides others.
756 const SetTheory::RecVec *Elements = RegBank.getSets().expand(Set: R);
757 const ListInit *AltOrders = R->getValueAsListInit(FieldName: "AltOrders");
758 Orders.resize(new_size: 1 + AltOrders->size());
759
760 // Default allocation order always contains all registers.
761 MemberBV.resize(N: RegBank.getRegisters().size());
762 Artificial = true;
763 for (const Record *Element : *Elements) {
764 Orders[0].push_back(Elt: Element);
765 const CodeGenRegister *Reg = RegBank.getReg(Element);
766 Members.push_back(x: Reg);
767 MemberBV.set(CodeGenRegBank::getRegIndex(Reg));
768 Artificial &= Reg->Artificial;
769 if (!Reg->getSuperRegs().empty())
770 RegsWithSuperRegsTopoSigs.set(Reg->getTopoSig());
771 }
772 sortAndUniqueRegisters(M&: Members);
773
774 // Alternative allocation orders may be subsets.
775 SetTheory::RecSet Order;
776 for (auto [Idx, AltOrderElem] : enumerate(First: AltOrders->getElements())) {
777 RegBank.getSets().evaluate(Expr: AltOrderElem, Elts&: Order, Loc: R->getLoc());
778 Orders[1 + Idx].append(in_start: Order.begin(), in_end: Order.end());
779 // Verify that all altorder members are regclass members.
780 while (!Order.empty()) {
781 CodeGenRegister *Reg = RegBank.getReg(Order.back());
782 Order.pop_back();
783 if (!contains(Reg))
784 PrintFatalError(ErrorLoc: R->getLoc(), Msg: " AltOrder register " + Reg->getName() +
785 " is not a class member");
786 }
787 }
788
789 Namespace = R->getValueAsString(FieldName: "Namespace");
790
791 if (const Record *RV = R->getValueAsOptionalDef(FieldName: "RegInfos"))
792 RSI = RegSizeInfoByHwMode(RV, RegBank.getHwModes());
793 unsigned Size = R->getValueAsInt(FieldName: "Size");
794 if (!RSI.hasDefault() && Size == 0 && !VTs[0].isSimple())
795 PrintFatalError(ErrorLoc: R->getLoc(), Msg: "Impossible to determine register size");
796 if (!RSI.hasDefault()) {
797 RegSizeInfo RI;
798 RI.RegSize = RI.SpillSize =
799 Size ? Size : VTs[0].getSimple().getSizeInBits();
800 RI.SpillAlignment = R->getValueAsInt(FieldName: "Alignment");
801 RSI.insertRegSizeForMode(Mode: DefaultMode, Info: RI);
802 }
803
804 int CopyCostParsed = R->getValueAsInt(FieldName: "CopyCost");
805 Allocatable = R->getValueAsBit(FieldName: "isAllocatable");
806 AltOrderSelect = R->getValueAsString(FieldName: "AltOrderSelect");
807 int SpillStackIDParsed = R->getValueAsInt(FieldName: "SpillStackID");
808 if (!isUInt<8>(x: SpillStackIDParsed))
809 PrintFatalError(ErrorLoc: R->getLoc(), Msg: "SpillStackID out of range [0,255]");
810 SpillStackID = SpillStackIDParsed;
811 int AllocationPriority = R->getValueAsInt(FieldName: "AllocationPriority");
812 if (!isUInt<5>(x: AllocationPriority))
813 PrintFatalError(ErrorLoc: R->getLoc(), Msg: "AllocationPriority out of range [0,31]");
814 this->AllocationPriority = AllocationPriority;
815
816 GlobalPriority = R->getValueAsBit(FieldName: "GlobalPriority");
817
818 const BitsInit *TSF = R->getValueAsBitsInit(FieldName: "TSFlags");
819 TSFlags = uint8_t(*TSF->convertInitializerToInt());
820
821 // Saturate negative costs to the maximum
822 if (CopyCostParsed < 0)
823 CopyCost = std::numeric_limits<uint8_t>::max();
824 else if (!isUInt<8>(x: CopyCostParsed))
825 PrintFatalError(ErrorLoc: R->getLoc(), Msg: "'CopyCost' must be an 8-bit value");
826
827 CopyCost = CopyCostParsed;
828}
829
830// Create an inferred register class that was missing from the .td files.
831// Most properties will be inherited from the closest super-class after the
832// class structure has been computed.
833CodeGenRegisterClass::CodeGenRegisterClass(CodeGenRegBank &RegBank,
834 StringRef Name, Key Props)
835 : Members(*Props.Members), TheDef(nullptr), Name(Name.str()),
836 RegsWithSuperRegsTopoSigs(RegBank.getNumTopoSigs()), EnumValue(-1),
837 RSI(Props.RSI), CopyCost(0), Allocatable(true), AllocationPriority(0),
838 GlobalPriority(false), TSFlags(0), SpillStackID(0) {
839 MemberBV.resize(N: RegBank.getRegisters().size());
840 Artificial = true;
841 GeneratePressureSet = false;
842 for (const auto R : Members) {
843 MemberBV.set(CodeGenRegBank::getRegIndex(Reg: R));
844 if (!R->getSuperRegs().empty())
845 RegsWithSuperRegsTopoSigs.set(R->getTopoSig());
846 Artificial &= R->Artificial;
847 }
848}
849
850// Compute inherited properties for a synthesized register class.
851void CodeGenRegisterClass::inheritProperties(CodeGenRegBank &RegBank) {
852 assert(!getDef() && "Only synthesized classes can inherit properties");
853 assert(!SuperClasses.empty() && "Synthesized class without super class");
854
855 // The last super-class is the smallest one in topological order. Check for
856 // allocatable super-classes and inherit from the nearest allocatable one if
857 // any.
858 auto NearestAllocSCRIt =
859 find_if(Range: reverse(C&: SuperClasses),
860 P: [&](const CodeGenRegisterClass *S) { return S->Allocatable; });
861 CodeGenRegisterClass &Super = NearestAllocSCRIt == SuperClasses.rend()
862 ? *SuperClasses.back()
863 : **NearestAllocSCRIt;
864
865 // Most properties are copied directly.
866 // Exceptions are members, size, and alignment
867 Namespace = Super.Namespace;
868 VTs = Super.VTs;
869 CopyCost = Super.CopyCost;
870 Allocatable = Super.Allocatable;
871 AltOrderSelect = Super.AltOrderSelect;
872 AllocationPriority = Super.AllocationPriority;
873 GlobalPriority = Super.GlobalPriority;
874 TSFlags = Super.TSFlags;
875 SpillStackID = Super.SpillStackID;
876 GeneratePressureSet |= Super.GeneratePressureSet;
877
878 // Copy all allocation orders, filter out foreign registers from the larger
879 // super-class.
880 Orders.resize(new_size: Super.Orders.size());
881 for (auto [Idx, Outer] : enumerate(First&: Super.Orders))
882 for (const Record *Reg : Outer)
883 if (contains(RegBank.getReg(Reg)))
884 Orders[Idx].push_back(Elt: Reg);
885}
886
887bool CodeGenRegisterClass::hasType(const ValueTypeByHwMode &VT) const {
888 if (llvm::is_contained(Range: VTs, Element: VT))
889 return true;
890
891 // If VT is not identical to any of this class's types, but is a simple
892 // type, check if any of the types for this class contain it under some
893 // mode.
894 // The motivating example came from RISC-V, where (likely because of being
895 // guarded by "64-bit" predicate), the type of X5 was {*:[i64]}, but the
896 // type in GRC was {*:[i32], m1:[i64]}.
897 if (VT.isSimple()) {
898 MVT T = VT.getSimple();
899 for (const ValueTypeByHwMode &OurVT : VTs) {
900 if (llvm::is_contained(Range: llvm::make_second_range(c: OurVT), Element: T))
901 return true;
902 }
903 }
904 return false;
905}
906
907bool CodeGenRegisterClass::contains(const CodeGenRegister *Reg) const {
908 return MemberBV.test(Idx: CodeGenRegBank::getRegIndex(Reg));
909}
910
911unsigned CodeGenRegisterClass::getWeight(const CodeGenRegBank &RegBank) const {
912 if (TheDef && !TheDef->isValueUnset(FieldName: "Weight"))
913 return TheDef->getValueAsInt(FieldName: "Weight");
914
915 if (Artificial)
916 return 0;
917
918 for (const CodeGenRegister *Reg : Members) {
919 if (!Reg->Artificial)
920 return Reg->getWeight(RegBank);
921 }
922
923 return 0;
924}
925
926// This is a simple lexicographical order that can be used to search for sets.
927// It is not the same as the topological order provided by TopoOrderRC.
928bool CodeGenRegisterClass::Key::operator<(
929 const CodeGenRegisterClass::Key &B) const {
930 assert(Members && B.Members);
931
932 // Lexicographical comparison. Ignores artificial registers when asked.
933 auto IA = Members->begin(), EA = Members->end();
934 auto IB = B.Members->begin(), EB = B.Members->end();
935 for (;;) {
936 while (IgnoreArtificialMembers && IA != EA && (*IA)->Artificial)
937 ++IA;
938 while (IgnoreArtificialMembers && IB != EB && (*IB)->Artificial)
939 ++IB;
940 if (IA == EA && IB == EB)
941 break;
942 if (IA == EA || IB == EB)
943 return IA == EA;
944 if (**IA != **IB)
945 return **IA < **IB;
946 ++IA;
947 ++IB;
948 }
949 return RSI < B.RSI;
950}
951
952// Returns true if RC is a strict subclass.
953// RC is a sub-class of this class if it is a valid replacement for any
954// instruction operand where a register of this classis required. It must
955// satisfy these conditions:
956//
957// 1. All RC registers are also in this.
958// 2. The RC spill size must not be smaller than our spill size.
959// 3. RC spill alignment must be compatible with ours.
960//
961static bool testSubClass(const CodeGenRegisterClass *A,
962 const CodeGenRegisterClass *B) {
963 return A->RSI.isSubClassOf(I: B->RSI) &&
964 llvm::includes(Range1: A->getMembers(), Range2: B->getMembers(), C: deref<std::less<>>());
965}
966
967/// Sorting predicate for register classes. This provides a topological
968/// ordering that arranges all register classes before their sub-classes.
969///
970/// Register classes with the same registers, spill size, and alignment form a
971/// clique. They will be ordered alphabetically.
972///
973static bool TopoOrderRC(const CodeGenRegisterClass &A,
974 const CodeGenRegisterClass &B) {
975 if (&A == &B)
976 return false;
977
978 constexpr size_t SIZET_MAX = std::numeric_limits<size_t>::max();
979
980 // Sort in the following order:
981 // (a) first by register size in ascending order.
982 // (b) then by set size in descending order.
983 // (c) finally, by name as a tie breaker.
984 //
985 // For set size, note that the classes' allocation order may not have been
986 // computed yet, but the members set is always valid. Also, since we use
987 // std::tie() < operator for ordering, we can achieve the descending set size
988 // ordering by using (SIZET_MAX - set_size) in the std::tie.
989 return std::tuple(A.RSI, SIZET_MAX - A.getMembers().size(),
990 StringRef(A.getName())) <
991 std::tuple(B.RSI, SIZET_MAX - B.getMembers().size(),
992 StringRef(B.getName()));
993}
994
995std::string CodeGenRegisterClass::getNamespaceQualification() const {
996 return Namespace.empty() ? "" : (Namespace + "::").str();
997}
998
999std::string CodeGenRegisterClass::getQualifiedName() const {
1000 return getNamespaceQualification() + getName();
1001}
1002
1003std::string CodeGenRegisterClass::getIdName() const {
1004 return getName() + "RegClassID";
1005}
1006
1007std::string CodeGenRegisterClass::getQualifiedIdName() const {
1008 return getNamespaceQualification() + getIdName();
1009}
1010
1011// Compute sub-classes of all register classes.
1012// Assume the classes are ordered topologically.
1013void CodeGenRegisterClass::computeSubClasses(CodeGenRegBank &RegBank) {
1014 std::list<CodeGenRegisterClass> &RegClasses = RegBank.getRegClasses();
1015
1016 const size_t NumRegClasses = RegClasses.size();
1017 // Visit backwards so sub-classes are seen first.
1018 for (auto I = RegClasses.rbegin(), E = RegClasses.rend(); I != E; ++I) {
1019 CodeGenRegisterClass &RC = *I;
1020 RC.SubClasses.resize(N: NumRegClasses);
1021 RC.SubClasses.set(RC.EnumValue);
1022 if (RC.Artificial)
1023 continue;
1024
1025 // Normally, all subclasses have IDs >= rci, unless RC is part of a clique.
1026 for (auto I2 = I.base(), E2 = RegClasses.end(); I2 != E2; ++I2) {
1027 CodeGenRegisterClass &SubRC = *I2;
1028 if (RC.SubClasses.test(Idx: SubRC.EnumValue))
1029 continue;
1030 if (!testSubClass(A: &RC, B: &SubRC))
1031 continue;
1032 // SubRC is a sub-class. Grap all its sub-classes so we won't have to
1033 // check them again.
1034 RC.SubClasses |= SubRC.SubClasses;
1035 }
1036
1037 // Sweep up missed clique members. They will be immediately preceding RC.
1038 for (auto I2 = std::next(x: I); I2 != E && testSubClass(A: &RC, B: &*I2); ++I2)
1039 RC.SubClasses.set(I2->EnumValue);
1040 }
1041
1042 // Compute the SuperClasses lists from the SubClasses vectors.
1043 for (auto &RC : RegClasses) {
1044 const BitVector &SC = RC.getSubClasses();
1045 auto I = RegClasses.begin();
1046 for (int s = 0, next_s = SC.find_first(); next_s != -1;
1047 next_s = SC.find_next(Prev: s)) {
1048 std::advance(i&: I, n: next_s - s);
1049 s = next_s;
1050 if (&*I == &RC)
1051 continue;
1052 I->SuperClasses.push_back(Elt: &RC);
1053 }
1054 }
1055
1056 // With the class hierarchy in place, let synthesized register classes inherit
1057 // properties from their closest super-class. The iteration order here can
1058 // propagate properties down multiple levels.
1059 for (CodeGenRegisterClass &RC : RegClasses)
1060 if (!RC.getDef())
1061 RC.inheritProperties(RegBank);
1062}
1063
1064std::optional<std::pair<CodeGenRegisterClass *, CodeGenRegisterClass *>>
1065CodeGenRegisterClass::getMatchingSubClassWithSubRegs(
1066 CodeGenRegBank &RegBank, const CodeGenSubRegIndex *SubIdx) const {
1067 auto WeakSizeOrder = [this](const CodeGenRegisterClass *A,
1068 const CodeGenRegisterClass *B) {
1069 // If there are multiple, identical register classes, prefer the original
1070 // register class.
1071 if (A == B)
1072 return false;
1073 if (A->getMembers().size() == B->getMembers().size()) {
1074 if (A->getBaseClassOrder() != B->getBaseClassOrder())
1075 return A->getBaseClassOrder() > B->getBaseClassOrder();
1076 return A == this;
1077 }
1078 return A->getMembers().size() > B->getMembers().size();
1079 };
1080
1081 std::list<CodeGenRegisterClass> &RegClasses = RegBank.getRegClasses();
1082
1083 // Find all the subclasses of this one that fully support the sub-register
1084 // index and order them by size. BiggestSuperRC should always be first.
1085 CodeGenRegisterClass *BiggestSuperRegRC = getSubClassWithSubReg(SubIdx);
1086 if (!BiggestSuperRegRC)
1087 return std::nullopt;
1088 BitVector SuperRegRCsBV = BiggestSuperRegRC->getSubClasses();
1089 std::vector<CodeGenRegisterClass *> SuperRegRCs;
1090 for (auto &RC : RegClasses)
1091 if (SuperRegRCsBV[RC.EnumValue])
1092 SuperRegRCs.emplace_back(args: &RC);
1093 llvm::stable_sort(Range&: SuperRegRCs, C: WeakSizeOrder);
1094
1095 assert((SuperRegRCs.front() == BiggestSuperRegRC ||
1096 SuperRegRCs.front()->getBaseClassOrder() >
1097 BiggestSuperRegRC->getBaseClassOrder()) &&
1098 "Biggest class wasn't first");
1099
1100 // Find all the subreg classes and order them by size too.
1101 std::vector<CodeGenRegisterClass *> SuperRegClasses;
1102 for (auto &RC : RegClasses) {
1103 if (RC.hasAnySuperRegClasses(SubIdx))
1104 SuperRegClasses.push_back(x: &RC);
1105 }
1106 llvm::stable_sort(Range&: SuperRegClasses, C: WeakSizeOrder);
1107
1108 // Find the biggest subclass and subreg class such that R:subidx is in the
1109 // subreg class for all R in subclass.
1110 //
1111 // For example:
1112 // All registers in X86's GR64 have a sub_32bit subregister but no class
1113 // exists that contains all the 32-bit subregisters because GR64 contains RIP
1114 // but GR32 does not contain EIP. Instead, we constrain SuperRegRC to
1115 // GR32_with_sub_8bit (which is identical to GR32_with_sub_32bit) and then,
1116 // having excluded RIP, we are able to find a SubRegRC (GR32).
1117 CodeGenRegisterClass *ChosenSuperRegClass = nullptr;
1118 CodeGenRegisterClass *SubRegRC = nullptr;
1119 for (CodeGenRegisterClass *SuperRegRC : SuperRegRCs) {
1120 for (CodeGenRegisterClass *SuperRegClass : SuperRegClasses) {
1121 if (SuperRegClass->hasSuperRegClass(SubIdx, RC: SuperRegRC)) {
1122 SubRegRC = SuperRegClass;
1123 ChosenSuperRegClass = SuperRegRC;
1124
1125 // If SubRegRC is bigger than SuperRegRC then there are members of
1126 // SubRegRC that don't have super registers via SubIdx. Keep looking to
1127 // find a better fit and fall back on this one if there isn't one.
1128 //
1129 // This is intended to prevent X86 from making odd choices such as
1130 // picking LOW32_ADDR_ACCESS_RBP instead of GR32 in the example above.
1131 // LOW32_ADDR_ACCESS_RBP is a valid choice but contains registers that
1132 // aren't subregisters of SuperRegRC whereas GR32 has a direct 1:1
1133 // mapping.
1134 if (SuperRegRC->getMembers().size() >= SubRegRC->getMembers().size())
1135 return std::pair(ChosenSuperRegClass, SubRegRC);
1136 }
1137 }
1138
1139 // If we found a fit but it wasn't quite ideal because SubRegRC had excess
1140 // registers, then we're done.
1141 if (ChosenSuperRegClass)
1142 return std::pair(ChosenSuperRegClass, SubRegRC);
1143 }
1144
1145 return std::nullopt;
1146}
1147
1148bool CodeGenRegisterClass::hasAnySuperRegClasses(
1149 const CodeGenSubRegIndex *SubIdx) const {
1150 return SuperRegClasses.contains(Val: SubIdx);
1151}
1152
1153bool CodeGenRegisterClass::hasSuperRegClass(
1154 const CodeGenSubRegIndex *SubIdx, const CodeGenRegisterClass *RC) const {
1155 auto FindI = SuperRegClasses.find(Val: SubIdx);
1156
1157 return FindI != SuperRegClasses.end() && FindI->second.contains(V: RC);
1158}
1159
1160void CodeGenRegisterClass::getSuperRegClasses(const CodeGenSubRegIndex *SubIdx,
1161 BitVector &Out) const {
1162 auto FindI = SuperRegClasses.find(Val: SubIdx);
1163 if (FindI == SuperRegClasses.end())
1164 return;
1165 for (CodeGenRegisterClass *RC : FindI->second)
1166 Out.set(RC->EnumValue);
1167}
1168
1169// Populate a unique sorted list of units from a register set.
1170void CodeGenRegisterClass::buildRegUnitSet(
1171 const CodeGenRegBank &RegBank, std::vector<unsigned> &RegUnits) const {
1172 std::vector<unsigned> TmpUnits;
1173 for (const CodeGenRegister *Reg : Members) {
1174 for (unsigned UnitI : Reg->getRegUnits()) {
1175 const RegUnit &RU = RegBank.getRegUnit(RUID: UnitI);
1176 if (!RU.Artificial)
1177 TmpUnits.push_back(x: UnitI);
1178 }
1179 }
1180 llvm::sort(C&: TmpUnits);
1181 std::unique_copy(first: TmpUnits.begin(), last: TmpUnits.end(),
1182 result: std::back_inserter(x&: RegUnits));
1183}
1184
1185// Combine our super classes of the given sub-register index with all of their
1186// super classes in turn.
1187void CodeGenRegisterClass::extendSuperRegClasses(CodeGenSubRegIndex *SubIdx) {
1188 auto It = SuperRegClasses.find(Val: SubIdx);
1189 if (It == SuperRegClasses.end())
1190 return;
1191
1192 SmallVector<CodeGenRegisterClass *> MidRCs;
1193 llvm::append_range(C&: MidRCs, R&: It->second);
1194
1195 for (CodeGenRegisterClass *MidRC : MidRCs) {
1196 for (auto &Pair : MidRC->SuperRegClasses) {
1197 CodeGenSubRegIndex *ComposedSubIdx = Pair.first->compose(Idx: SubIdx);
1198 if (!ComposedSubIdx)
1199 continue;
1200
1201 for (CodeGenRegisterClass *SuperRC : Pair.second)
1202 addSuperRegClass(SubIdx: ComposedSubIdx, SuperRC);
1203 }
1204 }
1205}
1206
1207//===----------------------------------------------------------------------===//
1208// CodeGenRegisterCategory
1209//===----------------------------------------------------------------------===//
1210
1211CodeGenRegisterCategory::CodeGenRegisterCategory(CodeGenRegBank &RegBank,
1212 const Record *R)
1213 : TheDef(R), Name(R->getName().str()) {
1214 for (const Record *RegClass : R->getValueAsListOfDefs(FieldName: "Classes"))
1215 Classes.push_back(x: RegBank.getRegClass(RegClass));
1216}
1217
1218//===----------------------------------------------------------------------===//
1219// CodeGenRegBank
1220//===----------------------------------------------------------------------===//
1221
1222CodeGenRegBank::CodeGenRegBank(const RecordKeeper &Records,
1223 const CodeGenHwModes &Modes,
1224 const bool RegistersAreIntervals)
1225 : Records(Records), CGH(Modes),
1226 RegistersAreIntervals(RegistersAreIntervals) {
1227 // Configure register Sets to understand register classes and tuples.
1228 Sets.addFieldExpander(ClassName: "RegisterClass", FieldName: "MemberList");
1229 Sets.addFieldExpander(ClassName: "CalleeSavedRegs", FieldName: "SaveList");
1230 Sets.addExpander(ClassName: "RegisterTuples",
1231 std::make_unique<TupleExpander>(args&: SynthDefs));
1232
1233 // Read in the user-defined (named) sub-register indices.
1234 // More indices will be synthesized later.
1235 for (const Record *SRI : Records.getAllDerivedDefinitions(ClassName: "SubRegIndex"))
1236 getSubRegIdx(SRI);
1237 // Build composite maps from ComposedOf fields.
1238 for (auto &Idx : SubRegIndices)
1239 Idx.updateComponents(RegBank&: *this);
1240
1241 // Read in the register and register tuple definitions.
1242 const RecordKeeper &RC = Records;
1243 std::vector<const Record *> Regs = RC.getAllDerivedDefinitions(ClassName: "Register");
1244 if (!Regs.empty() && Regs[0]->isSubClassOf(Name: "X86Reg")) {
1245 // For X86, we need to sort Registers and RegisterTuples together to list
1246 // new registers and register tuples at a later position. So that we can
1247 // reduce unnecessary iterations on unsupported registers in LiveVariables.
1248 // TODO: Remove this logic when migrate from LiveVariables to LiveIntervals
1249 // completely.
1250 for (const Record *R : Records.getAllDerivedDefinitions(ClassName: "RegisterTuples")) {
1251 // Expand tuples and merge the vectors
1252 std::vector<const Record *> TupRegs = *Sets.expand(Set: R);
1253 llvm::append_range(C&: Regs, R&: TupRegs);
1254 }
1255
1256 llvm::sort(C&: Regs, Comp: LessRecordRegister());
1257 // Assign the enumeration values.
1258 for (const Record *Reg : Regs)
1259 getReg(Reg);
1260 } else {
1261 llvm::sort(C&: Regs, Comp: LessRecordRegister());
1262 // Assign the enumeration values.
1263 for (const Record *Reg : Regs)
1264 getReg(Reg);
1265
1266 // Expand tuples and number the new registers.
1267 for (const Record *R : Records.getAllDerivedDefinitions(ClassName: "RegisterTuples")) {
1268 std::vector<const Record *> TupRegs = *Sets.expand(Set: R);
1269 llvm::sort(C&: TupRegs, Comp: LessRecordRegister());
1270 for (const Record *RC : TupRegs)
1271 getReg(RC);
1272 }
1273 }
1274
1275 // Now all the registers are known. Build the object graph of explicit
1276 // register-register references.
1277 for (CodeGenRegister &Reg : Registers)
1278 Reg.buildObjectGraph(RegBank&: *this);
1279
1280 // Compute register name map.
1281 for (CodeGenRegister &Reg : Registers)
1282 // FIXME: This could just be RegistersByName[name] = register, except that
1283 // causes some failures in MIPS - perhaps they have duplicate register name
1284 // entries? (or maybe there's a reason for it - I don't know much about this
1285 // code, just drive-by refactoring)
1286 RegistersByName.try_emplace(Key: Reg.TheDef->getValueAsString(FieldName: "AsmName"), Args: &Reg);
1287
1288 // Precompute all sub-register maps.
1289 // This will create Composite entries for all inferred sub-register indices.
1290 for (CodeGenRegister &Reg : Registers)
1291 Reg.computeSubRegs(RegBank&: *this);
1292
1293 // Compute transitive closure of subregister index ConcatenationOf vectors
1294 // and initialize ConcatIdx map.
1295 for (CodeGenSubRegIndex &SRI : SubRegIndices) {
1296 SRI.computeConcatTransitiveClosure();
1297 if (!SRI.ConcatenationOf.empty())
1298 ConcatIdx.try_emplace(
1299 k: SmallVector<CodeGenSubRegIndex *, 8>(SRI.ConcatenationOf.begin(),
1300 SRI.ConcatenationOf.end()),
1301 args: &SRI);
1302 }
1303
1304 // Infer even more sub-registers by combining leading super-registers.
1305 for (CodeGenRegister &Reg : Registers)
1306 if (Reg.CoveredBySubRegs)
1307 Reg.computeSecondarySubRegs(RegBank&: *this);
1308
1309 // After the sub-register graph is complete, compute the topologically
1310 // ordered SuperRegs list.
1311 for (CodeGenRegister &Reg : Registers)
1312 Reg.computeSuperRegs(RegBank&: *this);
1313
1314 // For each pair of Reg:SR, if both are non-artificial, mark the
1315 // corresponding sub-register index as non-artificial.
1316 for (CodeGenRegister &Reg : Registers) {
1317 if (Reg.Artificial)
1318 continue;
1319 for (auto [SRI, SR] : Reg.getSubRegs()) {
1320 if (!SR->Artificial)
1321 SRI->Artificial = false;
1322 }
1323 }
1324
1325 computeSubRegIndicesRPOT();
1326
1327 // Native register units are associated with a leaf register. They've all been
1328 // discovered now.
1329 NumNativeRegUnits = RegUnits.size();
1330
1331 // Read in register class definitions.
1332 ArrayRef<const Record *> RCs =
1333 Records.getAllDerivedDefinitions(ClassName: "RegisterClass");
1334 if (RCs.empty())
1335 PrintFatalError(Msg: "No 'RegisterClass' subclasses defined!");
1336
1337 // Allocate user-defined register classes.
1338 for (const Record *R : RCs) {
1339 RegClasses.emplace_back(args&: *this, args&: R);
1340 CodeGenRegisterClass &RC = RegClasses.back();
1341 if (!RC.Artificial)
1342 addToMaps(&RC);
1343 }
1344
1345 // Infer missing classes to create a full algebra.
1346 computeInferredRegisterClasses();
1347
1348 // Order register classes topologically and assign enum values.
1349 RegClasses.sort(comp: TopoOrderRC);
1350 for (auto [Idx, RC] : enumerate(First&: RegClasses))
1351 RC.EnumValue = Idx;
1352 CodeGenRegisterClass::computeSubClasses(RegBank&: *this);
1353
1354 // Read in the register category definitions.
1355 for (const Record *R : Records.getAllDerivedDefinitions(ClassName: "RegisterCategory"))
1356 RegCategories.emplace_back(args&: *this, args&: R);
1357
1358 // Now that register classes (and their sizes) are built, check that no
1359 // explicit SubRegIndex makes a sub-register overflow its register.
1360 for (const auto &Reg : Registers)
1361 Reg.checkSubRegIndexSizes(RegBank&: *this);
1362}
1363
1364// Create a synthetic CodeGenSubRegIndex without a corresponding Record.
1365CodeGenSubRegIndex *CodeGenRegBank::createSubRegIndex(StringRef Name,
1366 StringRef Namespace) {
1367 SubRegIndices.emplace_back(args&: Name, args&: Namespace, args: SubRegIndices.size() + 1);
1368 return &SubRegIndices.back();
1369}
1370
1371CodeGenSubRegIndex *CodeGenRegBank::getSubRegIdx(const Record *Def) {
1372 CodeGenSubRegIndex *&Idx = Def2SubRegIdx[Def];
1373 if (Idx)
1374 return Idx;
1375 SubRegIndices.emplace_back(args&: Def, args: SubRegIndices.size() + 1, args: getHwModes());
1376 Idx = &SubRegIndices.back();
1377 return Idx;
1378}
1379
1380const CodeGenSubRegIndex *
1381CodeGenRegBank::findSubRegIdx(const Record *Def) const {
1382 return Def2SubRegIdx.at(Val: Def);
1383}
1384
1385CodeGenRegister *CodeGenRegBank::getReg(const Record *Def) {
1386 CodeGenRegister *&Reg = Def2Reg[Def];
1387 if (Reg)
1388 return Reg;
1389 Registers.emplace_back(args&: Def, args: Registers.size() + 1);
1390 Reg = &Registers.back();
1391 return Reg;
1392}
1393
1394void CodeGenRegBank::addToMaps(CodeGenRegisterClass *RC) {
1395 if (const Record *Def = RC->getDef())
1396 Def2RC.try_emplace(Key: Def, Args&: RC);
1397
1398 // Duplicate classes are rejected by insert().
1399 // That's OK, we only care about the properties handled by CGRC::Key.
1400 CodeGenRegisterClass::Key K(*RC, /*IgnoreArtificialMembers=*/true);
1401 Key2RC.try_emplace(k: K, args&: RC);
1402}
1403
1404// Create a synthetic sub-class if it is missing.
1405std::pair<CodeGenRegisterClass *, bool>
1406CodeGenRegBank::getOrCreateSubClass(const CodeGenRegisterClass *RC,
1407 const CodeGenRegister::Vec *Members,
1408 StringRef Name) {
1409 // Synthetic sub-class has the same size and alignment as RC.
1410 CodeGenRegisterClass::Key K(Members, RC->RSI,
1411 /*IgnoreArtificialMembers=*/true);
1412 RCKeyMap::const_iterator FoundI = Key2RC.find(x: K);
1413 if (FoundI != Key2RC.end())
1414 return {FoundI->second, false};
1415
1416 // Sub-class doesn't exist, create a new one.
1417 RegClasses.emplace_back(args&: *this, args&: Name, args&: K);
1418 addToMaps(RC: &RegClasses.back());
1419 return {&RegClasses.back(), true};
1420}
1421
1422CodeGenRegisterClass *CodeGenRegBank::getRegClass(const Record *Def,
1423 ArrayRef<SMLoc> Loc) const {
1424 assert(Def->isSubClassOf("RegisterClassLike"));
1425 if (CodeGenRegisterClass *RC = Def2RC.lookup(Val: Def))
1426 return RC;
1427
1428 ArrayRef<SMLoc> DiagLoc = Loc.empty() ? Def->getLoc() : Loc;
1429 // TODO: Ideally we should update the API to allow resolving HwMode.
1430 if (Def->isSubClassOf(Name: "RegClassByHwMode"))
1431 PrintError(ErrorLoc: DiagLoc, Msg: "cannot resolve HwMode for " + Def->getName());
1432 else
1433 PrintError(ErrorLoc: DiagLoc, Msg: Def->getName() + " is not a known RegisterClass!");
1434 PrintFatalNote(ErrorLoc: Def->getLoc(), Msg: Def->getName() + " defined here");
1435}
1436
1437CodeGenSubRegIndex *
1438CodeGenRegBank::getCompositeSubRegIndex(CodeGenSubRegIndex *A,
1439 CodeGenSubRegIndex *B) {
1440 // Look for an existing entry.
1441 CodeGenSubRegIndex *Comp = A->compose(Idx: B);
1442 if (Comp)
1443 return Comp;
1444
1445 // None exists, synthesize one.
1446 std::string Name = A->getName() + "_then_" + B->getName();
1447 Comp = createSubRegIndex(Name, Namespace: A->getNamespace());
1448 A->addComposite(A: B, B: Comp, CGH: getHwModes());
1449 return Comp;
1450}
1451
1452CodeGenSubRegIndex *CodeGenRegBank::getConcatSubRegIndex(
1453 const SmallVector<CodeGenSubRegIndex *, 8> &Parts,
1454 const CodeGenHwModes &CGH) {
1455 assert(Parts.size() > 1 && "Need two parts to concatenate");
1456#ifndef NDEBUG
1457 for (CodeGenSubRegIndex *Idx : Parts) {
1458 assert(Idx->ConcatenationOf.empty() && "No transitive closure?");
1459 }
1460#endif
1461
1462 // Look for an existing entry.
1463 CodeGenSubRegIndex *&Idx = ConcatIdx[Parts];
1464 if (Idx)
1465 return Idx;
1466
1467 // None exists, synthesize one.
1468 std::string Name = Parts.front()->getName();
1469 const unsigned UnknownSize = (uint32_t)-1;
1470
1471 for (const CodeGenSubRegIndex *Part : ArrayRef(Parts).drop_front()) {
1472 Name += '_';
1473 Name += Part->getName();
1474 }
1475
1476 Idx = createSubRegIndex(Name, Namespace: Parts.front()->getNamespace());
1477 Idx->ConcatenationOf.assign(in_start: Parts.begin(), in_end: Parts.end());
1478
1479 unsigned NumModes = CGH.getNumModeIds();
1480 for (unsigned M = 0; M < NumModes; ++M) {
1481 const CodeGenSubRegIndex *FirstPart = Parts.front();
1482
1483 // Determine whether all parts are contiguous.
1484 bool IsContinuous = true;
1485 const SubRegRange &FirstPartRange = FirstPart->Range.get(Mode: M);
1486 unsigned Size = FirstPartRange.Size;
1487 unsigned LastOffset = FirstPartRange.Offset;
1488 unsigned LastSize = FirstPartRange.Size;
1489
1490 for (const CodeGenSubRegIndex *Part : ArrayRef(Parts).drop_front()) {
1491 const SubRegRange &PartRange = Part->Range.get(Mode: M);
1492 if (Size == UnknownSize || PartRange.Size == UnknownSize)
1493 Size = UnknownSize;
1494 else
1495 Size += PartRange.Size;
1496 if (LastSize == UnknownSize ||
1497 PartRange.Offset != (LastOffset + LastSize))
1498 IsContinuous = false;
1499 LastOffset = PartRange.Offset;
1500 LastSize = PartRange.Size;
1501 }
1502 unsigned Offset = IsContinuous ? FirstPartRange.Offset : -1;
1503 Idx->Range.get(Mode: M) = SubRegRange(Size, Offset);
1504 }
1505
1506 return Idx;
1507}
1508
1509void CodeGenRegBank::computeComposites() {
1510 using RegMap = std::map<const CodeGenRegister *, const CodeGenRegister *>;
1511
1512 // Subreg -> { Reg->Reg }, where the right-hand side is the mapping from
1513 // register to (sub)register associated with the action of the left-hand
1514 // side subregister.
1515 std::map<const CodeGenSubRegIndex *, RegMap> SubRegAction;
1516 for (const CodeGenRegister &R : Registers) {
1517 const CodeGenRegister::SubRegMap &SM = R.getSubRegs();
1518 for (auto [SRI, SubReg] : SM)
1519 SubRegAction[SRI].try_emplace(k: &R, args&: SubReg);
1520 }
1521
1522 // Calculate the composition of two subregisters as compositions of their
1523 // associated actions.
1524 auto compose = [&SubRegAction](const CodeGenSubRegIndex *Sub1,
1525 const CodeGenSubRegIndex *Sub2) {
1526 RegMap C;
1527 const RegMap &Img1 = SubRegAction.at(k: Sub1);
1528 const RegMap &Img2 = SubRegAction.at(k: Sub2);
1529 for (auto [R, SubReg] : Img1) {
1530 auto F = Img2.find(x: SubReg);
1531 if (F != Img2.end())
1532 C.try_emplace(k: R, args: F->second);
1533 }
1534 return C;
1535 };
1536
1537 // Check if the two maps agree on the intersection of their domains.
1538 auto agree = [](const RegMap &Map1, const RegMap &Map2) {
1539 // Technically speaking, an empty map agrees with any other map, but
1540 // this could flag false positives. We're interested in non-vacuous
1541 // agreements.
1542 if (Map1.empty() || Map2.empty())
1543 return false;
1544 for (auto [K, V] : Map1) {
1545 auto F = Map2.find(x: K);
1546 if (F == Map2.end() || V != F->second)
1547 return false;
1548 }
1549 return true;
1550 };
1551
1552 using CompositePair =
1553 std::pair<const CodeGenSubRegIndex *, const CodeGenSubRegIndex *>;
1554 SmallSet<CompositePair, 4> UserDefined;
1555 for (const CodeGenSubRegIndex &Idx : SubRegIndices)
1556 for (auto P : Idx.getComposites())
1557 UserDefined.insert(V: {&Idx, P.first});
1558
1559 // Keep track of TopoSigs visited. We only need to visit each TopoSig once,
1560 // and many registers will share TopoSigs on regular architectures.
1561 BitVector TopoSigs(getNumTopoSigs());
1562
1563 for (const CodeGenRegister &Reg1 : Registers) {
1564 // Skip identical subreg structures already processed.
1565 if (TopoSigs.test(Idx: Reg1.getTopoSig()))
1566 continue;
1567 TopoSigs.set(Reg1.getTopoSig());
1568
1569 const CodeGenRegister::SubRegMap &SRM1 = Reg1.getSubRegs();
1570 for (auto [Idx1, Reg2] : SRM1) {
1571 // Ignore identity compositions.
1572 if (&Reg1 == Reg2)
1573 continue;
1574 const CodeGenRegister::SubRegMap &SRM2 = Reg2->getSubRegs();
1575 // Try composing Idx1 with another SubRegIndex.
1576 for (auto I2 : SRM2) {
1577 CodeGenSubRegIndex *Idx2 = I2.first;
1578 CodeGenRegister *Reg3 = I2.second;
1579 // Ignore identity compositions.
1580 if (Reg2 == Reg3)
1581 continue;
1582 // OK Reg1:IdxPair == Reg3. Find the index with Reg:Idx == Reg3.
1583 CodeGenSubRegIndex *Idx3 = Reg1.getSubRegIndex(Reg: Reg3);
1584 assert(Idx3 && "Sub-register doesn't have an index");
1585
1586 // Conflicting composition? Emit a warning but allow it.
1587 if (CodeGenSubRegIndex *Prev =
1588 Idx1->addComposite(A: Idx2, B: Idx3, CGH: getHwModes())) {
1589 // If the composition was not user-defined, always emit a warning.
1590 if (!UserDefined.contains(V: {Idx1, Idx2}) ||
1591 agree(compose(Idx1, Idx2), SubRegAction.at(k: Idx3)))
1592 PrintWarning(Msg: Twine("SubRegIndex ") + Idx1->getQualifiedName() +
1593 " and " + Idx2->getQualifiedName() +
1594 " compose ambiguously as " + Prev->getQualifiedName() +
1595 " or " + Idx3->getQualifiedName());
1596 }
1597 }
1598 }
1599 }
1600}
1601
1602// Compute lane masks. This is similar to register units, but at the
1603// sub-register index level. Each bit in the lane mask is like a register unit
1604// class, and two lane masks will have a bit in common if two sub-register
1605// indices overlap in some register.
1606//
1607// Conservatively share a lane mask bit if two sub-register indices overlap in
1608// some registers, but not in others. That shouldn't happen a lot.
1609void CodeGenRegBank::computeSubRegLaneMasks() {
1610 // First assign individual bits to all the leaf indices.
1611 unsigned Bit = 0;
1612 // Determine mask of lanes that cover their registers.
1613 CoveringLanes = LaneBitmask::getAll();
1614 for (CodeGenSubRegIndex &Idx : SubRegIndices) {
1615 if (Idx.getComposites().empty()) {
1616 if (Bit >= LaneBitmask::BitWidth) {
1617 PrintFatalError(
1618 Msg: Twine("Ran out of lanemask bits to represent subregister ") +
1619 Idx.getName());
1620 }
1621 Idx.LaneMask = LaneBitmask::getLane(Lane: Bit);
1622 ++Bit;
1623 } else {
1624 Idx.LaneMask = LaneBitmask::getNone();
1625 }
1626 }
1627
1628 // Compute transformation sequences for composeSubRegIndexLaneMask. The idea
1629 // here is that for each possible target subregister we look at the leafs
1630 // in the subregister graph that compose for this target and create
1631 // transformation sequences for the lanemasks. Each step in the sequence
1632 // consists of a bitmask and a bitrotate operation. As the rotation amounts
1633 // are usually the same for many subregisters we can easily combine the steps
1634 // by combining the masks.
1635 for (const CodeGenSubRegIndex &Idx : SubRegIndices) {
1636 const CodeGenSubRegIndex::CompMap &Composites = Idx.getComposites();
1637 auto &LaneTransforms = Idx.CompositionLaneMaskTransform;
1638
1639 if (Composites.empty()) {
1640 // Moving from a class with no subregisters we just had a single lane:
1641 // The subregister must be a leaf subregister and only occupies 1 bit.
1642 // Move the bit from the class without subregisters into that position.
1643 unsigned DstBit = Idx.LaneMask.getHighestLane();
1644 assert(Idx.LaneMask == LaneBitmask::getLane(DstBit) &&
1645 "Must be a leaf subregister");
1646 MaskRolPair MaskRol = {.Mask: LaneBitmask::getLane(Lane: 0), .RotateLeft: (uint8_t)DstBit};
1647 LaneTransforms.push_back(Elt: MaskRol);
1648 } else {
1649 // Go through all leaf subregisters and find the ones that compose with
1650 // Idx. These make out all possible valid bits in the lane mask we want to
1651 // transform. Looking only at the leafs ensure that only a single bit in
1652 // the mask is set.
1653 for (CodeGenSubRegIndex &Idx2 : SubRegIndices) {
1654 // Skip non-leaf subregisters.
1655 if (!Idx2.getComposites().empty())
1656 continue;
1657 LaneBitmask SrcMask = Idx2.LaneMask;
1658
1659 // Get the composed subregister if there is any.
1660 auto C = Composites.find(x: &Idx2);
1661 if (C == Composites.end())
1662 continue;
1663 const CodeGenSubRegIndex *Composite = C->second;
1664 // The Composed subreg should be a leaf subreg too
1665 assert(Composite->getComposites().empty());
1666
1667 // Create Mask+Rotate operation and merge with existing ops if possible.
1668 unsigned SrcBit = SrcMask.getHighestLane();
1669 unsigned DstBit = Composite->LaneMask.getHighestLane();
1670 int Shift = DstBit - SrcBit;
1671 uint8_t RotateLeft =
1672 Shift >= 0 ? (uint8_t)Shift : LaneBitmask::BitWidth + Shift;
1673 for (MaskRolPair &I : LaneTransforms) {
1674 if (I.RotateLeft == RotateLeft) {
1675 I.Mask |= SrcMask;
1676 SrcMask = LaneBitmask::getNone();
1677 }
1678 }
1679 if (SrcMask.any()) {
1680 MaskRolPair MaskRol = {.Mask: SrcMask, .RotateLeft: RotateLeft};
1681 LaneTransforms.push_back(Elt: MaskRol);
1682 }
1683 }
1684 }
1685
1686 // Optimize if the transformation consists of one step only: Set mask to
1687 // 0xffffffff (including some irrelevant invalid bits) so that it should
1688 // merge with more entries later while compressing the table.
1689 if (LaneTransforms.size() == 1)
1690 LaneTransforms[0].Mask = LaneBitmask::getAll();
1691
1692 // Further compression optimization: For invalid compositions resulting
1693 // in a sequence with 0 entries we can just pick any other. Choose
1694 // Mask 0xffffffff with Rotation 0.
1695 if (LaneTransforms.size() == 0) {
1696 MaskRolPair P = {.Mask: LaneBitmask::getAll(), .RotateLeft: 0};
1697 LaneTransforms.push_back(Elt: P);
1698 }
1699 }
1700
1701 // FIXME: What if ad-hoc aliasing introduces overlaps that aren't represented
1702 // by the sub-register graph? This doesn't occur in any known targets.
1703
1704 // Inherit lanes from composites.
1705 for (const CodeGenSubRegIndex &Idx : SubRegIndices) {
1706 LaneBitmask Mask = Idx.computeLaneMask();
1707 // If some super-registers without CoveredBySubRegs use this index, we can
1708 // no longer assume that the lanes are covering their registers.
1709 if (!Idx.AllSuperRegsCovered)
1710 CoveringLanes &= ~Mask;
1711 }
1712
1713 // Compute lane mask combinations for register classes.
1714 for (auto &RegClass : RegClasses) {
1715 LaneBitmask LaneMask;
1716 for (const CodeGenSubRegIndex &SubRegIndex : SubRegIndices) {
1717 if (RegClass.getSubClassWithSubReg(SubIdx: &SubRegIndex) == nullptr)
1718 continue;
1719 LaneMask |= SubRegIndex.LaneMask;
1720 }
1721
1722 // For classes without any subregisters set LaneMask to 1 instead of 0.
1723 // This makes it easier for client code to handle classes uniformly.
1724 if (LaneMask.none())
1725 LaneMask = LaneBitmask::getLane(Lane: 0);
1726
1727 RegClass.LaneMask = LaneMask;
1728 }
1729}
1730
1731namespace {
1732
1733// A directed graph on sub-register indices with a virtual source node that
1734// has an arc to all other nodes, and an arc from A to B if sub-register index
1735// B can be obtained by composing A with some other sub-register index.
1736struct SubRegIndexCompositionGraph {
1737 std::deque<CodeGenSubRegIndex> &SubRegIndices;
1738 CodeGenSubRegIndex::CompMap EntryNode;
1739
1740 SubRegIndexCompositionGraph(std::deque<CodeGenSubRegIndex> &SubRegIndices)
1741 : SubRegIndices(SubRegIndices) {
1742 for (CodeGenSubRegIndex &Idx : SubRegIndices) {
1743 EntryNode.try_emplace(k: &Idx, args: &Idx);
1744 }
1745 }
1746};
1747
1748} // namespace
1749
1750template <> struct llvm::GraphTraits<SubRegIndexCompositionGraph> {
1751 using NodeRef =
1752 PointerUnion<CodeGenSubRegIndex *, const CodeGenSubRegIndex::CompMap *>;
1753
1754 // Using a reverse iterator causes sub-register indices to appear in their
1755 // more natural order in RPOT.
1756 using CompMapIt = CodeGenSubRegIndex::CompMap::const_reverse_iterator;
1757 struct ChildIteratorType
1758 : public iterator_adaptor_base<
1759 ChildIteratorType, CompMapIt,
1760 std::iterator_traits<CompMapIt>::iterator_category, NodeRef> {
1761 ChildIteratorType(CompMapIt I)
1762 : ChildIteratorType::iterator_adaptor_base(I) {}
1763
1764 NodeRef operator*() const { return wrapped()->second; }
1765 };
1766
1767 static NodeRef getEntryNode(const SubRegIndexCompositionGraph &G) {
1768 return &G.EntryNode;
1769 }
1770
1771 static const CodeGenSubRegIndex::CompMap *children(NodeRef N) {
1772 if (auto *Idx = dyn_cast<CodeGenSubRegIndex *>(Val&: N))
1773 return &Idx->getComposites();
1774 return cast<const CodeGenSubRegIndex::CompMap *>(Val&: N);
1775 }
1776
1777 static ChildIteratorType child_begin(NodeRef N) {
1778 return ChildIteratorType(children(N)->rbegin());
1779 }
1780 static ChildIteratorType child_end(NodeRef N) {
1781 return ChildIteratorType(children(N)->rend());
1782 }
1783
1784 static auto nodes_begin(SubRegIndexCompositionGraph *G) {
1785 return G->SubRegIndices.begin();
1786 }
1787 static auto nodes_end(SubRegIndexCompositionGraph *G) {
1788 return G->SubRegIndices.end();
1789 }
1790
1791 static unsigned size(SubRegIndexCompositionGraph *G) {
1792 return G->SubRegIndices.size();
1793 }
1794};
1795
1796void CodeGenRegBank::computeSubRegIndicesRPOT() {
1797 SubRegIndexCompositionGraph G(SubRegIndices);
1798 ReversePostOrderTraversal<SubRegIndexCompositionGraph> RPOT(G);
1799 for (const auto N : RPOT) {
1800 if (auto *Idx = dyn_cast<CodeGenSubRegIndex *>(Val: N))
1801 SubRegIndicesRPOT.push_back(x: Idx);
1802 }
1803}
1804
1805namespace {
1806
1807// UberRegSet is a helper class for computeRegUnitWeights. Each UberRegSet is
1808// the transitive closure of the union of overlapping register
1809// classes. Together, the UberRegSets form a partition of the registers. If we
1810// consider overlapping register classes to be connected, then each UberRegSet
1811// is a set of connected components.
1812//
1813// An UberRegSet will likely be a horizontal slice of register names of
1814// the same width. Nontrivial subregisters should then be in a separate
1815// UberRegSet. But this property isn't required for valid computation of
1816// register unit weights.
1817//
1818// A Weight field caches the max per-register unit weight in each UberRegSet.
1819//
1820// A set of SingularDeterminants flags single units of some register in this set
1821// for which the unit weight equals the set weight. These units should not have
1822// their weight increased.
1823struct UberRegSet {
1824 CodeGenRegister::Vec Regs;
1825 unsigned Weight = 0;
1826 CodeGenRegister::RegUnitList SingularDeterminants;
1827
1828 UberRegSet() = default;
1829};
1830
1831} // end anonymous namespace
1832
1833// Partition registers into UberRegSets, where each set is the transitive
1834// closure of the union of overlapping register classes.
1835//
1836// UberRegSets[0] is a special non-allocatable set.
1837static void computeUberSets(std::vector<UberRegSet> &UberSets,
1838 std::vector<UberRegSet *> &RegSets,
1839 CodeGenRegBank &RegBank) {
1840 const auto &Registers = RegBank.getRegisters();
1841
1842 // The Register EnumValue is one greater than its index into Registers.
1843 assert(Registers.size() == Registers.back().EnumValue &&
1844 "register enum value mismatch");
1845
1846 // For simplicitly make the SetID the same as EnumValue.
1847 IntEqClasses UberSetIDs(Registers.size() + 1);
1848 BitVector AllocatableRegs(Registers.size() + 1);
1849 for (CodeGenRegisterClass &RegClass : RegBank.getRegClasses()) {
1850 if (!RegClass.Allocatable)
1851 continue;
1852
1853 // Ignore artificial registers. They may be members of register
1854 // classes that together include registers and their subregisters,
1855 // in which case it is impossible to normalize the weights of
1856 // their register units.
1857 CodeGenRegister::Vec Regs;
1858 for (const CodeGenRegister *Reg : RegClass.getMembers()) {
1859 if (!Reg->Artificial)
1860 Regs.push_back(x: Reg);
1861 }
1862
1863 if (Regs.empty())
1864 continue;
1865
1866 unsigned USetID = UberSetIDs.findLeader(a: (*Regs.begin())->EnumValue);
1867 assert(USetID && "register number 0 is invalid");
1868
1869 AllocatableRegs.set((*Regs.begin())->EnumValue);
1870 for (const CodeGenRegister *CGR : llvm::drop_begin(RangeOrContainer&: Regs)) {
1871 AllocatableRegs.set(CGR->EnumValue);
1872 UberSetIDs.join(a: USetID, b: CGR->EnumValue);
1873 }
1874 }
1875 // Combine non-allocatable regs.
1876 for (const CodeGenRegister &Reg : Registers) {
1877 unsigned RegNum = Reg.EnumValue;
1878 if (AllocatableRegs.test(Idx: RegNum))
1879 continue;
1880
1881 UberSetIDs.join(a: 0, b: RegNum);
1882 }
1883 UberSetIDs.compress();
1884
1885 // Make the first UberSet a special unallocatable set.
1886 unsigned ZeroID = UberSetIDs[0];
1887
1888 // Insert Registers into the UberSets formed by union-find.
1889 // Do not resize after this.
1890 UberSets.resize(new_size: UberSetIDs.getNumClasses());
1891 for (auto [Idx, Reg] : enumerate(First: Registers)) {
1892 unsigned USetID = UberSetIDs[Reg.EnumValue];
1893 if (!USetID)
1894 USetID = ZeroID;
1895 else if (USetID == ZeroID)
1896 USetID = 0;
1897
1898 UberRegSet *USet = &UberSets[USetID];
1899 USet->Regs.push_back(x: &Reg);
1900 RegSets[Idx] = USet;
1901 }
1902}
1903
1904// Recompute a single UberSet's weight after a change to register-unit weights.
1905static void computeUberWeight(UberRegSet &S, CodeGenRegBank &RegBank) {
1906 // Initialize all unit weights in this set, and remember the max units/reg.
1907 unsigned MaxWeight = 0;
1908 for (const CodeGenRegister *R : S.Regs) {
1909 unsigned Weight = 0;
1910 for (unsigned U : R->getRegUnits()) {
1911 if (!RegBank.getRegUnit(RUID: U).Artificial) {
1912 unsigned UWeight = RegBank.getRegUnit(RUID: U).Weight;
1913 if (!UWeight) {
1914 UWeight = 1;
1915 RegBank.increaseRegUnitWeight(RUID: U, Inc: UWeight);
1916 }
1917 Weight += UWeight;
1918 }
1919 }
1920 MaxWeight = std::max(a: MaxWeight, b: Weight);
1921 }
1922 if (S.Weight != MaxWeight) {
1923 LLVM_DEBUG({
1924 dbgs() << "UberSet Weight " << MaxWeight;
1925 for (const CodeGenRegister *R : S.Regs)
1926 dbgs() << " " << R->getName();
1927 dbgs() << '\n';
1928 });
1929 // Update the set weight.
1930 S.Weight = MaxWeight;
1931 }
1932
1933 // Find singular determinants.
1934 for (const CodeGenRegister *R : S.Regs)
1935 if (R->getRegUnits().count() == 1 && R->getWeight(RegBank) == S.Weight)
1936 S.SingularDeterminants |= R->getRegUnits();
1937}
1938
1939// Recompute each UberSet weight after changing unit weights.
1940static void computeUberWeights(MutableArrayRef<UberRegSet> UberSets,
1941 CodeGenRegBank &RegBank) {
1942 // Skip the first unallocatable set.
1943 for (UberRegSet &S : UberSets.drop_front())
1944 computeUberWeight(S, RegBank);
1945}
1946
1947// normalizeWeight is a computeRegUnitWeights helper that adjusts the weight of
1948// a register and its subregisters so that they have the same weight as their
1949// UberSet. Self-recursion processes the subregister tree in postorder so
1950// subregisters are normalized first.
1951//
1952// Side effects:
1953// - creates new adopted register units
1954// - causes superregisters to inherit adopted units
1955// - increases the weight of "singular" units
1956// - induces recomputation of UberWeights.
1957static bool normalizeWeight(CodeGenRegister *Reg,
1958 std::vector<UberRegSet> &UberSets,
1959 std::vector<UberRegSet *> &RegSets,
1960 BitVector &NormalRegs,
1961 CodeGenRegister::RegUnitList &NormalUnits,
1962 CodeGenRegBank &RegBank) {
1963 NormalRegs.resize(N: std::max(a: Reg->EnumValue + 1, b: NormalRegs.size()));
1964 if (NormalRegs.test(Idx: Reg->EnumValue))
1965 return false;
1966 NormalRegs.set(Reg->EnumValue);
1967
1968 bool Changed = false;
1969 const CodeGenRegister::SubRegMap &SRM = Reg->getSubRegs();
1970 for (auto SRI : SRM) {
1971 if (SRI.second == Reg)
1972 continue; // self-cycles happen
1973
1974 Changed |= normalizeWeight(Reg: SRI.second, UberSets, RegSets, NormalRegs,
1975 NormalUnits, RegBank);
1976 }
1977 // Postorder register normalization.
1978
1979 // Inherit register units newly adopted by subregisters. Inheriting units
1980 // only changes this register's weight, so just its own UberSet can change;
1981 // recompute only that set rather than rescanning every UberSet.
1982 if (Reg->inheritRegUnits(RegBank))
1983 computeUberWeight(S&: *RegSets[RegBank.getRegIndex(Reg)], RegBank);
1984
1985 // Check if this register is too skinny for its UberRegSet.
1986 UberRegSet *UberSet = RegSets[RegBank.getRegIndex(Reg)];
1987
1988 unsigned RegWeight = Reg->getWeight(RegBank);
1989 if (UberSet->Weight > RegWeight) {
1990 // A register unit's weight can be adjusted only if it is the singular unit
1991 // for this register, has not been used to normalize a subregister's set,
1992 // and has not already been used to singularly determine this UberRegSet.
1993 unsigned AdjustUnit = *Reg->getRegUnits().begin();
1994 if (Reg->getRegUnits().count() != 1 || NormalUnits.test(Idx: AdjustUnit) ||
1995 UberSet->SingularDeterminants.test(Idx: AdjustUnit)) {
1996 // We don't have an adjustable unit, so adopt a new one.
1997 AdjustUnit = RegBank.newRegUnit(Weight: UberSet->Weight - RegWeight);
1998 Reg->adoptRegUnit(RUID: AdjustUnit);
1999 // Adopting a unit does not immediately require recomputing set weights.
2000 } else {
2001 // Adjust the existing single unit.
2002 if (!RegBank.getRegUnit(RUID: AdjustUnit).Artificial)
2003 RegBank.increaseRegUnitWeight(RUID: AdjustUnit, Inc: UberSet->Weight - RegWeight);
2004 // The unit may be shared among sets and registers within this set.
2005 computeUberWeights(UberSets, RegBank);
2006 }
2007 Changed = true;
2008 }
2009
2010 // Mark these units normalized so superregisters can't change their weights.
2011 NormalUnits |= Reg->getRegUnits();
2012
2013 return Changed;
2014}
2015
2016// Compute a weight for each register unit created during getSubRegs.
2017//
2018// The goal is that two registers in the same class will have the same weight,
2019// where each register's weight is defined as sum of its units' weights.
2020void CodeGenRegBank::computeRegUnitWeights() {
2021 std::vector<UberRegSet> UberSets;
2022 std::vector<UberRegSet *> RegSets(Registers.size());
2023 computeUberSets(UberSets, RegSets, RegBank&: *this);
2024 // UberSets and RegSets are now immutable.
2025
2026 computeUberWeights(UberSets, RegBank&: *this);
2027
2028 // Iterate over each Register, normalizing the unit weights until reaching
2029 // a fix point.
2030 unsigned NumIters = 0;
2031 for (bool Changed = true; Changed; ++NumIters) {
2032 assert(NumIters <= NumNativeRegUnits && "Runaway register unit weights");
2033 (void)NumIters;
2034 Changed = false;
2035 for (CodeGenRegister &Reg : Registers) {
2036 CodeGenRegister::RegUnitList NormalUnits;
2037 BitVector NormalRegs;
2038 Changed |= normalizeWeight(Reg: &Reg, UberSets, RegSets, NormalRegs,
2039 NormalUnits, RegBank&: *this);
2040 }
2041 }
2042}
2043
2044// isContiguous is a enforceRegUnitIntervals helper that returns true if all
2045// units in Units form a contiguous interval.
2046static bool isContiguous(const CodeGenRegister::RegUnitList &Units) {
2047 unsigned LastUnit = Units.find_first();
2048 for (auto ThisUnit : llvm::make_range(x: ++Units.begin(), y: Units.end())) {
2049 if (ThisUnit != LastUnit + 1)
2050 return false;
2051 LastUnit = ThisUnit;
2052 }
2053 return true;
2054}
2055
2056// Enforce that all registers are intervals of regunits if the target
2057// requests this property. This will renumber regunits to ensure the
2058// interval property holds, or error out if it cannot be satisfied.
2059void CodeGenRegBank::enforceRegUnitIntervals() {
2060 if (!RegistersAreIntervals)
2061 return;
2062
2063 LLVM_DEBUG(dbgs() << "Enforcing regunit intervals for target\n");
2064 std::vector<unsigned> RegUnitRenumbering(RegUnits.size(), ~0u);
2065
2066 // RegUnits that have been renumbered from X -> Y. Y is what is marked so that
2067 // it doesn't create a chain of swaps.
2068 SparseBitVector<> DontRenumberUnits;
2069
2070 auto GetRenumberedUnit = [&](unsigned RegUnit) -> unsigned {
2071 if (unsigned RenumberedUnit = RegUnitRenumbering[RegUnit];
2072 RenumberedUnit != ~0u)
2073 return RenumberedUnit;
2074 return RegUnit;
2075 };
2076
2077 // Process registers in definition order
2078 for (CodeGenRegister &Reg : Registers) {
2079 LLVM_DEBUG(dbgs() << "Processing register " << Reg.getName() << "\n");
2080 const auto &Units = Reg.getNativeRegUnits();
2081 if (Units.empty())
2082 continue;
2083 SparseBitVector<> RenumberedUnits;
2084 // First renumber all the units for this register according to previous
2085 // renumbering.
2086 LLVM_DEBUG(dbgs() << " Original (Renumbered) units:");
2087 for (unsigned U : Units) {
2088 LLVM_DEBUG(dbgs() << " " << U << "(" << GetRenumberedUnit(U) << "), ");
2089 RenumberedUnits.set(GetRenumberedUnit(U));
2090 }
2091 LLVM_DEBUG(dbgs() << "\n");
2092
2093 unsigned LastUnit = RenumberedUnits.find_first();
2094 for (auto ThisUnit :
2095 llvm::make_range(x: ++RenumberedUnits.begin(), y: RenumberedUnits.end())) {
2096 if (ThisUnit != LastUnit + 1) {
2097 if (DontRenumberUnits.test(Idx: LastUnit + 1)) {
2098 PrintFatalError(
2099 Msg: "cannot enforce regunit intervals for register " + Reg.getName() +
2100 ": unit " + Twine(LastUnit + 1) +
2101 " (root: " + RegUnits[LastUnit + 1].Roots[0]->getName() +
2102 ") has already been renumbered and cannot be swapped");
2103 }
2104 LLVM_DEBUG(dbgs() << " Renumbering unit " << ThisUnit << " to "
2105 << (LastUnit + 1) << "\n");
2106 RegUnitRenumbering[LastUnit + 1] = ThisUnit;
2107 RegUnitRenumbering[ThisUnit] = LastUnit + 1;
2108 DontRenumberUnits.set(LastUnit + 1);
2109 ThisUnit = LastUnit + 1;
2110 }
2111 LastUnit = ThisUnit;
2112 }
2113 }
2114
2115 // Apply the renumbering to all registers
2116 for (CodeGenRegister &Reg : Registers) {
2117 CodeGenRegister::RegUnitList NewRegUnits;
2118 for (unsigned OldUnit : Reg.getRegUnits())
2119 NewRegUnits.set(GetRenumberedUnit(OldUnit));
2120 Reg.setNewRegUnits(NewRegUnits);
2121
2122 CodeGenRegister::RegUnitList NewNativeUnits;
2123 for (unsigned OldUnit : Reg.getNativeRegUnits())
2124 NewNativeUnits.set(GetRenumberedUnit(OldUnit));
2125 if (!isContiguous(Units: NewNativeUnits)) {
2126 PrintFatalError(Msg: "cannot enforce regunit intervals, final "
2127 "renumbering did not produce contiguous units "
2128 "for register " +
2129 Reg.getName() + "\n");
2130 }
2131 Reg.NativeRegUnits = NewNativeUnits;
2132 }
2133}
2134
2135// Find a set in UniqueSets with the same elements as Set.
2136// Return an iterator into UniqueSets.
2137static std::vector<RegUnitSet>::const_iterator
2138findRegUnitSet(const std::vector<RegUnitSet> &UniqueSets,
2139 const RegUnitSet &Set) {
2140 return llvm::find_if(
2141 Range: UniqueSets, P: [&Set](const RegUnitSet &I) { return I.Units == Set.Units; });
2142}
2143
2144// Return true if the RUSubSet is a subset of RUSuperSet.
2145static bool isRegUnitSubSet(const std::vector<unsigned> &RUSubSet,
2146 const std::vector<unsigned> &RUSuperSet) {
2147 return llvm::includes(Range1: RUSuperSet, Range2: RUSubSet);
2148}
2149
2150/// Iteratively prune unit sets. Prune subsets that are close to the superset,
2151/// but with one or two registers removed. We occasionally have registers like
2152/// APSR and PC thrown in with the general registers. We also see many
2153/// special-purpose register subsets, such as tail-call and Thumb
2154/// encodings. Generating all possible overlapping sets is combinatorial and
2155/// overkill for modeling pressure. Ideally we could fix this statically in
2156/// tablegen by (1) having the target define register classes that only include
2157/// the allocatable registers and marking other classes as non-allocatable and
2158/// (2) having a way to mark special purpose classes as "don't-care" classes for
2159/// the purpose of pressure. However, we make an attempt to handle targets that
2160/// are not nicely defined by merging nearly identical register unit sets
2161/// statically. This generates smaller tables. Then, dynamically, we adjust the
2162/// set limit by filtering the reserved registers.
2163///
2164/// Merge sets only if the units have the same weight. For example, on ARM,
2165/// Q-tuples with ssub index 0 include all S regs but also include D16+. We
2166/// should not expand the S set to include D regs.
2167void CodeGenRegBank::pruneUnitSets() {
2168 assert(RegClassUnitSets.empty() && "this invalidates RegClassUnitSets");
2169
2170 // Form an equivalence class of UnitSets with no significant difference.
2171 std::vector<unsigned> SuperSetIDs;
2172 unsigned EndIdx = RegUnitSets.size();
2173 for (auto [SubIdx, SubSet] : enumerate(First&: RegUnitSets)) {
2174 unsigned SuperIdx = 0;
2175 for (; SuperIdx != EndIdx; ++SuperIdx) {
2176 if (SuperIdx == SubIdx)
2177 continue;
2178
2179 unsigned UnitWeight = RegUnits[SubSet.Units[0]].Weight;
2180 const RegUnitSet &SuperSet = RegUnitSets[SuperIdx];
2181 if (isRegUnitSubSet(RUSubSet: SubSet.Units, RUSuperSet: SuperSet.Units) &&
2182 (SubSet.Units.size() + 3 > SuperSet.Units.size()) &&
2183 UnitWeight == RegUnits[SuperSet.Units[0]].Weight &&
2184 UnitWeight == RegUnits[SuperSet.Units.back()].Weight) {
2185 LLVM_DEBUG({
2186 dbgs() << "UnitSet " << SubIdx << " subsumed by " << SuperIdx << '\n';
2187 });
2188 // We can pick any of the set names for the merged set. Go for the
2189 // shortest one to avoid picking the name of one of the classes that are
2190 // artificially created by tablegen. So "FPR128_lo" instead of
2191 // "QQQQ_with_qsub3_in_FPR128_lo".
2192 if (RegUnitSets[SubIdx].Name.size() < RegUnitSets[SuperIdx].Name.size())
2193 RegUnitSets[SuperIdx].Name = RegUnitSets[SubIdx].Name;
2194 break;
2195 }
2196 }
2197 if (SuperIdx == EndIdx)
2198 SuperSetIDs.push_back(x: SubIdx);
2199 }
2200 // Populate PrunedUnitSets with each equivalence class's superset.
2201 std::vector<RegUnitSet> PrunedUnitSets;
2202 PrunedUnitSets.reserve(n: SuperSetIDs.size());
2203 for (unsigned SuperIdx : SuperSetIDs) {
2204 PrunedUnitSets.emplace_back(args&: RegUnitSets[SuperIdx].Name);
2205 PrunedUnitSets.back().Units = std::move(RegUnitSets[SuperIdx].Units);
2206 }
2207 RegUnitSets = std::move(PrunedUnitSets);
2208}
2209
2210// Create a RegUnitSet for each RegClass that contains all units in the class
2211// including adopted units that are necessary to model register pressure. Then
2212// iteratively compute RegUnitSets such that the union of any two overlapping
2213// RegUnitSets is represented.
2214//
2215// RegisterInfoEmitter will map each RegClass to its RegUnitClass and any
2216// RegUnitSet that is a superset of that RegUnitClass.
2217void CodeGenRegBank::computeRegUnitSets() {
2218 assert(RegUnitSets.empty() && "dirty RegUnitSets");
2219
2220#ifndef NDEBUG
2221 // Helper to print register unit sets.
2222 auto PrintRegUnitSets = [this]() {
2223 for (auto [USIdx, US] : enumerate(RegUnitSets)) {
2224 dbgs() << "UnitSet " << USIdx << " " << US.Name << ":";
2225 printRegUnitNames(US.Units);
2226 }
2227 };
2228#endif // NDEBUG
2229
2230 // Compute a unique RegUnitSet for each RegClass.
2231 auto &RegClasses = getRegClasses();
2232 for (CodeGenRegisterClass &RC : RegClasses) {
2233 if (!RC.Allocatable || RC.Artificial || !RC.GeneratePressureSet)
2234 continue;
2235
2236 // Compute a sorted list of units in this class.
2237 RegUnitSet RUSet(RC.getName());
2238 RC.buildRegUnitSet(RegBank: *this, RegUnits&: RUSet.Units);
2239
2240 // Find an existing RegUnitSet.
2241 if (findRegUnitSet(UniqueSets: RegUnitSets, Set: RUSet) == RegUnitSets.end())
2242 RegUnitSets.push_back(x: std::move(RUSet));
2243 }
2244
2245 if (RegUnitSets.empty())
2246 PrintFatalError(Msg: "RegUnitSets cannot be empty!");
2247
2248 LLVM_DEBUG({
2249 dbgs() << "\nBefore pruning:\n";
2250 PrintRegUnitSets();
2251 });
2252
2253 // Iteratively prune unit sets.
2254 pruneUnitSets();
2255
2256 LLVM_DEBUG({
2257 dbgs() << "\nBefore union:\n";
2258 PrintRegUnitSets();
2259 dbgs() << "\nUnion sets:\n";
2260 });
2261
2262 // Iterate over all unit sets, including new ones added by this loop.
2263 // FIXME: Since `EndIdx` is computed just once during loop initialization,
2264 // does this really iterate over new unit sets added by this loop?
2265 unsigned NumRegUnitSubSets = RegUnitSets.size();
2266 for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx) {
2267 // In theory, this is combinatorial. In practice, it needs to be bounded
2268 // by a small number of sets for regpressure to be efficient.
2269 // If the assert is hit, we need to implement pruning.
2270 assert(Idx < (2 * NumRegUnitSubSets) && "runaway unit set inference");
2271
2272 // Compare new sets with all original classes.
2273 for (unsigned SearchIdx = (Idx >= NumRegUnitSubSets) ? 0 : Idx + 1;
2274 SearchIdx != EndIdx; ++SearchIdx) {
2275 std::vector<unsigned> Intersection;
2276 std::set_intersection(
2277 first1: RegUnitSets[Idx].Units.begin(), last1: RegUnitSets[Idx].Units.end(),
2278 first2: RegUnitSets[SearchIdx].Units.begin(),
2279 last2: RegUnitSets[SearchIdx].Units.end(), result: std::back_inserter(x&: Intersection));
2280 if (Intersection.empty())
2281 continue;
2282
2283 RegUnitSet RUSet(RegUnitSets[Idx].Name + "_with_" +
2284 RegUnitSets[SearchIdx].Name);
2285 std::set_union(first1: RegUnitSets[Idx].Units.begin(),
2286 last1: RegUnitSets[Idx].Units.end(),
2287 first2: RegUnitSets[SearchIdx].Units.begin(),
2288 last2: RegUnitSets[SearchIdx].Units.end(),
2289 result: std::inserter(x&: RUSet.Units, i: RUSet.Units.begin()));
2290
2291 // Find an existing RegUnitSet, or add the union to the unique sets.
2292 if (findRegUnitSet(UniqueSets: RegUnitSets, Set: RUSet) == RegUnitSets.end()) {
2293 LLVM_DEBUG({
2294 dbgs() << "UnitSet " << RegUnitSets.size() << " " << RUSet.Name
2295 << ":";
2296 printRegUnitNames(RUSet.Units);
2297 });
2298 RegUnitSets.push_back(x: std::move(RUSet));
2299 }
2300 }
2301 }
2302
2303 // Iteratively prune unit sets after inferring supersets.
2304 pruneUnitSets();
2305
2306 LLVM_DEBUG({
2307 dbgs() << '\n';
2308 PrintRegUnitSets();
2309 });
2310
2311 // For each register class, list the UnitSets that are supersets.
2312 RegClassUnitSets.resize(new_size: RegClasses.size());
2313 for (CodeGenRegisterClass &RC : RegClasses) {
2314 if (!RC.Allocatable)
2315 continue;
2316
2317 // Recompute the sorted list of units in this class.
2318 std::vector<unsigned> RCRegUnits;
2319 RC.buildRegUnitSet(RegBank: *this, RegUnits&: RCRegUnits);
2320
2321 // Don't increase pressure for unallocatable regclasses.
2322 if (RCRegUnits.empty())
2323 continue;
2324
2325 LLVM_DEBUG({
2326 dbgs() << "RC " << RC.getName() << " Units:\n";
2327 printRegUnitNames(RCRegUnits);
2328 dbgs() << "UnitSetIDs:";
2329 });
2330
2331 // Find all supersets.
2332 for (const auto &[USIdx, Set] : enumerate(First&: RegUnitSets)) {
2333 if (isRegUnitSubSet(RUSubSet: RCRegUnits, RUSuperSet: Set.Units)) {
2334 LLVM_DEBUG(dbgs() << " " << USIdx);
2335 RegClassUnitSets[RC.EnumValue].push_back(x: USIdx);
2336 }
2337 }
2338 LLVM_DEBUG(dbgs() << '\n');
2339 assert(
2340 (!RegClassUnitSets[RC.EnumValue].empty() || !RC.GeneratePressureSet) &&
2341 "missing unit set for regclass");
2342 }
2343
2344 // For each register unit, ensure that we have the list of UnitSets that
2345 // contain the unit. Normally, this matches an existing list of UnitSets for a
2346 // register class. If not, we create a new entry in RegClassUnitSets as a
2347 // "fake" register class.
2348 for (unsigned UnitIdx = 0, UnitEnd = NumNativeRegUnits; UnitIdx < UnitEnd;
2349 ++UnitIdx) {
2350 std::vector<unsigned> RUSets;
2351 for (auto [Idx, S] : enumerate(First&: RegUnitSets))
2352 if (is_contained(Range&: S.Units, Element: UnitIdx))
2353 RUSets.push_back(x: Idx);
2354
2355 unsigned RCUnitSetsIdx = 0;
2356 for (unsigned e = RegClassUnitSets.size(); RCUnitSetsIdx != e;
2357 ++RCUnitSetsIdx) {
2358 if (RegClassUnitSets[RCUnitSetsIdx] == RUSets) {
2359 break;
2360 }
2361 }
2362 RegUnits[UnitIdx].RegClassUnitSetsIdx = RCUnitSetsIdx;
2363 if (RCUnitSetsIdx == RegClassUnitSets.size()) {
2364 // Create a new list of UnitSets as a "fake" register class.
2365 RegClassUnitSets.push_back(x: std::move(RUSets));
2366 }
2367 }
2368}
2369
2370void CodeGenRegBank::computeRegUnitLaneMasks() {
2371 for (CodeGenRegister &Register : Registers) {
2372 // Create an initial lane mask for all register units.
2373 const auto &RegUnits = Register.getRegUnits();
2374 CodeGenRegister::RegUnitLaneMaskList RegUnitLaneMasks(
2375 RegUnits.count(), LaneBitmask::getAll());
2376 // Iterate through SubRegisters.
2377 using SubRegMap = CodeGenRegister::SubRegMap;
2378 const SubRegMap &SubRegs = Register.getSubRegs();
2379 for (auto [SubRegIndex, SubReg] : SubRegs) {
2380 // Ignore non-leaf subregisters, their lane masks are fully covered by
2381 // the leaf subregisters anyway.
2382 if (!SubReg->getSubRegs().empty())
2383 continue;
2384 LaneBitmask LaneMask = SubRegIndex->LaneMask;
2385 // Distribute LaneMask to Register Units touched.
2386 for (unsigned SUI : SubReg->getRegUnits()) {
2387 bool Found = false;
2388 unsigned u = 0;
2389 for (unsigned RU : RegUnits) {
2390 if (SUI == RU) {
2391 RegUnitLaneMasks[u] &= LaneMask;
2392 assert(!Found);
2393 Found = true;
2394 }
2395 ++u;
2396 }
2397 (void)Found;
2398 assert(Found);
2399 }
2400 }
2401 Register.setRegUnitLaneMasks(RegUnitLaneMasks);
2402 }
2403}
2404
2405void CodeGenRegBank::computeDerivedInfo() {
2406 computeComposites();
2407 computeSubRegLaneMasks();
2408
2409 // Compute a weight for each register unit created during getSubRegs.
2410 // This may create adopted register units (with unit # >= NumNativeRegUnits).
2411 Records.getTimer().startTimer(Name: "Compute reg unit weights");
2412 computeRegUnitWeights();
2413 Records.getTimer().stopTimer();
2414
2415 // Enforce regunit intervals if requested by the target.
2416 Records.getTimer().startTimer(Name: "Enforce regunit intervals");
2417 enforceRegUnitIntervals();
2418 Records.getTimer().stopTimer();
2419
2420 // Compute a unique set of RegUnitSets. One for each RegClass and inferred
2421 // supersets for the union of overlapping sets.
2422 computeRegUnitSets();
2423
2424 computeRegUnitLaneMasks();
2425
2426 // Compute register class HasDisjunctSubRegs/CoveredBySubRegs flag.
2427 for (CodeGenRegisterClass &RC : RegClasses) {
2428 RC.HasDisjunctSubRegs = false;
2429 RC.CoveredBySubRegs = true;
2430 for (const CodeGenRegister *Reg : RC.getMembers()) {
2431 RC.HasDisjunctSubRegs |= Reg->HasDisjunctSubRegs;
2432 RC.CoveredBySubRegs &= Reg->CoveredBySubRegs;
2433 }
2434 }
2435
2436 // Get the weight of each set.
2437 for (auto [Idx, US] : enumerate(First&: RegUnitSets))
2438 RegUnitSets[Idx].Weight = getRegUnitSetWeight(Units: US.Units);
2439
2440 // Find the order of each set.
2441 RegUnitSetOrder.reserve(n: RegUnitSets.size());
2442 for (unsigned Idx : seq<unsigned>(Size: RegUnitSets.size()))
2443 RegUnitSetOrder.push_back(x: Idx);
2444
2445 llvm::stable_sort(Range&: RegUnitSetOrder, C: [this](unsigned ID1, unsigned ID2) {
2446 return getRegPressureSet(Idx: ID1).Units.size() <
2447 getRegPressureSet(Idx: ID2).Units.size();
2448 });
2449 for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx)
2450 RegUnitSets[RegUnitSetOrder[Idx]].Order = Idx;
2451}
2452
2453//
2454// Synthesize missing register class intersections.
2455//
2456// Make sure that sub-classes of RC exists such that getCommonSubClass(RC, X)
2457// returns a maximal register class for all X.
2458//
2459void CodeGenRegBank::inferCommonSubClass(CodeGenRegisterClass *RC) {
2460 assert(!RegClasses.empty());
2461 // Stash the iterator to the last element so that this loop doesn't visit
2462 // elements added by the getOrCreateSubClass call within it.
2463 for (auto I = RegClasses.begin(), E = std::prev(x: RegClasses.end());
2464 I != std::next(x: E); ++I) {
2465 CodeGenRegisterClass *RC1 = RC;
2466 CodeGenRegisterClass *RC2 = &*I;
2467 if (RC1 == RC2)
2468 continue;
2469
2470 // Compute the set intersection of RC1 and RC2.
2471 const CodeGenRegister::Vec &Memb1 = RC1->getMembers();
2472 const CodeGenRegister::Vec &Memb2 = RC2->getMembers();
2473 CodeGenRegister::Vec Intersection;
2474 std::set_intersection(first1: Memb1.begin(), last1: Memb1.end(), first2: Memb2.begin(),
2475 last2: Memb2.end(),
2476 result: std::inserter(x&: Intersection, i: Intersection.begin()),
2477 comp: deref<std::less<>>());
2478
2479 // Skip disjoint class pairs.
2480 if (Intersection.empty())
2481 continue;
2482
2483 // Skip casses where the intersection is composed of artificial
2484 // registers.
2485 if (llvm::all_of(Range&: Intersection, P: [](const CodeGenRegister *Reg) {
2486 return Reg->Artificial;
2487 }))
2488 continue;
2489
2490 // If RC1 and RC2 have different spill sizes or alignments, use the
2491 // stricter one for sub-classing. If they are equal, prefer RC1.
2492 if (RC2->RSI.hasStricterSpillThan(I: RC1->RSI))
2493 std::swap(a&: RC1, b&: RC2);
2494
2495 getOrCreateSubClass(RC: RC1, Members: &Intersection,
2496 Name: RC1->getName() + "_and_" + RC2->getName());
2497 }
2498}
2499
2500//
2501// Synthesize missing sub-classes for getSubClassWithSubReg().
2502//
2503// Make sure that the set of registers in RC with a given SubIdx sub-register
2504// form a register class. Update RC->SubClassWithSubReg.
2505//
2506void CodeGenRegBank::inferSubClassWithSubReg(CodeGenRegisterClass *RC) {
2507 // Map SubRegIndex to set of registers in RC supporting that SubRegIndex.
2508 using SubReg2SetMap = std::map<const CodeGenSubRegIndex *,
2509 CodeGenRegister::Vec, deref<std::less<>>>;
2510
2511 // Compute the set of registers supporting each SubRegIndex.
2512 SubReg2SetMap SRSets;
2513 for (const CodeGenRegister *R : RC->getMembers()) {
2514 if (R->Artificial)
2515 continue;
2516 const CodeGenRegister::SubRegMap &SRM = R->getSubRegs();
2517 for (auto [I, _] : SRM)
2518 SRSets[I].push_back(x: R);
2519 }
2520
2521 // Find matching classes for all SRSets entries. Iterate in SubRegIndex
2522 // numerical order to visit synthetic indices last.
2523 for (const CodeGenSubRegIndex &SubIdx : SubRegIndices) {
2524 SubReg2SetMap::const_iterator I = SRSets.find(x: &SubIdx);
2525 // Unsupported SubRegIndex. Skip it.
2526 if (I == SRSets.end())
2527 continue;
2528 // In most cases, all RC registers support the SubRegIndex.
2529 auto IsNotArtificial = [](const CodeGenRegister *R) {
2530 return !R->Artificial;
2531 };
2532 if (I->second.size() ==
2533 (size_t)count_if(Range: RC->getMembers(), P: IsNotArtificial)) {
2534 RC->setSubClassWithSubReg(SubIdx: &SubIdx, SubRC: RC);
2535 continue;
2536 }
2537 if (SubIdx.Artificial)
2538 continue;
2539 // This is a real subset. See if we have a matching class.
2540 CodeGenRegisterClass *SubRC =
2541 getOrCreateSubClass(RC, Members: &I->second,
2542 Name: RC->getName() + "_with_" + I->first->getName())
2543 .first;
2544 RC->setSubClassWithSubReg(SubIdx: &SubIdx, SubRC);
2545 }
2546}
2547
2548//
2549// Synthesize missing sub-classes of RC for getMatchingSuperRegClass().
2550//
2551// Create sub-classes of RC such that getMatchingSuperRegClass(RC, SubIdx, X)
2552// has a maximal result for any SubIdx and any X >= FirstSubRegRC.
2553//
2554
2555void CodeGenRegBank::inferMatchingSuperRegClass(
2556 CodeGenRegisterClass *RC,
2557 std::list<CodeGenRegisterClass>::iterator FirstSubRegRC) {
2558 DenseSet<const CodeGenSubRegIndex *> ImpliedSubRegIndices;
2559 std::vector<const CodeGenRegister *> SubRegs;
2560 BitVector TopoSigs(getNumTopoSigs());
2561
2562 // Iterate subregister indices in topological order to visit larger indices
2563 // first. This allows us to skip the smaller indices in many cases because
2564 // their inferred super-register classes are implied.
2565 for (CodeGenSubRegIndex *SubIdx : SubRegIndicesRPOT) {
2566 // Skip indexes that aren't fully supported by RC's registers. This was
2567 // computed by inferSubClassWithSubReg() above which should have been
2568 // called first.
2569 if (RC->getSubClassWithSubReg(SubIdx) != RC)
2570 continue;
2571
2572 if (ImpliedSubRegIndices.contains(V: SubIdx))
2573 continue;
2574
2575 // Build list of (Sub, Super) pairs for this SubIdx, sorted by Sub. Note
2576 // that the list may contain entries with the same Sub but different Supers.
2577 SubRegs.clear();
2578 TopoSigs.reset();
2579 for (const CodeGenRegister *Super : RC->getMembers()) {
2580 if (Super->Artificial)
2581 continue;
2582 const CodeGenRegister *Sub = Super->getSubRegs().find(x: SubIdx)->second;
2583 assert(Sub && "Missing sub-register");
2584 SubRegs.push_back(x: Sub);
2585 TopoSigs.set(Sub->getTopoSig());
2586 }
2587
2588 // Iterate over sub-register class candidates. Ignore classes created by
2589 // this loop. They will never be useful.
2590 // Store an iterator to the last element (not end) so that this loop doesn't
2591 // visit newly inserted elements.
2592 assert(!RegClasses.empty());
2593 for (auto I = FirstSubRegRC, E = std::prev(x: RegClasses.end());
2594 I != std::next(x: E); ++I) {
2595 CodeGenRegisterClass &SubRC = *I;
2596 if (SubRC.Artificial)
2597 continue;
2598 // Topological shortcut: SubRC members have the wrong shape.
2599 if (!TopoSigs.anyCommon(RHS: SubRC.getRegsWithSuperRegsTopoSigs()))
2600 continue;
2601 // Compute the subset of RC that maps into SubRC.
2602 CodeGenRegister::Vec SubSetVec;
2603 auto IsNotArtificial = [](const CodeGenRegister *R) {
2604 return !R->Artificial;
2605 };
2606 auto NonArtificialMembers =
2607 make_filter_range(Range: RC->getMembers(), Pred: IsNotArtificial);
2608 for (const auto &[Sub, Super] :
2609 zip_equal(t&: SubRegs, u&: NonArtificialMembers)) {
2610 if (SubRC.contains(Reg: Sub))
2611 SubSetVec.push_back(x: Super);
2612 }
2613
2614 if (SubSetVec.empty())
2615 continue;
2616
2617 // RC injects completely into SubRC.
2618 if (SubSetVec.size() ==
2619 (size_t)count_if(Range: RC->getMembers(), P: IsNotArtificial)) {
2620 SubRC.addSuperRegClass(SubIdx, SuperRC: RC);
2621
2622 // We can skip checking subregister indices that can be composed from
2623 // the current SubIdx.
2624 //
2625 // Proof sketch: Let SubRC' be another register class and SubSubIdx
2626 // a subregister index that can be composed from SubIdx.
2627 //
2628 // Calling this function with SubRC in place of RC ensures the existence
2629 // of a subclass X of SubRC with the registers that have subregisters in
2630 // SubRC'.
2631 //
2632 // The set of registers in RC with SubSubIdx in SubRC' is equal to the
2633 // set of registers in RC with SubIdx in X (because every register in
2634 // RC has a corresponding subregister in SubRC), and so checking the
2635 // pair (SubSubIdx, SubRC') is redundant with checking (SubIdx, X).
2636 for (const auto &SubSubIdx : SubIdx->getComposites())
2637 ImpliedSubRegIndices.insert(V: SubSubIdx.second);
2638
2639 continue;
2640 }
2641
2642 // Only a subset of RC maps into SubRC. Make sure it is represented by a
2643 // class.
2644 //
2645 // The name of the inferred register class follows the template
2646 // "<RC>_with_<SubIdx>_in_<SubRC>".
2647 //
2648 // When SubRC is already an inferred class, prefer a name of the form
2649 // "<RC>_with_<CompositeSubIdx>_in_<SubSubRC>" over a chain of the form
2650 // "<RC>_with_<SubIdx>_in_<OtherRc>_with_<SubSubIdx>_in_<SubSubRC>".
2651 // If that preferred name is already used, fall back to the uncomposed
2652 // form so that different inferred classes do not alias through the same
2653 // composed name.
2654 CodeGenSubRegIndex *CompositeSubIdx = SubIdx;
2655 CodeGenRegisterClass *CompositeSubRC = &SubRC;
2656 if (CodeGenSubRegIndex *SubSubIdx = SubRC.getInferredFromSubRegIdx()) {
2657 auto It = SubIdx->getComposites().find(x: SubSubIdx);
2658 if (It != SubIdx->getComposites().end()) {
2659 CompositeSubIdx = It->second;
2660 CompositeSubRC = SubRC.getInferredFromRC();
2661 }
2662 }
2663
2664 std::string Name = RC->getName() + "_with_" + CompositeSubIdx->getName() +
2665 "_in_" + CompositeSubRC->getName();
2666
2667 const bool HasRegClassNamed =
2668 llvm::any_of(Range&: RegClasses, P: [&](const CodeGenRegisterClass &RC) {
2669 return RC.getName() == Name;
2670 });
2671
2672 if (HasRegClassNamed)
2673 Name = RC->getName() + "_with_" + SubIdx->getName() + "_in_" +
2674 SubRC.getName();
2675
2676 auto [SubSetRC, Inserted] = getOrCreateSubClass(RC, Members: &SubSetVec, Name);
2677
2678 if (Inserted)
2679 SubSetRC->setInferredFrom(Idx: CompositeSubIdx, RC: CompositeSubRC);
2680 }
2681 }
2682}
2683
2684//
2685// Infer missing register classes.
2686//
2687void CodeGenRegBank::computeInferredRegisterClasses() {
2688 assert(!RegClasses.empty());
2689 // When this function is called, the register classes have not been sorted
2690 // and assigned EnumValues yet. That means getSubClasses(),
2691 // getSuperClasses(), and hasSubClass() functions are defunct.
2692
2693 Records.getTimer().startTimer(Name: "Compute inferred register classes");
2694
2695 // Use one-before-the-end so it doesn't move forward when new elements are
2696 // added.
2697 auto FirstNewRC = std::prev(x: RegClasses.end());
2698
2699 // Visit all register classes, including the ones being added by the loop.
2700 // Watch out for iterator invalidation here.
2701 for (auto I = RegClasses.begin(), E = RegClasses.end(); I != E; ++I) {
2702 CodeGenRegisterClass *RC = &*I;
2703 if (RC->Artificial)
2704 continue;
2705
2706 // Synthesize answers for getSubClassWithSubReg().
2707 inferSubClassWithSubReg(RC);
2708
2709 // Synthesize answers for getCommonSubClass().
2710 inferCommonSubClass(RC);
2711
2712 // Synthesize answers for getMatchingSuperRegClass().
2713 inferMatchingSuperRegClass(RC);
2714
2715 // New register classes are created while this loop is running, and we need
2716 // to visit all of them. In particular, inferMatchingSuperRegClass needs
2717 // to match old super-register classes with sub-register classes created
2718 // after inferMatchingSuperRegClass was called. At this point,
2719 // inferMatchingSuperRegClass has checked SuperRC = [0..rci] with SubRC =
2720 // [0..FirstNewRC). We need to cover SubRC = [FirstNewRC..rci].
2721 if (I == FirstNewRC) {
2722 auto NextNewRC = std::prev(x: RegClasses.end());
2723 for (auto I2 = RegClasses.begin(), E2 = std::next(x: FirstNewRC); I2 != E2;
2724 ++I2)
2725 inferMatchingSuperRegClass(RC: &*I2, FirstSubRegRC: E2);
2726 FirstNewRC = NextNewRC;
2727 }
2728 }
2729
2730 Records.getTimer().startTimer(Name: "Extend super-register classes");
2731
2732 // Compute the transitive closure for super-register classes.
2733 //
2734 // By iterating over sub-register indices in topological order, we only ever
2735 // add super-register classes for sub-register indices that have not already
2736 // been visited. That allows computing the transitive closure in a single
2737 // pass.
2738 for (CodeGenSubRegIndex *SubIdx : SubRegIndicesRPOT) {
2739 for (CodeGenRegisterClass &SubRC : RegClasses)
2740 SubRC.extendSuperRegClasses(SubIdx);
2741 }
2742
2743 Records.getTimer().stopTimer();
2744}
2745
2746/// getRegisterClassForRegister - Find the register class that contains the
2747/// specified physical register. If the register is not in a register class,
2748/// return null. If the register is in multiple classes, and the classes have a
2749/// superset-subset relationship and the same set of types, return the
2750/// superclass. Otherwise return null.
2751const CodeGenRegisterClass *
2752CodeGenRegBank::getRegClassForRegister(const Record *R) {
2753 const CodeGenRegister *Reg = getReg(Def: R);
2754 const CodeGenRegisterClass *FoundRC = nullptr;
2755 for (const CodeGenRegisterClass &RC : getRegClasses()) {
2756 if (!RC.contains(Reg))
2757 continue;
2758
2759 // If this is the first class that contains the register,
2760 // make a note of it and go on to the next class.
2761 if (!FoundRC) {
2762 FoundRC = &RC;
2763 continue;
2764 }
2765
2766 // If a register's classes have different types, return null.
2767 if (RC.getValueTypes() != FoundRC->getValueTypes())
2768 return nullptr;
2769
2770 // Check to see if the previously found class that contains
2771 // the register is a subclass of the current class. If so,
2772 // prefer the superclass.
2773 if (RC.hasSubClass(RC: FoundRC)) {
2774 FoundRC = &RC;
2775 continue;
2776 }
2777
2778 // Check to see if the previously found class that contains
2779 // the register is a superclass of the current class. If so,
2780 // prefer the superclass.
2781 if (FoundRC->hasSubClass(RC: &RC))
2782 continue;
2783
2784 // Multiple classes, and neither is a superclass of the other.
2785 // Return null.
2786 return nullptr;
2787 }
2788 return FoundRC;
2789}
2790
2791bool CodeGenRegBank::regClassContainsReg(const Record *RegClassDef,
2792 const Record *RegDef,
2793 ArrayRef<SMLoc> Loc) {
2794 // Check all four combinations of Register[ByHwMode] X RegClass[ByHwMode],
2795 // starting with the two RegClassByHwMode cases.
2796 unsigned NumModes = CGH.getNumModeIds();
2797 std::optional<RegisterByHwMode> RegByMode;
2798 CodeGenRegister *Reg = nullptr;
2799 if (RegDef->isSubClassOf(Name: "RegisterByHwMode"))
2800 RegByMode = RegisterByHwMode(RegDef, *this);
2801 else
2802 Reg = getReg(Def: RegDef);
2803 if (RegClassDef->isSubClassOf(Name: "RegClassByHwMode")) {
2804 RegClassByHwMode RC(RegClassDef, *this);
2805 for (unsigned M = 0; M < NumModes; ++M) {
2806 if (RC.hasMode(M) && !RC.get(Mode: M)->contains(Reg: Reg ? Reg : RegByMode->get(Mode: M)))
2807 return false;
2808 }
2809 return true;
2810 }
2811 // Otherwise we have a plain register class, check Register[ByHwMode]
2812 CodeGenRegisterClass *RC = getRegClass(Def: RegClassDef, Loc);
2813 if (Reg)
2814 return RC->contains(Reg);
2815 for (unsigned M = 0; M < NumModes; ++M) {
2816 if (RegByMode->hasMode(M) && !RC->contains(Reg: RegByMode->get(Mode: M)))
2817 return false;
2818 }
2819 return true; // RegByMode contained for all possible modes.
2820}
2821
2822const CodeGenRegisterClass *
2823CodeGenRegBank::getMinimalPhysRegClass(const Record *RegRecord,
2824 ValueTypeByHwMode *VT) {
2825 const CodeGenRegister *Reg = getReg(Def: RegRecord);
2826 const CodeGenRegisterClass *BestRC = nullptr;
2827 for (const CodeGenRegisterClass &RC : getRegClasses()) {
2828 if ((!VT || RC.hasType(VT: *VT)) && RC.contains(Reg) &&
2829 (!BestRC || BestRC->hasSubClass(RC: &RC)))
2830 BestRC = &RC;
2831 }
2832
2833 assert(BestRC && "Couldn't find the register class");
2834 return BestRC;
2835}
2836
2837const CodeGenRegisterClass *
2838CodeGenRegBank::getSuperRegForSubReg(const ValueTypeByHwMode &ValueTy,
2839 const CodeGenSubRegIndex *SubIdx,
2840 bool MustBeAllocatable) const {
2841 std::vector<const CodeGenRegisterClass *> Candidates;
2842 auto &RegClasses = getRegClasses();
2843
2844 // Try to find a register class which supports ValueTy, and also contains
2845 // SubIdx.
2846 for (const CodeGenRegisterClass &RC : RegClasses) {
2847 // Is there a subclass of this class which contains this subregister index?
2848 const CodeGenRegisterClass *SubClassWithSubReg =
2849 RC.getSubClassWithSubReg(SubIdx);
2850 if (!SubClassWithSubReg)
2851 continue;
2852
2853 // We have a class. Check if it supports this value type.
2854 if (!llvm::is_contained(Range: SubClassWithSubReg->VTs, Element: ValueTy))
2855 continue;
2856
2857 // If necessary, check that it is allocatable.
2858 if (MustBeAllocatable && !SubClassWithSubReg->Allocatable)
2859 continue;
2860
2861 // We have a register class which supports both the value type and
2862 // subregister index. Remember it.
2863 Candidates.push_back(x: SubClassWithSubReg);
2864 }
2865
2866 // If we didn't find anything, we're done.
2867 if (Candidates.empty())
2868 return nullptr;
2869
2870 // Find and return the largest of our candidate classes.
2871 llvm::stable_sort(Range&: Candidates, C: [&](const CodeGenRegisterClass *A,
2872 const CodeGenRegisterClass *B) {
2873 if (A->getMembers().size() > B->getMembers().size())
2874 return true;
2875
2876 if (A->getMembers().size() < B->getMembers().size())
2877 return false;
2878
2879 // Order by name as a tie-breaker.
2880 return StringRef(A->getName()) < B->getName();
2881 });
2882
2883 return Candidates[0];
2884}
2885
2886BitVector
2887CodeGenRegBank::computeCoveredRegisters(ArrayRef<const Record *> Regs) {
2888 SetVector<const CodeGenRegister *> Set;
2889
2890 // First add Regs with all sub-registers.
2891 for (const Record *RegDef : Regs) {
2892 CodeGenRegister *Reg = getReg(Def: RegDef);
2893 if (Set.insert(X: Reg))
2894 // Reg is new, add all sub-registers.
2895 // The pre-ordering is not important here.
2896 Reg->addSubRegsPreOrder(OSet&: Set, RegBank&: *this);
2897 }
2898
2899 // Second, find all super-registers that are completely covered by the set.
2900 for (unsigned i = 0; i != Set.size(); ++i) {
2901 for (const CodeGenRegister *Super : Set[i]->getSuperRegs()) {
2902 if (!Super->CoveredBySubRegs || Set.contains(key: Super))
2903 continue;
2904 // This new super-register is covered by its sub-registers.
2905 bool AllSubsInSet = true;
2906 const CodeGenRegister::SubRegMap &SRM = Super->getSubRegs();
2907 for (auto [_, SR] : SRM)
2908 if (!Set.contains(key: SR)) {
2909 AllSubsInSet = false;
2910 break;
2911 }
2912 // All sub-registers in Set, add Super as well.
2913 // We will visit Super later to recheck its super-registers.
2914 if (AllSubsInSet)
2915 Set.insert(X: Super);
2916 }
2917 }
2918
2919 // Convert to BitVector.
2920 BitVector BV(Registers.size() + 1);
2921 for (const CodeGenRegister *Reg : Set)
2922 BV.set(Reg->EnumValue);
2923 return BV;
2924}
2925
2926void CodeGenRegBank::printRegUnitNames(ArrayRef<unsigned> Units) const {
2927 for (unsigned Unit : Units) {
2928 if (Unit < NumNativeRegUnits)
2929 dbgs() << ' ' << RegUnits[Unit].Roots[0]->getName();
2930 else
2931 dbgs() << " #" << Unit;
2932 }
2933 dbgs() << '\n';
2934}
2935