Remove TargetRegisterClass::SuperRegClasses.
[oota-llvm.git] / utils / TableGen / CodeGenRegisters.h
1 //===- CodeGenRegisters.h - Register and RegisterClass Info -----*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines structures to encapsulate information gleaned from the
11 // target register and register class definitions.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef CODEGEN_REGISTERS_H
16 #define CODEGEN_REGISTERS_H
17
18 #include "SetTheory.h"
19 #include "llvm/TableGen/Record.h"
20 #include "llvm/CodeGen/ValueTypes.h"
21 #include "llvm/ADT/ArrayRef.h"
22 #include "llvm/ADT/BitVector.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/SetVector.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include <cstdlib>
27 #include <map>
28 #include <string>
29 #include <set>
30 #include <vector>
31
32 namespace llvm {
33   class CodeGenRegBank;
34
35   /// CodeGenSubRegIndex - Represents a sub-register index.
36   class CodeGenSubRegIndex {
37     Record *const TheDef;
38     const unsigned EnumValue;
39
40   public:
41     CodeGenSubRegIndex(Record *R, unsigned Enum);
42
43     const std::string &getName() const;
44     std::string getNamespace() const;
45     std::string getQualifiedName() const;
46
47     // Order CodeGenSubRegIndex pointers by EnumValue.
48     struct Less {
49       bool operator()(const CodeGenSubRegIndex *A,
50                       const CodeGenSubRegIndex *B) const {
51         assert(A && B);
52         return A->EnumValue < B->EnumValue;
53       }
54     };
55
56     // Map of composite subreg indices.
57     typedef std::map<CodeGenSubRegIndex*, CodeGenSubRegIndex*, Less> CompMap;
58
59     // Returns the subreg index that results from composing this with Idx.
60     // Returns NULL if this and Idx don't compose.
61     CodeGenSubRegIndex *compose(CodeGenSubRegIndex *Idx) const {
62       CompMap::const_iterator I = Composed.find(Idx);
63       return I == Composed.end() ? 0 : I->second;
64     }
65
66     // Add a composite subreg index: this+A = B.
67     // Return a conflicting composite, or NULL
68     CodeGenSubRegIndex *addComposite(CodeGenSubRegIndex *A,
69                                      CodeGenSubRegIndex *B) {
70       std::pair<CompMap::iterator, bool> Ins =
71         Composed.insert(std::make_pair(A, B));
72       return (Ins.second || Ins.first->second == B) ? 0 : Ins.first->second;
73     }
74
75     // Update the composite maps of components specified in 'ComposedOf'.
76     void updateComponents(CodeGenRegBank&);
77
78     // Clean out redundant composite mappings.
79     void cleanComposites();
80
81     // Return the map of composites.
82     const CompMap &getComposites() const { return Composed; }
83
84   private:
85     CompMap Composed;
86   };
87
88   /// CodeGenRegister - Represents a register definition.
89   struct CodeGenRegister {
90     Record *TheDef;
91     unsigned EnumValue;
92     unsigned CostPerUse;
93     bool CoveredBySubRegs;
94
95     // Map SubRegIndex -> Register.
96     typedef std::map<CodeGenSubRegIndex*, CodeGenRegister*,
97                      CodeGenSubRegIndex::Less> SubRegMap;
98
99     CodeGenRegister(Record *R, unsigned Enum);
100
101     const std::string &getName() const;
102
103     // Get a map of sub-registers computed lazily.
104     // This includes unique entries for all sub-sub-registers.
105     const SubRegMap &getSubRegs(CodeGenRegBank&);
106
107     const SubRegMap &getSubRegs() const {
108       assert(SubRegsComplete && "Must precompute sub-registers");
109       return SubRegs;
110     }
111
112     // Add sub-registers to OSet following a pre-order defined by the .td file.
113     void addSubRegsPreOrder(SetVector<const CodeGenRegister*> &OSet,
114                             CodeGenRegBank&) const;
115
116     // List of super-registers in topological order, small to large.
117     typedef std::vector<const CodeGenRegister*> SuperRegList;
118
119     // Get the list of super-registers. This is valid after getSubReg
120     // visits all registers during RegBank construction.
121     const SuperRegList &getSuperRegs() const {
122       assert(SubRegsComplete && "Must precompute sub-registers");
123       return SuperRegs;
124     }
125
126     // List of register units in ascending order.
127     typedef SmallVector<unsigned, 16> RegUnitList;
128
129     // Get the list of register units.
130     // This is only valid after getSubRegs() completes.
131     const RegUnitList &getRegUnits() const { return RegUnits; }
132
133     // Inherit register units from subregisters.
134     // Return true if the RegUnits changed.
135     bool inheritRegUnits(CodeGenRegBank &RegBank);
136
137     // Adopt a register unit for pressure tracking.
138     // A unit is adopted iff its unit number is >= NumNativeRegUnits.
139     void adoptRegUnit(unsigned RUID) { RegUnits.push_back(RUID); }
140
141     // Get the sum of this register's register unit weights.
142     unsigned getWeight(const CodeGenRegBank &RegBank) const;
143
144     // Order CodeGenRegister pointers by EnumValue.
145     struct Less {
146       bool operator()(const CodeGenRegister *A,
147                       const CodeGenRegister *B) const {
148         assert(A && B);
149         return A->EnumValue < B->EnumValue;
150       }
151     };
152
153     // Canonically ordered set.
154     typedef std::set<const CodeGenRegister*, Less> Set;
155
156   private:
157     bool SubRegsComplete;
158     SubRegMap SubRegs;
159     SuperRegList SuperRegs;
160     RegUnitList RegUnits;
161   };
162
163
164   class CodeGenRegisterClass {
165     CodeGenRegister::Set Members;
166     // Allocation orders. Order[0] always contains all registers in Members.
167     std::vector<SmallVector<Record*, 16> > Orders;
168     // Bit mask of sub-classes including this, indexed by their EnumValue.
169     BitVector SubClasses;
170     // List of super-classes, topologocally ordered to have the larger classes
171     // first.  This is the same as sorting by EnumValue.
172     SmallVector<CodeGenRegisterClass*, 4> SuperClasses;
173     Record *TheDef;
174     std::string Name;
175
176     // For a synthesized class, inherit missing properties from the nearest
177     // super-class.
178     void inheritProperties(CodeGenRegBank&);
179
180     // Map SubRegIndex -> sub-class.  This is the largest sub-class where all
181     // registers have a SubRegIndex sub-register.
182     DenseMap<CodeGenSubRegIndex*, CodeGenRegisterClass*> SubClassWithSubReg;
183
184     // Map SubRegIndex -> set of super-reg classes.  This is all register
185     // classes SuperRC such that:
186     //
187     //   R:SubRegIndex in this RC for all R in SuperRC.
188     //
189     DenseMap<CodeGenSubRegIndex*,
190              SmallPtrSet<CodeGenRegisterClass*, 8> > SuperRegClasses;
191
192   public:
193     unsigned EnumValue;
194     std::string Namespace;
195     std::vector<MVT::SimpleValueType> VTs;
196     unsigned SpillSize;
197     unsigned SpillAlignment;
198     int CopyCost;
199     bool Allocatable;
200     std::string AltOrderSelect;
201
202     // Return the Record that defined this class, or NULL if the class was
203     // created by TableGen.
204     Record *getDef() const { return TheDef; }
205
206     const std::string &getName() const { return Name; }
207     std::string getQualifiedName() const;
208     const std::vector<MVT::SimpleValueType> &getValueTypes() const {return VTs;}
209     unsigned getNumValueTypes() const { return VTs.size(); }
210
211     MVT::SimpleValueType getValueTypeNum(unsigned VTNum) const {
212       if (VTNum < VTs.size())
213         return VTs[VTNum];
214       llvm_unreachable("VTNum greater than number of ValueTypes in RegClass!");
215     }
216
217     // Return true if this this class contains the register.
218     bool contains(const CodeGenRegister*) const;
219
220     // Returns true if RC is a subclass.
221     // RC is a sub-class of this class if it is a valid replacement for any
222     // instruction operand where a register of this classis required. It must
223     // satisfy these conditions:
224     //
225     // 1. All RC registers are also in this.
226     // 2. The RC spill size must not be smaller than our spill size.
227     // 3. RC spill alignment must be compatible with ours.
228     //
229     bool hasSubClass(const CodeGenRegisterClass *RC) const {
230       return SubClasses.test(RC->EnumValue);
231     }
232
233     // getSubClassWithSubReg - Returns the largest sub-class where all
234     // registers have a SubIdx sub-register.
235     CodeGenRegisterClass*
236     getSubClassWithSubReg(CodeGenSubRegIndex *SubIdx) const {
237       return SubClassWithSubReg.lookup(SubIdx);
238     }
239
240     void setSubClassWithSubReg(CodeGenSubRegIndex *SubIdx,
241                                CodeGenRegisterClass *SubRC) {
242       SubClassWithSubReg[SubIdx] = SubRC;
243     }
244
245     // getSuperRegClasses - Returns a bit vector of all register classes
246     // containing only SubIdx super-registers of this class.
247     void getSuperRegClasses(CodeGenSubRegIndex *SubIdx, BitVector &Out) const;
248
249     // addSuperRegClass - Add a class containing only SudIdx super-registers.
250     void addSuperRegClass(CodeGenSubRegIndex *SubIdx,
251                           CodeGenRegisterClass *SuperRC) {
252       SuperRegClasses[SubIdx].insert(SuperRC);
253     }
254
255     // getSubClasses - Returns a constant BitVector of subclasses indexed by
256     // EnumValue.
257     // The SubClasses vector includs an entry for this class.
258     const BitVector &getSubClasses() const { return SubClasses; }
259
260     // getSuperClasses - Returns a list of super classes ordered by EnumValue.
261     // The array does not include an entry for this class.
262     ArrayRef<CodeGenRegisterClass*> getSuperClasses() const {
263       return SuperClasses;
264     }
265
266     // Returns an ordered list of class members.
267     // The order of registers is the same as in the .td file.
268     // No = 0 is the default allocation order, No = 1 is the first alternative.
269     ArrayRef<Record*> getOrder(unsigned No = 0) const {
270         return Orders[No];
271     }
272
273     // Return the total number of allocation orders available.
274     unsigned getNumOrders() const { return Orders.size(); }
275
276     // Get the set of registers.  This set contains the same registers as
277     // getOrder(0).
278     const CodeGenRegister::Set &getMembers() const { return Members; }
279
280     // Populate a unique sorted list of units from a register set.
281     void buildRegUnitSet(std::vector<unsigned> &RegUnits) const;
282
283     CodeGenRegisterClass(CodeGenRegBank&, Record *R);
284
285     // A key representing the parts of a register class used for forming
286     // sub-classes.  Note the ordering provided by this key is not the same as
287     // the topological order used for the EnumValues.
288     struct Key {
289       const CodeGenRegister::Set *Members;
290       unsigned SpillSize;
291       unsigned SpillAlignment;
292
293       Key(const Key &O)
294         : Members(O.Members),
295           SpillSize(O.SpillSize),
296           SpillAlignment(O.SpillAlignment) {}
297
298       Key(const CodeGenRegister::Set *M, unsigned S = 0, unsigned A = 0)
299         : Members(M), SpillSize(S), SpillAlignment(A) {}
300
301       Key(const CodeGenRegisterClass &RC)
302         : Members(&RC.getMembers()),
303           SpillSize(RC.SpillSize),
304           SpillAlignment(RC.SpillAlignment) {}
305
306       // Lexicographical order of (Members, SpillSize, SpillAlignment).
307       bool operator<(const Key&) const;
308     };
309
310     // Create a non-user defined register class.
311     CodeGenRegisterClass(StringRef Name, Key Props);
312
313     // Called by CodeGenRegBank::CodeGenRegBank().
314     static void computeSubClasses(CodeGenRegBank&);
315   };
316
317   // Each RegUnitSet is a sorted vector with a name.
318   struct RegUnitSet {
319     typedef std::vector<unsigned>::const_iterator iterator;
320
321     std::string Name;
322     std::vector<unsigned> Units;
323   };
324
325   // CodeGenRegBank - Represent a target's registers and the relations between
326   // them.
327   class CodeGenRegBank {
328     RecordKeeper &Records;
329     SetTheory Sets;
330
331     // SubRegIndices.
332     std::vector<CodeGenSubRegIndex*> SubRegIndices;
333     DenseMap<Record*, CodeGenSubRegIndex*> Def2SubRegIdx;
334     unsigned NumNamedIndices;
335
336     // Registers.
337     std::vector<CodeGenRegister*> Registers;
338     DenseMap<Record*, CodeGenRegister*> Def2Reg;
339     unsigned NumNativeRegUnits;
340     unsigned NumRegUnits; // # native + adopted register units.
341
342     // Map each register unit to a weight (for register pressure).
343     // Includes native and adopted register units.
344     std::vector<unsigned> RegUnitWeights;
345
346     // Register classes.
347     std::vector<CodeGenRegisterClass*> RegClasses;
348     DenseMap<Record*, CodeGenRegisterClass*> Def2RC;
349     typedef std::map<CodeGenRegisterClass::Key, CodeGenRegisterClass*> RCKeyMap;
350     RCKeyMap Key2RC;
351
352     // Remember each unique set of register units. Initially, this contains a
353     // unique set for each register class. Simliar sets are coalesced with
354     // pruneUnitSets and new supersets are inferred during computeRegUnitSets.
355     std::vector<RegUnitSet> RegUnitSets;
356
357     // Map RegisterClass index to the index of the RegUnitSet that contains the
358     // class's units and any inferred RegUnit supersets.
359     std::vector<std::vector<unsigned> > RegClassUnitSets;
360
361     // Add RC to *2RC maps.
362     void addToMaps(CodeGenRegisterClass*);
363
364     // Create a synthetic sub-class if it is missing.
365     CodeGenRegisterClass *getOrCreateSubClass(const CodeGenRegisterClass *RC,
366                                               const CodeGenRegister::Set *Membs,
367                                               StringRef Name);
368
369     // Infer missing register classes.
370     void computeInferredRegisterClasses();
371     void inferCommonSubClass(CodeGenRegisterClass *RC);
372     void inferSubClassWithSubReg(CodeGenRegisterClass *RC);
373     void inferMatchingSuperRegClass(CodeGenRegisterClass *RC,
374                                     unsigned FirstSubRegRC = 0);
375
376     // Iteratively prune unit sets.
377     void pruneUnitSets();
378
379     // Compute a weight for each register unit created during getSubRegs.
380     void computeRegUnitWeights();
381
382     // Create a RegUnitSet for each RegClass and infer superclasses.
383     void computeRegUnitSets();
384
385     // Populate the Composite map from sub-register relationships.
386     void computeComposites();
387
388   public:
389     CodeGenRegBank(RecordKeeper&);
390
391     SetTheory &getSets() { return Sets; }
392
393     // Sub-register indices. The first NumNamedIndices are defined by the user
394     // in the .td files. The rest are synthesized such that all sub-registers
395     // have a unique name.
396     ArrayRef<CodeGenSubRegIndex*> getSubRegIndices() { return SubRegIndices; }
397     unsigned getNumNamedIndices() { return NumNamedIndices; }
398
399     // Find a SubRegIndex form its Record def.
400     CodeGenSubRegIndex *getSubRegIdx(Record*);
401
402     // Find or create a sub-register index representing the A+B composition.
403     CodeGenSubRegIndex *getCompositeSubRegIndex(CodeGenSubRegIndex *A,
404                                                 CodeGenSubRegIndex *B);
405
406     const std::vector<CodeGenRegister*> &getRegisters() { return Registers; }
407
408     // Find a register from its Record def.
409     CodeGenRegister *getReg(Record*);
410
411     // Get a Register's index into the Registers array.
412     unsigned getRegIndex(const CodeGenRegister *Reg) const {
413       return Reg->EnumValue - 1;
414     }
415
416     // Create a new non-native register unit that can be adopted by a register
417     // to increase its pressure. Note that NumNativeRegUnits is not increased.
418     unsigned newRegUnit(unsigned Weight) {
419       if (!RegUnitWeights.empty()) {
420         assert(Weight && "should only add allocatable units");
421         RegUnitWeights.resize(NumRegUnits+1);
422         RegUnitWeights[NumRegUnits] = Weight;
423       }
424       return NumRegUnits++;
425     }
426
427     // Native units are the singular unit of a leaf register. Register aliasing
428     // is completely characterized by native units. Adopted units exist to give
429     // register additional weight but don't affect aliasing.
430     bool isNativeUnit(unsigned RUID) {
431       return RUID < NumNativeRegUnits;
432     }
433
434     ArrayRef<CodeGenRegisterClass*> getRegClasses() const {
435       return RegClasses;
436     }
437
438     // Find a register class from its def.
439     CodeGenRegisterClass *getRegClass(Record*);
440
441     /// getRegisterClassForRegister - Find the register class that contains the
442     /// specified physical register.  If the register is not in a register
443     /// class, return null. If the register is in multiple classes, and the
444     /// classes have a superset-subset relationship and the same set of types,
445     /// return the superclass.  Otherwise return null.
446     const CodeGenRegisterClass* getRegClassForRegister(Record *R);
447
448     // Get a register unit's weight. Zero for unallocatable registers.
449     unsigned getRegUnitWeight(unsigned RUID) const {
450       return RegUnitWeights[RUID];
451     }
452
453     // Get the sum of unit weights.
454     unsigned getRegUnitSetWeight(const std::vector<unsigned> &Units) const {
455       unsigned Weight = 0;
456       for (std::vector<unsigned>::const_iterator
457              I = Units.begin(), E = Units.end(); I != E; ++I)
458         Weight += getRegUnitWeight(*I);
459       return Weight;
460     }
461
462     // Increase a RegUnitWeight.
463     void increaseRegUnitWeight(unsigned RUID, unsigned Inc) {
464       RegUnitWeights[RUID] += Inc;
465     }
466
467     // Get the number of register pressure dimensions.
468     unsigned getNumRegPressureSets() const { return RegUnitSets.size(); }
469
470     // Get a set of register unit IDs for a given dimension of pressure.
471     RegUnitSet getRegPressureSet(unsigned Idx) const {
472       return RegUnitSets[Idx];
473     }
474
475     // Get a list of pressure set IDs for a register class. Liveness of a
476     // register in this class impacts each pressure set in this list by the
477     // weight of the register. An exact solution requires all registers in a
478     // class to have the same class, but it is not strictly guaranteed.
479     ArrayRef<unsigned> getRCPressureSetIDs(unsigned RCIdx) const {
480       return RegClassUnitSets[RCIdx];
481     }
482
483     // Computed derived records such as missing sub-register indices.
484     void computeDerivedInfo();
485
486     // Compute full overlap sets for every register. These sets include the
487     // rarely used aliases that are neither sub nor super-registers.
488     //
489     // Map[R1].count(R2) is reflexive and symmetric, but not transitive.
490     //
491     // If R1 is a sub-register of R2, Map[R1] is a subset of Map[R2].
492     void computeOverlaps(std::map<const CodeGenRegister*,
493                                   CodeGenRegister::Set> &Map);
494
495     // Compute the set of registers completely covered by the registers in Regs.
496     // The returned BitVector will have a bit set for each register in Regs,
497     // all sub-registers, and all super-registers that are covered by the
498     // registers in Regs.
499     //
500     // This is used to compute the mask of call-preserved registers from a list
501     // of callee-saves.
502     BitVector computeCoveredRegisters(ArrayRef<Record*> Regs);
503   };
504 }
505
506 #endif