4b2a2fb769e2f84576c7da3ec9710bd293a42a0b
[oota-llvm.git] / utils / TableGen / DAGISelEmitter.h
1 //===- DAGISelEmitter.h - Generate an instruction selector ------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This tablegen backend emits a DAG instruction selector.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef DAGISEL_EMITTER_H
15 #define DAGISEL_EMITTER_H
16
17 #include "TableGenBackend.h"
18 #include "CodeGenTarget.h"
19
20 namespace llvm {
21   class Record;
22   struct Init;
23   class ListInit;
24   class DagInit;
25   class SDNodeInfo;
26   class TreePattern;
27   class TreePatternNode;
28   class DAGISelEmitter;
29   
30   /// SDTypeConstraint - This is a discriminated union of constraints,
31   /// corresponding to the SDTypeConstraint tablegen class in Target.td.
32   struct SDTypeConstraint {
33     SDTypeConstraint(Record *R);
34     
35     unsigned OperandNo;   // The operand # this constraint applies to.
36     enum { 
37       SDTCisVT, SDTCisInt, SDTCisFP, SDTCisSameAs, SDTCisVTSmallerThanOp,
38       SDTCisOpSmallerThanOp
39     } ConstraintType;
40     
41     union {   // The discriminated union.
42       struct {
43         MVT::ValueType VT;
44       } SDTCisVT_Info;
45       struct {
46         unsigned OtherOperandNum;
47       } SDTCisSameAs_Info;
48       struct {
49         unsigned OtherOperandNum;
50       } SDTCisVTSmallerThanOp_Info;
51       struct {
52         unsigned BigOperandNum;
53       } SDTCisOpSmallerThanOp_Info;
54     } x;
55
56     /// ApplyTypeConstraint - Given a node in a pattern, apply this type
57     /// constraint to the nodes operands.  This returns true if it makes a
58     /// change, false otherwise.  If a type contradiction is found, throw an
59     /// exception.
60     bool ApplyTypeConstraint(TreePatternNode *N, const SDNodeInfo &NodeInfo,
61                              TreePattern &TP) const;
62     
63     /// getOperandNum - Return the node corresponding to operand #OpNo in tree
64     /// N, which has NumResults results.
65     TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
66                                    unsigned NumResults) const;
67   };
68   
69   /// SDNodeInfo - One of these records is created for each SDNode instance in
70   /// the target .td file.  This represents the various dag nodes we will be
71   /// processing.
72   class SDNodeInfo {
73     Record *Def;
74     std::string EnumName;
75     std::string SDClassName;
76     unsigned Properties;
77     unsigned NumResults;
78     int NumOperands;
79     std::vector<SDTypeConstraint> TypeConstraints;
80   public:
81     SDNodeInfo(Record *R);  // Parse the specified record.
82     
83     unsigned getNumResults() const { return NumResults; }
84     int getNumOperands() const { return NumOperands; }
85     Record *getRecord() const { return Def; }
86     const std::string &getEnumName() const { return EnumName; }
87     const std::string &getSDClassName() const { return SDClassName; }
88     
89     const std::vector<SDTypeConstraint> &getTypeConstraints() const {
90       return TypeConstraints;
91     }
92     
93     // SelectionDAG node properties.
94     enum SDNP { SDNPCommutative, SDNPAssociative };
95
96     /// hasProperty - Return true if this node has the specified property.
97     ///
98     bool hasProperty(enum SDNP Prop) const { return Properties & (1 << Prop); }
99
100     /// ApplyTypeConstraints - Given a node in a pattern, apply the type
101     /// constraints for this node to the operands of the node.  This returns
102     /// true if it makes a change, false otherwise.  If a type contradiction is
103     /// found, throw an exception.
104     bool ApplyTypeConstraints(TreePatternNode *N, TreePattern &TP) const {
105       bool MadeChange = false;
106       for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i)
107         MadeChange |= TypeConstraints[i].ApplyTypeConstraint(N, *this, TP);
108       return MadeChange;
109     }
110   };
111
112   /// FIXME: TreePatternNode's can be shared in some cases (due to dag-shaped
113   /// patterns), and as such should be ref counted.  We currently just leak all
114   /// TreePatternNode objects!
115   class TreePatternNode {
116     /// The inferred type for this node, or MVT::LAST_VALUETYPE if it hasn't
117     /// been determined yet.
118     MVT::ValueType Ty;
119
120     /// Operator - The Record for the operator if this is an interior node (not
121     /// a leaf).
122     Record *Operator;
123     
124     /// Val - The init value (e.g. the "GPRC" record, or "7") for a leaf.
125     ///
126     Init *Val;
127     
128     /// Name - The name given to this node with the :$foo notation.
129     ///
130     std::string Name;
131     
132     /// PredicateFn - The predicate function to execute on this node to check
133     /// for a match.  If this string is empty, no predicate is involved.
134     std::string PredicateFn;
135     
136     /// TransformFn - The transformation function to execute on this node before
137     /// it can be substituted into the resulting instruction on a pattern match.
138     Record *TransformFn;
139     
140     std::vector<TreePatternNode*> Children;
141   public:
142     TreePatternNode(Record *Op, const std::vector<TreePatternNode*> &Ch) 
143       : Ty(MVT::LAST_VALUETYPE), Operator(Op), Val(0), TransformFn(0),
144         Children(Ch) {}
145     TreePatternNode(Init *val)    // leaf ctor
146       : Ty(MVT::LAST_VALUETYPE), Operator(0), Val(val), TransformFn(0) {}
147     ~TreePatternNode();
148     
149     const std::string &getName() const { return Name; }
150     void setName(const std::string &N) { Name = N; }
151     
152     bool isLeaf() const { return Val != 0; }
153     bool hasTypeSet() const { return Ty != MVT::LAST_VALUETYPE; }
154     MVT::ValueType getType() const { return Ty; }
155     void setType(MVT::ValueType VT) { Ty = VT; }
156     
157     Init *getLeafValue() const { assert(isLeaf()); return Val; }
158     Record *getOperator() const { assert(!isLeaf()); return Operator; }
159     
160     unsigned getNumChildren() const { return Children.size(); }
161     TreePatternNode *getChild(unsigned N) const { return Children[N]; }
162     void setChild(unsigned i, TreePatternNode *N) {
163       Children[i] = N;
164     }
165     
166     const std::string &getPredicateFn() const { return PredicateFn; }
167     void setPredicateFn(const std::string &Fn) { PredicateFn = Fn; }
168
169     Record *getTransformFn() const { return TransformFn; }
170     void setTransformFn(Record *Fn) { TransformFn = Fn; }
171     
172     void print(std::ostream &OS) const;
173     void dump() const;
174     
175   public:   // Higher level manipulation routines.
176
177     /// clone - Return a new copy of this tree.
178     ///
179     TreePatternNode *clone() const;
180     
181     /// isIsomorphicTo - Return true if this node is recursively isomorphic to
182     /// the specified node.  For this comparison, all of the state of the node
183     /// is considered, except for the assigned name.  Nodes with differing names
184     /// that are otherwise identical are considered isomorphic.
185     bool isIsomorphicTo(const TreePatternNode *N) const;
186     
187     /// SubstituteFormalArguments - Replace the formal arguments in this tree
188     /// with actual values specified by ArgMap.
189     void SubstituteFormalArguments(std::map<std::string,
190                                             TreePatternNode*> &ArgMap);
191
192     /// InlinePatternFragments - If this pattern refers to any pattern
193     /// fragments, inline them into place, giving us a pattern without any
194     /// PatFrag references.
195     TreePatternNode *InlinePatternFragments(TreePattern &TP);
196     
197     /// ApplyTypeConstraints - Apply all of the type constraints relevent to
198     /// this node and its children in the tree.  This returns true if it makes a
199     /// change, false otherwise.  If a type contradiction is found, throw an
200     /// exception.
201     bool ApplyTypeConstraints(TreePattern &TP, bool NotRegisters);
202     
203     /// UpdateNodeType - Set the node type of N to VT if VT contains
204     /// information.  If N already contains a conflicting type, then throw an
205     /// exception.  This returns true if any information was updated.
206     ///
207     bool UpdateNodeType(MVT::ValueType VT, TreePattern &TP);
208     
209     /// ContainsUnresolvedType - Return true if this tree contains any
210     /// unresolved types.
211     bool ContainsUnresolvedType() const {
212       if (Ty == MVT::LAST_VALUETYPE) return true;
213       for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
214         if (getChild(i)->ContainsUnresolvedType()) return true;
215       return false;
216     }
217     
218     /// canPatternMatch - If it is impossible for this pattern to match on this
219     /// target, fill in Reason and return false.  Otherwise, return true.
220     bool canPatternMatch(std::string &Reason, DAGISelEmitter &ISE);
221   };
222   
223   
224   /// TreePattern - Represent a pattern, used for instructions, pattern
225   /// fragments, etc.
226   ///
227   class TreePattern {
228     /// Trees - The list of pattern trees which corresponds to this pattern.
229     /// Note that PatFrag's only have a single tree.
230     ///
231     std::vector<TreePatternNode*> Trees;
232     
233     /// TheRecord - The actual TableGen record corresponding to this pattern.
234     ///
235     Record *TheRecord;
236       
237     /// Args - This is a list of all of the arguments to this pattern (for
238     /// PatFrag patterns), which are the 'node' markers in this pattern.
239     std::vector<std::string> Args;
240     
241     /// ISE - the DAG isel emitter coordinating this madness.
242     ///
243     DAGISelEmitter &ISE;
244   public:
245       
246     /// TreePattern constructor - Parse the specified DagInits into the
247     /// current record.
248     TreePattern(Record *TheRec, ListInit *RawPat, DAGISelEmitter &ise);
249     TreePattern(Record *TheRec, DagInit *Pat, DAGISelEmitter &ise);
250     TreePattern(Record *TheRec, TreePatternNode *Pat, DAGISelEmitter &ise);
251         
252     /// getTrees - Return the tree patterns which corresponds to this pattern.
253     ///
254     const std::vector<TreePatternNode*> &getTrees() const { return Trees; }
255     unsigned getNumTrees() const { return Trees.size(); }
256     TreePatternNode *getTree(unsigned i) const { return Trees[i]; }
257     TreePatternNode *getOnlyTree() const {
258       assert(Trees.size() == 1 && "Doesn't have exactly one pattern!");
259       return Trees[0];
260     }
261         
262     /// getRecord - Return the actual TableGen record corresponding to this
263     /// pattern.
264     ///
265     Record *getRecord() const { return TheRecord; }
266     
267     unsigned getNumArgs() const { return Args.size(); }
268     const std::string &getArgName(unsigned i) const {
269       assert(i < Args.size() && "Argument reference out of range!");
270       return Args[i];
271     }
272     std::vector<std::string> &getArgList() { return Args; }
273     
274     DAGISelEmitter &getDAGISelEmitter() const { return ISE; }
275
276     /// InlinePatternFragments - If this pattern refers to any pattern
277     /// fragments, inline them into place, giving us a pattern without any
278     /// PatFrag references.
279     void InlinePatternFragments() {
280       for (unsigned i = 0, e = Trees.size(); i != e; ++i)
281         Trees[i] = Trees[i]->InlinePatternFragments(*this);
282     }
283     
284     /// InferAllTypes - Infer/propagate as many types throughout the expression
285     /// patterns as possible.  Return true if all types are infered, false
286     /// otherwise.  Throw an exception if a type contradiction is found.
287     bool InferAllTypes();
288     
289     /// error - Throw an exception, prefixing it with information about this
290     /// pattern.
291     void error(const std::string &Msg) const;
292     
293     void print(std::ostream &OS) const;
294     void dump() const;
295     
296   private:
297     TreePatternNode *ParseTreePattern(DagInit *DI);
298   };
299
300
301   class DAGInstruction {
302     TreePattern *Pattern;
303     unsigned NumResults;
304     unsigned NumOperands;
305     std::vector<MVT::ValueType> ResultTypes;
306     std::vector<MVT::ValueType> OperandTypes;
307     TreePatternNode *ResultPattern;
308   public:
309     DAGInstruction(TreePattern *TP,
310                    const std::vector<MVT::ValueType> &resultTypes,
311                    const std::vector<MVT::ValueType> &operandTypes)
312       : Pattern(TP), ResultTypes(resultTypes), OperandTypes(operandTypes), 
313         ResultPattern(0) {}
314
315     TreePattern *getPattern() const { return Pattern; }
316     unsigned getNumResults() const { return ResultTypes.size(); }
317     unsigned getNumOperands() const { return OperandTypes.size(); }
318     
319     void setResultPattern(TreePatternNode *R) { ResultPattern = R; }
320     
321     MVT::ValueType getResultType(unsigned RN) const {
322       assert(RN < ResultTypes.size());
323       return ResultTypes[RN];
324     }
325     
326     MVT::ValueType getOperandType(unsigned ON) const {
327       assert(ON < OperandTypes.size());
328       return OperandTypes[ON];
329     }
330     TreePatternNode *getResultPattern() const { return ResultPattern; }
331   };
332   
333   
334 /// InstrSelectorEmitter - The top-level class which coordinates construction
335 /// and emission of the instruction selector.
336 ///
337 class DAGISelEmitter : public TableGenBackend {
338 public:
339   typedef std::pair<TreePatternNode*, TreePatternNode*> PatternToMatch;
340 private:
341   RecordKeeper &Records;
342   CodeGenTarget Target;
343
344   std::map<Record*, SDNodeInfo> SDNodes;
345   std::map<Record*, std::pair<Record*, std::string> > SDNodeXForms;
346   std::map<Record*, TreePattern*> PatternFragments;
347   std::map<Record*, DAGInstruction> Instructions;
348   
349   /// PatternsToMatch - All of the things we are matching on the DAG.  The first
350   /// value is the pattern to match, the second pattern is the result to
351   /// emit.
352   std::vector<PatternToMatch> PatternsToMatch;
353 public:
354   DAGISelEmitter(RecordKeeper &R) : Records(R) {}
355
356   // run - Output the isel, returning true on failure.
357   void run(std::ostream &OS);
358   
359   const CodeGenTarget &getTargetInfo() const { return Target; }
360   
361   const SDNodeInfo &getSDNodeInfo(Record *R) const {
362     assert(SDNodes.count(R) && "Unknown node!");
363     return SDNodes.find(R)->second;
364   }
365
366   TreePattern *getPatternFragment(Record *R) const {
367     assert(PatternFragments.count(R) && "Invalid pattern fragment request!");
368     return PatternFragments.find(R)->second;
369   }
370   
371   const std::pair<Record*, std::string> &getSDNodeTransform(Record *R) const {
372     assert(SDNodeXForms.count(R) && "Invalid transform!");
373     return SDNodeXForms.find(R)->second;
374   }
375   
376   const DAGInstruction &getInstruction(Record *R) const {
377     assert(Instructions.count(R) && "Unknown instruction!");
378     return Instructions.find(R)->second;
379   }
380   
381 private:
382   void ParseNodeInfo();
383   void ParseNodeTransforms(std::ostream &OS);
384   void ParsePatternFragments(std::ostream &OS);
385   void ParseInstructions();
386   void ParsePatterns();
387   void GenerateVariants();
388   void FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
389                                    std::map<std::string,
390                                             TreePatternNode*> &InstInputs,
391                                    std::map<std::string, Record*> &InstResults);
392   void EmitMatchForPattern(TreePatternNode *N, const std::string &RootName,
393                            std::map<std::string,std::string> &VarMap,
394                            unsigned PatternNo, std::ostream &OS);
395   unsigned CodeGenPatternResult(TreePatternNode *N, unsigned &Ctr,
396                                 std::map<std::string,std::string> &VariableMap, 
397                                 std::ostream &OS);      
398   void EmitCodeForPattern(PatternToMatch &Pattern, std::ostream &OS);
399   void EmitInstructionSelector(std::ostream &OS);
400 };
401
402 } // End llvm namespace
403
404 #endif