ec0231ad12c2cde8c038dfd87cee722b3d65d1bd
[oota-llvm.git] / support / tools / TableGen / InstrSelectorEmitter.h
1 //===- InstrInfoEmitter.h - Generate a Instruction Set Desc. ----*- C++ -*-===//
2 //
3 // This tablegen backend is responsible for emitting a description of the target
4 // instruction set for the code generator.
5 //
6 //===----------------------------------------------------------------------===//
7
8 #ifndef INSTRSELECTOR_EMITTER_H
9 #define INSTRSELECTOR_EMITTER_H
10
11 #include "TableGenBackend.h"
12 #include "CodeGenWrappers.h"
13 #include <vector>
14 #include <map>
15 class DagInit;
16 class Init;
17 class InstrSelectorEmitter;
18
19 /// NodeType - Represents Information parsed from the DagNode entries.
20 ///
21 struct NodeType {
22   enum ArgResultTypes {
23     // Both argument and return types...
24     Val,            // A non-void type
25     Arg0,           // Value matches the type of Arg0
26     Ptr,            // Tree node is the type of the target pointer
27
28     // Return types
29     Void,           // Tree node always returns void
30   };
31
32   ArgResultTypes ResultType;
33   std::vector<ArgResultTypes> ArgTypes;
34
35   NodeType(ArgResultTypes RT, std::vector<ArgResultTypes> &AT) : ResultType(RT){
36     AT.swap(ArgTypes);
37   }
38
39   NodeType() : ResultType(Val) {}
40   NodeType(const NodeType &N) : ResultType(N.ResultType), ArgTypes(N.ArgTypes){}
41
42   static ArgResultTypes Translate(Record *R);
43 };
44
45
46
47 /// TreePatternNode - Represent a node of the tree patterns.
48 ///
49 class TreePatternNode {
50   /// Operator - The operation that this node represents... this is null if this
51   /// is a leaf.
52   Record *Operator;
53
54   /// Type - The inferred value type...
55   ///
56   MVT::ValueType                Type;
57
58   /// Children - If this is not a leaf (Operator != 0), this is the subtrees
59   /// that we contain.
60   std::vector<TreePatternNode*> Children;
61
62   /// Value - If this node is a leaf, this indicates what the thing is.
63   ///
64   Init *Value;
65 public:
66   TreePatternNode(Record *o, const std::vector<TreePatternNode*> &c)
67     : Operator(o), Type(MVT::Other), Children(c), Value(0) {}
68   TreePatternNode(Init *V) : Operator(0), Type(MVT::Other), Value(V) {}
69
70   Record *getOperator() const {
71     assert(Operator && "This is a leaf node!");
72     return Operator;
73   }
74   MVT::ValueType getType() const { return Type; }
75   void setType(MVT::ValueType T) { Type = T; }
76
77   bool isLeaf() const { return Operator == 0; }
78
79   const std::vector<TreePatternNode*> &getChildren() const {
80     assert(Operator != 0 && "This is a leaf node!");
81     return Children;
82   }
83   unsigned getNumChildren() const { return Children.size(); }
84   TreePatternNode *getChild(unsigned c) const {
85     assert(c < Children.size() && "Child access out of range!");
86     return getChildren()[c];
87   }
88
89   Init *getValue() const {
90     assert(Operator == 0 && "This is not a leaf node!");
91     return Value;
92   }
93
94   /// getValueRecord - Returns the value of this tree node as a record.  For now
95   /// we only allow DefInit's as our leaf values, so this is used.
96   Record *getValueRecord() const;
97
98   /// clone - Make a copy of this tree and all of its children.
99   ///
100   TreePatternNode *clone() const;
101
102   void dump() const;
103
104   /// InstantiateNonterminals - If this pattern refers to any nonterminals which
105   /// are not themselves completely resolved, clone the nonterminal and resolve
106   /// it with the using context we provide.
107   void InstantiateNonterminals(InstrSelectorEmitter &ISE);
108
109   /// UpdateNodeType - Set the node type of N to VT if VT contains information.
110   /// If N already contains a conflicting type, then throw an exception.  This
111   /// returns true if any information was updated.
112   ///
113   bool updateNodeType(MVT::ValueType VT, const std::string &RecName);
114 };
115
116 std::ostream &operator<<(std::ostream &OS, const TreePatternNode &N);
117
118
119
120 /// Pattern - Represent a pattern of one form or another.  Currently, three
121 /// types of patterns are possible: Instruction's, Nonterminals, and Expanders.
122 ///
123 struct Pattern {
124   enum PatternType {
125     Nonterminal, Instruction, Expander
126   };
127 private:
128   /// PTy - The type of pattern this is.
129   ///
130   PatternType PTy;
131
132   /// Tree - The tree pattern which corresponds to this pattern.  Note that if
133   /// there was a (set) node on the outside level that it has been stripped off.
134   ///
135   TreePatternNode *Tree;
136   
137   /// Result - If this is an instruction or expander pattern, this is the
138   /// register result, specified with a (set) in the pattern.
139   ///
140   Record *Result;
141
142   /// TheRecord - The actual TableGen record corresponding to this pattern.
143   ///
144   Record *TheRecord;
145
146   /// Resolved - This is true of the pattern is useful in practice.  In
147   /// particular, some non-terminals will have non-resolvable types.  When a
148   /// user of the non-terminal is later found, they will have inferred a type
149   /// for the result of the non-terminal, which cause a clone of an unresolved
150   /// nonterminal to be made which is "resolved".
151   ///
152   bool Resolved;
153
154   /// ISE - the instruction selector emitter coordinating this madness.
155   ///
156   InstrSelectorEmitter &ISE;
157 public:
158
159   /// Pattern constructor - Parse the specified DagInitializer into the current
160   /// record.
161   Pattern(PatternType pty, DagInit *RawPat, Record *TheRec,
162           InstrSelectorEmitter &ise);
163
164   /// Pattern - Constructor used for cloning nonterminal patterns
165   Pattern(TreePatternNode *tree, Record *rec, bool res,
166           InstrSelectorEmitter &ise) : PTy(Nonterminal), Tree(tree), Result(0),
167                                        TheRecord(rec), Resolved(res), ISE(ise){}
168
169   /// getPatternType - Return what flavor of Record this pattern originated from
170   ///
171   PatternType getPatternType() const { return PTy; }
172
173   /// getTree - Return the tree pattern which corresponds to this pattern.
174   ///
175   TreePatternNode *getTree() const { return Tree; }
176   
177   Record *getResult() const { return Result; }
178
179   /// getRecord - Return the actual TableGen record corresponding to this
180   /// pattern.
181   ///
182   Record *getRecord() const { return TheRecord; }
183
184   bool isResolved() const { return Resolved; }
185
186   /// InferAllTypes - Runs the type inference engine on the current pattern,
187   /// stopping when nothing can be inferred, then updating the Resolved field.
188   void InferAllTypes();
189
190   /// InstantiateNonterminals - If this pattern refers to any nonterminals which
191   /// are not themselves completely resolved, clone the nonterminal and resolve
192   /// it with the using context we provide.
193   void InstantiateNonterminals() {
194     Tree->InstantiateNonterminals(ISE);
195   }
196
197   /// clone - This method is used to make an exact copy of the current pattern,
198   /// then change the "TheRecord" instance variable to the specified record.
199   ///
200   Pattern *clone(Record *R) const;
201
202   /// error - Throw an exception, prefixing it with information about this
203   /// pattern.
204   void error(const std::string &Msg) const;
205
206   /// getSlotName - If this is a leaf node, return the slot name that the
207   /// operand will update.
208   std::string getSlotName() const;
209   static std::string getSlotName(Record *R);
210
211   void dump() const;
212
213 private:
214   MVT::ValueType getIntrinsicType(Record *R) const;
215   TreePatternNode *ParseTreePattern(DagInit *DI);
216   bool InferTypes(TreePatternNode *N, bool &MadeChange);
217 };
218
219 std::ostream &operator<<(std::ostream &OS, const Pattern &P);
220
221
222 /// PatternOrganizer - This class represents all of the patterns which are
223 /// useful for the instruction selector, neatly catagorized in a hierarchical
224 /// structure.
225 struct PatternOrganizer {
226   /// PatternsForNode - The list of patterns which can produce a value of a
227   /// particular slot type, given a particular root node in the tree.  All of
228   /// the patterns in this vector produce the same value type and have the same
229   /// root DAG node.
230   typedef std::vector<Pattern*> PatternsForNode;
231
232   /// NodesForSlot - This map keeps track of all of the root DAG nodes which can
233   /// lead to the production of a value for this slot.  All of the patterns in
234   /// this data structure produces values of the same slot.
235   typedef std::map<Record*, PatternsForNode> NodesForSlot;
236
237   /// AllPatterns - This data structure contains all patterns in the instruction
238   /// selector.
239   std::map<std::string, NodesForSlot> AllPatterns;
240
241   // Forwarding functions...
242   typedef std::map<std::string, NodesForSlot>::iterator iterator;
243   iterator begin() { return AllPatterns.begin(); }
244   iterator end()   { return AllPatterns.end(); }
245
246
247   /// addPattern - Add the specified pattern to the appropriate location in the
248   /// collection.
249   void addPattern(Pattern *P);
250 };
251
252
253 /// InstrSelectorEmitter - The top-level class which coordinates construction
254 /// and emission of the instruction selector.
255 ///
256 class InstrSelectorEmitter : public TableGenBackend {
257   RecordKeeper &Records;
258   CodeGenTarget Target;
259
260   std::map<Record*, NodeType> NodeTypes;
261
262   /// Patterns - a list of all of the patterns defined by the target description
263   ///
264   std::map<Record*, Pattern*> Patterns;
265
266   /// InstantiatedNTs - A data structure to keep track of which nonterminals
267   /// have been instantiated already...
268   ///
269   std::map<std::pair<Pattern*,MVT::ValueType>, Record*> InstantiatedNTs;
270
271   /// ComputableValues - This map indicates which patterns can be used to
272   /// generate a value that is used by the selector.  The keys of this map
273   /// implicitly define the values that are used by the selector.
274   ///
275   PatternOrganizer ComputableValues;
276
277 public:
278   InstrSelectorEmitter(RecordKeeper &R) : Records(R) {}
279   
280   // run - Output the instruction set description, returning true on failure.
281   void run(std::ostream &OS);
282
283   const CodeGenTarget &getTarget() const { return Target; }
284   std::map<Record*, NodeType> &getNodeTypes() { return NodeTypes; }
285   const NodeType &getNodeType(Record *R) const {
286     std::map<Record*, NodeType>::const_iterator I = NodeTypes.find(R);
287     assert(I != NodeTypes.end() && "Unknown node type!");
288     return I->second;
289   }
290
291   /// getPattern - return the pattern corresponding to the specified record, or
292   /// null if there is none.
293   Pattern *getPattern(Record *R) const {
294     std::map<Record*, Pattern*>::const_iterator I = Patterns.find(R);
295     return I != Patterns.end() ? I->second : 0;
296   }
297
298   /// ReadNonterminal - This method parses the specified record as a
299   /// nonterminal, but only if it hasn't been read in already.
300   Pattern *ReadNonterminal(Record *R);
301
302   /// InstantiateNonterminal - This method takes the nonterminal specified by
303   /// NT, which should not be completely resolved, clones it, applies ResultTy
304   /// to its root, then runs the type inference stuff on it.  This should
305   /// produce a newly resolved nonterminal, which we make a record for and
306   /// return.  To be extra fancy and efficient, this only makes one clone for
307   /// each type it is instantiated with.
308   Record *InstantiateNonterminal(Pattern *NT, MVT::ValueType ResultTy);
309
310 private:
311   // ReadNodeTypes - Read in all of the node types in the current RecordKeeper,
312   // turning them into the more accessible NodeTypes data structure.
313   void ReadNodeTypes();
314
315   // ReadNonTerminals - Read in all nonterminals and incorporate them into our
316   // pattern database.
317   void ReadNonterminals();
318
319   // ReadInstructionPatterns - Read in all subclasses of Instruction, and
320   // process those with a useful Pattern field.
321   void ReadInstructionPatterns();
322
323   // ReadExpanderPatterns - Read in all of the expanded patterns.
324   void ReadExpanderPatterns();
325
326   // InstantiateNonterminals - Instantiate any unresolved nonterminals with
327   // information from the context that they are used in.
328   void InstantiateNonterminals();
329   
330   // CalculateComputableValues - Fill in the ComputableValues map through
331   // analysis of the patterns we are playing with.
332   void CalculateComputableValues();
333
334   // EmitMatchCosters - Given a list of patterns, which all have the same root
335   // pattern operator, emit an efficient decision tree to decide which one to
336   // pick.  This is structured this way to avoid reevaluations of non-obvious
337   // subexpressions.
338   void EmitMatchCosters(std::ostream &OS,
339             const std::vector<std::pair<Pattern*, TreePatternNode*> > &Patterns,
340                         const std::string &VarPrefix, unsigned Indent);
341 };
342
343 #endif