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