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