Tablegen support for insert & extract element matching
[oota-llvm.git] / utils / TableGen / CodeGenDAGPatterns.h
1 //===- CodeGenDAGPatterns.h - Read DAG patterns from .td file ---*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file declares the CodeGenDAGPatterns class, which is used to read and
11 // represent the patterns present in a .td file for instructions.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef CODEGEN_DAGPATTERNS_H
16 #define CODEGEN_DAGPATTERNS_H
17
18 #include "TableGenBackend.h"
19 #include "CodeGenTarget.h"
20 #include "CodeGenIntrinsics.h"
21
22 namespace llvm {
23   class Record;
24   struct Init;
25   class ListInit;
26   class DagInit;
27   class SDNodeInfo;
28   class TreePattern;
29   class TreePatternNode;
30   class CodeGenDAGPatterns;
31   class ComplexPattern;
32
33 /// MVT::DAGISelGenValueType - These are some extended forms of MVT::ValueType
34 /// that we use as lattice values during type inferrence.
35 namespace MVT {
36   enum DAGISelGenValueType {
37     isFP  = MVT::LAST_VALUETYPE,
38     isInt,
39     isUnknown
40   };
41   
42   /// isExtIntegerVT - Return true if the specified extended value type vector
43   /// contains isInt or an integer value type.
44   bool isExtIntegerInVTs(const std::vector<unsigned char> &EVTs);
45
46   /// isExtFloatingPointVT - Return true if the specified extended value type 
47   /// vector contains isFP or a FP value type.
48   bool isExtFloatingPointInVTs(const std::vector<unsigned char> &EVTs);
49 }
50
51 /// SDTypeConstraint - This is a discriminated union of constraints,
52 /// corresponding to the SDTypeConstraint tablegen class in Target.td.
53 struct SDTypeConstraint {
54   SDTypeConstraint(Record *R);
55   
56   unsigned OperandNo;   // The operand # this constraint applies to.
57   enum { 
58     SDTCisVT, SDTCisPtrTy, SDTCisInt, SDTCisFP, SDTCisSameAs, 
59     SDTCisVTSmallerThanOp, SDTCisOpSmallerThanOp, SDTCisIntVectorOfSameSize,
60     SDTCisEltOfVec
61   } ConstraintType;
62   
63   union {   // The discriminated union.
64     struct {
65       MVT::ValueType VT;
66     } SDTCisVT_Info;
67     struct {
68       unsigned OtherOperandNum;
69     } SDTCisSameAs_Info;
70     struct {
71       unsigned OtherOperandNum;
72     } SDTCisVTSmallerThanOp_Info;
73     struct {
74       unsigned BigOperandNum;
75     } SDTCisOpSmallerThanOp_Info;
76     struct {
77       unsigned OtherOperandNum;
78     } SDTCisIntVectorOfSameSize_Info;
79     struct {
80       unsigned OtherOperandNum;
81     } SDTCisEltOfVec_Info;
82   } x;
83
84   /// ApplyTypeConstraint - Given a node in a pattern, apply this type
85   /// constraint to the nodes operands.  This returns true if it makes a
86   /// change, false otherwise.  If a type contradiction is found, throw an
87   /// exception.
88   bool ApplyTypeConstraint(TreePatternNode *N, const SDNodeInfo &NodeInfo,
89                            TreePattern &TP) const;
90   
91   /// getOperandNum - Return the node corresponding to operand #OpNo in tree
92   /// N, which has NumResults results.
93   TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
94                                  unsigned NumResults) const;
95 };
96
97 /// SDNodeInfo - One of these records is created for each SDNode instance in
98 /// the target .td file.  This represents the various dag nodes we will be
99 /// processing.
100 class SDNodeInfo {
101   Record *Def;
102   std::string EnumName;
103   std::string SDClassName;
104   unsigned Properties;
105   unsigned NumResults;
106   int NumOperands;
107   std::vector<SDTypeConstraint> TypeConstraints;
108 public:
109   SDNodeInfo(Record *R);  // Parse the specified record.
110   
111   unsigned getNumResults() const { return NumResults; }
112   int getNumOperands() const { return NumOperands; }
113   Record *getRecord() const { return Def; }
114   const std::string &getEnumName() const { return EnumName; }
115   const std::string &getSDClassName() const { return SDClassName; }
116   
117   const std::vector<SDTypeConstraint> &getTypeConstraints() const {
118     return TypeConstraints;
119   }
120   
121   /// hasProperty - Return true if this node has the specified property.
122   ///
123   bool hasProperty(enum SDNP Prop) const { return Properties & (1 << Prop); }
124
125   /// ApplyTypeConstraints - Given a node in a pattern, apply the type
126   /// constraints for this node to the operands of the node.  This returns
127   /// true if it makes a change, false otherwise.  If a type contradiction is
128   /// found, throw an exception.
129   bool ApplyTypeConstraints(TreePatternNode *N, TreePattern &TP) const {
130     bool MadeChange = false;
131     for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i)
132       MadeChange |= TypeConstraints[i].ApplyTypeConstraint(N, *this, TP);
133     return MadeChange;
134   }
135 };
136
137 /// FIXME: TreePatternNode's can be shared in some cases (due to dag-shaped
138 /// patterns), and as such should be ref counted.  We currently just leak all
139 /// TreePatternNode objects!
140 class TreePatternNode {
141   /// The inferred type for this node, or MVT::isUnknown if it hasn't
142   /// been determined yet.
143   std::vector<unsigned char> Types;
144   
145   /// Operator - The Record for the operator if this is an interior node (not
146   /// a leaf).
147   Record *Operator;
148   
149   /// Val - The init value (e.g. the "GPRC" record, or "7") for a leaf.
150   ///
151   Init *Val;
152   
153   /// Name - The name given to this node with the :$foo notation.
154   ///
155   std::string Name;
156   
157   /// PredicateFn - The predicate function to execute on this node to check
158   /// for a match.  If this string is empty, no predicate is involved.
159   std::string PredicateFn;
160   
161   /// TransformFn - The transformation function to execute on this node before
162   /// it can be substituted into the resulting instruction on a pattern match.
163   Record *TransformFn;
164   
165   std::vector<TreePatternNode*> Children;
166 public:
167   TreePatternNode(Record *Op, const std::vector<TreePatternNode*> &Ch) 
168     : Types(), Operator(Op), Val(0), TransformFn(0),
169     Children(Ch) { Types.push_back(MVT::isUnknown); }
170   TreePatternNode(Init *val)    // leaf ctor
171     : Types(), Operator(0), Val(val), TransformFn(0) {
172     Types.push_back(MVT::isUnknown);
173   }
174   ~TreePatternNode();
175   
176   const std::string &getName() const { return Name; }
177   void setName(const std::string &N) { Name = N; }
178   
179   bool isLeaf() const { return Val != 0; }
180   bool hasTypeSet() const {
181     return (Types[0] < MVT::LAST_VALUETYPE) || (Types[0] == MVT::iPTR);
182   }
183   bool isTypeCompletelyUnknown() const {
184     return Types[0] == MVT::isUnknown;
185   }
186   bool isTypeDynamicallyResolved() const {
187     return Types[0] == MVT::iPTR;
188   }
189   MVT::ValueType getTypeNum(unsigned Num) const {
190     assert(hasTypeSet() && "Doesn't have a type yet!");
191     assert(Types.size() > Num && "Type num out of range!");
192     return (MVT::ValueType)Types[Num];
193   }
194   unsigned char getExtTypeNum(unsigned Num) const { 
195     assert(Types.size() > Num && "Extended type num out of range!");
196     return Types[Num]; 
197   }
198   const std::vector<unsigned char> &getExtTypes() const { return Types; }
199   void setTypes(const std::vector<unsigned char> &T) { Types = T; }
200   void removeTypes() { Types = std::vector<unsigned char>(1,MVT::isUnknown); }
201   
202   Init *getLeafValue() const { assert(isLeaf()); return Val; }
203   Record *getOperator() const { assert(!isLeaf()); return Operator; }
204   
205   unsigned getNumChildren() const { return Children.size(); }
206   TreePatternNode *getChild(unsigned N) const { return Children[N]; }
207   void setChild(unsigned i, TreePatternNode *N) {
208     Children[i] = N;
209   }
210
211   const std::string &getPredicateFn() const { return PredicateFn; }
212   void setPredicateFn(const std::string &Fn) { PredicateFn = Fn; }
213
214   Record *getTransformFn() const { return TransformFn; }
215   void setTransformFn(Record *Fn) { TransformFn = Fn; }
216   
217   /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
218   /// CodeGenIntrinsic information for it, otherwise return a null pointer.
219   const CodeGenIntrinsic *getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const;
220   
221   void print(std::ostream &OS) const;
222   void dump() const;
223   
224 public:   // Higher level manipulation routines.
225
226   /// clone - Return a new copy of this tree.
227   ///
228   TreePatternNode *clone() const;
229   
230   /// isIsomorphicTo - Return true if this node is recursively isomorphic to
231   /// the specified node.  For this comparison, all of the state of the node
232   /// is considered, except for the assigned name.  Nodes with differing names
233   /// that are otherwise identical are considered isomorphic.
234   bool isIsomorphicTo(const TreePatternNode *N) const;
235   
236   /// SubstituteFormalArguments - Replace the formal arguments in this tree
237   /// with actual values specified by ArgMap.
238   void SubstituteFormalArguments(std::map<std::string,
239                                           TreePatternNode*> &ArgMap);
240
241   /// InlinePatternFragments - If this pattern refers to any pattern
242   /// fragments, inline them into place, giving us a pattern without any
243   /// PatFrag references.
244   TreePatternNode *InlinePatternFragments(TreePattern &TP);
245   
246   /// ApplyTypeConstraints - Apply all of the type constraints relevent to
247   /// this node and its children in the tree.  This returns true if it makes a
248   /// change, false otherwise.  If a type contradiction is found, throw an
249   /// exception.
250   bool ApplyTypeConstraints(TreePattern &TP, bool NotRegisters);
251   
252   /// UpdateNodeType - Set the node type of N to VT if VT contains
253   /// information.  If N already contains a conflicting type, then throw an
254   /// exception.  This returns true if any information was updated.
255   ///
256   bool UpdateNodeType(const std::vector<unsigned char> &ExtVTs,
257                       TreePattern &TP);
258   bool UpdateNodeType(unsigned char ExtVT, TreePattern &TP) {
259     std::vector<unsigned char> ExtVTs(1, ExtVT);
260     return UpdateNodeType(ExtVTs, TP);
261   }
262   
263   /// ContainsUnresolvedType - Return true if this tree contains any
264   /// unresolved types.
265   bool ContainsUnresolvedType() const {
266     if (!hasTypeSet() && !isTypeDynamicallyResolved()) return true;
267     for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
268       if (getChild(i)->ContainsUnresolvedType()) return true;
269     return false;
270   }
271   
272   /// canPatternMatch - If it is impossible for this pattern to match on this
273   /// target, fill in Reason and return false.  Otherwise, return true.
274   bool canPatternMatch(std::string &Reason, CodeGenDAGPatterns &CDP);
275 };
276
277
278 /// TreePattern - Represent a pattern, used for instructions, pattern
279 /// fragments, etc.
280 ///
281 class TreePattern {
282   /// Trees - The list of pattern trees which corresponds to this pattern.
283   /// Note that PatFrag's only have a single tree.
284   ///
285   std::vector<TreePatternNode*> Trees;
286   
287   /// TheRecord - The actual TableGen record corresponding to this pattern.
288   ///
289   Record *TheRecord;
290     
291   /// Args - This is a list of all of the arguments to this pattern (for
292   /// PatFrag patterns), which are the 'node' markers in this pattern.
293   std::vector<std::string> Args;
294   
295   /// CDP - the top-level object coordinating this madness.
296   ///
297   CodeGenDAGPatterns &CDP;
298
299   /// isInputPattern - True if this is an input pattern, something to match.
300   /// False if this is an output pattern, something to emit.
301   bool isInputPattern;
302 public:
303     
304   /// TreePattern constructor - Parse the specified DagInits into the
305   /// current record.
306   TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
307               CodeGenDAGPatterns &ise);
308   TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
309               CodeGenDAGPatterns &ise);
310   TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
311               CodeGenDAGPatterns &ise);
312       
313   /// getTrees - Return the tree patterns which corresponds to this pattern.
314   ///
315   const std::vector<TreePatternNode*> &getTrees() const { return Trees; }
316   unsigned getNumTrees() const { return Trees.size(); }
317   TreePatternNode *getTree(unsigned i) const { return Trees[i]; }
318   TreePatternNode *getOnlyTree() const {
319     assert(Trees.size() == 1 && "Doesn't have exactly one pattern!");
320     return Trees[0];
321   }
322       
323   /// getRecord - Return the actual TableGen record corresponding to this
324   /// pattern.
325   ///
326   Record *getRecord() const { return TheRecord; }
327   
328   unsigned getNumArgs() const { return Args.size(); }
329   const std::string &getArgName(unsigned i) const {
330     assert(i < Args.size() && "Argument reference out of range!");
331     return Args[i];
332   }
333   std::vector<std::string> &getArgList() { return Args; }
334   
335   CodeGenDAGPatterns &getDAGPatterns() const { return CDP; }
336
337   /// InlinePatternFragments - If this pattern refers to any pattern
338   /// fragments, inline them into place, giving us a pattern without any
339   /// PatFrag references.
340   void InlinePatternFragments() {
341     for (unsigned i = 0, e = Trees.size(); i != e; ++i)
342       Trees[i] = Trees[i]->InlinePatternFragments(*this);
343   }
344   
345   /// InferAllTypes - Infer/propagate as many types throughout the expression
346   /// patterns as possible.  Return true if all types are infered, false
347   /// otherwise.  Throw an exception if a type contradiction is found.
348   bool InferAllTypes();
349   
350   /// error - Throw an exception, prefixing it with information about this
351   /// pattern.
352   void error(const std::string &Msg) const;
353   
354   void print(std::ostream &OS) const;
355   void dump() const;
356   
357 private:
358   TreePatternNode *ParseTreePattern(DagInit *DI);
359 };
360
361 /// DAGDefaultOperand - One of these is created for each PredicateOperand
362 /// or OptionalDefOperand that has a set ExecuteAlways / DefaultOps field.
363 struct DAGDefaultOperand {
364   std::vector<TreePatternNode*> DefaultOps;
365 };
366
367 class DAGInstruction {
368   TreePattern *Pattern;
369   std::vector<Record*> Results;
370   std::vector<Record*> Operands;
371   std::vector<Record*> ImpResults;
372   std::vector<Record*> ImpOperands;
373   TreePatternNode *ResultPattern;
374 public:
375   DAGInstruction(TreePattern *TP,
376                  const std::vector<Record*> &results,
377                  const std::vector<Record*> &operands,
378                  const std::vector<Record*> &impresults,
379                  const std::vector<Record*> &impoperands)
380     : Pattern(TP), Results(results), Operands(operands), 
381       ImpResults(impresults), ImpOperands(impoperands),
382       ResultPattern(0) {}
383
384   const TreePattern *getPattern() const { return Pattern; }
385   unsigned getNumResults() const { return Results.size(); }
386   unsigned getNumOperands() const { return Operands.size(); }
387   unsigned getNumImpResults() const { return ImpResults.size(); }
388   unsigned getNumImpOperands() const { return ImpOperands.size(); }
389   const std::vector<Record*>& getImpResults() const { return ImpResults; }
390   
391   void setResultPattern(TreePatternNode *R) { ResultPattern = R; }
392   
393   Record *getResult(unsigned RN) const {
394     assert(RN < Results.size());
395     return Results[RN];
396   }
397   
398   Record *getOperand(unsigned ON) const {
399     assert(ON < Operands.size());
400     return Operands[ON];
401   }
402
403   Record *getImpResult(unsigned RN) const {
404     assert(RN < ImpResults.size());
405     return ImpResults[RN];
406   }
407   
408   Record *getImpOperand(unsigned ON) const {
409     assert(ON < ImpOperands.size());
410     return ImpOperands[ON];
411   }
412
413   TreePatternNode *getResultPattern() const { return ResultPattern; }
414 };
415   
416 /// PatternToMatch - Used by CodeGenDAGPatterns to keep tab of patterns
417 /// processed to produce isel.
418 struct PatternToMatch {
419   PatternToMatch(ListInit *preds,
420                  TreePatternNode *src, TreePatternNode *dst,
421                  const std::vector<Record*> &dstregs,
422                  unsigned complexity):
423     Predicates(preds), SrcPattern(src), DstPattern(dst), Dstregs(dstregs),
424     AddedComplexity(complexity) {};
425
426   ListInit        *Predicates;  // Top level predicate conditions to match.
427   TreePatternNode *SrcPattern;  // Source pattern to match.
428   TreePatternNode *DstPattern;  // Resulting pattern.
429   std::vector<Record*> Dstregs; // Physical register defs being matched.
430   unsigned         AddedComplexity; // Add to matching pattern complexity.
431
432   ListInit        *getPredicates() const { return Predicates; }
433   TreePatternNode *getSrcPattern() const { return SrcPattern; }
434   TreePatternNode *getDstPattern() const { return DstPattern; }
435   const std::vector<Record*> &getDstRegs() const { return Dstregs; }
436   unsigned         getAddedComplexity() const { return AddedComplexity; }
437 };
438
439   
440 class CodeGenDAGPatterns {
441   RecordKeeper &Records;
442   CodeGenTarget Target;
443   std::vector<CodeGenIntrinsic> Intrinsics;
444   
445   std::map<Record*, SDNodeInfo> SDNodes;
446   std::map<Record*, std::pair<Record*, std::string> > SDNodeXForms;
447   std::map<Record*, ComplexPattern> ComplexPatterns;
448   std::map<Record*, TreePattern*> PatternFragments;
449   std::map<Record*, DAGDefaultOperand> DefaultOperands;
450   std::map<Record*, DAGInstruction> Instructions;
451   
452   // Specific SDNode definitions:
453   Record *intrinsic_void_sdnode;
454   Record *intrinsic_w_chain_sdnode, *intrinsic_wo_chain_sdnode;
455   
456   /// PatternsToMatch - All of the things we are matching on the DAG.  The first
457   /// value is the pattern to match, the second pattern is the result to
458   /// emit.
459   std::vector<PatternToMatch> PatternsToMatch;
460 public:
461   CodeGenDAGPatterns(RecordKeeper &R); 
462   ~CodeGenDAGPatterns();
463   
464   const CodeGenTarget &getTargetInfo() const { return Target; }
465   
466   Record *getSDNodeNamed(const std::string &Name) const;
467   
468   const SDNodeInfo &getSDNodeInfo(Record *R) const {
469     assert(SDNodes.count(R) && "Unknown node!");
470     return SDNodes.find(R)->second;
471   }
472   
473   // Node transformation lookups.
474   typedef std::pair<Record*, std::string> NodeXForm;
475   const NodeXForm &getSDNodeTransform(Record *R) const {
476     assert(SDNodeXForms.count(R) && "Invalid transform!");
477     return SDNodeXForms.find(R)->second;
478   }
479   
480   typedef std::map<Record*, NodeXForm>::const_iterator nx_iterator;
481   nx_iterator nx_begin() const { return SDNodeXForms.begin(); }
482   nx_iterator nx_end() const { return SDNodeXForms.end(); }
483
484   
485   const ComplexPattern &getComplexPattern(Record *R) const {
486     assert(ComplexPatterns.count(R) && "Unknown addressing mode!");
487     return ComplexPatterns.find(R)->second;
488   }
489   
490   const CodeGenIntrinsic &getIntrinsic(Record *R) const {
491     for (unsigned i = 0, e = Intrinsics.size(); i != e; ++i)
492       if (Intrinsics[i].TheDef == R) return Intrinsics[i];
493     assert(0 && "Unknown intrinsic!");
494     abort();
495   }
496   
497   const CodeGenIntrinsic &getIntrinsicInfo(unsigned IID) const {
498     assert(IID-1 < Intrinsics.size() && "Bad intrinsic ID!");
499     return Intrinsics[IID-1];
500   }
501   
502   unsigned getIntrinsicID(Record *R) const {
503     for (unsigned i = 0, e = Intrinsics.size(); i != e; ++i)
504       if (Intrinsics[i].TheDef == R) return i;
505     assert(0 && "Unknown intrinsic!");
506     abort();
507   }
508   
509   const DAGDefaultOperand &getDefaultOperand(Record *R) {
510     assert(DefaultOperands.count(R) &&"Isn't an analyzed default operand!");
511     return DefaultOperands.find(R)->second;
512   }
513   
514   // Pattern Fragment information.
515   TreePattern *getPatternFragment(Record *R) const {
516     assert(PatternFragments.count(R) && "Invalid pattern fragment request!");
517     return PatternFragments.find(R)->second;
518   }
519   typedef std::map<Record*, TreePattern*>::const_iterator pf_iterator;
520   pf_iterator pf_begin() const { return PatternFragments.begin(); }
521   pf_iterator pf_end() const { return PatternFragments.end(); }
522
523   // Patterns to match information.
524   typedef std::vector<PatternToMatch>::const_iterator ptm_iterator;
525   ptm_iterator ptm_begin() const { return PatternsToMatch.begin(); }
526   ptm_iterator ptm_end() const { return PatternsToMatch.end(); }
527   
528   
529   
530   const DAGInstruction &getInstruction(Record *R) const {
531     assert(Instructions.count(R) && "Unknown instruction!");
532     return Instructions.find(R)->second;
533   }
534   
535   Record *get_intrinsic_void_sdnode() const {
536     return intrinsic_void_sdnode;
537   }
538   Record *get_intrinsic_w_chain_sdnode() const {
539     return intrinsic_w_chain_sdnode;
540   }
541   Record *get_intrinsic_wo_chain_sdnode() const {
542     return intrinsic_wo_chain_sdnode;
543   }
544   
545 private:
546   void ParseNodeInfo();
547   void ParseNodeTransforms();
548   void ParseComplexPatterns();
549   void ParsePatternFragments();
550   void ParseDefaultOperands();
551   void ParseInstructions();
552   void ParsePatterns();
553   void GenerateVariants();
554   
555   void FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
556                                    std::map<std::string,
557                                    TreePatternNode*> &InstInputs,
558                                    std::map<std::string,
559                                    TreePatternNode*> &InstResults,
560                                    std::vector<Record*> &InstImpInputs,
561                                    std::vector<Record*> &InstImpResults);
562 };
563 } // end namespace llvm
564
565 #endif