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