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