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