1 //===- DAGISelEmitter.h - Generate an instruction selector ------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
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.
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"
27 class TreePatternNode;
30 /// SDTypeConstraint - This is a discriminated union of constraints,
31 /// corresponding to the SDTypeConstraint tablegen class in Target.td.
32 struct SDTypeConstraint {
33 SDTypeConstraint(Record *R);
35 unsigned OperandNo; // The operand # this constraint applies to.
37 SDTCisVT, SDTCisInt, SDTCisFP, SDTCisSameAs, SDTCisVTSmallerThanOp,
41 union { // The discriminated union.
46 unsigned OtherOperandNum;
49 unsigned OtherOperandNum;
50 } SDTCisVTSmallerThanOp_Info;
52 unsigned BigOperandNum;
53 } SDTCisOpSmallerThanOp_Info;
56 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
57 /// constraint to the nodes operands. This returns true if it makes a
58 /// change, false otherwise. If a type contradiction is found, throw an
60 bool ApplyTypeConstraint(TreePatternNode *N, const SDNodeInfo &NodeInfo,
61 TreePattern &TP) const;
63 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
64 /// N, which has NumResults results.
65 TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
66 unsigned NumResults) const;
69 /// SDNodeInfo - One of these records is created for each SDNode instance in
70 /// the target .td file. This represents the various dag nodes we will be
75 std::string SDClassName;
79 std::vector<SDTypeConstraint> TypeConstraints;
81 SDNodeInfo(Record *R); // Parse the specified record.
83 unsigned getNumResults() const { return NumResults; }
84 int getNumOperands() const { return NumOperands; }
85 Record *getRecord() const { return Def; }
86 const std::string &getEnumName() const { return EnumName; }
87 const std::string &getSDClassName() const { return SDClassName; }
89 const std::vector<SDTypeConstraint> &getTypeConstraints() const {
90 return TypeConstraints;
93 // SelectionDAG node properties.
94 enum SDNP { SDNPCommutative, SDNPAssociative };
96 /// hasProperty - Return true if this node has the specified property.
98 bool hasProperty(enum SDNP Prop) const { return Properties & (1 << Prop); }
100 /// ApplyTypeConstraints - Given a node in a pattern, apply the type
101 /// constraints for this node to the operands of the node. This returns
102 /// true if it makes a change, false otherwise. If a type contradiction is
103 /// found, throw an exception.
104 bool ApplyTypeConstraints(TreePatternNode *N, TreePattern &TP) const {
105 bool MadeChange = false;
106 for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i)
107 MadeChange |= TypeConstraints[i].ApplyTypeConstraint(N, *this, TP);
112 /// FIXME: TreePatternNode's can be shared in some cases (due to dag-shaped
113 /// patterns), and as such should be ref counted. We currently just leak all
114 /// TreePatternNode objects!
115 class TreePatternNode {
116 /// The inferred type for this node, or MVT::LAST_VALUETYPE if it hasn't
117 /// been determined yet.
120 /// Operator - The Record for the operator if this is an interior node (not
124 /// Val - The init value (e.g. the "GPRC" record, or "7") for a leaf.
128 /// Name - The name given to this node with the :$foo notation.
132 /// PredicateFn - The predicate function to execute on this node to check
133 /// for a match. If this string is empty, no predicate is involved.
134 std::string PredicateFn;
136 /// TransformFn - The transformation function to execute on this node before
137 /// it can be substituted into the resulting instruction on a pattern match.
140 std::vector<TreePatternNode*> Children;
142 TreePatternNode(Record *Op, const std::vector<TreePatternNode*> &Ch)
143 : Ty(MVT::LAST_VALUETYPE), Operator(Op), Val(0), TransformFn(0),
145 TreePatternNode(Init *val) // leaf ctor
146 : Ty(MVT::LAST_VALUETYPE), Operator(0), Val(val), TransformFn(0) {}
149 const std::string &getName() const { return Name; }
150 void setName(const std::string &N) { Name = N; }
152 bool isLeaf() const { return Val != 0; }
153 bool hasTypeSet() const { return Ty != MVT::LAST_VALUETYPE; }
154 MVT::ValueType getType() const { return Ty; }
155 void setType(MVT::ValueType VT) { Ty = VT; }
157 Init *getLeafValue() const { assert(isLeaf()); return Val; }
158 Record *getOperator() const { assert(!isLeaf()); return Operator; }
160 unsigned getNumChildren() const { return Children.size(); }
161 TreePatternNode *getChild(unsigned N) const { return Children[N]; }
162 void setChild(unsigned i, TreePatternNode *N) {
166 const std::string &getPredicateFn() const { return PredicateFn; }
167 void setPredicateFn(const std::string &Fn) { PredicateFn = Fn; }
169 Record *getTransformFn() const { return TransformFn; }
170 void setTransformFn(Record *Fn) { TransformFn = Fn; }
172 void print(std::ostream &OS) const;
175 public: // Higher level manipulation routines.
177 /// clone - Return a new copy of this tree.
179 TreePatternNode *clone() const;
181 /// isIsomorphicTo - Return true if this node is recursively isomorphic to
182 /// the specified node. For this comparison, all of the state of the node
183 /// is considered, except for the assigned name. Nodes with differing names
184 /// that are otherwise identical are considered isomorphic.
185 bool isIsomorphicTo(const TreePatternNode *N) const;
187 /// SubstituteFormalArguments - Replace the formal arguments in this tree
188 /// with actual values specified by ArgMap.
189 void SubstituteFormalArguments(std::map<std::string,
190 TreePatternNode*> &ArgMap);
192 /// InlinePatternFragments - If this pattern refers to any pattern
193 /// fragments, inline them into place, giving us a pattern without any
194 /// PatFrag references.
195 TreePatternNode *InlinePatternFragments(TreePattern &TP);
197 /// ApplyTypeConstraints - Apply all of the type constraints relevent to
198 /// this node and its children in the tree. This returns true if it makes a
199 /// change, false otherwise. If a type contradiction is found, throw an
201 bool ApplyTypeConstraints(TreePattern &TP, bool NotRegisters);
203 /// UpdateNodeType - Set the node type of N to VT if VT contains
204 /// information. If N already contains a conflicting type, then throw an
205 /// exception. This returns true if any information was updated.
207 bool UpdateNodeType(MVT::ValueType VT, TreePattern &TP);
209 /// ContainsUnresolvedType - Return true if this tree contains any
210 /// unresolved types.
211 bool ContainsUnresolvedType() const {
212 if (Ty == MVT::LAST_VALUETYPE) return true;
213 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
214 if (getChild(i)->ContainsUnresolvedType()) return true;
218 /// canPatternMatch - If it is impossible for this pattern to match on this
219 /// target, fill in Reason and return false. Otherwise, return true.
220 bool canPatternMatch(std::string &Reason, DAGISelEmitter &ISE);
224 /// TreePattern - Represent a pattern, used for instructions, pattern
228 /// Trees - The list of pattern trees which corresponds to this pattern.
229 /// Note that PatFrag's only have a single tree.
231 std::vector<TreePatternNode*> Trees;
233 /// TheRecord - The actual TableGen record corresponding to this pattern.
237 /// Args - This is a list of all of the arguments to this pattern (for
238 /// PatFrag patterns), which are the 'node' markers in this pattern.
239 std::vector<std::string> Args;
241 /// ISE - the DAG isel emitter coordinating this madness.
246 /// TreePattern constructor - Parse the specified DagInits into the
248 TreePattern(Record *TheRec, ListInit *RawPat, DAGISelEmitter &ise);
249 TreePattern(Record *TheRec, DagInit *Pat, DAGISelEmitter &ise);
250 TreePattern(Record *TheRec, TreePatternNode *Pat, DAGISelEmitter &ise);
252 /// getTrees - Return the tree patterns which corresponds to this pattern.
254 const std::vector<TreePatternNode*> &getTrees() const { return Trees; }
255 unsigned getNumTrees() const { return Trees.size(); }
256 TreePatternNode *getTree(unsigned i) const { return Trees[i]; }
257 TreePatternNode *getOnlyTree() const {
258 assert(Trees.size() == 1 && "Doesn't have exactly one pattern!");
262 /// getRecord - Return the actual TableGen record corresponding to this
265 Record *getRecord() const { return TheRecord; }
267 unsigned getNumArgs() const { return Args.size(); }
268 const std::string &getArgName(unsigned i) const {
269 assert(i < Args.size() && "Argument reference out of range!");
272 std::vector<std::string> &getArgList() { return Args; }
274 DAGISelEmitter &getDAGISelEmitter() const { return ISE; }
276 /// InlinePatternFragments - If this pattern refers to any pattern
277 /// fragments, inline them into place, giving us a pattern without any
278 /// PatFrag references.
279 void InlinePatternFragments() {
280 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
281 Trees[i] = Trees[i]->InlinePatternFragments(*this);
284 /// InferAllTypes - Infer/propagate as many types throughout the expression
285 /// patterns as possible. Return true if all types are infered, false
286 /// otherwise. Throw an exception if a type contradiction is found.
287 bool InferAllTypes();
289 /// error - Throw an exception, prefixing it with information about this
291 void error(const std::string &Msg) const;
293 void print(std::ostream &OS) const;
297 TreePatternNode *ParseTreePattern(DagInit *DI);
301 class DAGInstruction {
302 TreePattern *Pattern;
304 unsigned NumOperands;
305 std::vector<MVT::ValueType> ResultTypes;
306 std::vector<MVT::ValueType> OperandTypes;
307 TreePatternNode *ResultPattern;
309 DAGInstruction(TreePattern *TP,
310 const std::vector<MVT::ValueType> &resultTypes,
311 const std::vector<MVT::ValueType> &operandTypes)
312 : Pattern(TP), ResultTypes(resultTypes), OperandTypes(operandTypes),
315 TreePattern *getPattern() const { return Pattern; }
316 unsigned getNumResults() const { return ResultTypes.size(); }
317 unsigned getNumOperands() const { return OperandTypes.size(); }
319 void setResultPattern(TreePatternNode *R) { ResultPattern = R; }
321 MVT::ValueType getResultType(unsigned RN) const {
322 assert(RN < ResultTypes.size());
323 return ResultTypes[RN];
326 MVT::ValueType getOperandType(unsigned ON) const {
327 assert(ON < OperandTypes.size());
328 return OperandTypes[ON];
330 TreePatternNode *getResultPattern() const { return ResultPattern; }
334 /// InstrSelectorEmitter - The top-level class which coordinates construction
335 /// and emission of the instruction selector.
337 class DAGISelEmitter : public TableGenBackend {
339 typedef std::pair<TreePatternNode*, TreePatternNode*> PatternToMatch;
341 RecordKeeper &Records;
342 CodeGenTarget Target;
344 std::map<Record*, SDNodeInfo> SDNodes;
345 std::map<Record*, std::pair<Record*, std::string> > SDNodeXForms;
346 std::map<Record*, TreePattern*> PatternFragments;
347 std::map<Record*, DAGInstruction> Instructions;
349 /// PatternsToMatch - All of the things we are matching on the DAG. The first
350 /// value is the pattern to match, the second pattern is the result to
352 std::vector<PatternToMatch> PatternsToMatch;
354 DAGISelEmitter(RecordKeeper &R) : Records(R) {}
356 // run - Output the isel, returning true on failure.
357 void run(std::ostream &OS);
359 const CodeGenTarget &getTargetInfo() const { return Target; }
361 const SDNodeInfo &getSDNodeInfo(Record *R) const {
362 assert(SDNodes.count(R) && "Unknown node!");
363 return SDNodes.find(R)->second;
366 TreePattern *getPatternFragment(Record *R) const {
367 assert(PatternFragments.count(R) && "Invalid pattern fragment request!");
368 return PatternFragments.find(R)->second;
371 const std::pair<Record*, std::string> &getSDNodeTransform(Record *R) const {
372 assert(SDNodeXForms.count(R) && "Invalid transform!");
373 return SDNodeXForms.find(R)->second;
376 const DAGInstruction &getInstruction(Record *R) const {
377 assert(Instructions.count(R) && "Unknown instruction!");
378 return Instructions.find(R)->second;
382 void ParseNodeInfo();
383 void ParseNodeTransforms(std::ostream &OS);
384 void ParsePatternFragments(std::ostream &OS);
385 void ParseInstructions();
386 void ParsePatterns();
387 void GenerateVariants();
388 void FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
389 std::map<std::string,
390 TreePatternNode*> &InstInputs,
391 std::map<std::string, Record*> &InstResults);
392 void EmitMatchForPattern(TreePatternNode *N, const std::string &RootName,
393 std::map<std::string,std::string> &VarMap,
394 unsigned PatternNo, std::ostream &OS);
395 unsigned CodeGenPatternResult(TreePatternNode *N, unsigned &Ctr,
396 std::map<std::string,std::string> &VariableMap,
398 void EmitCodeForPattern(PatternToMatch &Pattern, std::ostream &OS);
399 void EmitInstructionSelector(std::ostream &OS);
402 } // End llvm namespace