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;
31 /// MVT::DAGISelGenValueType - These are some extended forms of MVT::ValueType
32 /// that we use as lattice values during type inferrence.
34 enum DAGISelGenValueType {
35 isFP = MVT::LAST_VALUETYPE,
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);
46 unsigned OperandNo; // The operand # this constraint applies to.
48 SDTCisVT, SDTCisInt, SDTCisFP, SDTCisSameAs, SDTCisVTSmallerThanOp,
52 union { // The discriminated union.
57 unsigned OtherOperandNum;
60 unsigned OtherOperandNum;
61 } SDTCisVTSmallerThanOp_Info;
63 unsigned BigOperandNum;
64 } SDTCisOpSmallerThanOp_Info;
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
71 bool ApplyTypeConstraint(TreePatternNode *N, const SDNodeInfo &NodeInfo,
72 TreePattern &TP) const;
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;
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
86 std::string SDClassName;
90 std::vector<SDTypeConstraint> TypeConstraints;
92 SDNodeInfo(Record *R); // Parse the specified record.
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; }
100 const std::vector<SDTypeConstraint> &getTypeConstraints() const {
101 return TypeConstraints;
104 // SelectionDAG node properties.
105 enum SDNP { SDNPCommutative, SDNPAssociative, SDNPHasChain };
107 /// hasProperty - Return true if this node has the specified property.
109 bool hasProperty(enum SDNP Prop) const { return Properties & (1 << Prop); }
111 /// ApplyTypeConstraints - Given a node in a pattern, apply the type
112 /// constraints for this node to the operands of the node. This returns
113 /// true if it makes a change, false otherwise. If a type contradiction is
114 /// found, throw an exception.
115 bool ApplyTypeConstraints(TreePatternNode *N, TreePattern &TP) const {
116 bool MadeChange = false;
117 for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i)
118 MadeChange |= TypeConstraints[i].ApplyTypeConstraint(N, *this, TP);
123 /// FIXME: TreePatternNode's can be shared in some cases (due to dag-shaped
124 /// patterns), and as such should be ref counted. We currently just leak all
125 /// TreePatternNode objects!
126 class TreePatternNode {
127 /// The inferred type for this node, or MVT::LAST_VALUETYPE if it hasn't
128 /// been determined yet.
131 /// Operator - The Record for the operator if this is an interior node (not
135 /// Val - The init value (e.g. the "GPRC" record, or "7") for a leaf.
139 /// Name - The name given to this node with the :$foo notation.
143 /// PredicateFn - The predicate function to execute on this node to check
144 /// for a match. If this string is empty, no predicate is involved.
145 std::string PredicateFn;
147 /// TransformFn - The transformation function to execute on this node before
148 /// it can be substituted into the resulting instruction on a pattern match.
151 std::vector<TreePatternNode*> Children;
153 TreePatternNode(Record *Op, const std::vector<TreePatternNode*> &Ch)
154 : Ty(MVT::isUnknown), Operator(Op), Val(0), TransformFn(0),
156 TreePatternNode(Init *val) // leaf ctor
157 : Ty(MVT::isUnknown), Operator(0), Val(val), TransformFn(0) {}
160 const std::string &getName() const { return Name; }
161 void setName(const std::string &N) { Name = N; }
163 bool isLeaf() const { return Val != 0; }
164 bool hasTypeSet() const { return Ty < MVT::LAST_VALUETYPE; }
165 bool isTypeCompletelyUnknown() const {
166 return Ty == MVT::isUnknown;
168 MVT::ValueType getType() const {
169 assert(hasTypeSet() && "Doesn't have a type yet!");
170 return (MVT::ValueType)Ty;
172 unsigned char getExtType() const { return Ty; }
173 void setType(unsigned char VT) { Ty = VT; }
175 Init *getLeafValue() const { assert(isLeaf()); return Val; }
176 Record *getOperator() const { assert(!isLeaf()); return Operator; }
178 unsigned getNumChildren() const { return Children.size(); }
179 TreePatternNode *getChild(unsigned N) const { return Children[N]; }
180 void setChild(unsigned i, TreePatternNode *N) {
184 const std::string &getPredicateFn() const { return PredicateFn; }
185 void setPredicateFn(const std::string &Fn) { PredicateFn = Fn; }
187 Record *getTransformFn() const { return TransformFn; }
188 void setTransformFn(Record *Fn) { TransformFn = Fn; }
190 void print(std::ostream &OS) const;
193 public: // Higher level manipulation routines.
195 /// clone - Return a new copy of this tree.
197 TreePatternNode *clone() const;
199 /// isIsomorphicTo - Return true if this node is recursively isomorphic to
200 /// the specified node. For this comparison, all of the state of the node
201 /// is considered, except for the assigned name. Nodes with differing names
202 /// that are otherwise identical are considered isomorphic.
203 bool isIsomorphicTo(const TreePatternNode *N) const;
205 /// SubstituteFormalArguments - Replace the formal arguments in this tree
206 /// with actual values specified by ArgMap.
207 void SubstituteFormalArguments(std::map<std::string,
208 TreePatternNode*> &ArgMap);
210 /// InlinePatternFragments - If this pattern refers to any pattern
211 /// fragments, inline them into place, giving us a pattern without any
212 /// PatFrag references.
213 TreePatternNode *InlinePatternFragments(TreePattern &TP);
215 /// ApplyTypeConstraints - Apply all of the type constraints relevent to
216 /// this node and its children in the tree. This returns true if it makes a
217 /// change, false otherwise. If a type contradiction is found, throw an
219 bool ApplyTypeConstraints(TreePattern &TP, bool NotRegisters);
221 /// UpdateNodeType - Set the node type of N to VT if VT contains
222 /// information. If N already contains a conflicting type, then throw an
223 /// exception. This returns true if any information was updated.
225 bool UpdateNodeType(unsigned char EVT, TreePattern &TP);
227 /// ContainsUnresolvedType - Return true if this tree contains any
228 /// unresolved types.
229 bool ContainsUnresolvedType() const {
230 if (!hasTypeSet()) return true;
231 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
232 if (getChild(i)->ContainsUnresolvedType()) return true;
236 /// canPatternMatch - If it is impossible for this pattern to match on this
237 /// target, fill in Reason and return false. Otherwise, return true.
238 bool canPatternMatch(std::string &Reason, DAGISelEmitter &ISE);
242 /// TreePattern - Represent a pattern, used for instructions, pattern
246 /// Trees - The list of pattern trees which corresponds to this pattern.
247 /// Note that PatFrag's only have a single tree.
249 std::vector<TreePatternNode*> Trees;
251 /// TheRecord - The actual TableGen record corresponding to this pattern.
255 /// Args - This is a list of all of the arguments to this pattern (for
256 /// PatFrag patterns), which are the 'node' markers in this pattern.
257 std::vector<std::string> Args;
259 /// ISE - the DAG isel emitter coordinating this madness.
263 /// isInputPattern - True if this is an input pattern, something to match.
264 /// False if this is an output pattern, something to emit.
268 /// TreePattern constructor - Parse the specified DagInits into the
270 TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
271 DAGISelEmitter &ise);
272 TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
273 DAGISelEmitter &ise);
274 TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
275 DAGISelEmitter &ise);
277 /// getTrees - Return the tree patterns which corresponds to this pattern.
279 const std::vector<TreePatternNode*> &getTrees() const { return Trees; }
280 unsigned getNumTrees() const { return Trees.size(); }
281 TreePatternNode *getTree(unsigned i) const { return Trees[i]; }
282 TreePatternNode *getOnlyTree() const {
283 assert(Trees.size() == 1 && "Doesn't have exactly one pattern!");
287 /// getRecord - Return the actual TableGen record corresponding to this
290 Record *getRecord() const { return TheRecord; }
292 unsigned getNumArgs() const { return Args.size(); }
293 const std::string &getArgName(unsigned i) const {
294 assert(i < Args.size() && "Argument reference out of range!");
297 std::vector<std::string> &getArgList() { return Args; }
299 DAGISelEmitter &getDAGISelEmitter() const { return ISE; }
301 /// InlinePatternFragments - If this pattern refers to any pattern
302 /// fragments, inline them into place, giving us a pattern without any
303 /// PatFrag references.
304 void InlinePatternFragments() {
305 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
306 Trees[i] = Trees[i]->InlinePatternFragments(*this);
309 /// InferAllTypes - Infer/propagate as many types throughout the expression
310 /// patterns as possible. Return true if all types are infered, false
311 /// otherwise. Throw an exception if a type contradiction is found.
312 bool InferAllTypes();
314 /// error - Throw an exception, prefixing it with information about this
316 void error(const std::string &Msg) const;
318 void print(std::ostream &OS) const;
322 TreePatternNode *ParseTreePattern(DagInit *DI);
326 class DAGInstruction {
327 TreePattern *Pattern;
328 std::vector<Record*> Results;
329 std::vector<Record*> Operands;
330 TreePatternNode *ResultPattern;
332 DAGInstruction(TreePattern *TP,
333 const std::vector<Record*> &results,
334 const std::vector<Record*> &operands)
335 : Pattern(TP), Results(results), Operands(operands),
338 TreePattern *getPattern() const { return Pattern; }
339 unsigned getNumResults() const { return Results.size(); }
340 unsigned getNumOperands() const { return Operands.size(); }
342 void setResultPattern(TreePatternNode *R) { ResultPattern = R; }
344 Record *getResult(unsigned RN) const {
345 assert(RN < Results.size());
349 Record *getOperand(unsigned ON) const {
350 assert(ON < Operands.size());
353 TreePatternNode *getResultPattern() const { return ResultPattern; }
357 /// InstrSelectorEmitter - The top-level class which coordinates construction
358 /// and emission of the instruction selector.
360 class DAGISelEmitter : public TableGenBackend {
362 typedef std::pair<TreePatternNode*, TreePatternNode*> PatternToMatch;
364 RecordKeeper &Records;
365 CodeGenTarget Target;
367 std::map<Record*, SDNodeInfo> SDNodes;
368 std::map<Record*, std::pair<Record*, std::string> > SDNodeXForms;
369 std::map<Record*, ComplexPattern> ComplexPatterns;
370 std::map<Record*, TreePattern*> PatternFragments;
371 std::map<Record*, DAGInstruction> Instructions;
373 /// PatternsToMatch - All of the things we are matching on the DAG. The first
374 /// value is the pattern to match, the second pattern is the result to
376 std::vector<PatternToMatch> PatternsToMatch;
378 DAGISelEmitter(RecordKeeper &R) : Records(R) {}
380 // run - Output the isel, returning true on failure.
381 void run(std::ostream &OS);
383 const CodeGenTarget &getTargetInfo() const { return Target; }
385 Record *getSDNodeNamed(const std::string &Name) const;
387 const SDNodeInfo &getSDNodeInfo(Record *R) const {
388 assert(SDNodes.count(R) && "Unknown node!");
389 return SDNodes.find(R)->second;
392 const std::pair<Record*, std::string> &getSDNodeTransform(Record *R) const {
393 assert(SDNodeXForms.count(R) && "Invalid transform!");
394 return SDNodeXForms.find(R)->second;
397 const ComplexPattern &getComplexPattern(Record *R) const {
398 assert(ComplexPatterns.count(R) && "Unknown addressing mode!");
399 return ComplexPatterns.find(R)->second;
402 TreePattern *getPatternFragment(Record *R) const {
403 assert(PatternFragments.count(R) && "Invalid pattern fragment request!");
404 return PatternFragments.find(R)->second;
407 const DAGInstruction &getInstruction(Record *R) const {
408 assert(Instructions.count(R) && "Unknown instruction!");
409 return Instructions.find(R)->second;
413 void ParseNodeInfo();
414 void ParseNodeTransforms(std::ostream &OS);
415 void ParseComplexPatterns();
416 void ParsePatternFragments(std::ostream &OS);
417 void ParseInstructions();
418 void ParsePatterns();
419 void GenerateVariants();
420 void FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
421 std::map<std::string,
422 TreePatternNode*> &InstInputs,
423 std::map<std::string, Record*> &InstResults);
424 void EmitMatchForPattern(TreePatternNode *N, const std::string &RootName,
425 std::map<std::string,std::string> &VarMap,
426 unsigned PatternNo, std::ostream &OS,
427 std::string &ChainName,
428 bool &HasChain, bool &InFlag, bool isRoot = false);
429 void EmitCopyToRegsForPattern(TreePatternNode *N, const std::string &RootName,
430 std::ostream &OS, bool HasChain);
431 std::pair<unsigned, unsigned>
432 CodeGenPatternResult(TreePatternNode *M, TreePatternNode *N, unsigned &Ctr,
433 std::string &ChainName,
434 std::map<std::string,std::string> &VariableMap,
435 unsigned PatternNo, std::ostream &OS,
436 bool InFlag, bool isRoot = false);
437 void EmitCodeForPattern(PatternToMatch &Pattern, std::ostream &OS);
438 void EmitInstructionSelector(std::ostream &OS);
441 } // End llvm namespace