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
20 #include "CodeGenTarget.h"
21 #include "CodeGenIntrinsics.h"
30 class TreePatternNode;
31 class CodeGenDAGPatterns;
34 /// EMVT::DAGISelGenValueType - These are some extended forms of
35 /// MVT::SimpleValueType that we use as lattice values during type inference.
37 enum DAGISelGenValueType {
38 isFP = MVT::LAST_VALUETYPE,
43 /// isExtIntegerVT - Return true if the specified extended value type vector
44 /// contains isInt or an integer value type.
45 bool isExtIntegerInVTs(const std::vector<unsigned char> &EVTs);
47 /// isExtFloatingPointVT - Return true if the specified extended value type
48 /// vector contains isFP or a FP value type.
49 bool isExtFloatingPointInVTs(const std::vector<unsigned char> &EVTs);
52 /// Set type used to track multiply used variables in patterns
53 typedef std::set<std::string> MultipleUseVarSet;
55 /// SDTypeConstraint - This is a discriminated union of constraints,
56 /// corresponding to the SDTypeConstraint tablegen class in Target.td.
57 struct SDTypeConstraint {
58 SDTypeConstraint(Record *R);
60 unsigned OperandNo; // The operand # this constraint applies to.
62 SDTCisVT, SDTCisPtrTy, SDTCisInt, SDTCisFP, SDTCisSameAs,
63 SDTCisVTSmallerThanOp, SDTCisOpSmallerThanOp, SDTCisIntVectorOfSameSize,
67 union { // The discriminated union.
72 unsigned OtherOperandNum;
75 unsigned OtherOperandNum;
76 } SDTCisVTSmallerThanOp_Info;
78 unsigned BigOperandNum;
79 } SDTCisOpSmallerThanOp_Info;
81 unsigned OtherOperandNum;
82 } SDTCisIntVectorOfSameSize_Info;
84 unsigned OtherOperandNum;
85 } SDTCisEltOfVec_Info;
88 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
89 /// constraint to the nodes operands. This returns true if it makes a
90 /// change, false otherwise. If a type contradiction is found, throw an
92 bool ApplyTypeConstraint(TreePatternNode *N, const SDNodeInfo &NodeInfo,
93 TreePattern &TP) const;
95 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
96 /// N, which has NumResults results.
97 TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
98 unsigned NumResults) const;
101 /// SDNodeInfo - One of these records is created for each SDNode instance in
102 /// the target .td file. This represents the various dag nodes we will be
106 std::string EnumName;
107 std::string SDClassName;
111 std::vector<SDTypeConstraint> TypeConstraints;
113 SDNodeInfo(Record *R); // Parse the specified record.
115 unsigned getNumResults() const { return NumResults; }
116 int getNumOperands() const { return NumOperands; }
117 Record *getRecord() const { return Def; }
118 const std::string &getEnumName() const { return EnumName; }
119 const std::string &getSDClassName() const { return SDClassName; }
121 const std::vector<SDTypeConstraint> &getTypeConstraints() const {
122 return TypeConstraints;
125 /// hasProperty - Return true if this node has the specified property.
127 bool hasProperty(enum SDNP Prop) const { return Properties & (1 << Prop); }
129 /// ApplyTypeConstraints - Given a node in a pattern, apply the type
130 /// constraints for this node to the operands of the node. This returns
131 /// true if it makes a change, false otherwise. If a type contradiction is
132 /// found, throw an exception.
133 bool ApplyTypeConstraints(TreePatternNode *N, TreePattern &TP) const {
134 bool MadeChange = false;
135 for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i)
136 MadeChange |= TypeConstraints[i].ApplyTypeConstraint(N, *this, TP);
141 /// FIXME: TreePatternNode's can be shared in some cases (due to dag-shaped
142 /// patterns), and as such should be ref counted. We currently just leak all
143 /// TreePatternNode objects!
144 class TreePatternNode {
145 /// The inferred type for this node, or EMVT::isUnknown if it hasn't
146 /// been determined yet.
147 std::vector<unsigned char> Types;
149 /// Operator - The Record for the operator if this is an interior node (not
153 /// Val - The init value (e.g. the "GPRC" record, or "7") for a leaf.
157 /// Name - The name given to this node with the :$foo notation.
161 /// PredicateFn - The predicate function to execute on this node to check
162 /// for a match. If this string is empty, no predicate is involved.
163 std::string PredicateFn;
165 /// TransformFn - The transformation function to execute on this node before
166 /// it can be substituted into the resulting instruction on a pattern match.
169 std::vector<TreePatternNode*> Children;
171 TreePatternNode(Record *Op, const std::vector<TreePatternNode*> &Ch)
172 : Types(), Operator(Op), Val(0), TransformFn(0),
173 Children(Ch) { Types.push_back(EMVT::isUnknown); }
174 TreePatternNode(Init *val) // leaf ctor
175 : Types(), Operator(0), Val(val), TransformFn(0) {
176 Types.push_back(EMVT::isUnknown);
180 const std::string &getName() const { return Name; }
181 void setName(const std::string &N) { Name = N; }
183 bool isLeaf() const { return Val != 0; }
184 bool hasTypeSet() const {
185 return (Types[0] < MVT::LAST_VALUETYPE) || (Types[0] == MVT::iPTR) ||
186 (Types[0] == MVT::iPTRAny);
188 bool isTypeCompletelyUnknown() const {
189 return Types[0] == EMVT::isUnknown;
191 bool isTypeDynamicallyResolved() const {
192 return (Types[0] == MVT::iPTR) || (Types[0] == MVT::iPTRAny);
194 MVT::SimpleValueType 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::SimpleValueType)Types[Num];
199 unsigned char getExtTypeNum(unsigned Num) const {
200 assert(Types.size() > Num && "Extended type num out of range!");
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, EMVT::isUnknown); }
207 Init *getLeafValue() const { assert(isLeaf()); return Val; }
208 Record *getOperator() const { assert(!isLeaf()); return Operator; }
210 unsigned getNumChildren() const { return Children.size(); }
211 TreePatternNode *getChild(unsigned N) const { return Children[N]; }
212 void setChild(unsigned i, TreePatternNode *N) {
216 const std::string &getPredicateFn() const { return PredicateFn; }
217 void setPredicateFn(const std::string &Fn) { PredicateFn = Fn; }
219 Record *getTransformFn() const { return TransformFn; }
220 void setTransformFn(Record *Fn) { TransformFn = Fn; }
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;
226 /// isCommutativeIntrinsic - Return true if the node is an intrinsic which is
227 /// marked isCommutative.
228 bool isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const;
230 void print(std::ostream &OS) const;
233 public: // Higher level manipulation routines.
235 /// clone - Return a new copy of this tree.
237 TreePatternNode *clone() const;
239 /// isIsomorphicTo - Return true if this node is recursively isomorphic to
240 /// the specified node. For this comparison, all of the state of the node
241 /// is considered, except for the assigned name. Nodes with differing names
242 /// that are otherwise identical are considered isomorphic.
243 bool isIsomorphicTo(const TreePatternNode *N,
244 const MultipleUseVarSet &DepVars) const;
246 /// SubstituteFormalArguments - Replace the formal arguments in this tree
247 /// with actual values specified by ArgMap.
248 void SubstituteFormalArguments(std::map<std::string,
249 TreePatternNode*> &ArgMap);
251 /// InlinePatternFragments - If this pattern refers to any pattern
252 /// fragments, inline them into place, giving us a pattern without any
253 /// PatFrag references.
254 TreePatternNode *InlinePatternFragments(TreePattern &TP);
256 /// ApplyTypeConstraints - Apply all of the type constraints relevent to
257 /// this node and its children in the tree. This returns true if it makes a
258 /// change, false otherwise. If a type contradiction is found, throw an
260 bool ApplyTypeConstraints(TreePattern &TP, bool NotRegisters);
262 /// UpdateNodeType - Set the node type of N to VT if VT contains
263 /// information. If N already contains a conflicting type, then throw an
264 /// exception. This returns true if any information was updated.
266 bool UpdateNodeType(const std::vector<unsigned char> &ExtVTs,
268 bool UpdateNodeType(unsigned char ExtVT, TreePattern &TP) {
269 std::vector<unsigned char> ExtVTs(1, ExtVT);
270 return UpdateNodeType(ExtVTs, TP);
273 /// ContainsUnresolvedType - Return true if this tree contains any
274 /// unresolved types.
275 bool ContainsUnresolvedType() const {
276 if (!hasTypeSet() && !isTypeDynamicallyResolved()) return true;
277 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
278 if (getChild(i)->ContainsUnresolvedType()) return true;
282 /// canPatternMatch - If it is impossible for this pattern to match on this
283 /// target, fill in Reason and return false. Otherwise, return true.
284 bool canPatternMatch(std::string &Reason, const CodeGenDAGPatterns &CDP);
288 /// TreePattern - Represent a pattern, used for instructions, pattern
292 /// Trees - The list of pattern trees which corresponds to this pattern.
293 /// Note that PatFrag's only have a single tree.
295 std::vector<TreePatternNode*> Trees;
297 /// TheRecord - The actual TableGen record corresponding to this pattern.
301 /// Args - This is a list of all of the arguments to this pattern (for
302 /// PatFrag patterns), which are the 'node' markers in this pattern.
303 std::vector<std::string> Args;
305 /// CDP - the top-level object coordinating this madness.
307 CodeGenDAGPatterns &CDP;
309 /// isInputPattern - True if this is an input pattern, something to match.
310 /// False if this is an output pattern, something to emit.
314 /// TreePattern constructor - Parse the specified DagInits into the
316 TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
317 CodeGenDAGPatterns &ise);
318 TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
319 CodeGenDAGPatterns &ise);
320 TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
321 CodeGenDAGPatterns &ise);
323 /// getTrees - Return the tree patterns which corresponds to this pattern.
325 const std::vector<TreePatternNode*> &getTrees() const { return Trees; }
326 unsigned getNumTrees() const { return Trees.size(); }
327 TreePatternNode *getTree(unsigned i) const { return Trees[i]; }
328 TreePatternNode *getOnlyTree() const {
329 assert(Trees.size() == 1 && "Doesn't have exactly one pattern!");
333 /// getRecord - Return the actual TableGen record corresponding to this
336 Record *getRecord() const { return TheRecord; }
338 unsigned getNumArgs() const { return Args.size(); }
339 const std::string &getArgName(unsigned i) const {
340 assert(i < Args.size() && "Argument reference out of range!");
343 std::vector<std::string> &getArgList() { return Args; }
345 CodeGenDAGPatterns &getDAGPatterns() const { return CDP; }
347 /// InlinePatternFragments - If this pattern refers to any pattern
348 /// fragments, inline them into place, giving us a pattern without any
349 /// PatFrag references.
350 void InlinePatternFragments() {
351 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
352 Trees[i] = Trees[i]->InlinePatternFragments(*this);
355 /// InferAllTypes - Infer/propagate as many types throughout the expression
356 /// patterns as possible. Return true if all types are infered, false
357 /// otherwise. Throw an exception if a type contradiction is found.
358 bool InferAllTypes();
360 /// error - Throw an exception, prefixing it with information about this
362 void error(const std::string &Msg) const;
364 void print(std::ostream &OS) const;
368 TreePatternNode *ParseTreePattern(DagInit *DI);
371 /// DAGDefaultOperand - One of these is created for each PredicateOperand
372 /// or OptionalDefOperand that has a set ExecuteAlways / DefaultOps field.
373 struct DAGDefaultOperand {
374 std::vector<TreePatternNode*> DefaultOps;
377 class DAGInstruction {
378 TreePattern *Pattern;
379 std::vector<Record*> Results;
380 std::vector<Record*> Operands;
381 std::vector<Record*> ImpResults;
382 std::vector<Record*> ImpOperands;
383 TreePatternNode *ResultPattern;
385 DAGInstruction(TreePattern *TP,
386 const std::vector<Record*> &results,
387 const std::vector<Record*> &operands,
388 const std::vector<Record*> &impresults,
389 const std::vector<Record*> &impoperands)
390 : Pattern(TP), Results(results), Operands(operands),
391 ImpResults(impresults), ImpOperands(impoperands),
394 const TreePattern *getPattern() const { return Pattern; }
395 unsigned getNumResults() const { return Results.size(); }
396 unsigned getNumOperands() const { return Operands.size(); }
397 unsigned getNumImpResults() const { return ImpResults.size(); }
398 unsigned getNumImpOperands() const { return ImpOperands.size(); }
399 const std::vector<Record*>& getImpResults() const { return ImpResults; }
401 void setResultPattern(TreePatternNode *R) { ResultPattern = R; }
403 Record *getResult(unsigned RN) const {
404 assert(RN < Results.size());
408 Record *getOperand(unsigned ON) const {
409 assert(ON < Operands.size());
413 Record *getImpResult(unsigned RN) const {
414 assert(RN < ImpResults.size());
415 return ImpResults[RN];
418 Record *getImpOperand(unsigned ON) const {
419 assert(ON < ImpOperands.size());
420 return ImpOperands[ON];
423 TreePatternNode *getResultPattern() const { return ResultPattern; }
426 /// PatternToMatch - Used by CodeGenDAGPatterns to keep tab of patterns
427 /// processed to produce isel.
428 struct PatternToMatch {
429 PatternToMatch(ListInit *preds,
430 TreePatternNode *src, TreePatternNode *dst,
431 const std::vector<Record*> &dstregs,
432 unsigned complexity):
433 Predicates(preds), SrcPattern(src), DstPattern(dst), Dstregs(dstregs),
434 AddedComplexity(complexity) {};
436 ListInit *Predicates; // Top level predicate conditions to match.
437 TreePatternNode *SrcPattern; // Source pattern to match.
438 TreePatternNode *DstPattern; // Resulting pattern.
439 std::vector<Record*> Dstregs; // Physical register defs being matched.
440 unsigned AddedComplexity; // Add to matching pattern complexity.
442 ListInit *getPredicates() const { return Predicates; }
443 TreePatternNode *getSrcPattern() const { return SrcPattern; }
444 TreePatternNode *getDstPattern() const { return DstPattern; }
445 const std::vector<Record*> &getDstRegs() const { return Dstregs; }
446 unsigned getAddedComplexity() const { return AddedComplexity; }
448 std::string getPredicateCheck() const;
452 class CodeGenDAGPatterns {
453 RecordKeeper &Records;
454 CodeGenTarget Target;
455 std::vector<CodeGenIntrinsic> Intrinsics;
457 std::map<Record*, SDNodeInfo> SDNodes;
458 std::map<Record*, std::pair<Record*, std::string> > SDNodeXForms;
459 std::map<Record*, ComplexPattern> ComplexPatterns;
460 std::map<Record*, TreePattern*> PatternFragments;
461 std::map<Record*, DAGDefaultOperand> DefaultOperands;
462 std::map<Record*, DAGInstruction> Instructions;
464 // Specific SDNode definitions:
465 Record *intrinsic_void_sdnode;
466 Record *intrinsic_w_chain_sdnode, *intrinsic_wo_chain_sdnode;
468 /// PatternsToMatch - All of the things we are matching on the DAG. The first
469 /// value is the pattern to match, the second pattern is the result to
471 std::vector<PatternToMatch> PatternsToMatch;
473 CodeGenDAGPatterns(RecordKeeper &R);
474 ~CodeGenDAGPatterns();
476 CodeGenTarget &getTargetInfo() { return Target; }
477 const CodeGenTarget &getTargetInfo() const { return Target; }
479 Record *getSDNodeNamed(const std::string &Name) const;
481 const SDNodeInfo &getSDNodeInfo(Record *R) const {
482 assert(SDNodes.count(R) && "Unknown node!");
483 return SDNodes.find(R)->second;
486 // Node transformation lookups.
487 typedef std::pair<Record*, std::string> NodeXForm;
488 const NodeXForm &getSDNodeTransform(Record *R) const {
489 assert(SDNodeXForms.count(R) && "Invalid transform!");
490 return SDNodeXForms.find(R)->second;
493 typedef std::map<Record*, NodeXForm>::const_iterator nx_iterator;
494 nx_iterator nx_begin() const { return SDNodeXForms.begin(); }
495 nx_iterator nx_end() const { return SDNodeXForms.end(); }
498 const ComplexPattern &getComplexPattern(Record *R) const {
499 assert(ComplexPatterns.count(R) && "Unknown addressing mode!");
500 return ComplexPatterns.find(R)->second;
503 const CodeGenIntrinsic &getIntrinsic(Record *R) const {
504 for (unsigned i = 0, e = Intrinsics.size(); i != e; ++i)
505 if (Intrinsics[i].TheDef == R) return Intrinsics[i];
506 assert(0 && "Unknown intrinsic!");
510 const CodeGenIntrinsic &getIntrinsicInfo(unsigned IID) const {
511 assert(IID-1 < Intrinsics.size() && "Bad intrinsic ID!");
512 return Intrinsics[IID-1];
515 unsigned getIntrinsicID(Record *R) const {
516 for (unsigned i = 0, e = Intrinsics.size(); i != e; ++i)
517 if (Intrinsics[i].TheDef == R) return i;
518 assert(0 && "Unknown intrinsic!");
522 const DAGDefaultOperand &getDefaultOperand(Record *R) {
523 assert(DefaultOperands.count(R) &&"Isn't an analyzed default operand!");
524 return DefaultOperands.find(R)->second;
527 // Pattern Fragment information.
528 TreePattern *getPatternFragment(Record *R) const {
529 assert(PatternFragments.count(R) && "Invalid pattern fragment request!");
530 return PatternFragments.find(R)->second;
532 typedef std::map<Record*, TreePattern*>::const_iterator pf_iterator;
533 pf_iterator pf_begin() const { return PatternFragments.begin(); }
534 pf_iterator pf_end() const { return PatternFragments.end(); }
536 // Patterns to match information.
537 typedef std::vector<PatternToMatch>::const_iterator ptm_iterator;
538 ptm_iterator ptm_begin() const { return PatternsToMatch.begin(); }
539 ptm_iterator ptm_end() const { return PatternsToMatch.end(); }
543 const DAGInstruction &getInstruction(Record *R) const {
544 assert(Instructions.count(R) && "Unknown instruction!");
545 return Instructions.find(R)->second;
548 Record *get_intrinsic_void_sdnode() const {
549 return intrinsic_void_sdnode;
551 Record *get_intrinsic_w_chain_sdnode() const {
552 return intrinsic_w_chain_sdnode;
554 Record *get_intrinsic_wo_chain_sdnode() const {
555 return intrinsic_wo_chain_sdnode;
559 void ParseNodeInfo();
560 void ParseNodeTransforms();
561 void ParseComplexPatterns();
562 void ParsePatternFragments();
563 void ParseDefaultOperands();
564 void ParseInstructions();
565 void ParsePatterns();
566 void InferInstructionFlags();
567 void GenerateVariants();
569 void FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
570 std::map<std::string,
571 TreePatternNode*> &InstInputs,
572 std::map<std::string,
573 TreePatternNode*> &InstResults,
574 std::vector<Record*> &InstImpInputs,
575 std::vector<Record*> &InstImpResults);
577 } // end namespace llvm