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 CODEGEN_REGISTERS_H
16 #define CODEGEN_REGISTERS_H
18 #include "SetTheory.h"
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/BitVector.h"
21 #include "llvm/ADT/DenseMap.h"
22 #include "llvm/ADT/SetVector.h"
23 #include "llvm/CodeGen/ValueTypes.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/TableGen/Record.h"
35 /// CodeGenSubRegIndex - Represents a sub-register index.
36 class CodeGenSubRegIndex {
39 std::string Namespace;
42 const unsigned EnumValue;
45 CodeGenSubRegIndex(Record *R, unsigned Enum);
46 CodeGenSubRegIndex(StringRef N, StringRef Nspace, unsigned Enum);
48 const std::string &getName() const { return Name; }
49 const std::string &getNamespace() const { return Namespace; }
50 std::string getQualifiedName() const;
52 // Order CodeGenSubRegIndex pointers by EnumValue.
54 bool operator()(const CodeGenSubRegIndex *A,
55 const CodeGenSubRegIndex *B) const {
57 return A->EnumValue < B->EnumValue;
61 // Map of composite subreg indices.
62 typedef std::map<CodeGenSubRegIndex*, CodeGenSubRegIndex*, Less> CompMap;
64 // Returns the subreg index that results from composing this with Idx.
65 // Returns NULL if this and Idx don't compose.
66 CodeGenSubRegIndex *compose(CodeGenSubRegIndex *Idx) const {
67 CompMap::const_iterator I = Composed.find(Idx);
68 return I == Composed.end() ? 0 : I->second;
71 // Add a composite subreg index: this+A = B.
72 // Return a conflicting composite, or NULL
73 CodeGenSubRegIndex *addComposite(CodeGenSubRegIndex *A,
74 CodeGenSubRegIndex *B) {
76 std::pair<CompMap::iterator, bool> Ins =
77 Composed.insert(std::make_pair(A, B));
78 return (Ins.second || Ins.first->second == B) ? 0 : Ins.first->second;
81 // Update the composite maps of components specified in 'ComposedOf'.
82 void updateComponents(CodeGenRegBank&);
84 // Return the map of composites.
85 const CompMap &getComposites() const { return Composed; }
87 // Compute LaneMask from Composed. Return LaneMask.
88 unsigned computeLaneMask();
94 /// CodeGenRegister - Represents a register definition.
95 struct CodeGenRegister {
99 bool CoveredBySubRegs;
101 // Map SubRegIndex -> Register.
102 typedef std::map<CodeGenSubRegIndex*, CodeGenRegister*,
103 CodeGenSubRegIndex::Less> SubRegMap;
105 CodeGenRegister(Record *R, unsigned Enum);
107 const std::string &getName() const;
109 // Extract more information from TheDef. This is used to build an object
110 // graph after all CodeGenRegister objects have been created.
111 void buildObjectGraph(CodeGenRegBank&);
113 // Lazily compute a map of all sub-registers.
114 // This includes unique entries for all sub-sub-registers.
115 const SubRegMap &computeSubRegs(CodeGenRegBank&);
117 // Compute extra sub-registers by combining the existing sub-registers.
118 void computeSecondarySubRegs(CodeGenRegBank&);
120 // Add this as a super-register to all sub-registers after the sub-register
121 // graph has been built.
122 void computeSuperRegs(CodeGenRegBank&);
124 const SubRegMap &getSubRegs() const {
125 assert(SubRegsComplete && "Must precompute sub-registers");
129 // Add sub-registers to OSet following a pre-order defined by the .td file.
130 void addSubRegsPreOrder(SetVector<const CodeGenRegister*> &OSet,
131 CodeGenRegBank&) const;
133 // Return the sub-register index naming Reg as a sub-register of this
134 // register. Returns NULL if Reg is not a sub-register.
135 CodeGenSubRegIndex *getSubRegIndex(const CodeGenRegister *Reg) const {
136 return SubReg2Idx.lookup(Reg);
139 typedef std::vector<const CodeGenRegister*> SuperRegList;
141 // Get the list of super-registers in topological order, small to large.
142 // This is valid after computeSubRegs visits all registers during RegBank
144 const SuperRegList &getSuperRegs() const {
145 assert(SubRegsComplete && "Must precompute sub-registers");
149 // Get the list of ad hoc aliases. The graph is symmetric, so the list
150 // contains all registers in 'Aliases', and all registers that mention this
151 // register in 'Aliases'.
152 ArrayRef<CodeGenRegister*> getExplicitAliases() const {
153 return ExplicitAliases;
156 // Get the topological signature of this register. This is a small integer
157 // less than RegBank.getNumTopoSigs(). Registers with the same TopoSig have
158 // identical sub-register structure. That is, they support the same set of
159 // sub-register indices mapping to the same kind of sub-registers
161 unsigned getTopoSig() const {
162 assert(SuperRegsComplete && "TopoSigs haven't been computed yet.");
166 // List of register units in ascending order.
167 typedef SmallVector<unsigned, 16> RegUnitList;
169 // How many entries in RegUnitList are native?
170 unsigned NumNativeRegUnits;
172 // Get the list of register units.
173 // This is only valid after computeSubRegs() completes.
174 const RegUnitList &getRegUnits() const { return RegUnits; }
176 // Get the native register units. This is a prefix of getRegUnits().
177 ArrayRef<unsigned> getNativeRegUnits() const {
178 return makeArrayRef(RegUnits).slice(0, NumNativeRegUnits);
181 // Inherit register units from subregisters.
182 // Return true if the RegUnits changed.
183 bool inheritRegUnits(CodeGenRegBank &RegBank);
185 // Adopt a register unit for pressure tracking.
186 // A unit is adopted iff its unit number is >= NumNativeRegUnits.
187 void adoptRegUnit(unsigned RUID) { RegUnits.push_back(RUID); }
189 // Get the sum of this register's register unit weights.
190 unsigned getWeight(const CodeGenRegBank &RegBank) const;
192 // Order CodeGenRegister pointers by EnumValue.
194 bool operator()(const CodeGenRegister *A,
195 const CodeGenRegister *B) const {
197 return A->EnumValue < B->EnumValue;
201 // Canonically ordered set.
202 typedef std::set<const CodeGenRegister*, Less> Set;
204 // Compute the set of registers overlapping this.
205 void computeOverlaps(Set &Overlaps, const CodeGenRegBank&) const;
208 bool SubRegsComplete;
209 bool SuperRegsComplete;
212 // The sub-registers explicit in the .td file form a tree.
213 SmallVector<CodeGenSubRegIndex*, 8> ExplicitSubRegIndices;
214 SmallVector<CodeGenRegister*, 8> ExplicitSubRegs;
216 // Explicit ad hoc aliases, symmetrized to form an undirected graph.
217 SmallVector<CodeGenRegister*, 8> ExplicitAliases;
219 // Super-registers where this is the first explicit sub-register.
220 SuperRegList LeadingSuperRegs;
223 SuperRegList SuperRegs;
224 DenseMap<const CodeGenRegister*, CodeGenSubRegIndex*> SubReg2Idx;
225 RegUnitList RegUnits;
229 class CodeGenRegisterClass {
230 CodeGenRegister::Set Members;
231 // Allocation orders. Order[0] always contains all registers in Members.
232 std::vector<SmallVector<Record*, 16> > Orders;
233 // Bit mask of sub-classes including this, indexed by their EnumValue.
234 BitVector SubClasses;
235 // List of super-classes, topologocally ordered to have the larger classes
236 // first. This is the same as sorting by EnumValue.
237 SmallVector<CodeGenRegisterClass*, 4> SuperClasses;
241 // For a synthesized class, inherit missing properties from the nearest
243 void inheritProperties(CodeGenRegBank&);
245 // Map SubRegIndex -> sub-class. This is the largest sub-class where all
246 // registers have a SubRegIndex sub-register.
247 DenseMap<CodeGenSubRegIndex*, CodeGenRegisterClass*> SubClassWithSubReg;
249 // Map SubRegIndex -> set of super-reg classes. This is all register
250 // classes SuperRC such that:
252 // R:SubRegIndex in this RC for all R in SuperRC.
254 DenseMap<CodeGenSubRegIndex*,
255 SmallPtrSet<CodeGenRegisterClass*, 8> > SuperRegClasses;
257 // Bit vector of TopoSigs for the registers in this class. This will be
258 // very sparse on regular architectures.
263 std::string Namespace;
264 std::vector<MVT::SimpleValueType> VTs;
266 unsigned SpillAlignment;
269 std::string AltOrderSelect;
271 // Return the Record that defined this class, or NULL if the class was
272 // created by TableGen.
273 Record *getDef() const { return TheDef; }
275 const std::string &getName() const { return Name; }
276 std::string getQualifiedName() const;
277 const std::vector<MVT::SimpleValueType> &getValueTypes() const {return VTs;}
278 unsigned getNumValueTypes() const { return VTs.size(); }
280 MVT::SimpleValueType getValueTypeNum(unsigned VTNum) const {
281 if (VTNum < VTs.size())
283 llvm_unreachable("VTNum greater than number of ValueTypes in RegClass!");
286 // Return true if this this class contains the register.
287 bool contains(const CodeGenRegister*) const;
289 // Returns true if RC is a subclass.
290 // RC is a sub-class of this class if it is a valid replacement for any
291 // instruction operand where a register of this classis required. It must
292 // satisfy these conditions:
294 // 1. All RC registers are also in this.
295 // 2. The RC spill size must not be smaller than our spill size.
296 // 3. RC spill alignment must be compatible with ours.
298 bool hasSubClass(const CodeGenRegisterClass *RC) const {
299 return SubClasses.test(RC->EnumValue);
302 // getSubClassWithSubReg - Returns the largest sub-class where all
303 // registers have a SubIdx sub-register.
304 CodeGenRegisterClass*
305 getSubClassWithSubReg(CodeGenSubRegIndex *SubIdx) const {
306 return SubClassWithSubReg.lookup(SubIdx);
309 void setSubClassWithSubReg(CodeGenSubRegIndex *SubIdx,
310 CodeGenRegisterClass *SubRC) {
311 SubClassWithSubReg[SubIdx] = SubRC;
314 // getSuperRegClasses - Returns a bit vector of all register classes
315 // containing only SubIdx super-registers of this class.
316 void getSuperRegClasses(CodeGenSubRegIndex *SubIdx, BitVector &Out) const;
318 // addSuperRegClass - Add a class containing only SudIdx super-registers.
319 void addSuperRegClass(CodeGenSubRegIndex *SubIdx,
320 CodeGenRegisterClass *SuperRC) {
321 SuperRegClasses[SubIdx].insert(SuperRC);
324 // getSubClasses - Returns a constant BitVector of subclasses indexed by
326 // The SubClasses vector includs an entry for this class.
327 const BitVector &getSubClasses() const { return SubClasses; }
329 // getSuperClasses - Returns a list of super classes ordered by EnumValue.
330 // The array does not include an entry for this class.
331 ArrayRef<CodeGenRegisterClass*> getSuperClasses() const {
335 // Returns an ordered list of class members.
336 // The order of registers is the same as in the .td file.
337 // No = 0 is the default allocation order, No = 1 is the first alternative.
338 ArrayRef<Record*> getOrder(unsigned No = 0) const {
342 // Return the total number of allocation orders available.
343 unsigned getNumOrders() const { return Orders.size(); }
345 // Get the set of registers. This set contains the same registers as
347 const CodeGenRegister::Set &getMembers() const { return Members; }
349 // Get a bit vector of TopoSigs present in this register class.
350 const BitVector &getTopoSigs() const { return TopoSigs; }
352 // Populate a unique sorted list of units from a register set.
353 void buildRegUnitSet(std::vector<unsigned> &RegUnits) const;
355 CodeGenRegisterClass(CodeGenRegBank&, Record *R);
357 // A key representing the parts of a register class used for forming
358 // sub-classes. Note the ordering provided by this key is not the same as
359 // the topological order used for the EnumValues.
361 const CodeGenRegister::Set *Members;
363 unsigned SpillAlignment;
366 : Members(O.Members),
367 SpillSize(O.SpillSize),
368 SpillAlignment(O.SpillAlignment) {}
370 Key(const CodeGenRegister::Set *M, unsigned S = 0, unsigned A = 0)
371 : Members(M), SpillSize(S), SpillAlignment(A) {}
373 Key(const CodeGenRegisterClass &RC)
374 : Members(&RC.getMembers()),
375 SpillSize(RC.SpillSize),
376 SpillAlignment(RC.SpillAlignment) {}
378 // Lexicographical order of (Members, SpillSize, SpillAlignment).
379 bool operator<(const Key&) const;
382 // Create a non-user defined register class.
383 CodeGenRegisterClass(CodeGenRegBank&, StringRef Name, Key Props);
385 // Called by CodeGenRegBank::CodeGenRegBank().
386 static void computeSubClasses(CodeGenRegBank&);
389 // Register units are used to model interference and register pressure.
390 // Every register is assigned one or more register units such that two
391 // registers overlap if and only if they have a register unit in common.
393 // Normally, one register unit is created per leaf register. Non-leaf
394 // registers inherit the units of their sub-registers.
396 // Weight assigned to this RegUnit for estimating register pressure.
397 // This is useful when equalizing weights in register classes with mixed
398 // register topologies.
401 // Each native RegUnit corresponds to one or two root registers. The full
402 // set of registers containing this unit can be computed as the union of
403 // these two registers and their super-registers.
404 const CodeGenRegister *Roots[2];
406 // Index into RegClassUnitSets where we can find the list of UnitSets that
407 // contain this unit.
408 unsigned RegClassUnitSetsIdx;
410 RegUnit() : Weight(0), RegClassUnitSetsIdx(0) { Roots[0] = Roots[1] = 0; }
412 ArrayRef<const CodeGenRegister*> getRoots() const {
413 assert(!(Roots[1] && !Roots[0]) && "Invalid roots array");
414 return makeArrayRef(Roots, !!Roots[0] + !!Roots[1]);
418 // Each RegUnitSet is a sorted vector with a name.
420 typedef std::vector<unsigned>::const_iterator iterator;
423 std::vector<unsigned> Units;
426 // Base vector for identifying TopoSigs. The contents uniquely identify a
427 // TopoSig, only computeSuperRegs needs to know how.
428 typedef SmallVector<unsigned, 16> TopoSigId;
430 // CodeGenRegBank - Represent a target's registers and the relations between
432 class CodeGenRegBank {
436 std::vector<CodeGenSubRegIndex*> SubRegIndices;
437 DenseMap<Record*, CodeGenSubRegIndex*> Def2SubRegIdx;
439 CodeGenSubRegIndex *createSubRegIndex(StringRef Name, StringRef NameSpace);
441 typedef std::map<SmallVector<CodeGenSubRegIndex*, 8>,
442 CodeGenSubRegIndex*> ConcatIdxMap;
443 ConcatIdxMap ConcatIdx;
446 std::vector<CodeGenRegister*> Registers;
447 StringMap<CodeGenRegister*> RegistersByName;
448 DenseMap<Record*, CodeGenRegister*> Def2Reg;
449 unsigned NumNativeRegUnits;
451 std::map<TopoSigId, unsigned> TopoSigs;
453 // Includes native (0..NumNativeRegUnits-1) and adopted register units.
454 SmallVector<RegUnit, 8> RegUnits;
457 std::vector<CodeGenRegisterClass*> RegClasses;
458 DenseMap<Record*, CodeGenRegisterClass*> Def2RC;
459 typedef std::map<CodeGenRegisterClass::Key, CodeGenRegisterClass*> RCKeyMap;
462 // Remember each unique set of register units. Initially, this contains a
463 // unique set for each register class. Simliar sets are coalesced with
464 // pruneUnitSets and new supersets are inferred during computeRegUnitSets.
465 std::vector<RegUnitSet> RegUnitSets;
467 // Map RegisterClass index to the index of the RegUnitSet that contains the
468 // class's units and any inferred RegUnit supersets.
470 // NOTE: This could grow beyond the number of register classes when we map
471 // register units to lists of unit sets. If the list of unit sets does not
472 // already exist for a register class, we create a new entry in this vector.
473 std::vector<std::vector<unsigned> > RegClassUnitSets;
475 // Add RC to *2RC maps.
476 void addToMaps(CodeGenRegisterClass*);
478 // Create a synthetic sub-class if it is missing.
479 CodeGenRegisterClass *getOrCreateSubClass(const CodeGenRegisterClass *RC,
480 const CodeGenRegister::Set *Membs,
483 // Infer missing register classes.
484 void computeInferredRegisterClasses();
485 void inferCommonSubClass(CodeGenRegisterClass *RC);
486 void inferSubClassWithSubReg(CodeGenRegisterClass *RC);
487 void inferMatchingSuperRegClass(CodeGenRegisterClass *RC,
488 unsigned FirstSubRegRC = 0);
490 // Iteratively prune unit sets.
491 void pruneUnitSets();
493 // Compute a weight for each register unit created during getSubRegs.
494 void computeRegUnitWeights();
496 // Create a RegUnitSet for each RegClass and infer superclasses.
497 void computeRegUnitSets();
499 // Populate the Composite map from sub-register relationships.
500 void computeComposites();
502 // Compute a lane mask for each sub-register index.
503 void computeSubRegIndexLaneMasks();
506 CodeGenRegBank(RecordKeeper&);
508 SetTheory &getSets() { return Sets; }
510 // Sub-register indices. The first NumNamedIndices are defined by the user
511 // in the .td files. The rest are synthesized such that all sub-registers
512 // have a unique name.
513 ArrayRef<CodeGenSubRegIndex*> getSubRegIndices() { return SubRegIndices; }
515 // Find a SubRegIndex form its Record def.
516 CodeGenSubRegIndex *getSubRegIdx(Record*);
518 // Find or create a sub-register index representing the A+B composition.
519 CodeGenSubRegIndex *getCompositeSubRegIndex(CodeGenSubRegIndex *A,
520 CodeGenSubRegIndex *B);
522 // Find or create a sub-register index representing the concatenation of
523 // non-overlapping sibling indices.
525 getConcatSubRegIndex(const SmallVector<CodeGenSubRegIndex*, 8>&);
528 addConcatSubRegIndex(const SmallVector<CodeGenSubRegIndex*, 8> &Parts,
529 CodeGenSubRegIndex *Idx) {
530 ConcatIdx.insert(std::make_pair(Parts, Idx));
533 const std::vector<CodeGenRegister*> &getRegisters() { return Registers; }
534 const StringMap<CodeGenRegister*> &getRegistersByName() {
535 return RegistersByName;
538 // Find a register from its Record def.
539 CodeGenRegister *getReg(Record*);
541 // Get a Register's index into the Registers array.
542 unsigned getRegIndex(const CodeGenRegister *Reg) const {
543 return Reg->EnumValue - 1;
546 // Return the number of allocated TopoSigs. The first TopoSig representing
547 // leaf registers is allocated number 0.
548 unsigned getNumTopoSigs() const {
549 return TopoSigs.size();
552 // Find or create a TopoSig for the given TopoSigId.
553 // This function is only for use by CodeGenRegister::computeSuperRegs().
554 // Others should simply use Reg->getTopoSig().
555 unsigned getTopoSig(const TopoSigId &Id) {
556 return TopoSigs.insert(std::make_pair(Id, TopoSigs.size())).first->second;
559 // Create a native register unit that is associated with one or two root
561 unsigned newRegUnit(CodeGenRegister *R0, CodeGenRegister *R1 = 0) {
562 RegUnits.resize(RegUnits.size() + 1);
563 RegUnits.back().Roots[0] = R0;
564 RegUnits.back().Roots[1] = R1;
565 return RegUnits.size() - 1;
568 // Create a new non-native register unit that can be adopted by a register
569 // to increase its pressure. Note that NumNativeRegUnits is not increased.
570 unsigned newRegUnit(unsigned Weight) {
571 RegUnits.resize(RegUnits.size() + 1);
572 RegUnits.back().Weight = Weight;
573 return RegUnits.size() - 1;
576 // Native units are the singular unit of a leaf register. Register aliasing
577 // is completely characterized by native units. Adopted units exist to give
578 // register additional weight but don't affect aliasing.
579 bool isNativeUnit(unsigned RUID) {
580 return RUID < NumNativeRegUnits;
583 unsigned getNumNativeRegUnits() const {
584 return NumNativeRegUnits;
587 RegUnit &getRegUnit(unsigned RUID) { return RegUnits[RUID]; }
588 const RegUnit &getRegUnit(unsigned RUID) const { return RegUnits[RUID]; }
590 ArrayRef<CodeGenRegisterClass*> getRegClasses() const {
594 // Find a register class from its def.
595 CodeGenRegisterClass *getRegClass(Record*);
597 /// getRegisterClassForRegister - Find the register class that contains the
598 /// specified physical register. If the register is not in a register
599 /// class, return null. If the register is in multiple classes, and the
600 /// classes have a superset-subset relationship and the same set of types,
601 /// return the superclass. Otherwise return null.
602 const CodeGenRegisterClass* getRegClassForRegister(Record *R);
604 // Get the sum of unit weights.
605 unsigned getRegUnitSetWeight(const std::vector<unsigned> &Units) const {
607 for (std::vector<unsigned>::const_iterator
608 I = Units.begin(), E = Units.end(); I != E; ++I)
609 Weight += getRegUnit(*I).Weight;
613 // Increase a RegUnitWeight.
614 void increaseRegUnitWeight(unsigned RUID, unsigned Inc) {
615 getRegUnit(RUID).Weight += Inc;
618 // Get the number of register pressure dimensions.
619 unsigned getNumRegPressureSets() const { return RegUnitSets.size(); }
621 // Get a set of register unit IDs for a given dimension of pressure.
622 RegUnitSet getRegPressureSet(unsigned Idx) const {
623 return RegUnitSets[Idx];
626 // The number of pressure set lists may be larget than the number of
627 // register classes if some register units appeared in a list of sets that
628 // did not correspond to an existing register class.
629 unsigned getNumRegClassPressureSetLists() const {
630 return RegClassUnitSets.size();
633 // Get a list of pressure set IDs for a register class. Liveness of a
634 // register in this class impacts each pressure set in this list by the
635 // weight of the register. An exact solution requires all registers in a
636 // class to have the same class, but it is not strictly guaranteed.
637 ArrayRef<unsigned> getRCPressureSetIDs(unsigned RCIdx) const {
638 return RegClassUnitSets[RCIdx];
641 // Computed derived records such as missing sub-register indices.
642 void computeDerivedInfo();
644 // Compute the set of registers completely covered by the registers in Regs.
645 // The returned BitVector will have a bit set for each register in Regs,
646 // all sub-registers, and all super-registers that are covered by the
647 // registers in Regs.
649 // This is used to compute the mask of call-preserved registers from a list
651 BitVector computeCoveredRegisters(ArrayRef<Record*> Regs);