1 //===- InstrInfoEmitter.h - Generate a Instruction Set Desc. ----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This tablegen backend is responsible for emitting a description of the target
11 // instruction set for the code generator.
13 //===----------------------------------------------------------------------===//
15 #ifndef INSTRSELECTOR_EMITTER_H
16 #define INSTRSELECTOR_EMITTER_H
18 #include "TableGenBackend.h"
19 #include "CodeGenWrappers.h"
28 class InstrSelectorEmitter;
30 /// NodeType - Represents Information parsed from the DagNode entries.
34 Any, // No constraint on type
35 Val, // A non-void type
36 Arg0, // Value matches the type of Arg0
37 Arg1, // Value matches the type of Arg1
38 Ptr, // Tree node is the type of the target pointer
40 Void, // Tree node always returns void
43 ArgResultTypes ResultType;
44 std::vector<ArgResultTypes> ArgTypes;
46 NodeType(ArgResultTypes RT, std::vector<ArgResultTypes> &AT) : ResultType(RT){
50 NodeType() : ResultType(Val) {}
51 NodeType(const NodeType &N) : ResultType(N.ResultType), ArgTypes(N.ArgTypes){}
53 static ArgResultTypes Translate(Record *R);
58 /// TreePatternNode - Represent a node of the tree patterns.
60 class TreePatternNode {
61 /// Operator - The operation that this node represents... this is null if this
65 /// Type - The inferred value type...
69 /// Children - If this is not a leaf (Operator != 0), this is the subtrees
71 std::vector<std::pair<TreePatternNode*, std::string> > Children;
73 /// Value - If this node is a leaf, this indicates what the thing is.
77 TreePatternNode(Record *o, const std::vector<std::pair<TreePatternNode*,
79 : Operator(o), Type(MVT::Other), Children(c), Value(0) {}
80 TreePatternNode(Init *V) : Operator(0), Type(MVT::Other), Value(V) {}
82 Record *getOperator() const {
83 assert(Operator && "This is a leaf node!");
86 MVT::ValueType getType() const { return Type; }
87 void setType(MVT::ValueType T) { Type = T; }
89 bool isLeaf() const { return Operator == 0; }
91 unsigned getNumChildren() const { return Children.size(); }
92 TreePatternNode *getChild(unsigned c) const {
93 assert(Operator != 0 && "This is a leaf node!");
94 assert(c < Children.size() && "Child access out of range!");
95 return Children[c].first;
97 const std::string &getChildName(unsigned c) const {
98 assert(Operator != 0 && "This is a leaf node!");
99 assert(c < Children.size() && "Child access out of range!");
100 return Children[c].second;
103 Init *getValue() const {
104 assert(Operator == 0 && "This is not a leaf node!");
108 /// getValueRecord - Returns the value of this tree node as a record. For now
109 /// we only allow DefInit's as our leaf values, so this is used.
110 Record *getValueRecord() const;
112 /// clone - Make a copy of this tree and all of its children.
114 TreePatternNode *clone() const;
118 /// InstantiateNonterminals - If this pattern refers to any nonterminals which
119 /// are not themselves completely resolved, clone the nonterminal and resolve
120 /// it with the using context we provide.
121 void InstantiateNonterminals(InstrSelectorEmitter &ISE);
123 /// UpdateNodeType - Set the node type of N to VT if VT contains information.
124 /// If N already contains a conflicting type, then throw an exception. This
125 /// returns true if any information was updated.
127 bool updateNodeType(MVT::ValueType VT, const std::string &RecName);
130 std::ostream &operator<<(std::ostream &OS, const TreePatternNode &N);
134 /// Pattern - Represent a pattern of one form or another. Currently, three
135 /// types of patterns are possible: Instruction's, Nonterminals, and Expanders.
139 Nonterminal, Instruction, Expander
142 /// PTy - The type of pattern this is.
146 /// Tree - The tree pattern which corresponds to this pattern. Note that if
147 /// there was a (set) node on the outside level that it has been stripped off.
149 TreePatternNode *Tree;
151 /// Result - If this is an instruction or expander pattern, this is the
152 /// register result, specified with a (set) in the pattern.
154 std::string ResultName; // The name of the result value...
155 TreePatternNode *ResultNode; // The leaf node for the result register...
157 /// TheRecord - The actual TableGen record corresponding to this pattern.
161 /// Resolved - This is true of the pattern is useful in practice. In
162 /// particular, some non-terminals will have non-resolvable types. When a
163 /// user of the non-terminal is later found, they will have inferred a type
164 /// for the result of the non-terminal, which cause a clone of an unresolved
165 /// nonterminal to be made which is "resolved".
169 /// Args - This is a list of all of the arguments to this pattern, which are
170 /// the non-void leaf nodes in this pattern.
171 std::vector<std::pair<TreePatternNode*, std::string> > Args;
173 /// ISE - the instruction selector emitter coordinating this madness.
175 InstrSelectorEmitter &ISE;
178 /// Pattern constructor - Parse the specified DagInitializer into the current
180 Pattern(PatternType pty, DagInit *RawPat, Record *TheRec,
181 InstrSelectorEmitter &ise);
183 /// Pattern - Constructor used for cloning nonterminal patterns
184 Pattern(TreePatternNode *tree, Record *rec, bool res,
185 InstrSelectorEmitter &ise)
186 : PTy(Nonterminal), Tree(tree), ResultNode(0), TheRecord(rec),
187 Resolved(res), ISE(ise) {
188 calculateArgs(Tree, "");
191 /// getPatternType - Return what flavor of Record this pattern originated from
193 PatternType getPatternType() const { return PTy; }
195 /// getTree - Return the tree pattern which corresponds to this pattern.
197 TreePatternNode *getTree() const { return Tree; }
199 Record *getResult() const {
200 return ResultNode ? ResultNode->getValueRecord() : 0;
202 const std::string &getResultName() const { return ResultName; }
203 TreePatternNode *getResultNode() const { return ResultNode; }
205 /// getRecord - Return the actual TableGen record corresponding to this
208 Record *getRecord() const { return TheRecord; }
210 unsigned getNumArgs() const { return Args.size(); }
211 TreePatternNode *getArg(unsigned i) const {
212 assert(i < Args.size() && "Argument reference out of range!");
213 return Args[i].first;
215 Record *getArgRec(unsigned i) const {
216 return getArg(i)->getValueRecord();
218 Init *getArgVal(unsigned i) const {
219 return getArg(i)->getValue();
221 const std::string &getArgName(unsigned i) const {
222 assert(i < Args.size() && "Argument reference out of range!");
223 return Args[i].second;
226 bool isResolved() const { return Resolved; }
228 /// InferAllTypes - Runs the type inference engine on the current pattern,
229 /// stopping when nothing can be inferred, then updating the Resolved field.
230 void InferAllTypes();
232 /// InstantiateNonterminals - If this pattern refers to any nonterminals which
233 /// are not themselves completely resolved, clone the nonterminal and resolve
234 /// it with the using context we provide.
235 void InstantiateNonterminals() {
236 Tree->InstantiateNonterminals(ISE);
239 /// clone - This method is used to make an exact copy of the current pattern,
240 /// then change the "TheRecord" instance variable to the specified record.
242 Pattern *clone(Record *R) const;
244 /// error - Throw an exception, prefixing it with information about this
246 void error(const std::string &Msg) const;
248 /// getSlotName - If this is a leaf node, return the slot name that the
249 /// operand will update.
250 std::string getSlotName() const;
251 static std::string getSlotName(Record *R);
256 void calculateArgs(TreePatternNode *N, const std::string &Name);
257 MVT::ValueType getIntrinsicType(Record *R) const;
258 TreePatternNode *ParseTreePattern(DagInit *DI);
259 bool InferTypes(TreePatternNode *N, bool &MadeChange);
262 std::ostream &operator<<(std::ostream &OS, const Pattern &P);
265 /// PatternOrganizer - This class represents all of the patterns which are
266 /// useful for the instruction selector, neatly catagorized in a hierarchical
268 struct PatternOrganizer {
269 /// PatternsForNode - The list of patterns which can produce a value of a
270 /// particular slot type, given a particular root node in the tree. All of
271 /// the patterns in this vector produce the same value type and have the same
273 typedef std::vector<Pattern*> PatternsForNode;
275 /// NodesForSlot - This map keeps track of all of the root DAG nodes which can
276 /// lead to the production of a value for this slot. All of the patterns in
277 /// this data structure produces values of the same slot.
278 typedef std::map<Record*, PatternsForNode> NodesForSlot;
280 /// AllPatterns - This data structure contains all patterns in the instruction
282 std::map<std::string, NodesForSlot> AllPatterns;
284 // Forwarding functions...
285 typedef std::map<std::string, NodesForSlot>::iterator iterator;
286 iterator begin() { return AllPatterns.begin(); }
287 iterator end() { return AllPatterns.end(); }
290 /// addPattern - Add the specified pattern to the appropriate location in the
292 void addPattern(Pattern *P);
296 /// InstrSelectorEmitter - The top-level class which coordinates construction
297 /// and emission of the instruction selector.
299 class InstrSelectorEmitter : public TableGenBackend {
300 RecordKeeper &Records;
301 CodeGenTarget Target;
303 std::map<Record*, NodeType> NodeTypes;
305 /// Patterns - a list of all of the patterns defined by the target description
307 std::map<Record*, Pattern*> Patterns;
309 /// InstantiatedNTs - A data structure to keep track of which nonterminals
310 /// have been instantiated already...
312 std::map<std::pair<Pattern*,MVT::ValueType>, Record*> InstantiatedNTs;
314 /// ComputableValues - This map indicates which patterns can be used to
315 /// generate a value that is used by the selector. The keys of this map
316 /// implicitly define the values that are used by the selector.
318 PatternOrganizer ComputableValues;
321 InstrSelectorEmitter(RecordKeeper &R) : Records(R) {}
323 // run - Output the instruction set description, returning true on failure.
324 void run(std::ostream &OS);
326 const CodeGenTarget &getTarget() const { return Target; }
327 std::map<Record*, NodeType> &getNodeTypes() { return NodeTypes; }
328 const NodeType &getNodeType(Record *R) const {
329 std::map<Record*, NodeType>::const_iterator I = NodeTypes.find(R);
330 assert(I != NodeTypes.end() && "Unknown node type!");
334 /// getPattern - return the pattern corresponding to the specified record, or
335 /// null if there is none.
336 Pattern *getPattern(Record *R) const {
337 std::map<Record*, Pattern*>::const_iterator I = Patterns.find(R);
338 return I != Patterns.end() ? I->second : 0;
341 /// ReadNonterminal - This method parses the specified record as a
342 /// nonterminal, but only if it hasn't been read in already.
343 Pattern *ReadNonterminal(Record *R);
345 /// InstantiateNonterminal - This method takes the nonterminal specified by
346 /// NT, which should not be completely resolved, clones it, applies ResultTy
347 /// to its root, then runs the type inference stuff on it. This should
348 /// produce a newly resolved nonterminal, which we make a record for and
349 /// return. To be extra fancy and efficient, this only makes one clone for
350 /// each type it is instantiated with.
351 Record *InstantiateNonterminal(Pattern *NT, MVT::ValueType ResultTy);
354 // ReadNodeTypes - Read in all of the node types in the current RecordKeeper,
355 // turning them into the more accessible NodeTypes data structure.
356 void ReadNodeTypes();
358 // ReadNonTerminals - Read in all nonterminals and incorporate them into our
360 void ReadNonterminals();
362 // ReadInstructionPatterns - Read in all subclasses of Instruction, and
363 // process those with a useful Pattern field.
364 void ReadInstructionPatterns();
366 // ReadExpanderPatterns - Read in all of the expanded patterns.
367 void ReadExpanderPatterns();
369 // InstantiateNonterminals - Instantiate any unresolved nonterminals with
370 // information from the context that they are used in.
371 void InstantiateNonterminals();
373 // CalculateComputableValues - Fill in the ComputableValues map through
374 // analysis of the patterns we are playing with.
375 void CalculateComputableValues();
377 // EmitMatchCosters - Given a list of patterns, which all have the same root
378 // pattern operator, emit an efficient decision tree to decide which one to
379 // pick. This is structured this way to avoid reevaluations of non-obvious
381 void EmitMatchCosters(std::ostream &OS,
382 const std::vector<std::pair<Pattern*, TreePatternNode*> > &Patterns,
383 const std::string &VarPrefix, unsigned Indent);
385 /// PrintExpanderOperand - Print out Arg as part of the instruction emission
386 /// process for the expander pattern P. This argument may be referencing some
387 /// values defined in P, or may just be physical register references or
388 /// something like that. If PrintArg is true, we are printing out arguments
389 /// to the BuildMI call. If it is false, we are printing the result register
391 void PrintExpanderOperand(Init *Arg, const std::string &NameVar,
392 TreePatternNode *ArgDecl, Pattern *P,
393 bool PrintArg, std::ostream &OS);
396 } // End llvm namespace