1 //===- InstrInfoEmitter.h - Generate a Instruction Set Desc. ----*- C++ -*-===//
3 // This tablegen backend is responsible for emitting a description of the target
4 // instruction set for the code generator.
6 //===----------------------------------------------------------------------===//
8 #ifndef INSTRSELECTOR_EMITTER_H
9 #define INSTRSELECTOR_EMITTER_H
11 #include "TableGenBackend.h"
12 #include "CodeGenWrappers.h"
17 class InstrSelectorEmitter;
19 /// NodeType - Represents Information parsed from the DagNode entries.
23 // Both argument and return types...
24 Val, // A non-void type
25 Arg0, // Value matches the type of Arg0
26 Arg1, // Value matches the type of Arg1
27 Ptr, // Tree node is the type of the target pointer
29 Void, // Tree node always returns void
32 ArgResultTypes ResultType;
33 std::vector<ArgResultTypes> ArgTypes;
35 NodeType(ArgResultTypes RT, std::vector<ArgResultTypes> &AT) : ResultType(RT){
39 NodeType() : ResultType(Val) {}
40 NodeType(const NodeType &N) : ResultType(N.ResultType), ArgTypes(N.ArgTypes){}
42 static ArgResultTypes Translate(Record *R);
47 /// TreePatternNode - Represent a node of the tree patterns.
49 class TreePatternNode {
50 /// Operator - The operation that this node represents... this is null if this
54 /// Type - The inferred value type...
58 /// Children - If this is not a leaf (Operator != 0), this is the subtrees
60 std::vector<std::pair<TreePatternNode*, std::string> > Children;
62 /// Value - If this node is a leaf, this indicates what the thing is.
66 TreePatternNode(Record *o, const std::vector<std::pair<TreePatternNode*,
68 : Operator(o), Type(MVT::Other), Children(c), Value(0) {}
69 TreePatternNode(Init *V) : Operator(0), Type(MVT::Other), Value(V) {}
71 Record *getOperator() const {
72 assert(Operator && "This is a leaf node!");
75 MVT::ValueType getType() const { return Type; }
76 void setType(MVT::ValueType T) { Type = T; }
78 bool isLeaf() const { return Operator == 0; }
80 unsigned getNumChildren() const { return Children.size(); }
81 TreePatternNode *getChild(unsigned c) const {
82 assert(Operator != 0 && "This is a leaf node!");
83 assert(c < Children.size() && "Child access out of range!");
84 return Children[c].first;
86 const std::string &getChildName(unsigned c) const {
87 assert(Operator != 0 && "This is a leaf node!");
88 assert(c < Children.size() && "Child access out of range!");
89 return Children[c].second;
92 Init *getValue() const {
93 assert(Operator == 0 && "This is not a leaf node!");
97 /// getValueRecord - Returns the value of this tree node as a record. For now
98 /// we only allow DefInit's as our leaf values, so this is used.
99 Record *getValueRecord() const;
101 /// clone - Make a copy of this tree and all of its children.
103 TreePatternNode *clone() const;
107 /// InstantiateNonterminals - If this pattern refers to any nonterminals which
108 /// are not themselves completely resolved, clone the nonterminal and resolve
109 /// it with the using context we provide.
110 void InstantiateNonterminals(InstrSelectorEmitter &ISE);
112 /// UpdateNodeType - Set the node type of N to VT if VT contains information.
113 /// If N already contains a conflicting type, then throw an exception. This
114 /// returns true if any information was updated.
116 bool updateNodeType(MVT::ValueType VT, const std::string &RecName);
119 std::ostream &operator<<(std::ostream &OS, const TreePatternNode &N);
123 /// Pattern - Represent a pattern of one form or another. Currently, three
124 /// types of patterns are possible: Instruction's, Nonterminals, and Expanders.
128 Nonterminal, Instruction, Expander
131 /// PTy - The type of pattern this is.
135 /// Tree - The tree pattern which corresponds to this pattern. Note that if
136 /// there was a (set) node on the outside level that it has been stripped off.
138 TreePatternNode *Tree;
140 /// Result - If this is an instruction or expander pattern, this is the
141 /// register result, specified with a (set) in the pattern.
143 std::string ResultName; // The name of the result value...
144 TreePatternNode *ResultNode; // The leaf node for the result register...
146 /// TheRecord - The actual TableGen record corresponding to this pattern.
150 /// Resolved - This is true of the pattern is useful in practice. In
151 /// particular, some non-terminals will have non-resolvable types. When a
152 /// user of the non-terminal is later found, they will have inferred a type
153 /// for the result of the non-terminal, which cause a clone of an unresolved
154 /// nonterminal to be made which is "resolved".
158 /// Args - This is a list of all of the arguments to this pattern, which are
159 /// the non-void leaf nodes in this pattern.
160 std::vector<std::pair<TreePatternNode*, std::string> > Args;
162 /// ISE - the instruction selector emitter coordinating this madness.
164 InstrSelectorEmitter &ISE;
167 /// Pattern constructor - Parse the specified DagInitializer into the current
169 Pattern(PatternType pty, DagInit *RawPat, Record *TheRec,
170 InstrSelectorEmitter &ise);
172 /// Pattern - Constructor used for cloning nonterminal patterns
173 Pattern(TreePatternNode *tree, Record *rec, bool res,
174 InstrSelectorEmitter &ise)
175 : PTy(Nonterminal), Tree(tree), ResultNode(0), TheRecord(rec),
176 Resolved(res), ISE(ise) {
177 calculateArgs(Tree, "");
180 /// getPatternType - Return what flavor of Record this pattern originated from
182 PatternType getPatternType() const { return PTy; }
184 /// getTree - Return the tree pattern which corresponds to this pattern.
186 TreePatternNode *getTree() const { return Tree; }
188 Record *getResult() const {
189 return ResultNode ? ResultNode->getValueRecord() : 0;
191 const std::string &getResultName() const { return ResultName; }
192 TreePatternNode *getResultNode() const { return ResultNode; }
194 /// getRecord - Return the actual TableGen record corresponding to this
197 Record *getRecord() const { return TheRecord; }
199 unsigned getNumArgs() const { return Args.size(); }
200 TreePatternNode *getArg(unsigned i) const {
201 assert(i < Args.size() && "Argument reference out of range!");
202 return Args[i].first;
204 Record *getArgRec(unsigned i) const {
205 return getArg(i)->getValueRecord();
207 Init *getArgVal(unsigned i) const {
208 return getArg(i)->getValue();
210 const std::string &getArgName(unsigned i) const {
211 assert(i < Args.size() && "Argument reference out of range!");
212 return Args[i].second;
215 bool isResolved() const { return Resolved; }
217 /// InferAllTypes - Runs the type inference engine on the current pattern,
218 /// stopping when nothing can be inferred, then updating the Resolved field.
219 void InferAllTypes();
221 /// InstantiateNonterminals - If this pattern refers to any nonterminals which
222 /// are not themselves completely resolved, clone the nonterminal and resolve
223 /// it with the using context we provide.
224 void InstantiateNonterminals() {
225 Tree->InstantiateNonterminals(ISE);
228 /// clone - This method is used to make an exact copy of the current pattern,
229 /// then change the "TheRecord" instance variable to the specified record.
231 Pattern *clone(Record *R) const;
233 /// error - Throw an exception, prefixing it with information about this
235 void error(const std::string &Msg) const;
237 /// getSlotName - If this is a leaf node, return the slot name that the
238 /// operand will update.
239 std::string getSlotName() const;
240 static std::string getSlotName(Record *R);
245 void calculateArgs(TreePatternNode *N, const std::string &Name);
246 MVT::ValueType getIntrinsicType(Record *R) const;
247 TreePatternNode *ParseTreePattern(DagInit *DI);
248 bool InferTypes(TreePatternNode *N, bool &MadeChange);
251 std::ostream &operator<<(std::ostream &OS, const Pattern &P);
254 /// PatternOrganizer - This class represents all of the patterns which are
255 /// useful for the instruction selector, neatly catagorized in a hierarchical
257 struct PatternOrganizer {
258 /// PatternsForNode - The list of patterns which can produce a value of a
259 /// particular slot type, given a particular root node in the tree. All of
260 /// the patterns in this vector produce the same value type and have the same
262 typedef std::vector<Pattern*> PatternsForNode;
264 /// NodesForSlot - This map keeps track of all of the root DAG nodes which can
265 /// lead to the production of a value for this slot. All of the patterns in
266 /// this data structure produces values of the same slot.
267 typedef std::map<Record*, PatternsForNode> NodesForSlot;
269 /// AllPatterns - This data structure contains all patterns in the instruction
271 std::map<std::string, NodesForSlot> AllPatterns;
273 // Forwarding functions...
274 typedef std::map<std::string, NodesForSlot>::iterator iterator;
275 iterator begin() { return AllPatterns.begin(); }
276 iterator end() { return AllPatterns.end(); }
279 /// addPattern - Add the specified pattern to the appropriate location in the
281 void addPattern(Pattern *P);
285 /// InstrSelectorEmitter - The top-level class which coordinates construction
286 /// and emission of the instruction selector.
288 class InstrSelectorEmitter : public TableGenBackend {
289 RecordKeeper &Records;
290 CodeGenTarget Target;
292 std::map<Record*, NodeType> NodeTypes;
294 /// Patterns - a list of all of the patterns defined by the target description
296 std::map<Record*, Pattern*> Patterns;
298 /// InstantiatedNTs - A data structure to keep track of which nonterminals
299 /// have been instantiated already...
301 std::map<std::pair<Pattern*,MVT::ValueType>, Record*> InstantiatedNTs;
303 /// ComputableValues - This map indicates which patterns can be used to
304 /// generate a value that is used by the selector. The keys of this map
305 /// implicitly define the values that are used by the selector.
307 PatternOrganizer ComputableValues;
310 InstrSelectorEmitter(RecordKeeper &R) : Records(R) {}
312 // run - Output the instruction set description, returning true on failure.
313 void run(std::ostream &OS);
315 const CodeGenTarget &getTarget() const { return Target; }
316 std::map<Record*, NodeType> &getNodeTypes() { return NodeTypes; }
317 const NodeType &getNodeType(Record *R) const {
318 std::map<Record*, NodeType>::const_iterator I = NodeTypes.find(R);
319 assert(I != NodeTypes.end() && "Unknown node type!");
323 /// getPattern - return the pattern corresponding to the specified record, or
324 /// null if there is none.
325 Pattern *getPattern(Record *R) const {
326 std::map<Record*, Pattern*>::const_iterator I = Patterns.find(R);
327 return I != Patterns.end() ? I->second : 0;
330 /// ReadNonterminal - This method parses the specified record as a
331 /// nonterminal, but only if it hasn't been read in already.
332 Pattern *ReadNonterminal(Record *R);
334 /// InstantiateNonterminal - This method takes the nonterminal specified by
335 /// NT, which should not be completely resolved, clones it, applies ResultTy
336 /// to its root, then runs the type inference stuff on it. This should
337 /// produce a newly resolved nonterminal, which we make a record for and
338 /// return. To be extra fancy and efficient, this only makes one clone for
339 /// each type it is instantiated with.
340 Record *InstantiateNonterminal(Pattern *NT, MVT::ValueType ResultTy);
343 // ReadNodeTypes - Read in all of the node types in the current RecordKeeper,
344 // turning them into the more accessible NodeTypes data structure.
345 void ReadNodeTypes();
347 // ReadNonTerminals - Read in all nonterminals and incorporate them into our
349 void ReadNonterminals();
351 // ReadInstructionPatterns - Read in all subclasses of Instruction, and
352 // process those with a useful Pattern field.
353 void ReadInstructionPatterns();
355 // ReadExpanderPatterns - Read in all of the expanded patterns.
356 void ReadExpanderPatterns();
358 // InstantiateNonterminals - Instantiate any unresolved nonterminals with
359 // information from the context that they are used in.
360 void InstantiateNonterminals();
362 // CalculateComputableValues - Fill in the ComputableValues map through
363 // analysis of the patterns we are playing with.
364 void CalculateComputableValues();
366 // EmitMatchCosters - Given a list of patterns, which all have the same root
367 // pattern operator, emit an efficient decision tree to decide which one to
368 // pick. This is structured this way to avoid reevaluations of non-obvious
370 void EmitMatchCosters(std::ostream &OS,
371 const std::vector<std::pair<Pattern*, TreePatternNode*> > &Patterns,
372 const std::string &VarPrefix, unsigned Indent);
374 /// PrintExpanderOperand - Print out Arg as part of the instruction emission
375 /// process for the expander pattern P. This argument may be referencing some
376 /// values defined in P, or may just be physical register references or
377 /// something like that. If PrintArg is true, we are printing out arguments
378 /// to the BuildMI call. If it is false, we are printing the result register
380 void PrintExpanderOperand(Init *Arg, const std::string &NameVar,
381 TreePatternNode *ArgDecl, Pattern *P,
382 bool PrintArg, std::ostream &OS);