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