1 //===- CodeGenDAGPatterns.h - Read DAG patterns from .td file ---*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file declares the CodeGenDAGPatterns class, which is used to read and
11 // represent the patterns present in a .td file for instructions.
13 //===----------------------------------------------------------------------===//
15 #ifndef CODEGEN_DAGPATTERNS_H
16 #define CODEGEN_DAGPATTERNS_H
18 #include "TableGenBackend.h"
19 #include "CodeGenTarget.h"
20 #include "CodeGenIntrinsics.h"
29 class TreePatternNode;
30 class CodeGenDAGPatterns;
33 /// MVT::DAGISelGenValueType - These are some extended forms of MVT::ValueType
34 /// that we use as lattice values during type inferrence.
36 enum DAGISelGenValueType {
37 isFP = MVT::LAST_VALUETYPE,
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);
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);
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);
56 unsigned OperandNo; // The operand # this constraint applies to.
58 SDTCisVT, SDTCisPtrTy, SDTCisInt, SDTCisFP, SDTCisSameAs,
59 SDTCisVTSmallerThanOp, SDTCisOpSmallerThanOp, SDTCisIntVectorOfSameSize,
63 union { // The discriminated union.
68 unsigned OtherOperandNum;
71 unsigned OtherOperandNum;
72 } SDTCisVTSmallerThanOp_Info;
74 unsigned BigOperandNum;
75 } SDTCisOpSmallerThanOp_Info;
77 unsigned OtherOperandNum;
78 } SDTCisIntVectorOfSameSize_Info;
80 unsigned OtherOperandNum;
81 } SDTCisEltOfVec_Info;
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
88 bool ApplyTypeConstraint(TreePatternNode *N, const SDNodeInfo &NodeInfo,
89 TreePattern &TP) const;
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;
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
102 std::string EnumName;
103 std::string SDClassName;
107 std::vector<SDTypeConstraint> TypeConstraints;
109 SDNodeInfo(Record *R); // Parse the specified record.
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; }
117 const std::vector<SDTypeConstraint> &getTypeConstraints() const {
118 return TypeConstraints;
121 /// hasProperty - Return true if this node has the specified property.
123 bool hasProperty(enum SDNP Prop) const { return Properties & (1 << Prop); }
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);
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;
145 /// Operator - The Record for the operator if this is an interior node (not
149 /// Val - The init value (e.g. the "GPRC" record, or "7") for a leaf.
153 /// Name - The name given to this node with the :$foo notation.
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;
161 /// TransformFn - The transformation function to execute on this node before
162 /// it can be substituted into the resulting instruction on a pattern match.
165 std::vector<TreePatternNode*> Children;
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);
176 const std::string &getName() const { return Name; }
177 void setName(const std::string &N) { Name = N; }
179 bool isLeaf() const { return Val != 0; }
180 bool hasTypeSet() const {
181 return (Types[0] < MVT::LAST_VALUETYPE) || (Types[0] == MVT::iPTR);
183 bool isTypeCompletelyUnknown() const {
184 return Types[0] == MVT::isUnknown;
186 bool isTypeDynamicallyResolved() const {
187 return Types[0] == MVT::iPTR;
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];
194 unsigned char getExtTypeNum(unsigned Num) const {
195 assert(Types.size() > Num && "Extended type num out of range!");
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); }
202 Init *getLeafValue() const { assert(isLeaf()); return Val; }
203 Record *getOperator() const { assert(!isLeaf()); return Operator; }
205 unsigned getNumChildren() const { return Children.size(); }
206 TreePatternNode *getChild(unsigned N) const { return Children[N]; }
207 void setChild(unsigned i, TreePatternNode *N) {
211 const std::string &getPredicateFn() const { return PredicateFn; }
212 void setPredicateFn(const std::string &Fn) { PredicateFn = Fn; }
214 Record *getTransformFn() const { return TransformFn; }
215 void setTransformFn(Record *Fn) { TransformFn = Fn; }
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;
221 void print(std::ostream &OS) const;
224 public: // Higher level manipulation routines.
226 /// clone - Return a new copy of this tree.
228 TreePatternNode *clone() const;
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;
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);
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);
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
250 bool ApplyTypeConstraints(TreePattern &TP, bool NotRegisters);
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.
256 bool UpdateNodeType(const std::vector<unsigned char> &ExtVTs,
258 bool UpdateNodeType(unsigned char ExtVT, TreePattern &TP) {
259 std::vector<unsigned char> ExtVTs(1, ExtVT);
260 return UpdateNodeType(ExtVTs, TP);
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;
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);
278 /// TreePattern - Represent a pattern, used for instructions, pattern
282 /// Trees - The list of pattern trees which corresponds to this pattern.
283 /// Note that PatFrag's only have a single tree.
285 std::vector<TreePatternNode*> Trees;
287 /// TheRecord - The actual TableGen record corresponding to this pattern.
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;
295 /// CDP - the top-level object coordinating this madness.
297 CodeGenDAGPatterns &CDP;
299 /// isInputPattern - True if this is an input pattern, something to match.
300 /// False if this is an output pattern, something to emit.
304 /// TreePattern constructor - Parse the specified DagInits into the
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);
313 /// getTrees - Return the tree patterns which corresponds to this pattern.
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!");
323 /// getRecord - Return the actual TableGen record corresponding to this
326 Record *getRecord() const { return TheRecord; }
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!");
333 std::vector<std::string> &getArgList() { return Args; }
335 CodeGenDAGPatterns &getDAGPatterns() const { return CDP; }
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);
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();
350 /// error - Throw an exception, prefixing it with information about this
352 void error(const std::string &Msg) const;
354 void print(std::ostream &OS) const;
358 TreePatternNode *ParseTreePattern(DagInit *DI);
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;
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;
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),
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; }
391 void setResultPattern(TreePatternNode *R) { ResultPattern = R; }
393 Record *getResult(unsigned RN) const {
394 assert(RN < Results.size());
398 Record *getOperand(unsigned ON) const {
399 assert(ON < Operands.size());
403 Record *getImpResult(unsigned RN) const {
404 assert(RN < ImpResults.size());
405 return ImpResults[RN];
408 Record *getImpOperand(unsigned ON) const {
409 assert(ON < ImpOperands.size());
410 return ImpOperands[ON];
413 TreePatternNode *getResultPattern() const { return ResultPattern; }
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) {};
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.
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; }
440 class CodeGenDAGPatterns {
441 RecordKeeper &Records;
442 CodeGenTarget Target;
443 std::vector<CodeGenIntrinsic> Intrinsics;
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;
452 // Specific SDNode definitions:
453 Record *intrinsic_void_sdnode;
454 Record *intrinsic_w_chain_sdnode, *intrinsic_wo_chain_sdnode;
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
459 std::vector<PatternToMatch> PatternsToMatch;
461 CodeGenDAGPatterns(RecordKeeper &R);
462 ~CodeGenDAGPatterns();
464 const CodeGenTarget &getTargetInfo() const { return Target; }
466 Record *getSDNodeNamed(const std::string &Name) const;
468 const SDNodeInfo &getSDNodeInfo(Record *R) const {
469 assert(SDNodes.count(R) && "Unknown node!");
470 return SDNodes.find(R)->second;
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;
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(); }
485 const ComplexPattern &getComplexPattern(Record *R) const {
486 assert(ComplexPatterns.count(R) && "Unknown addressing mode!");
487 return ComplexPatterns.find(R)->second;
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!");
497 const CodeGenIntrinsic &getIntrinsicInfo(unsigned IID) const {
498 assert(IID-1 < Intrinsics.size() && "Bad intrinsic ID!");
499 return Intrinsics[IID-1];
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!");
509 const DAGDefaultOperand &getDefaultOperand(Record *R) {
510 assert(DefaultOperands.count(R) &&"Isn't an analyzed default operand!");
511 return DefaultOperands.find(R)->second;
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;
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(); }
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(); }
530 const DAGInstruction &getInstruction(Record *R) const {
531 assert(Instructions.count(R) && "Unknown instruction!");
532 return Instructions.find(R)->second;
535 Record *get_intrinsic_void_sdnode() const {
536 return intrinsic_void_sdnode;
538 Record *get_intrinsic_w_chain_sdnode() const {
539 return intrinsic_w_chain_sdnode;
541 Record *get_intrinsic_wo_chain_sdnode() const {
542 return intrinsic_wo_chain_sdnode;
546 void ParseNodeInfo();
547 void ParseNodeTransforms();
548 void ParseComplexPatterns();
549 void ParsePatternFragments();
550 void ParseDefaultOperands();
551 void ParseInstructions();
552 void ParsePatterns();
553 void GenerateVariants();
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);
563 } // end namespace llvm