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