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