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