1 //===- CodeGenRegisters.h - Register and RegisterClass Info -----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines structures to encapsulate information gleaned from the
11 // target register and register class definitions.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_UTILS_TABLEGEN_CODEGENREGISTERS_H
16 #define LLVM_UTILS_TABLEGEN_CODEGENREGISTERS_H
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/BitVector.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/CodeGen/MachineValueType.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/TableGen/Record.h"
25 #include "llvm/TableGen/SetTheory.h"
35 /// CodeGenSubRegIndex - Represents a sub-register index.
36 class CodeGenSubRegIndex {
39 std::string Namespace;
44 const unsigned EnumValue;
47 // Are all super-registers containing this SubRegIndex covered by their
49 bool AllSuperRegsCovered;
51 CodeGenSubRegIndex(Record *R, unsigned Enum);
52 CodeGenSubRegIndex(StringRef N, StringRef Nspace, unsigned Enum);
54 const std::string &getName() const { return Name; }
55 const std::string &getNamespace() const { return Namespace; }
56 std::string getQualifiedName() const;
58 // Order CodeGenSubRegIndex pointers by EnumValue.
60 bool operator()(const CodeGenSubRegIndex *A,
61 const CodeGenSubRegIndex *B) const {
63 return A->EnumValue < B->EnumValue;
67 // Map of composite subreg indices.
68 typedef std::map<CodeGenSubRegIndex*, CodeGenSubRegIndex*, Less> CompMap;
70 // Returns the subreg index that results from composing this with Idx.
71 // Returns NULL if this and Idx don't compose.
72 CodeGenSubRegIndex *compose(CodeGenSubRegIndex *Idx) const {
73 CompMap::const_iterator I = Composed.find(Idx);
74 return I == Composed.end() ? nullptr : I->second;
77 // Add a composite subreg index: this+A = B.
78 // Return a conflicting composite, or NULL
79 CodeGenSubRegIndex *addComposite(CodeGenSubRegIndex *A,
80 CodeGenSubRegIndex *B) {
82 std::pair<CompMap::iterator, bool> Ins =
83 Composed.insert(std::make_pair(A, B));
84 // Synthetic subreg indices that aren't contiguous (for instance ARM
85 // register tuples) don't have a bit range, so it's OK to let
86 // B->Offset == -1. For the other cases, accumulate the offset and set
87 // the size here. Only do so if there is no offset yet though.
88 if ((Offset != (uint16_t)-1 && A->Offset != (uint16_t)-1) &&
89 (B->Offset == (uint16_t)-1)) {
90 B->Offset = Offset + A->Offset;
93 return (Ins.second || Ins.first->second == B) ? nullptr
97 // Update the composite maps of components specified in 'ComposedOf'.
98 void updateComponents(CodeGenRegBank&);
100 // Return the map of composites.
101 const CompMap &getComposites() const { return Composed; }
103 // Compute LaneMask from Composed. Return LaneMask.
104 unsigned computeLaneMask();
110 /// CodeGenRegister - Represents a register definition.
111 struct CodeGenRegister {
115 bool CoveredBySubRegs;
117 // Map SubRegIndex -> Register.
118 typedef std::map<CodeGenSubRegIndex*, CodeGenRegister*,
119 CodeGenSubRegIndex::Less> SubRegMap;
121 CodeGenRegister(Record *R, unsigned Enum);
123 const std::string &getName() const;
125 // Extract more information from TheDef. This is used to build an object
126 // graph after all CodeGenRegister objects have been created.
127 void buildObjectGraph(CodeGenRegBank&);
129 // Lazily compute a map of all sub-registers.
130 // This includes unique entries for all sub-sub-registers.
131 const SubRegMap &computeSubRegs(CodeGenRegBank&);
133 // Compute extra sub-registers by combining the existing sub-registers.
134 void computeSecondarySubRegs(CodeGenRegBank&);
136 // Add this as a super-register to all sub-registers after the sub-register
137 // graph has been built.
138 void computeSuperRegs(CodeGenRegBank&);
140 const SubRegMap &getSubRegs() const {
141 assert(SubRegsComplete && "Must precompute sub-registers");
145 // Add sub-registers to OSet following a pre-order defined by the .td file.
146 void addSubRegsPreOrder(SetVector<const CodeGenRegister*> &OSet,
147 CodeGenRegBank&) const;
149 // Return the sub-register index naming Reg as a sub-register of this
150 // register. Returns NULL if Reg is not a sub-register.
151 CodeGenSubRegIndex *getSubRegIndex(const CodeGenRegister *Reg) const {
152 return SubReg2Idx.lookup(Reg);
155 typedef std::vector<const CodeGenRegister*> SuperRegList;
157 // Get the list of super-registers in topological order, small to large.
158 // This is valid after computeSubRegs visits all registers during RegBank
160 const SuperRegList &getSuperRegs() const {
161 assert(SubRegsComplete && "Must precompute sub-registers");
165 // Get the list of ad hoc aliases. The graph is symmetric, so the list
166 // contains all registers in 'Aliases', and all registers that mention this
167 // register in 'Aliases'.
168 ArrayRef<CodeGenRegister*> getExplicitAliases() const {
169 return ExplicitAliases;
172 // Get the topological signature of this register. This is a small integer
173 // less than RegBank.getNumTopoSigs(). Registers with the same TopoSig have
174 // identical sub-register structure. That is, they support the same set of
175 // sub-register indices mapping to the same kind of sub-registers
177 unsigned getTopoSig() const {
178 assert(SuperRegsComplete && "TopoSigs haven't been computed yet.");
182 // List of register units in ascending order.
183 typedef SmallVector<unsigned, 16> RegUnitList;
185 // How many entries in RegUnitList are native?
186 unsigned NumNativeRegUnits;
188 // Get the list of register units.
189 // This is only valid after computeSubRegs() completes.
190 const RegUnitList &getRegUnits() const { return RegUnits; }
192 // Get the native register units. This is a prefix of getRegUnits().
193 ArrayRef<unsigned> getNativeRegUnits() const {
194 return makeArrayRef(RegUnits).slice(0, NumNativeRegUnits);
197 // Inherit register units from subregisters.
198 // Return true if the RegUnits changed.
199 bool inheritRegUnits(CodeGenRegBank &RegBank);
201 // Adopt a register unit for pressure tracking.
202 // A unit is adopted iff its unit number is >= NumNativeRegUnits.
203 void adoptRegUnit(unsigned RUID) { RegUnits.push_back(RUID); }
205 // Get the sum of this register's register unit weights.
206 unsigned getWeight(const CodeGenRegBank &RegBank) const;
208 // Order CodeGenRegister pointers by EnumValue.
210 bool operator()(const CodeGenRegister *A,
211 const CodeGenRegister *B) const {
213 return A->EnumValue < B->EnumValue;
217 // Canonically ordered set.
218 typedef std::set<const CodeGenRegister*, Less> Set;
221 bool SubRegsComplete;
222 bool SuperRegsComplete;
225 // The sub-registers explicit in the .td file form a tree.
226 SmallVector<CodeGenSubRegIndex*, 8> ExplicitSubRegIndices;
227 SmallVector<CodeGenRegister*, 8> ExplicitSubRegs;
229 // Explicit ad hoc aliases, symmetrized to form an undirected graph.
230 SmallVector<CodeGenRegister*, 8> ExplicitAliases;
232 // Super-registers where this is the first explicit sub-register.
233 SuperRegList LeadingSuperRegs;
236 SuperRegList SuperRegs;
237 DenseMap<const CodeGenRegister*, CodeGenSubRegIndex*> SubReg2Idx;
238 RegUnitList RegUnits;
242 class CodeGenRegisterClass {
243 CodeGenRegister::Set Members;
244 // Allocation orders. Order[0] always contains all registers in Members.
245 std::vector<SmallVector<Record*, 16> > Orders;
246 // Bit mask of sub-classes including this, indexed by their EnumValue.
247 BitVector SubClasses;
248 // List of super-classes, topologocally ordered to have the larger classes
249 // first. This is the same as sorting by EnumValue.
250 SmallVector<CodeGenRegisterClass*, 4> SuperClasses;
254 // For a synthesized class, inherit missing properties from the nearest
256 void inheritProperties(CodeGenRegBank&);
258 // Map SubRegIndex -> sub-class. This is the largest sub-class where all
259 // registers have a SubRegIndex sub-register.
260 DenseMap<CodeGenSubRegIndex*, CodeGenRegisterClass*> SubClassWithSubReg;
262 // Map SubRegIndex -> set of super-reg classes. This is all register
263 // classes SuperRC such that:
265 // R:SubRegIndex in this RC for all R in SuperRC.
267 DenseMap<CodeGenSubRegIndex*,
268 SmallPtrSet<CodeGenRegisterClass*, 8> > SuperRegClasses;
270 // Bit vector of TopoSigs for the registers in this class. This will be
271 // very sparse on regular architectures.
276 std::string Namespace;
277 SmallVector<MVT::SimpleValueType, 4> VTs;
279 unsigned SpillAlignment;
282 std::string AltOrderSelect;
284 // Return the Record that defined this class, or NULL if the class was
285 // created by TableGen.
286 Record *getDef() const { return TheDef; }
288 const std::string &getName() const { return Name; }
289 std::string getQualifiedName() const;
290 ArrayRef<MVT::SimpleValueType> getValueTypes() const {return VTs;}
291 unsigned getNumValueTypes() const { return VTs.size(); }
293 MVT::SimpleValueType getValueTypeNum(unsigned VTNum) const {
294 if (VTNum < VTs.size())
296 llvm_unreachable("VTNum greater than number of ValueTypes in RegClass!");
299 // Return true if this this class contains the register.
300 bool contains(const CodeGenRegister*) const;
302 // Returns true if RC is a subclass.
303 // RC is a sub-class of this class if it is a valid replacement for any
304 // instruction operand where a register of this classis required. It must
305 // satisfy these conditions:
307 // 1. All RC registers are also in this.
308 // 2. The RC spill size must not be smaller than our spill size.
309 // 3. RC spill alignment must be compatible with ours.
311 bool hasSubClass(const CodeGenRegisterClass *RC) const {
312 return SubClasses.test(RC->EnumValue);
315 // getSubClassWithSubReg - Returns the largest sub-class where all
316 // registers have a SubIdx sub-register.
317 CodeGenRegisterClass*
318 getSubClassWithSubReg(CodeGenSubRegIndex *SubIdx) const {
319 return SubClassWithSubReg.lookup(SubIdx);
322 void setSubClassWithSubReg(CodeGenSubRegIndex *SubIdx,
323 CodeGenRegisterClass *SubRC) {
324 SubClassWithSubReg[SubIdx] = SubRC;
327 // getSuperRegClasses - Returns a bit vector of all register classes
328 // containing only SubIdx super-registers of this class.
329 void getSuperRegClasses(CodeGenSubRegIndex *SubIdx, BitVector &Out) const;
331 // addSuperRegClass - Add a class containing only SudIdx super-registers.
332 void addSuperRegClass(CodeGenSubRegIndex *SubIdx,
333 CodeGenRegisterClass *SuperRC) {
334 SuperRegClasses[SubIdx].insert(SuperRC);
337 // getSubClasses - Returns a constant BitVector of subclasses indexed by
339 // The SubClasses vector includes an entry for this class.
340 const BitVector &getSubClasses() const { return SubClasses; }
342 // getSuperClasses - Returns a list of super classes ordered by EnumValue.
343 // The array does not include an entry for this class.
344 ArrayRef<CodeGenRegisterClass*> getSuperClasses() const {
348 // Returns an ordered list of class members.
349 // The order of registers is the same as in the .td file.
350 // No = 0 is the default allocation order, No = 1 is the first alternative.
351 ArrayRef<Record*> getOrder(unsigned No = 0) const {
355 // Return the total number of allocation orders available.
356 unsigned getNumOrders() const { return Orders.size(); }
358 // Get the set of registers. This set contains the same registers as
360 const CodeGenRegister::Set &getMembers() const { return Members; }
362 // Get a bit vector of TopoSigs present in this register class.
363 const BitVector &getTopoSigs() const { return TopoSigs; }
365 // Populate a unique sorted list of units from a register set.
366 void buildRegUnitSet(std::vector<unsigned> &RegUnits) const;
368 CodeGenRegisterClass(CodeGenRegBank&, Record *R);
370 // A key representing the parts of a register class used for forming
371 // sub-classes. Note the ordering provided by this key is not the same as
372 // the topological order used for the EnumValues.
374 const CodeGenRegister::Set *Members;
376 unsigned SpillAlignment;
378 Key(const CodeGenRegister::Set *M, unsigned S = 0, unsigned A = 0)
379 : Members(M), SpillSize(S), SpillAlignment(A) {}
381 Key(const CodeGenRegisterClass &RC)
382 : Members(&RC.getMembers()),
383 SpillSize(RC.SpillSize),
384 SpillAlignment(RC.SpillAlignment) {}
386 // Lexicographical order of (Members, SpillSize, SpillAlignment).
387 bool operator<(const Key&) const;
390 // Create a non-user defined register class.
391 CodeGenRegisterClass(CodeGenRegBank&, StringRef Name, Key Props);
393 // Called by CodeGenRegBank::CodeGenRegBank().
394 static void computeSubClasses(CodeGenRegBank&);
397 // Register units are used to model interference and register pressure.
398 // Every register is assigned one or more register units such that two
399 // registers overlap if and only if they have a register unit in common.
401 // Normally, one register unit is created per leaf register. Non-leaf
402 // registers inherit the units of their sub-registers.
404 // Weight assigned to this RegUnit for estimating register pressure.
405 // This is useful when equalizing weights in register classes with mixed
406 // register topologies.
409 // Each native RegUnit corresponds to one or two root registers. The full
410 // set of registers containing this unit can be computed as the union of
411 // these two registers and their super-registers.
412 const CodeGenRegister *Roots[2];
414 // Index into RegClassUnitSets where we can find the list of UnitSets that
415 // contain this unit.
416 unsigned RegClassUnitSetsIdx;
418 RegUnit() : Weight(0), RegClassUnitSetsIdx(0) {
419 Roots[0] = Roots[1] = nullptr;
422 ArrayRef<const CodeGenRegister*> getRoots() const {
423 assert(!(Roots[1] && !Roots[0]) && "Invalid roots array");
424 return makeArrayRef(Roots, !!Roots[0] + !!Roots[1]);
428 // Each RegUnitSet is a sorted vector with a name.
430 typedef std::vector<unsigned>::const_iterator iterator;
433 std::vector<unsigned> Units;
434 unsigned Weight; // Cache the sum of all unit weights.
435 unsigned Order; // Cache the sort key.
437 RegUnitSet() : Weight(0), Order(0) {}
440 // Base vector for identifying TopoSigs. The contents uniquely identify a
441 // TopoSig, only computeSuperRegs needs to know how.
442 typedef SmallVector<unsigned, 16> TopoSigId;
444 // CodeGenRegBank - Represent a target's registers and the relations between
446 class CodeGenRegBank {
450 std::vector<CodeGenSubRegIndex*> SubRegIndices;
451 DenseMap<Record*, CodeGenSubRegIndex*> Def2SubRegIdx;
453 CodeGenSubRegIndex *createSubRegIndex(StringRef Name, StringRef NameSpace);
455 typedef std::map<SmallVector<CodeGenSubRegIndex*, 8>,
456 CodeGenSubRegIndex*> ConcatIdxMap;
457 ConcatIdxMap ConcatIdx;
460 std::vector<CodeGenRegister*> Registers;
461 StringMap<CodeGenRegister*> RegistersByName;
462 DenseMap<Record*, CodeGenRegister*> Def2Reg;
463 unsigned NumNativeRegUnits;
465 std::map<TopoSigId, unsigned> TopoSigs;
467 // Includes native (0..NumNativeRegUnits-1) and adopted register units.
468 SmallVector<RegUnit, 8> RegUnits;
471 std::vector<CodeGenRegisterClass*> RegClasses;
472 DenseMap<Record*, CodeGenRegisterClass*> Def2RC;
473 typedef std::map<CodeGenRegisterClass::Key, CodeGenRegisterClass*> RCKeyMap;
476 // Remember each unique set of register units. Initially, this contains a
477 // unique set for each register class. Simliar sets are coalesced with
478 // pruneUnitSets and new supersets are inferred during computeRegUnitSets.
479 std::vector<RegUnitSet> RegUnitSets;
481 // Map RegisterClass index to the index of the RegUnitSet that contains the
482 // class's units and any inferred RegUnit supersets.
484 // NOTE: This could grow beyond the number of register classes when we map
485 // register units to lists of unit sets. If the list of unit sets does not
486 // already exist for a register class, we create a new entry in this vector.
487 std::vector<std::vector<unsigned> > RegClassUnitSets;
489 // Give each register unit set an order based on sorting criteria.
490 std::vector<unsigned> RegUnitSetOrder;
492 // Add RC to *2RC maps.
493 void addToMaps(CodeGenRegisterClass*);
495 // Create a synthetic sub-class if it is missing.
496 CodeGenRegisterClass *getOrCreateSubClass(const CodeGenRegisterClass *RC,
497 const CodeGenRegister::Set *Membs,
500 // Infer missing register classes.
501 void computeInferredRegisterClasses();
502 void inferCommonSubClass(CodeGenRegisterClass *RC);
503 void inferSubClassWithSubReg(CodeGenRegisterClass *RC);
504 void inferMatchingSuperRegClass(CodeGenRegisterClass *RC,
505 unsigned FirstSubRegRC = 0);
507 // Iteratively prune unit sets.
508 void pruneUnitSets();
510 // Compute a weight for each register unit created during getSubRegs.
511 void computeRegUnitWeights();
513 // Create a RegUnitSet for each RegClass and infer superclasses.
514 void computeRegUnitSets();
516 // Populate the Composite map from sub-register relationships.
517 void computeComposites();
519 // Compute a lane mask for each sub-register index.
520 void computeSubRegIndexLaneMasks();
523 CodeGenRegBank(RecordKeeper&);
525 SetTheory &getSets() { return Sets; }
527 // Sub-register indices. The first NumNamedIndices are defined by the user
528 // in the .td files. The rest are synthesized such that all sub-registers
529 // have a unique name.
530 ArrayRef<CodeGenSubRegIndex*> getSubRegIndices() { return SubRegIndices; }
532 // Find a SubRegIndex form its Record def.
533 CodeGenSubRegIndex *getSubRegIdx(Record*);
535 // Find or create a sub-register index representing the A+B composition.
536 CodeGenSubRegIndex *getCompositeSubRegIndex(CodeGenSubRegIndex *A,
537 CodeGenSubRegIndex *B);
539 // Find or create a sub-register index representing the concatenation of
540 // non-overlapping sibling indices.
542 getConcatSubRegIndex(const SmallVector<CodeGenSubRegIndex *, 8>&);
545 addConcatSubRegIndex(const SmallVector<CodeGenSubRegIndex *, 8> &Parts,
546 CodeGenSubRegIndex *Idx) {
547 ConcatIdx.insert(std::make_pair(Parts, Idx));
550 const std::vector<CodeGenRegister*> &getRegisters() { return Registers; }
551 const StringMap<CodeGenRegister*> &getRegistersByName() {
552 return RegistersByName;
555 // Find a register from its Record def.
556 CodeGenRegister *getReg(Record*);
558 // Get a Register's index into the Registers array.
559 unsigned getRegIndex(const CodeGenRegister *Reg) const {
560 return Reg->EnumValue - 1;
563 // Return the number of allocated TopoSigs. The first TopoSig representing
564 // leaf registers is allocated number 0.
565 unsigned getNumTopoSigs() const {
566 return TopoSigs.size();
569 // Find or create a TopoSig for the given TopoSigId.
570 // This function is only for use by CodeGenRegister::computeSuperRegs().
571 // Others should simply use Reg->getTopoSig().
572 unsigned getTopoSig(const TopoSigId &Id) {
573 return TopoSigs.insert(std::make_pair(Id, TopoSigs.size())).first->second;
576 // Create a native register unit that is associated with one or two root
578 unsigned newRegUnit(CodeGenRegister *R0, CodeGenRegister *R1 = nullptr) {
579 RegUnits.resize(RegUnits.size() + 1);
580 RegUnits.back().Roots[0] = R0;
581 RegUnits.back().Roots[1] = R1;
582 return RegUnits.size() - 1;
585 // Create a new non-native register unit that can be adopted by a register
586 // to increase its pressure. Note that NumNativeRegUnits is not increased.
587 unsigned newRegUnit(unsigned Weight) {
588 RegUnits.resize(RegUnits.size() + 1);
589 RegUnits.back().Weight = Weight;
590 return RegUnits.size() - 1;
593 // Native units are the singular unit of a leaf register. Register aliasing
594 // is completely characterized by native units. Adopted units exist to give
595 // register additional weight but don't affect aliasing.
596 bool isNativeUnit(unsigned RUID) {
597 return RUID < NumNativeRegUnits;
600 unsigned getNumNativeRegUnits() const {
601 return NumNativeRegUnits;
604 RegUnit &getRegUnit(unsigned RUID) { return RegUnits[RUID]; }
605 const RegUnit &getRegUnit(unsigned RUID) const { return RegUnits[RUID]; }
607 ArrayRef<CodeGenRegisterClass*> getRegClasses() const {
611 // Find a register class from its def.
612 CodeGenRegisterClass *getRegClass(Record*);
614 /// getRegisterClassForRegister - Find the register class that contains the
615 /// specified physical register. If the register is not in a register
616 /// class, return null. If the register is in multiple classes, and the
617 /// classes have a superset-subset relationship and the same set of types,
618 /// return the superclass. Otherwise return null.
619 const CodeGenRegisterClass* getRegClassForRegister(Record *R);
621 // Get the sum of unit weights.
622 unsigned getRegUnitSetWeight(const std::vector<unsigned> &Units) const {
624 for (std::vector<unsigned>::const_iterator
625 I = Units.begin(), E = Units.end(); I != E; ++I)
626 Weight += getRegUnit(*I).Weight;
630 unsigned getRegSetIDAt(unsigned Order) const {
631 return RegUnitSetOrder[Order];
633 const RegUnitSet &getRegSetAt(unsigned Order) const {
634 return RegUnitSets[RegUnitSetOrder[Order]];
637 // Increase a RegUnitWeight.
638 void increaseRegUnitWeight(unsigned RUID, unsigned Inc) {
639 getRegUnit(RUID).Weight += Inc;
642 // Get the number of register pressure dimensions.
643 unsigned getNumRegPressureSets() const { return RegUnitSets.size(); }
645 // Get a set of register unit IDs for a given dimension of pressure.
646 const RegUnitSet &getRegPressureSet(unsigned Idx) const {
647 return RegUnitSets[Idx];
650 // The number of pressure set lists may be larget than the number of
651 // register classes if some register units appeared in a list of sets that
652 // did not correspond to an existing register class.
653 unsigned getNumRegClassPressureSetLists() const {
654 return RegClassUnitSets.size();
657 // Get a list of pressure set IDs for a register class. Liveness of a
658 // register in this class impacts each pressure set in this list by the
659 // weight of the register. An exact solution requires all registers in a
660 // class to have the same class, but it is not strictly guaranteed.
661 ArrayRef<unsigned> getRCPressureSetIDs(unsigned RCIdx) const {
662 return RegClassUnitSets[RCIdx];
665 // Computed derived records such as missing sub-register indices.
666 void computeDerivedInfo();
668 // Compute the set of registers completely covered by the registers in Regs.
669 // The returned BitVector will have a bit set for each register in Regs,
670 // all sub-registers, and all super-registers that are covered by the
671 // registers in Regs.
673 // This is used to compute the mask of call-preserved registers from a list
675 BitVector computeCoveredRegisters(ArrayRef<Record*> Regs);
677 // Bit mask of lanes that cover their registers. A sub-register index whose
678 // LaneMask is contained in CoveringLanes will be completely covered by
679 // another sub-register with the same or larger lane mask.
680 unsigned CoveringLanes;