1 //===- CodeGenRegisters.h - Register and RegisterClass Info -----*- C++ -*-===//
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 #ifndef LLVM_UTILS_TABLEGEN_CODEGENREGISTERS_H
15 #define LLVM_UTILS_TABLEGEN_CODEGENREGISTERS_H
16 
17 #include "InfoByHwMode.h"
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/BitVector.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/SetVector.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/SparseBitVector.h"
26 #include "llvm/ADT/StringMap.h"
27 #include "llvm/ADT/StringRef.h"
28 #include "llvm/MC/LaneBitmask.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/TableGen/Record.h"
31 #include "llvm/TableGen/SetTheory.h"
32 #include <cassert>
33 #include <cstdint>
34 #include <deque>
35 #include <list>
36 #include <map>
37 #include <string>
38 #include <utility>
39 #include <vector>
40 
41 namespace llvm {
42 
43   class CodeGenRegBank;
44   template <typename T, typename Vector, typename Set> class SetVector;
45 
46   /// Used to encode a step in a register lane mask transformation.
47   /// Mask the bits specified in Mask, then rotate them Rol bits to the left
48   /// assuming a wraparound at 32bits.
49   struct MaskRolPair {
50     LaneBitmask Mask;
51     uint8_t RotateLeft;
52 
53     bool operator==(const MaskRolPair Other) const {
54       return Mask == Other.Mask && RotateLeft == Other.RotateLeft;
55     }
56     bool operator!=(const MaskRolPair Other) const {
57       return Mask != Other.Mask || RotateLeft != Other.RotateLeft;
58     }
59   };
60 
61   /// CodeGenSubRegIndex - Represents a sub-register index.
62   class CodeGenSubRegIndex {
63     Record *const TheDef;
64     std::string Name;
65     std::string Namespace;
66 
67   public:
68     uint16_t Size;
69     uint16_t Offset;
70     const unsigned EnumValue;
71     mutable LaneBitmask LaneMask;
72     mutable SmallVector<MaskRolPair,1> CompositionLaneMaskTransform;
73 
74     /// A list of subregister indexes concatenated resulting in this
75     /// subregister index. This is the reverse of CodeGenRegBank::ConcatIdx.
76     SmallVector<CodeGenSubRegIndex*,4> ConcatenationOf;
77 
78     // Are all super-registers containing this SubRegIndex covered by their
79     // sub-registers?
80     bool AllSuperRegsCovered;
81     // A subregister index is "artificial" if every subregister obtained
82     // from applying this index is artificial. Artificial subregister
83     // indexes are not used to create new register classes.
84     bool Artificial;
85 
86     CodeGenSubRegIndex(Record *R, unsigned Enum);
87     CodeGenSubRegIndex(StringRef N, StringRef Nspace, unsigned Enum);
88     CodeGenSubRegIndex(CodeGenSubRegIndex&) = delete;
89 
90     const std::string &getName() const { return Name; }
91     const std::string &getNamespace() const { return Namespace; }
92     std::string getQualifiedName() const;
93 
94     // Map of composite subreg indices.
95     typedef std::map<CodeGenSubRegIndex *, CodeGenSubRegIndex *,
96                      deref<std::less<>>>
97         CompMap;
98 
99     // Returns the subreg index that results from composing this with Idx.
100     // Returns NULL if this and Idx don't compose.
101     CodeGenSubRegIndex *compose(CodeGenSubRegIndex *Idx) const {
102       CompMap::const_iterator I = Composed.find(Idx);
103       return I == Composed.end() ? nullptr : I->second;
104     }
105 
106     // Add a composite subreg index: this+A = B.
107     // Return a conflicting composite, or NULL
108     CodeGenSubRegIndex *addComposite(CodeGenSubRegIndex *A,
109                                      CodeGenSubRegIndex *B) {
110       assert(A && B);
111       std::pair<CompMap::iterator, bool> Ins =
112         Composed.insert(std::make_pair(A, B));
113       // Synthetic subreg indices that aren't contiguous (for instance ARM
114       // register tuples) don't have a bit range, so it's OK to let
115       // B->Offset == -1. For the other cases, accumulate the offset and set
116       // the size here. Only do so if there is no offset yet though.
117       if ((Offset != (uint16_t)-1 && A->Offset != (uint16_t)-1) &&
118           (B->Offset == (uint16_t)-1)) {
119         B->Offset = Offset + A->Offset;
120         B->Size = A->Size;
121       }
122       return (Ins.second || Ins.first->second == B) ? nullptr
123                                                     : Ins.first->second;
124     }
125 
126     // Update the composite maps of components specified in 'ComposedOf'.
127     void updateComponents(CodeGenRegBank&);
128 
129     // Return the map of composites.
130     const CompMap &getComposites() const { return Composed; }
131 
132     // Compute LaneMask from Composed. Return LaneMask.
133     LaneBitmask computeLaneMask() const;
134 
135     void setConcatenationOf(ArrayRef<CodeGenSubRegIndex*> Parts);
136 
137     /// Replaces subregister indexes in the `ConcatenationOf` list with
138     /// list of subregisters they are composed of (if any). Do this recursively.
139     void computeConcatTransitiveClosure();
140 
141     bool operator<(const CodeGenSubRegIndex &RHS) const {
142       return this->EnumValue < RHS.EnumValue;
143     }
144 
145   private:
146     CompMap Composed;
147   };
148 
149   /// CodeGenRegister - Represents a register definition.
150   struct CodeGenRegister {
151     Record *TheDef;
152     unsigned EnumValue;
153     std::vector<int64_t> CostPerUse;
154     bool CoveredBySubRegs;
155     bool HasDisjunctSubRegs;
156     bool Artificial;
157 
158     // Map SubRegIndex -> Register.
159     typedef std::map<CodeGenSubRegIndex *, CodeGenRegister *,
160                      deref<std::less<>>>
161         SubRegMap;
162 
163     CodeGenRegister(Record *R, unsigned Enum);
164 
165     StringRef getName() const;
166 
167     // Extract more information from TheDef. This is used to build an object
168     // graph after all CodeGenRegister objects have been created.
169     void buildObjectGraph(CodeGenRegBank&);
170 
171     // Lazily compute a map of all sub-registers.
172     // This includes unique entries for all sub-sub-registers.
173     const SubRegMap &computeSubRegs(CodeGenRegBank&);
174 
175     // Compute extra sub-registers by combining the existing sub-registers.
176     void computeSecondarySubRegs(CodeGenRegBank&);
177 
178     // Add this as a super-register to all sub-registers after the sub-register
179     // graph has been built.
180     void computeSuperRegs(CodeGenRegBank&);
181 
182     const SubRegMap &getSubRegs() const {
183       assert(SubRegsComplete && "Must precompute sub-registers");
184       return SubRegs;
185     }
186 
187     // Add sub-registers to OSet following a pre-order defined by the .td file.
188     void addSubRegsPreOrder(SetVector<const CodeGenRegister*> &OSet,
189                             CodeGenRegBank&) const;
190 
191     // Return the sub-register index naming Reg as a sub-register of this
192     // register. Returns NULL if Reg is not a sub-register.
193     CodeGenSubRegIndex *getSubRegIndex(const CodeGenRegister *Reg) const {
194       return SubReg2Idx.lookup(Reg);
195     }
196 
197     typedef std::vector<const CodeGenRegister*> SuperRegList;
198 
199     // Get the list of super-registers in topological order, small to large.
200     // This is valid after computeSubRegs visits all registers during RegBank
201     // construction.
202     const SuperRegList &getSuperRegs() const {
203       assert(SubRegsComplete && "Must precompute sub-registers");
204       return SuperRegs;
205     }
206 
207     // Get the list of ad hoc aliases. The graph is symmetric, so the list
208     // contains all registers in 'Aliases', and all registers that mention this
209     // register in 'Aliases'.
210     ArrayRef<CodeGenRegister*> getExplicitAliases() const {
211       return ExplicitAliases;
212     }
213 
214     // Get the topological signature of this register. This is a small integer
215     // less than RegBank.getNumTopoSigs(). Registers with the same TopoSig have
216     // identical sub-register structure. That is, they support the same set of
217     // sub-register indices mapping to the same kind of sub-registers
218     // (TopoSig-wise).
219     unsigned getTopoSig() const {
220       assert(SuperRegsComplete && "TopoSigs haven't been computed yet.");
221       return TopoSig;
222     }
223 
224     // List of register units in ascending order.
225     typedef SparseBitVector<> RegUnitList;
226     typedef SmallVector<LaneBitmask, 16> RegUnitLaneMaskList;
227 
228     // How many entries in RegUnitList are native?
229     RegUnitList NativeRegUnits;
230 
231     // Get the list of register units.
232     // This is only valid after computeSubRegs() completes.
233     const RegUnitList &getRegUnits() const { return RegUnits; }
234 
235     ArrayRef<LaneBitmask> getRegUnitLaneMasks() const {
236       return makeArrayRef(RegUnitLaneMasks).slice(0, NativeRegUnits.count());
237     }
238 
239     // Get the native register units. This is a prefix of getRegUnits().
240     RegUnitList getNativeRegUnits() const {
241       return NativeRegUnits;
242     }
243 
244     void setRegUnitLaneMasks(const RegUnitLaneMaskList &LaneMasks) {
245       RegUnitLaneMasks = LaneMasks;
246     }
247 
248     // Inherit register units from subregisters.
249     // Return true if the RegUnits changed.
250     bool inheritRegUnits(CodeGenRegBank &RegBank);
251 
252     // Adopt a register unit for pressure tracking.
253     // A unit is adopted iff its unit number is >= NativeRegUnits.count().
254     void adoptRegUnit(unsigned RUID) { RegUnits.set(RUID); }
255 
256     // Get the sum of this register's register unit weights.
257     unsigned getWeight(const CodeGenRegBank &RegBank) const;
258 
259     // Canonically ordered set.
260     typedef std::vector<const CodeGenRegister*> Vec;
261 
262   private:
263     bool SubRegsComplete;
264     bool SuperRegsComplete;
265     unsigned TopoSig;
266 
267     // The sub-registers explicit in the .td file form a tree.
268     SmallVector<CodeGenSubRegIndex*, 8> ExplicitSubRegIndices;
269     SmallVector<CodeGenRegister*, 8> ExplicitSubRegs;
270 
271     // Explicit ad hoc aliases, symmetrized to form an undirected graph.
272     SmallVector<CodeGenRegister*, 8> ExplicitAliases;
273 
274     // Super-registers where this is the first explicit sub-register.
275     SuperRegList LeadingSuperRegs;
276 
277     SubRegMap SubRegs;
278     SuperRegList SuperRegs;
279     DenseMap<const CodeGenRegister*, CodeGenSubRegIndex*> SubReg2Idx;
280     RegUnitList RegUnits;
281     RegUnitLaneMaskList RegUnitLaneMasks;
282   };
283 
284   inline bool operator<(const CodeGenRegister &A, const CodeGenRegister &B) {
285     return A.EnumValue < B.EnumValue;
286   }
287 
288   inline bool operator==(const CodeGenRegister &A, const CodeGenRegister &B) {
289     return A.EnumValue == B.EnumValue;
290   }
291 
292   class CodeGenRegisterClass {
293     CodeGenRegister::Vec Members;
294     // Allocation orders. Order[0] always contains all registers in Members.
295     std::vector<SmallVector<Record*, 16>> Orders;
296     // Bit mask of sub-classes including this, indexed by their EnumValue.
297     BitVector SubClasses;
298     // List of super-classes, topologocally ordered to have the larger classes
299     // first.  This is the same as sorting by EnumValue.
300     SmallVector<CodeGenRegisterClass*, 4> SuperClasses;
301     Record *TheDef;
302     std::string Name;
303 
304     // For a synthesized class, inherit missing properties from the nearest
305     // super-class.
306     void inheritProperties(CodeGenRegBank&);
307 
308     // Map SubRegIndex -> sub-class.  This is the largest sub-class where all
309     // registers have a SubRegIndex sub-register.
310     DenseMap<const CodeGenSubRegIndex *, CodeGenRegisterClass *>
311         SubClassWithSubReg;
312 
313     // Map SubRegIndex -> set of super-reg classes.  This is all register
314     // classes SuperRC such that:
315     //
316     //   R:SubRegIndex in this RC for all R in SuperRC.
317     //
318     DenseMap<const CodeGenSubRegIndex *, SmallPtrSet<CodeGenRegisterClass *, 8>>
319         SuperRegClasses;
320 
321     // Bit vector of TopoSigs for the registers in this class. This will be
322     // very sparse on regular architectures.
323     BitVector TopoSigs;
324 
325   public:
326     unsigned EnumValue;
327     StringRef Namespace;
328     SmallVector<ValueTypeByHwMode, 4> VTs;
329     RegSizeInfoByHwMode RSI;
330     int CopyCost;
331     bool Allocatable;
332     StringRef AltOrderSelect;
333     uint8_t AllocationPriority;
334     uint8_t TSFlags;
335     /// Contains the combination of the lane masks of all subregisters.
336     LaneBitmask LaneMask;
337     /// True if there are at least 2 subregisters which do not interfere.
338     bool HasDisjunctSubRegs;
339     bool CoveredBySubRegs;
340     /// A register class is artificial if all its members are artificial.
341     bool Artificial;
342     /// Generate register pressure set for this register class and any class
343     /// synthesized from it.
344     bool GeneratePressureSet;
345 
346     // Return the Record that defined this class, or NULL if the class was
347     // created by TableGen.
348     Record *getDef() const { return TheDef; }
349 
350     const std::string &getName() const { return Name; }
351     std::string getQualifiedName() const;
352     ArrayRef<ValueTypeByHwMode> getValueTypes() const { return VTs; }
353     unsigned getNumValueTypes() const { return VTs.size(); }
354 
355     bool hasType(const ValueTypeByHwMode &VT) const {
356       return llvm::is_contained(VTs, VT);
357     }
358 
359     const ValueTypeByHwMode &getValueTypeNum(unsigned VTNum) const {
360       if (VTNum < VTs.size())
361         return VTs[VTNum];
362       llvm_unreachable("VTNum greater than number of ValueTypes in RegClass!");
363     }
364 
365     // Return true if this this class contains the register.
366     bool contains(const CodeGenRegister*) const;
367 
368     // Returns true if RC is a subclass.
369     // RC is a sub-class of this class if it is a valid replacement for any
370     // instruction operand where a register of this classis required. It must
371     // satisfy these conditions:
372     //
373     // 1. All RC registers are also in this.
374     // 2. The RC spill size must not be smaller than our spill size.
375     // 3. RC spill alignment must be compatible with ours.
376     //
377     bool hasSubClass(const CodeGenRegisterClass *RC) const {
378       return SubClasses.test(RC->EnumValue);
379     }
380 
381     // getSubClassWithSubReg - Returns the largest sub-class where all
382     // registers have a SubIdx sub-register.
383     CodeGenRegisterClass *
384     getSubClassWithSubReg(const CodeGenSubRegIndex *SubIdx) const {
385       return SubClassWithSubReg.lookup(SubIdx);
386     }
387 
388     /// Find largest subclass where all registers have SubIdx subregisters in
389     /// SubRegClass and the largest subregister class that contains those
390     /// subregisters without (as far as possible) also containing additional registers.
391     ///
392     /// This can be used to find a suitable pair of classes for subregister copies.
393     /// \return std::pair<SubClass, SubRegClass> where SubClass is a SubClass is
394     /// a class where every register has SubIdx and SubRegClass is a class where
395     /// every register is covered by the SubIdx subregister of SubClass.
396     Optional<std::pair<CodeGenRegisterClass *, CodeGenRegisterClass *>>
397     getMatchingSubClassWithSubRegs(CodeGenRegBank &RegBank,
398                                    const CodeGenSubRegIndex *SubIdx) const;
399 
400     void setSubClassWithSubReg(const CodeGenSubRegIndex *SubIdx,
401                                CodeGenRegisterClass *SubRC) {
402       SubClassWithSubReg[SubIdx] = SubRC;
403     }
404 
405     // getSuperRegClasses - Returns a bit vector of all register classes
406     // containing only SubIdx super-registers of this class.
407     void getSuperRegClasses(const CodeGenSubRegIndex *SubIdx,
408                             BitVector &Out) const;
409 
410     // addSuperRegClass - Add a class containing only SubIdx super-registers.
411     void addSuperRegClass(CodeGenSubRegIndex *SubIdx,
412                           CodeGenRegisterClass *SuperRC) {
413       SuperRegClasses[SubIdx].insert(SuperRC);
414     }
415 
416     // getSubClasses - Returns a constant BitVector of subclasses indexed by
417     // EnumValue.
418     // The SubClasses vector includes an entry for this class.
419     const BitVector &getSubClasses() const { return SubClasses; }
420 
421     // getSuperClasses - Returns a list of super classes ordered by EnumValue.
422     // The array does not include an entry for this class.
423     ArrayRef<CodeGenRegisterClass*> getSuperClasses() const {
424       return SuperClasses;
425     }
426 
427     // Returns an ordered list of class members.
428     // The order of registers is the same as in the .td file.
429     // No = 0 is the default allocation order, No = 1 is the first alternative.
430     ArrayRef<Record*> getOrder(unsigned No = 0) const {
431         return Orders[No];
432     }
433 
434     // Return the total number of allocation orders available.
435     unsigned getNumOrders() const { return Orders.size(); }
436 
437     // Get the set of registers.  This set contains the same registers as
438     // getOrder(0).
439     const CodeGenRegister::Vec &getMembers() const { return Members; }
440 
441     // Get a bit vector of TopoSigs present in this register class.
442     const BitVector &getTopoSigs() const { return TopoSigs; }
443 
444     // Get a weight of this register class.
445     unsigned getWeight(const CodeGenRegBank&) const;
446 
447     // Populate a unique sorted list of units from a register set.
448     void buildRegUnitSet(const CodeGenRegBank &RegBank,
449                          std::vector<unsigned> &RegUnits) const;
450 
451     CodeGenRegisterClass(CodeGenRegBank&, Record *R);
452     CodeGenRegisterClass(CodeGenRegisterClass&) = delete;
453 
454     // A key representing the parts of a register class used for forming
455     // sub-classes.  Note the ordering provided by this key is not the same as
456     // the topological order used for the EnumValues.
457     struct Key {
458       const CodeGenRegister::Vec *Members;
459       RegSizeInfoByHwMode RSI;
460 
461       Key(const CodeGenRegister::Vec *M, const RegSizeInfoByHwMode &I)
462         : Members(M), RSI(I) {}
463 
464       Key(const CodeGenRegisterClass &RC)
465         : Members(&RC.getMembers()), RSI(RC.RSI) {}
466 
467       // Lexicographical order of (Members, RegSizeInfoByHwMode).
468       bool operator<(const Key&) const;
469     };
470 
471     // Create a non-user defined register class.
472     CodeGenRegisterClass(CodeGenRegBank&, StringRef Name, Key Props);
473 
474     // Called by CodeGenRegBank::CodeGenRegBank().
475     static void computeSubClasses(CodeGenRegBank&);
476   };
477 
478   // Register categories are used when we need to deterine the category a
479   // register falls into (GPR, vector, fixed, etc.) without having to know
480   // specific information about the target architecture.
481   class CodeGenRegisterCategory {
482     Record *TheDef;
483     std::string Name;
484     std::list<CodeGenRegisterClass *> Classes;
485 
486   public:
487     CodeGenRegisterCategory(CodeGenRegBank &, Record *R);
488     CodeGenRegisterCategory(CodeGenRegisterCategory &) = delete;
489 
490     // Return the Record that defined this class, or NULL if the class was
491     // created by TableGen.
492     Record *getDef() const { return TheDef; }
493 
494     std::string getName() const { return Name; }
495     std::list<CodeGenRegisterClass *> getClasses() const { return Classes; }
496   };
497 
498   // Register units are used to model interference and register pressure.
499   // Every register is assigned one or more register units such that two
500   // registers overlap if and only if they have a register unit in common.
501   //
502   // Normally, one register unit is created per leaf register. Non-leaf
503   // registers inherit the units of their sub-registers.
504   struct RegUnit {
505     // Weight assigned to this RegUnit for estimating register pressure.
506     // This is useful when equalizing weights in register classes with mixed
507     // register topologies.
508     unsigned Weight;
509 
510     // Each native RegUnit corresponds to one or two root registers. The full
511     // set of registers containing this unit can be computed as the union of
512     // these two registers and their super-registers.
513     const CodeGenRegister *Roots[2];
514 
515     // Index into RegClassUnitSets where we can find the list of UnitSets that
516     // contain this unit.
517     unsigned RegClassUnitSetsIdx;
518     // A register unit is artificial if at least one of its roots is
519     // artificial.
520     bool Artificial;
521 
522     RegUnit() : Weight(0), RegClassUnitSetsIdx(0), Artificial(false) {
523       Roots[0] = Roots[1] = nullptr;
524     }
525 
526     ArrayRef<const CodeGenRegister*> getRoots() const {
527       assert(!(Roots[1] && !Roots[0]) && "Invalid roots array");
528       return makeArrayRef(Roots, !!Roots[0] + !!Roots[1]);
529     }
530   };
531 
532   // Each RegUnitSet is a sorted vector with a name.
533   struct RegUnitSet {
534     typedef std::vector<unsigned>::const_iterator iterator;
535 
536     std::string Name;
537     std::vector<unsigned> Units;
538     unsigned Weight = 0; // Cache the sum of all unit weights.
539     unsigned Order = 0;  // Cache the sort key.
540 
541     RegUnitSet() = default;
542   };
543 
544   // Base vector for identifying TopoSigs. The contents uniquely identify a
545   // TopoSig, only computeSuperRegs needs to know how.
546   typedef SmallVector<unsigned, 16> TopoSigId;
547 
548   // CodeGenRegBank - Represent a target's registers and the relations between
549   // them.
550   class CodeGenRegBank {
551     SetTheory Sets;
552 
553     const CodeGenHwModes &CGH;
554 
555     std::deque<CodeGenSubRegIndex> SubRegIndices;
556     DenseMap<Record*, CodeGenSubRegIndex*> Def2SubRegIdx;
557 
558     CodeGenSubRegIndex *createSubRegIndex(StringRef Name, StringRef NameSpace);
559 
560     typedef std::map<SmallVector<CodeGenSubRegIndex*, 8>,
561                      CodeGenSubRegIndex*> ConcatIdxMap;
562     ConcatIdxMap ConcatIdx;
563 
564     // Registers.
565     std::deque<CodeGenRegister> Registers;
566     StringMap<CodeGenRegister*> RegistersByName;
567     DenseMap<Record*, CodeGenRegister*> Def2Reg;
568     unsigned NumNativeRegUnits;
569 
570     std::map<TopoSigId, unsigned> TopoSigs;
571 
572     // Includes native (0..NumNativeRegUnits-1) and adopted register units.
573     SmallVector<RegUnit, 8> RegUnits;
574 
575     // Register classes.
576     std::list<CodeGenRegisterClass> RegClasses;
577     DenseMap<Record*, CodeGenRegisterClass*> Def2RC;
578     typedef std::map<CodeGenRegisterClass::Key, CodeGenRegisterClass*> RCKeyMap;
579     RCKeyMap Key2RC;
580 
581     // Register categories.
582     std::list<CodeGenRegisterCategory> RegCategories;
583     DenseMap<Record *, CodeGenRegisterCategory *> Def2RCat;
584     using RCatKeyMap =
585         std::map<CodeGenRegisterClass::Key, CodeGenRegisterCategory *>;
586     RCatKeyMap Key2RCat;
587 
588     // Remember each unique set of register units. Initially, this contains a
589     // unique set for each register class. Simliar sets are coalesced with
590     // pruneUnitSets and new supersets are inferred during computeRegUnitSets.
591     std::vector<RegUnitSet> RegUnitSets;
592 
593     // Map RegisterClass index to the index of the RegUnitSet that contains the
594     // class's units and any inferred RegUnit supersets.
595     //
596     // NOTE: This could grow beyond the number of register classes when we map
597     // register units to lists of unit sets. If the list of unit sets does not
598     // already exist for a register class, we create a new entry in this vector.
599     std::vector<std::vector<unsigned>> RegClassUnitSets;
600 
601     // Give each register unit set an order based on sorting criteria.
602     std::vector<unsigned> RegUnitSetOrder;
603 
604     // Keep track of synthesized definitions generated in TupleExpander.
605     std::vector<std::unique_ptr<Record>> SynthDefs;
606 
607     // Add RC to *2RC maps.
608     void addToMaps(CodeGenRegisterClass*);
609 
610     // Create a synthetic sub-class if it is missing.
611     CodeGenRegisterClass *getOrCreateSubClass(const CodeGenRegisterClass *RC,
612                                               const CodeGenRegister::Vec *Membs,
613                                               StringRef Name);
614 
615     // Infer missing register classes.
616     void computeInferredRegisterClasses();
617     void inferCommonSubClass(CodeGenRegisterClass *RC);
618     void inferSubClassWithSubReg(CodeGenRegisterClass *RC);
619 
620     void inferMatchingSuperRegClass(CodeGenRegisterClass *RC) {
621       inferMatchingSuperRegClass(RC, RegClasses.begin());
622     }
623 
624     void inferMatchingSuperRegClass(
625         CodeGenRegisterClass *RC,
626         std::list<CodeGenRegisterClass>::iterator FirstSubRegRC);
627 
628     // Iteratively prune unit sets.
629     void pruneUnitSets();
630 
631     // Compute a weight for each register unit created during getSubRegs.
632     void computeRegUnitWeights();
633 
634     // Create a RegUnitSet for each RegClass and infer superclasses.
635     void computeRegUnitSets();
636 
637     // Populate the Composite map from sub-register relationships.
638     void computeComposites();
639 
640     // Compute a lane mask for each sub-register index.
641     void computeSubRegLaneMasks();
642 
643     /// Computes a lane mask for each register unit enumerated by a physical
644     /// register.
645     void computeRegUnitLaneMasks();
646 
647   public:
648     CodeGenRegBank(RecordKeeper&, const CodeGenHwModes&);
649     CodeGenRegBank(CodeGenRegBank&) = delete;
650 
651     SetTheory &getSets() { return Sets; }
652 
653     const CodeGenHwModes &getHwModes() const { return CGH; }
654 
655     // Sub-register indices. The first NumNamedIndices are defined by the user
656     // in the .td files. The rest are synthesized such that all sub-registers
657     // have a unique name.
658     const std::deque<CodeGenSubRegIndex> &getSubRegIndices() const {
659       return SubRegIndices;
660     }
661 
662     // Find a SubRegIndex from its Record def or add to the list if it does
663     // not exist there yet.
664     CodeGenSubRegIndex *getSubRegIdx(Record*);
665 
666     // Find a SubRegIndex from its Record def.
667     const CodeGenSubRegIndex *findSubRegIdx(const Record* Def) const;
668 
669     // Find or create a sub-register index representing the A+B composition.
670     CodeGenSubRegIndex *getCompositeSubRegIndex(CodeGenSubRegIndex *A,
671                                                 CodeGenSubRegIndex *B);
672 
673     // Find or create a sub-register index representing the concatenation of
674     // non-overlapping sibling indices.
675     CodeGenSubRegIndex *
676       getConcatSubRegIndex(const SmallVector<CodeGenSubRegIndex *, 8>&);
677 
678     const std::deque<CodeGenRegister> &getRegisters() const {
679       return Registers;
680     }
681 
682     const StringMap<CodeGenRegister *> &getRegistersByName() const {
683       return RegistersByName;
684     }
685 
686     // Find a register from its Record def.
687     CodeGenRegister *getReg(Record*);
688 
689     // Get a Register's index into the Registers array.
690     unsigned getRegIndex(const CodeGenRegister *Reg) const {
691       return Reg->EnumValue - 1;
692     }
693 
694     // Return the number of allocated TopoSigs. The first TopoSig representing
695     // leaf registers is allocated number 0.
696     unsigned getNumTopoSigs() const {
697       return TopoSigs.size();
698     }
699 
700     // Find or create a TopoSig for the given TopoSigId.
701     // This function is only for use by CodeGenRegister::computeSuperRegs().
702     // Others should simply use Reg->getTopoSig().
703     unsigned getTopoSig(const TopoSigId &Id) {
704       return TopoSigs.insert(std::make_pair(Id, TopoSigs.size())).first->second;
705     }
706 
707     // Create a native register unit that is associated with one or two root
708     // registers.
709     unsigned newRegUnit(CodeGenRegister *R0, CodeGenRegister *R1 = nullptr) {
710       RegUnits.resize(RegUnits.size() + 1);
711       RegUnit &RU = RegUnits.back();
712       RU.Roots[0] = R0;
713       RU.Roots[1] = R1;
714       RU.Artificial = R0->Artificial;
715       if (R1)
716         RU.Artificial |= R1->Artificial;
717       return RegUnits.size() - 1;
718     }
719 
720     // Create a new non-native register unit that can be adopted by a register
721     // to increase its pressure. Note that NumNativeRegUnits is not increased.
722     unsigned newRegUnit(unsigned Weight) {
723       RegUnits.resize(RegUnits.size() + 1);
724       RegUnits.back().Weight = Weight;
725       return RegUnits.size() - 1;
726     }
727 
728     // Native units are the singular unit of a leaf register. Register aliasing
729     // is completely characterized by native units. Adopted units exist to give
730     // register additional weight but don't affect aliasing.
731     bool isNativeUnit(unsigned RUID) const {
732       return RUID < NumNativeRegUnits;
733     }
734 
735     unsigned getNumNativeRegUnits() const {
736       return NumNativeRegUnits;
737     }
738 
739     RegUnit &getRegUnit(unsigned RUID) { return RegUnits[RUID]; }
740     const RegUnit &getRegUnit(unsigned RUID) const { return RegUnits[RUID]; }
741 
742     std::list<CodeGenRegisterClass> &getRegClasses() { return RegClasses; }
743 
744     const std::list<CodeGenRegisterClass> &getRegClasses() const {
745       return RegClasses;
746     }
747 
748     std::list<CodeGenRegisterCategory> &getRegCategories() {
749       return RegCategories;
750     }
751 
752     const std::list<CodeGenRegisterCategory> &getRegCategories() const {
753       return RegCategories;
754     }
755 
756     // Find a register class from its def.
757     CodeGenRegisterClass *getRegClass(const Record *) const;
758 
759     /// getRegisterClassForRegister - Find the register class that contains the
760     /// specified physical register.  If the register is not in a register
761     /// class, return null. If the register is in multiple classes, and the
762     /// classes have a superset-subset relationship and the same set of types,
763     /// return the superclass.  Otherwise return null.
764     const CodeGenRegisterClass* getRegClassForRegister(Record *R);
765 
766     // Analog of TargetRegisterInfo::getMinimalPhysRegClass. Unlike
767     // getRegClassForRegister, this tries to find the smallest class containing
768     // the physical register. If \p VT is specified, it will only find classes
769     // with a matching type
770     const CodeGenRegisterClass *
771     getMinimalPhysRegClass(Record *RegRecord, ValueTypeByHwMode *VT = nullptr);
772 
773     // Get the sum of unit weights.
774     unsigned getRegUnitSetWeight(const std::vector<unsigned> &Units) const {
775       unsigned Weight = 0;
776       for (unsigned Unit : Units)
777         Weight += getRegUnit(Unit).Weight;
778       return Weight;
779     }
780 
781     unsigned getRegSetIDAt(unsigned Order) const {
782       return RegUnitSetOrder[Order];
783     }
784 
785     const RegUnitSet &getRegSetAt(unsigned Order) const {
786       return RegUnitSets[RegUnitSetOrder[Order]];
787     }
788 
789     // Increase a RegUnitWeight.
790     void increaseRegUnitWeight(unsigned RUID, unsigned Inc) {
791       getRegUnit(RUID).Weight += Inc;
792     }
793 
794     // Get the number of register pressure dimensions.
795     unsigned getNumRegPressureSets() const { return RegUnitSets.size(); }
796 
797     // Get a set of register unit IDs for a given dimension of pressure.
798     const RegUnitSet &getRegPressureSet(unsigned Idx) const {
799       return RegUnitSets[Idx];
800     }
801 
802     // The number of pressure set lists may be larget than the number of
803     // register classes if some register units appeared in a list of sets that
804     // did not correspond to an existing register class.
805     unsigned getNumRegClassPressureSetLists() const {
806       return RegClassUnitSets.size();
807     }
808 
809     // Get a list of pressure set IDs for a register class. Liveness of a
810     // register in this class impacts each pressure set in this list by the
811     // weight of the register. An exact solution requires all registers in a
812     // class to have the same class, but it is not strictly guaranteed.
813     ArrayRef<unsigned> getRCPressureSetIDs(unsigned RCIdx) const {
814       return RegClassUnitSets[RCIdx];
815     }
816 
817     // Computed derived records such as missing sub-register indices.
818     void computeDerivedInfo();
819 
820     // Compute the set of registers completely covered by the registers in Regs.
821     // The returned BitVector will have a bit set for each register in Regs,
822     // all sub-registers, and all super-registers that are covered by the
823     // registers in Regs.
824     //
825     // This is used to compute the mask of call-preserved registers from a list
826     // of callee-saves.
827     BitVector computeCoveredRegisters(ArrayRef<Record*> Regs);
828 
829     // Bit mask of lanes that cover their registers. A sub-register index whose
830     // LaneMask is contained in CoveringLanes will be completely covered by
831     // another sub-register with the same or larger lane mask.
832     LaneBitmask CoveringLanes;
833 
834     // Helper function for printing debug information. Handles artificial
835     // (non-native) reg units.
836     void printRegUnitName(unsigned Unit) const;
837   };
838 
839 } // end namespace llvm
840 
841 #endif // LLVM_UTILS_TABLEGEN_CODEGENREGISTERS_H
842