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