1 //===- DAGISelEmitter.h - Generate an instruction selector ------*- 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 tablegen backend emits a DAG instruction selector.
12 //===----------------------------------------------------------------------===//
14 #ifndef DAGISEL_EMITTER_H
15 #define DAGISEL_EMITTER_H
17 #include "TableGenBackend.h"
18 #include "CodeGenTarget.h"
19 #include "CodeGenIntrinsics.h"
29 class TreePatternNode;
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,
43 /// SDTypeConstraint - This is a discriminated union of constraints,
44 /// corresponding to the SDTypeConstraint tablegen class in Target.td.
45 struct SDTypeConstraint {
46 SDTypeConstraint(Record *R);
48 unsigned OperandNo; // The operand # this constraint applies to.
50 SDTCisVT, SDTCisPtrTy, SDTCisInt, SDTCisFP, SDTCisSameAs,
51 SDTCisVTSmallerThanOp, SDTCisOpSmallerThanOp, SDTCisIntVectorOfSameSize
54 union { // The discriminated union.
59 unsigned OtherOperandNum;
62 unsigned OtherOperandNum;
63 } SDTCisVTSmallerThanOp_Info;
65 unsigned BigOperandNum;
66 } SDTCisOpSmallerThanOp_Info;
68 unsigned OtherOperandNum;
69 } SDTCisIntVectorOfSameSize_Info;
72 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
73 /// constraint to the nodes operands. This returns true if it makes a
74 /// change, false otherwise. If a type contradiction is found, throw an
76 bool ApplyTypeConstraint(TreePatternNode *N, const SDNodeInfo &NodeInfo,
77 TreePattern &TP) const;
79 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
80 /// N, which has NumResults results.
81 TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
82 unsigned NumResults) const;
85 /// SDNodeInfo - One of these records is created for each SDNode instance in
86 /// the target .td file. This represents the various dag nodes we will be
91 std::string SDClassName;
95 std::vector<SDTypeConstraint> TypeConstraints;
97 SDNodeInfo(Record *R); // Parse the specified record.
99 unsigned getNumResults() const { return NumResults; }
100 int getNumOperands() const { return NumOperands; }
101 Record *getRecord() const { return Def; }
102 const std::string &getEnumName() const { return EnumName; }
103 const std::string &getSDClassName() const { return SDClassName; }
105 const std::vector<SDTypeConstraint> &getTypeConstraints() const {
106 return TypeConstraints;
109 /// hasProperty - Return true if this node has the specified property.
111 bool hasProperty(enum SDNP Prop) const { return Properties & (1 << Prop); }
113 /// ApplyTypeConstraints - Given a node in a pattern, apply the type
114 /// constraints for this node to the operands of the node. This returns
115 /// true if it makes a change, false otherwise. If a type contradiction is
116 /// found, throw an exception.
117 bool ApplyTypeConstraints(TreePatternNode *N, TreePattern &TP) const {
118 bool MadeChange = false;
119 for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i)
120 MadeChange |= TypeConstraints[i].ApplyTypeConstraint(N, *this, TP);
125 /// FIXME: TreePatternNode's can be shared in some cases (due to dag-shaped
126 /// patterns), and as such should be ref counted. We currently just leak all
127 /// TreePatternNode objects!
128 class TreePatternNode {
129 /// The inferred type for this node, or MVT::isUnknown if it hasn't
130 /// been determined yet.
131 std::vector<unsigned char> Types;
133 /// Operator - The Record for the operator if this is an interior node (not
137 /// Val - The init value (e.g. the "GPRC" record, or "7") for a leaf.
141 /// Name - The name given to this node with the :$foo notation.
145 /// PredicateFn - The predicate function to execute on this node to check
146 /// for a match. If this string is empty, no predicate is involved.
147 std::string PredicateFn;
149 /// TransformFn - The transformation function to execute on this node before
150 /// it can be substituted into the resulting instruction on a pattern match.
153 std::vector<TreePatternNode*> Children;
155 TreePatternNode(Record *Op, const std::vector<TreePatternNode*> &Ch)
156 : Types(), Operator(Op), Val(0), TransformFn(0),
157 Children(Ch) { Types.push_back(MVT::isUnknown); }
158 TreePatternNode(Init *val) // leaf ctor
159 : Types(), Operator(0), Val(val), TransformFn(0) {
160 Types.push_back(MVT::isUnknown);
164 const std::string &getName() const { return Name; }
165 void setName(const std::string &N) { Name = N; }
167 bool isLeaf() const { return Val != 0; }
168 bool hasTypeSet() const {
169 return (Types[0] < MVT::LAST_VALUETYPE) || (Types[0] == MVT::iPTR);
171 bool isTypeCompletelyUnknown() const {
172 return Types[0] == MVT::isUnknown;
174 bool isTypeDynamicallyResolved() const {
175 return Types[0] == MVT::iPTR;
177 MVT::ValueType getTypeNum(unsigned Num) const {
178 assert(hasTypeSet() && "Doesn't have a type yet!");
179 assert(Types.size() > Num && "Type num out of range!");
180 return (MVT::ValueType)Types[Num];
182 unsigned char getExtTypeNum(unsigned Num) const {
183 assert(Types.size() > Num && "Extended type num out of range!");
186 const std::vector<unsigned char> &getExtTypes() const { return Types; }
187 void setTypes(const std::vector<unsigned char> &T) { Types = T; }
188 void removeTypes() { Types = std::vector<unsigned char>(1,MVT::isUnknown); }
190 Init *getLeafValue() const { assert(isLeaf()); return Val; }
191 Record *getOperator() const { assert(!isLeaf()); return Operator; }
193 unsigned getNumChildren() const { return Children.size(); }
194 TreePatternNode *getChild(unsigned N) const { return Children[N]; }
195 void setChild(unsigned i, TreePatternNode *N) {
200 const std::string &getPredicateFn() const { return PredicateFn; }
201 void setPredicateFn(const std::string &Fn) { PredicateFn = Fn; }
203 Record *getTransformFn() const { return TransformFn; }
204 void setTransformFn(Record *Fn) { TransformFn = Fn; }
206 void print(std::ostream &OS) const;
209 public: // Higher level manipulation routines.
211 /// clone - Return a new copy of this tree.
213 TreePatternNode *clone() const;
215 /// isIsomorphicTo - Return true if this node is recursively isomorphic to
216 /// the specified node. For this comparison, all of the state of the node
217 /// is considered, except for the assigned name. Nodes with differing names
218 /// that are otherwise identical are considered isomorphic.
219 bool isIsomorphicTo(const TreePatternNode *N) const;
221 /// SubstituteFormalArguments - Replace the formal arguments in this tree
222 /// with actual values specified by ArgMap.
223 void SubstituteFormalArguments(std::map<std::string,
224 TreePatternNode*> &ArgMap);
226 /// InlinePatternFragments - If this pattern refers to any pattern
227 /// fragments, inline them into place, giving us a pattern without any
228 /// PatFrag references.
229 TreePatternNode *InlinePatternFragments(TreePattern &TP);
231 /// ApplyTypeConstraints - Apply all of the type constraints relevent to
232 /// this node and its children in the tree. This returns true if it makes a
233 /// change, false otherwise. If a type contradiction is found, throw an
235 bool ApplyTypeConstraints(TreePattern &TP, bool NotRegisters);
237 /// UpdateNodeType - Set the node type of N to VT if VT contains
238 /// information. If N already contains a conflicting type, then throw an
239 /// exception. This returns true if any information was updated.
241 bool UpdateNodeType(const std::vector<unsigned char> &ExtVTs,
243 bool UpdateNodeType(unsigned char ExtVT, TreePattern &TP) {
244 std::vector<unsigned char> ExtVTs(1, ExtVT);
245 return UpdateNodeType(ExtVTs, TP);
248 /// ContainsUnresolvedType - Return true if this tree contains any
249 /// unresolved types.
250 bool ContainsUnresolvedType() const {
251 if (!hasTypeSet() && !isTypeDynamicallyResolved()) return true;
252 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
253 if (getChild(i)->ContainsUnresolvedType()) return true;
257 /// canPatternMatch - If it is impossible for this pattern to match on this
258 /// target, fill in Reason and return false. Otherwise, return true.
259 bool canPatternMatch(std::string &Reason, DAGISelEmitter &ISE);
263 /// TreePattern - Represent a pattern, used for instructions, pattern
267 /// Trees - The list of pattern trees which corresponds to this pattern.
268 /// Note that PatFrag's only have a single tree.
270 std::vector<TreePatternNode*> Trees;
272 /// TheRecord - The actual TableGen record corresponding to this pattern.
276 /// Args - This is a list of all of the arguments to this pattern (for
277 /// PatFrag patterns), which are the 'node' markers in this pattern.
278 std::vector<std::string> Args;
280 /// ISE - the DAG isel emitter coordinating this madness.
284 /// isInputPattern - True if this is an input pattern, something to match.
285 /// False if this is an output pattern, something to emit.
289 /// TreePattern constructor - Parse the specified DagInits into the
291 TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
292 DAGISelEmitter &ise);
293 TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
294 DAGISelEmitter &ise);
295 TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
296 DAGISelEmitter &ise);
298 /// getTrees - Return the tree patterns which corresponds to this pattern.
300 const std::vector<TreePatternNode*> &getTrees() const { return Trees; }
301 unsigned getNumTrees() const { return Trees.size(); }
302 TreePatternNode *getTree(unsigned i) const { return Trees[i]; }
303 TreePatternNode *getOnlyTree() const {
304 assert(Trees.size() == 1 && "Doesn't have exactly one pattern!");
308 /// getRecord - Return the actual TableGen record corresponding to this
311 Record *getRecord() const { return TheRecord; }
313 unsigned getNumArgs() const { return Args.size(); }
314 const std::string &getArgName(unsigned i) const {
315 assert(i < Args.size() && "Argument reference out of range!");
318 std::vector<std::string> &getArgList() { return Args; }
320 DAGISelEmitter &getDAGISelEmitter() const { return ISE; }
322 /// InlinePatternFragments - If this pattern refers to any pattern
323 /// fragments, inline them into place, giving us a pattern without any
324 /// PatFrag references.
325 void InlinePatternFragments() {
326 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
327 Trees[i] = Trees[i]->InlinePatternFragments(*this);
330 /// InferAllTypes - Infer/propagate as many types throughout the expression
331 /// patterns as possible. Return true if all types are infered, false
332 /// otherwise. Throw an exception if a type contradiction is found.
333 bool InferAllTypes();
335 /// error - Throw an exception, prefixing it with information about this
337 void error(const std::string &Msg) const;
339 void print(std::ostream &OS) const;
343 TreePatternNode *ParseTreePattern(DagInit *DI);
346 /// DAGDefaultOperand - One of these is created for each PredicateOperand
347 /// or OptionalDefOperand that has a set ExecuteAlways / DefaultOps field.
348 struct DAGDefaultOperand {
349 std::vector<TreePatternNode*> DefaultOps;
352 class DAGInstruction {
353 TreePattern *Pattern;
354 std::vector<Record*> Results;
355 std::vector<Record*> Operands;
356 std::vector<Record*> ImpResults;
357 std::vector<Record*> ImpOperands;
358 TreePatternNode *ResultPattern;
360 DAGInstruction(TreePattern *TP,
361 const std::vector<Record*> &results,
362 const std::vector<Record*> &operands,
363 const std::vector<Record*> &impresults,
364 const std::vector<Record*> &impoperands)
365 : Pattern(TP), Results(results), Operands(operands),
366 ImpResults(impresults), ImpOperands(impoperands),
369 TreePattern *getPattern() const { return Pattern; }
370 unsigned getNumResults() const { return Results.size(); }
371 unsigned getNumOperands() const { return Operands.size(); }
372 unsigned getNumImpResults() const { return ImpResults.size(); }
373 unsigned getNumImpOperands() const { return ImpOperands.size(); }
374 const std::vector<Record*>& getImpResults() const { return ImpResults; }
376 void setResultPattern(TreePatternNode *R) { ResultPattern = R; }
378 Record *getResult(unsigned RN) const {
379 assert(RN < Results.size());
383 Record *getOperand(unsigned ON) const {
384 assert(ON < Operands.size());
388 Record *getImpResult(unsigned RN) const {
389 assert(RN < ImpResults.size());
390 return ImpResults[RN];
393 Record *getImpOperand(unsigned ON) const {
394 assert(ON < ImpOperands.size());
395 return ImpOperands[ON];
398 TreePatternNode *getResultPattern() const { return ResultPattern; }
401 /// PatternToMatch - Used by DAGISelEmitter to keep tab of patterns processed
403 struct PatternToMatch {
404 PatternToMatch(ListInit *preds,
405 TreePatternNode *src, TreePatternNode *dst,
406 const std::vector<Record*> &dstregs,
407 unsigned complexity):
408 Predicates(preds), SrcPattern(src), DstPattern(dst), Dstregs(dstregs),
409 AddedComplexity(complexity) {};
411 ListInit *Predicates; // Top level predicate conditions to match.
412 TreePatternNode *SrcPattern; // Source pattern to match.
413 TreePatternNode *DstPattern; // Resulting pattern.
414 std::vector<Record*> Dstregs; // Physical register defs being matched.
415 unsigned AddedComplexity; // Add to matching pattern complexity.
417 ListInit *getPredicates() const { return Predicates; }
418 TreePatternNode *getSrcPattern() const { return SrcPattern; }
419 TreePatternNode *getDstPattern() const { return DstPattern; }
420 const std::vector<Record*> &getDstRegs() const { return Dstregs; }
421 unsigned getAddedComplexity() const { return AddedComplexity; }
424 /// DAGISelEmitter - The top-level class which coordinates construction
425 /// and emission of the instruction selector.
427 class DAGISelEmitter : public TableGenBackend {
429 RecordKeeper &Records;
430 CodeGenTarget Target;
431 std::vector<CodeGenIntrinsic> Intrinsics;
433 std::map<Record*, SDNodeInfo> SDNodes;
434 std::map<Record*, std::pair<Record*, std::string> > SDNodeXForms;
435 std::map<Record*, ComplexPattern> ComplexPatterns;
436 std::map<Record*, TreePattern*> PatternFragments;
437 std::map<Record*, DAGDefaultOperand> DefaultOperands;
438 std::map<Record*, DAGInstruction> Instructions;
440 // Specific SDNode definitions:
441 Record *intrinsic_void_sdnode;
442 Record *intrinsic_w_chain_sdnode, *intrinsic_wo_chain_sdnode;
444 /// PatternsToMatch - All of the things we are matching on the DAG. The first
445 /// value is the pattern to match, the second pattern is the result to
447 std::vector<PatternToMatch> PatternsToMatch;
449 DAGISelEmitter(RecordKeeper &R) : Records(R) {}
451 // run - Output the isel, returning true on failure.
452 void run(std::ostream &OS);
454 const CodeGenTarget &getTargetInfo() const { return Target; }
456 Record *getSDNodeNamed(const std::string &Name) const;
458 const SDNodeInfo &getSDNodeInfo(Record *R) const {
459 assert(SDNodes.count(R) && "Unknown node!");
460 return SDNodes.find(R)->second;
463 const std::pair<Record*, std::string> &getSDNodeTransform(Record *R) const {
464 assert(SDNodeXForms.count(R) && "Invalid transform!");
465 return SDNodeXForms.find(R)->second;
468 const ComplexPattern &getComplexPattern(Record *R) const {
469 assert(ComplexPatterns.count(R) && "Unknown addressing mode!");
470 return ComplexPatterns.find(R)->second;
473 const CodeGenIntrinsic &getIntrinsic(Record *R) const {
474 for (unsigned i = 0, e = Intrinsics.size(); i != e; ++i)
475 if (Intrinsics[i].TheDef == R) return Intrinsics[i];
476 assert(0 && "Unknown intrinsic!");
480 const CodeGenIntrinsic &getIntrinsicInfo(unsigned IID) const {
481 assert(IID-1 < Intrinsics.size() && "Bad intrinsic ID!");
482 return Intrinsics[IID-1];
485 unsigned getIntrinsicID(Record *R) const {
486 for (unsigned i = 0, e = Intrinsics.size(); i != e; ++i)
487 if (Intrinsics[i].TheDef == R) return i;
488 assert(0 && "Unknown intrinsic!");
492 const DAGDefaultOperand &getDefaultOperand(Record *R) {
493 assert(DefaultOperands.count(R) &&"Isn't an analyzed default operand!");
494 return DefaultOperands.find(R)->second;
497 TreePattern *getPatternFragment(Record *R) const {
498 assert(PatternFragments.count(R) && "Invalid pattern fragment request!");
499 return PatternFragments.find(R)->second;
502 const DAGInstruction &getInstruction(Record *R) const {
503 assert(Instructions.count(R) && "Unknown instruction!");
504 return Instructions.find(R)->second;
507 Record *get_intrinsic_void_sdnode() const {
508 return intrinsic_void_sdnode;
510 Record *get_intrinsic_w_chain_sdnode() const {
511 return intrinsic_w_chain_sdnode;
513 Record *get_intrinsic_wo_chain_sdnode() const {
514 return intrinsic_wo_chain_sdnode;
519 void ParseNodeInfo();
520 void ParseNodeTransforms(std::ostream &OS);
521 void ParseComplexPatterns();
522 void ParsePatternFragments(std::ostream &OS);
523 void ParseDefaultOperands();
524 void ParseInstructions();
525 void ParsePatterns();
526 void GenerateVariants();
527 void FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
528 std::map<std::string,
529 TreePatternNode*> &InstInputs,
530 std::map<std::string,
531 TreePatternNode*> &InstResults,
532 std::vector<Record*> &InstImpInputs,
533 std::vector<Record*> &InstImpResults);
534 void GenerateCodeForPattern(PatternToMatch &Pattern,
535 std::vector<std::pair<unsigned, std::string> > &GeneratedCode,
536 std::set<std::string> &GeneratedDecl,
537 std::vector<std::string> &TargetOpcodes,
538 std::vector<std::string> &TargetVTs);
539 void EmitPatterns(std::vector<std::pair<PatternToMatch*,
540 std::vector<std::pair<unsigned, std::string> > > > &Patterns,
541 unsigned Indent, std::ostream &OS);
542 void EmitInstructionSelector(std::ostream &OS);
545 } // End llvm namespace