blob: dde7f6770dfdda3a931e9edf09c1b580dc5a0b79 [file] [log] [blame]
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001//===- DAGISelEmitter.cpp - Generate an instruction selector --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
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.
7//
8//===----------------------------------------------------------------------===//
9//
10// This tablegen backend emits a DAG instruction selector.
11//
12//===----------------------------------------------------------------------===//
13
14#include "DAGISelEmitter.h"
15#include "Record.h"
16#include "llvm/ADT/StringExtras.h"
17#include "llvm/Support/Debug.h"
Jeff Cohena48283b2005-09-25 19:04:43 +000018#include <algorithm>
Chris Lattner54cb8fd2005-09-07 23:44:43 +000019#include <set>
20using namespace llvm;
21
Chris Lattnerca559d02005-09-08 21:03:01 +000022//===----------------------------------------------------------------------===//
Chris Lattner33c92e92005-09-08 21:27:15 +000023// SDTypeConstraint implementation
24//
25
26SDTypeConstraint::SDTypeConstraint(Record *R) {
27 OperandNo = R->getValueAsInt("OperandNum");
28
29 if (R->isSubClassOf("SDTCisVT")) {
30 ConstraintType = SDTCisVT;
31 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
32 } else if (R->isSubClassOf("SDTCisInt")) {
33 ConstraintType = SDTCisInt;
34 } else if (R->isSubClassOf("SDTCisFP")) {
35 ConstraintType = SDTCisFP;
36 } else if (R->isSubClassOf("SDTCisSameAs")) {
37 ConstraintType = SDTCisSameAs;
38 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
39 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
40 ConstraintType = SDTCisVTSmallerThanOp;
41 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
42 R->getValueAsInt("OtherOperandNum");
43 } else {
44 std::cerr << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
45 exit(1);
46 }
47}
48
Chris Lattner32707602005-09-08 23:22:48 +000049/// getOperandNum - Return the node corresponding to operand #OpNo in tree
50/// N, which has NumResults results.
51TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
52 TreePatternNode *N,
53 unsigned NumResults) const {
54 assert(NumResults == 1 && "We only work with single result nodes so far!");
55
56 if (OpNo < NumResults)
57 return N; // FIXME: need value #
58 else
59 return N->getChild(OpNo-NumResults);
60}
61
62/// ApplyTypeConstraint - Given a node in a pattern, apply this type
63/// constraint to the nodes operands. This returns true if it makes a
64/// change, false otherwise. If a type contradiction is found, throw an
65/// exception.
66bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
67 const SDNodeInfo &NodeInfo,
68 TreePattern &TP) const {
69 unsigned NumResults = NodeInfo.getNumResults();
70 assert(NumResults == 1 && "We only work with single result nodes so far!");
71
72 // Check that the number of operands is sane.
73 if (NodeInfo.getNumOperands() >= 0) {
74 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
75 TP.error(N->getOperator()->getName() + " node requires exactly " +
76 itostr(NodeInfo.getNumOperands()) + " operands!");
77 }
78
79 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
80
81 switch (ConstraintType) {
82 default: assert(0 && "Unknown constraint type!");
83 case SDTCisVT:
84 // Operand must be a particular type.
85 return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
86 case SDTCisInt:
87 if (NodeToApply->hasTypeSet() && !MVT::isInteger(NodeToApply->getType()))
88 NodeToApply->UpdateNodeType(MVT::i1, TP); // throw an error.
89
90 // FIXME: can tell from the target if there is only one Int type supported.
91 return false;
92 case SDTCisFP:
93 if (NodeToApply->hasTypeSet() &&
94 !MVT::isFloatingPoint(NodeToApply->getType()))
95 NodeToApply->UpdateNodeType(MVT::f32, TP); // throw an error.
96 // FIXME: can tell from the target if there is only one FP type supported.
97 return false;
98 case SDTCisSameAs: {
99 TreePatternNode *OtherNode =
100 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
101 return NodeToApply->UpdateNodeType(OtherNode->getType(), TP) |
102 OtherNode->UpdateNodeType(NodeToApply->getType(), TP);
103 }
104 case SDTCisVTSmallerThanOp: {
105 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
106 // have an integer type that is smaller than the VT.
107 if (!NodeToApply->isLeaf() ||
108 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
109 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
110 ->isSubClassOf("ValueType"))
111 TP.error(N->getOperator()->getName() + " expects a VT operand!");
112 MVT::ValueType VT =
113 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
114 if (!MVT::isInteger(VT))
115 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
116
117 TreePatternNode *OtherNode =
118 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
119 if (OtherNode->hasTypeSet() &&
120 (!MVT::isInteger(OtherNode->getType()) ||
121 OtherNode->getType() <= VT))
122 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
123 return false;
124 }
125 }
126 return false;
127}
128
129
Chris Lattner33c92e92005-09-08 21:27:15 +0000130//===----------------------------------------------------------------------===//
Chris Lattnerca559d02005-09-08 21:03:01 +0000131// SDNodeInfo implementation
132//
133SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
134 EnumName = R->getValueAsString("Opcode");
135 SDClassName = R->getValueAsString("SDClass");
Chris Lattner33c92e92005-09-08 21:27:15 +0000136 Record *TypeProfile = R->getValueAsDef("TypeProfile");
137 NumResults = TypeProfile->getValueAsInt("NumResults");
138 NumOperands = TypeProfile->getValueAsInt("NumOperands");
139
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000140 // Parse the properties.
141 Properties = 0;
142 ListInit *LI = R->getValueAsListInit("Properties");
143 for (unsigned i = 0, e = LI->getSize(); i != e; ++i) {
144 DefInit *DI = dynamic_cast<DefInit*>(LI->getElement(i));
145 assert(DI && "Properties list must be list of defs!");
146 if (DI->getDef()->getName() == "SDNPCommutative") {
147 Properties |= 1 << SDNPCommutative;
148 } else {
149 std::cerr << "Unknown SD Node property '" << DI->getDef()->getName()
150 << "' on node '" << R->getName() << "'!\n";
151 exit(1);
152 }
153 }
154
155
Chris Lattner33c92e92005-09-08 21:27:15 +0000156 // Parse the type constraints.
157 ListInit *Constraints = TypeProfile->getValueAsListInit("Constraints");
158 for (unsigned i = 0, e = Constraints->getSize(); i != e; ++i) {
159 assert(dynamic_cast<DefInit*>(Constraints->getElement(i)) &&
160 "Constraints list should contain constraint definitions!");
161 Record *Constraint =
162 static_cast<DefInit*>(Constraints->getElement(i))->getDef();
163 TypeConstraints.push_back(Constraint);
164 }
Chris Lattnerca559d02005-09-08 21:03:01 +0000165}
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000166
167//===----------------------------------------------------------------------===//
168// TreePatternNode implementation
169//
170
171TreePatternNode::~TreePatternNode() {
172#if 0 // FIXME: implement refcounted tree nodes!
173 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
174 delete getChild(i);
175#endif
176}
177
Chris Lattner32707602005-09-08 23:22:48 +0000178/// UpdateNodeType - Set the node type of N to VT if VT contains
179/// information. If N already contains a conflicting type, then throw an
180/// exception. This returns true if any information was updated.
181///
182bool TreePatternNode::UpdateNodeType(MVT::ValueType VT, TreePattern &TP) {
183 if (VT == MVT::LAST_VALUETYPE || getType() == VT) return false;
184 if (getType() == MVT::LAST_VALUETYPE) {
185 setType(VT);
186 return true;
187 }
188
189 TP.error("Type inference contradiction found in node " +
190 getOperator()->getName() + "!");
191 return true; // unreachable
192}
193
194
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000195void TreePatternNode::print(std::ostream &OS) const {
196 if (isLeaf()) {
197 OS << *getLeafValue();
198 } else {
199 OS << "(" << getOperator()->getName();
200 }
201
202 if (getType() == MVT::Other)
203 OS << ":Other";
204 else if (getType() == MVT::LAST_VALUETYPE)
205 ;//OS << ":?";
206 else
207 OS << ":" << getType();
208
209 if (!isLeaf()) {
210 if (getNumChildren() != 0) {
211 OS << " ";
212 getChild(0)->print(OS);
213 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
214 OS << ", ";
215 getChild(i)->print(OS);
216 }
217 }
218 OS << ")";
219 }
220
221 if (!PredicateFn.empty())
Chris Lattner24eeeb82005-09-13 21:51:00 +0000222 OS << "<<P:" << PredicateFn << ">>";
Chris Lattnerb0276202005-09-14 22:55:26 +0000223 if (TransformFn)
224 OS << "<<X:" << TransformFn->getName() << ">>";
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000225 if (!getName().empty())
226 OS << ":$" << getName();
227
228}
229void TreePatternNode::dump() const {
230 print(std::cerr);
231}
232
233/// clone - Make a copy of this tree and all of its children.
234///
235TreePatternNode *TreePatternNode::clone() const {
236 TreePatternNode *New;
237 if (isLeaf()) {
238 New = new TreePatternNode(getLeafValue());
239 } else {
240 std::vector<TreePatternNode*> CChildren;
241 CChildren.reserve(Children.size());
242 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
243 CChildren.push_back(getChild(i)->clone());
244 New = new TreePatternNode(getOperator(), CChildren);
245 }
246 New->setName(getName());
247 New->setType(getType());
248 New->setPredicateFn(getPredicateFn());
Chris Lattner24eeeb82005-09-13 21:51:00 +0000249 New->setTransformFn(getTransformFn());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000250 return New;
251}
252
Chris Lattner32707602005-09-08 23:22:48 +0000253/// SubstituteFormalArguments - Replace the formal arguments in this tree
254/// with actual values specified by ArgMap.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000255void TreePatternNode::
256SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
257 if (isLeaf()) return;
258
259 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
260 TreePatternNode *Child = getChild(i);
261 if (Child->isLeaf()) {
262 Init *Val = Child->getLeafValue();
263 if (dynamic_cast<DefInit*>(Val) &&
264 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
265 // We found a use of a formal argument, replace it with its value.
266 Child = ArgMap[Child->getName()];
267 assert(Child && "Couldn't find formal argument!");
268 setChild(i, Child);
269 }
270 } else {
271 getChild(i)->SubstituteFormalArguments(ArgMap);
272 }
273 }
274}
275
276
277/// InlinePatternFragments - If this pattern refers to any pattern
278/// fragments, inline them into place, giving us a pattern without any
279/// PatFrag references.
280TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
281 if (isLeaf()) return this; // nothing to do.
282 Record *Op = getOperator();
283
284 if (!Op->isSubClassOf("PatFrag")) {
285 // Just recursively inline children nodes.
286 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
287 setChild(i, getChild(i)->InlinePatternFragments(TP));
288 return this;
289 }
290
291 // Otherwise, we found a reference to a fragment. First, look up its
292 // TreePattern record.
293 TreePattern *Frag = TP.getDAGISelEmitter().getPatternFragment(Op);
294
295 // Verify that we are passing the right number of operands.
296 if (Frag->getNumArgs() != Children.size())
297 TP.error("'" + Op->getName() + "' fragment requires " +
298 utostr(Frag->getNumArgs()) + " operands!");
299
Chris Lattner37937092005-09-09 01:15:01 +0000300 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000301
302 // Resolve formal arguments to their actual value.
303 if (Frag->getNumArgs()) {
304 // Compute the map of formal to actual arguments.
305 std::map<std::string, TreePatternNode*> ArgMap;
306 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
307 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
308
309 FragTree->SubstituteFormalArguments(ArgMap);
310 }
311
Chris Lattnerfbf8e572005-09-08 17:45:12 +0000312 FragTree->setName(getName());
313
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000314 // Get a new copy of this fragment to stitch into here.
315 //delete this; // FIXME: implement refcounting!
316 return FragTree;
317}
318
Chris Lattner32707602005-09-08 23:22:48 +0000319/// ApplyTypeConstraints - Apply all of the type constraints relevent to
320/// this node and its children in the tree. This returns true if it makes a
321/// change, false otherwise. If a type contradiction is found, throw an
322/// exception.
323bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP) {
324 if (isLeaf()) return false;
325
326 // special handling for set, which isn't really an SDNode.
327 if (getOperator()->getName() == "set") {
328 assert (getNumChildren() == 2 && "Only handle 2 operand set's for now!");
329 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP);
330 MadeChange |= getChild(1)->ApplyTypeConstraints(TP);
331
332 // Types of operands must match.
333 MadeChange |= getChild(0)->UpdateNodeType(getChild(1)->getType(), TP);
334 MadeChange |= getChild(1)->UpdateNodeType(getChild(0)->getType(), TP);
335 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
336 return MadeChange;
Chris Lattnerabbb6052005-09-15 21:42:00 +0000337 } else if (getOperator()->isSubClassOf("SDNode")) {
338 const SDNodeInfo &NI = TP.getDAGISelEmitter().getSDNodeInfo(getOperator());
339
340 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
341 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
342 MadeChange |= getChild(i)->ApplyTypeConstraints(TP);
343 return MadeChange;
Chris Lattnera28aec12005-09-15 22:23:50 +0000344 } else if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattnerae5b3502005-09-15 21:57:35 +0000345 const DAGInstruction &Inst =
346 TP.getDAGISelEmitter().getInstruction(getOperator());
347
Chris Lattnera28aec12005-09-15 22:23:50 +0000348 assert(Inst.getNumResults() == 1 && "Only supports one result instrs!");
349 // Apply the result type to the node
350 bool MadeChange = UpdateNodeType(Inst.getResultType(0), TP);
351
352 if (getNumChildren() != Inst.getNumOperands())
353 TP.error("Instruction '" + getOperator()->getName() + " expects " +
354 utostr(Inst.getNumOperands()) + " operands, not " +
355 utostr(getNumChildren()) + " operands!");
356 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
357 MadeChange |= getChild(i)->UpdateNodeType(Inst.getOperandType(i), TP);
358 MadeChange |= getChild(i)->ApplyTypeConstraints(TP);
359 }
360 return MadeChange;
361 } else {
362 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
363
364 // Node transforms always take one operand, and take and return the same
365 // type.
366 if (getNumChildren() != 1)
367 TP.error("Node transform '" + getOperator()->getName() +
368 "' requires one operand!");
369 bool MadeChange = UpdateNodeType(getChild(0)->getType(), TP);
370 MadeChange |= getChild(0)->UpdateNodeType(getType(), TP);
371 return MadeChange;
Chris Lattner32707602005-09-08 23:22:48 +0000372 }
Chris Lattner32707602005-09-08 23:22:48 +0000373}
374
375
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000376//===----------------------------------------------------------------------===//
377// TreePattern implementation
378//
379
Chris Lattnera28aec12005-09-15 22:23:50 +0000380TreePattern::TreePattern(Record *TheRec, ListInit *RawPat,
Chris Lattneree9f0c32005-09-13 21:20:49 +0000381 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattnera28aec12005-09-15 22:23:50 +0000382 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
383 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000384}
385
Chris Lattnera28aec12005-09-15 22:23:50 +0000386TreePattern::TreePattern(Record *TheRec, DagInit *Pat,
387 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
388 Trees.push_back(ParseTreePattern(Pat));
389}
390
391TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat,
392 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
393 Trees.push_back(Pat);
394}
395
396
397
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000398void TreePattern::error(const std::string &Msg) const {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000399 dump();
Chris Lattneree9f0c32005-09-13 21:20:49 +0000400 throw "In " + TheRecord->getName() + ": " + Msg;
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000401}
402
403/// getIntrinsicType - Check to see if the specified record has an intrinsic
404/// type which should be applied to it. This infer the type of register
405/// references from the register file information, for example.
406///
407MVT::ValueType TreePattern::getIntrinsicType(Record *R) const {
408 // Check to see if this is a register or a register class...
409 if (R->isSubClassOf("RegisterClass"))
410 return getValueType(R->getValueAsDef("RegType"));
411 else if (R->isSubClassOf("PatFrag")) {
Chris Lattner37937092005-09-09 01:15:01 +0000412 // Pattern fragment types will be resolved when they are inlined.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000413 return MVT::LAST_VALUETYPE;
414 } else if (R->isSubClassOf("Register")) {
415 assert(0 && "Explicit registers not handled here yet!\n");
416 return MVT::LAST_VALUETYPE;
417 } else if (R->isSubClassOf("ValueType")) {
418 // Using a VTSDNode.
419 return MVT::Other;
420 } else if (R->getName() == "node") {
421 // Placeholder.
422 return MVT::LAST_VALUETYPE;
423 }
424
Chris Lattner72fe91c2005-09-24 00:40:24 +0000425 error("Unknown node flavor used in pattern: " + R->getName());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000426 return MVT::Other;
427}
428
429TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
430 Record *Operator = Dag->getNodeType();
431
432 if (Operator->isSubClassOf("ValueType")) {
433 // If the operator is a ValueType, then this must be "type cast" of a leaf
434 // node.
435 if (Dag->getNumArgs() != 1)
436 error("Type cast only valid for a leaf node!");
437
438 Init *Arg = Dag->getArg(0);
439 TreePatternNode *New;
440 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
Chris Lattner72fe91c2005-09-24 00:40:24 +0000441 Record *R = DI->getDef();
442 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
443 Dag->setArg(0, new DagInit(R,
444 std::vector<std::pair<Init*, std::string> >()));
445 TreePatternNode *TPN = ParseTreePattern(Dag);
446 TPN->setName(Dag->getArgName(0));
447 return TPN;
448 }
449
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000450 New = new TreePatternNode(DI);
451 // If it's a regclass or something else known, set the type.
452 New->setType(getIntrinsicType(DI->getDef()));
453 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
454 New = ParseTreePattern(DI);
455 } else {
456 Arg->dump();
457 error("Unknown leaf value for tree pattern!");
458 return 0;
459 }
460
Chris Lattner32707602005-09-08 23:22:48 +0000461 // Apply the type cast.
462 New->UpdateNodeType(getValueType(Operator), *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000463 return New;
464 }
465
466 // Verify that this is something that makes sense for an operator.
467 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
Chris Lattnerabbb6052005-09-15 21:42:00 +0000468 !Operator->isSubClassOf("Instruction") &&
469 !Operator->isSubClassOf("SDNodeXForm") &&
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000470 Operator->getName() != "set")
471 error("Unrecognized node '" + Operator->getName() + "'!");
472
473 std::vector<TreePatternNode*> Children;
474
475 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
476 Init *Arg = Dag->getArg(i);
477 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
478 Children.push_back(ParseTreePattern(DI));
479 Children.back()->setName(Dag->getArgName(i));
480 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
481 Record *R = DefI->getDef();
482 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
483 // TreePatternNode if its own.
484 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
485 Dag->setArg(i, new DagInit(R,
486 std::vector<std::pair<Init*, std::string> >()));
487 --i; // Revisit this node...
488 } else {
489 TreePatternNode *Node = new TreePatternNode(DefI);
490 Node->setName(Dag->getArgName(i));
491 Children.push_back(Node);
492
493 // If it's a regclass or something else known, set the type.
494 Node->setType(getIntrinsicType(R));
495
496 // Input argument?
497 if (R->getName() == "node") {
498 if (Dag->getArgName(i).empty())
499 error("'node' argument requires a name to match with operand list");
500 Args.push_back(Dag->getArgName(i));
501 }
502 }
503 } else {
504 Arg->dump();
505 error("Unknown leaf value for tree pattern!");
506 }
507 }
508
509 return new TreePatternNode(Operator, Children);
510}
511
Chris Lattner32707602005-09-08 23:22:48 +0000512/// InferAllTypes - Infer/propagate as many types throughout the expression
513/// patterns as possible. Return true if all types are infered, false
514/// otherwise. Throw an exception if a type contradiction is found.
515bool TreePattern::InferAllTypes() {
516 bool MadeChange = true;
517 while (MadeChange) {
518 MadeChange = false;
519 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
520 MadeChange |= Trees[i]->ApplyTypeConstraints(*this);
521 }
522
523 bool HasUnresolvedTypes = false;
524 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
525 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
526 return !HasUnresolvedTypes;
527}
528
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000529void TreePattern::print(std::ostream &OS) const {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000530 OS << getRecord()->getName();
531 if (!Args.empty()) {
532 OS << "(" << Args[0];
533 for (unsigned i = 1, e = Args.size(); i != e; ++i)
534 OS << ", " << Args[i];
535 OS << ")";
536 }
537 OS << ": ";
538
539 if (Trees.size() > 1)
540 OS << "[\n";
541 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
542 OS << "\t";
543 Trees[i]->print(OS);
544 OS << "\n";
545 }
546
547 if (Trees.size() > 1)
548 OS << "]\n";
549}
550
551void TreePattern::dump() const { print(std::cerr); }
552
553
554
555//===----------------------------------------------------------------------===//
556// DAGISelEmitter implementation
557//
558
Chris Lattnerca559d02005-09-08 21:03:01 +0000559// Parse all of the SDNode definitions for the target, populating SDNodes.
560void DAGISelEmitter::ParseNodeInfo() {
561 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
562 while (!Nodes.empty()) {
563 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
564 Nodes.pop_back();
565 }
566}
567
Chris Lattner24eeeb82005-09-13 21:51:00 +0000568/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
569/// map, and emit them to the file as functions.
570void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
571 OS << "\n// Node transformations.\n";
572 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
573 while (!Xforms.empty()) {
574 Record *XFormNode = Xforms.back();
575 Record *SDNode = XFormNode->getValueAsDef("Opcode");
576 std::string Code = XFormNode->getValueAsCode("XFormFunction");
577 SDNodeXForms.insert(std::make_pair(XFormNode,
578 std::make_pair(SDNode, Code)));
579
Chris Lattner1048b7a2005-09-13 22:03:37 +0000580 if (!Code.empty()) {
Chris Lattner24eeeb82005-09-13 21:51:00 +0000581 std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
582 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
583
Chris Lattner1048b7a2005-09-13 22:03:37 +0000584 OS << "inline SDOperand Transform_" << XFormNode->getName()
Chris Lattner24eeeb82005-09-13 21:51:00 +0000585 << "(SDNode *" << C2 << ") {\n";
586 if (ClassName != "SDNode")
587 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
588 OS << Code << "\n}\n";
589 }
590
591 Xforms.pop_back();
592 }
593}
594
595
596
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000597/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
598/// file, building up the PatternFragments map. After we've collected them all,
599/// inline fragments together as necessary, so that there are no references left
600/// inside a pattern fragment to a pattern fragment.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000601///
602/// This also emits all of the predicate functions to the output file.
603///
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000604void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000605 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
606
607 // First step, parse all of the fragments and emit predicate functions.
608 OS << "\n// Predicate functions.\n";
609 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +0000610 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
611 TreePattern *P = new TreePattern(Fragments[i], Tree, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000612 PatternFragments[Fragments[i]] = P;
Chris Lattneree9f0c32005-09-13 21:20:49 +0000613
614 // Validate the argument list, converting it to map, to discard duplicates.
615 std::vector<std::string> &Args = P->getArgList();
616 std::set<std::string> OperandsMap(Args.begin(), Args.end());
617
618 if (OperandsMap.count(""))
619 P->error("Cannot have unnamed 'node' values in pattern fragment!");
620
621 // Parse the operands list.
622 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
623 if (OpsList->getNodeType()->getName() != "ops")
624 P->error("Operands list should start with '(ops ... '!");
625
626 // Copy over the arguments.
627 Args.clear();
628 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
629 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
630 static_cast<DefInit*>(OpsList->getArg(j))->
631 getDef()->getName() != "node")
632 P->error("Operands list should all be 'node' values.");
633 if (OpsList->getArgName(j).empty())
634 P->error("Operands list should have names for each operand!");
635 if (!OperandsMap.count(OpsList->getArgName(j)))
636 P->error("'" + OpsList->getArgName(j) +
637 "' does not occur in pattern or was multiply specified!");
638 OperandsMap.erase(OpsList->getArgName(j));
639 Args.push_back(OpsList->getArgName(j));
640 }
641
642 if (!OperandsMap.empty())
643 P->error("Operands list does not contain an entry for operand '" +
644 *OperandsMap.begin() + "'!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000645
646 // If there is a code init for this fragment, emit the predicate code and
647 // keep track of the fact that this fragment uses it.
Chris Lattner24eeeb82005-09-13 21:51:00 +0000648 std::string Code = Fragments[i]->getValueAsCode("Predicate");
649 if (!Code.empty()) {
Chris Lattner37937092005-09-09 01:15:01 +0000650 assert(!P->getOnlyTree()->isLeaf() && "Can't be a leaf!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000651 std::string ClassName =
Chris Lattner37937092005-09-09 01:15:01 +0000652 getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000653 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
654
Chris Lattner1048b7a2005-09-13 22:03:37 +0000655 OS << "inline bool Predicate_" << Fragments[i]->getName()
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000656 << "(SDNode *" << C2 << ") {\n";
657 if (ClassName != "SDNode")
658 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
Chris Lattner24eeeb82005-09-13 21:51:00 +0000659 OS << Code << "\n}\n";
Chris Lattner37937092005-09-09 01:15:01 +0000660 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000661 }
Chris Lattner6de8b532005-09-13 21:59:15 +0000662
663 // If there is a node transformation corresponding to this, keep track of
664 // it.
665 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
666 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
Chris Lattnerb0276202005-09-14 22:55:26 +0000667 P->getOnlyTree()->setTransformFn(Transform);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000668 }
669
670 OS << "\n\n";
671
672 // Now that we've parsed all of the tree fragments, do a closure on them so
673 // that there are not references to PatFrags left inside of them.
674 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
675 E = PatternFragments.end(); I != E; ++I) {
Chris Lattner32707602005-09-08 23:22:48 +0000676 TreePattern *ThePat = I->second;
677 ThePat->InlinePatternFragments();
Chris Lattneree9f0c32005-09-13 21:20:49 +0000678
Chris Lattner32707602005-09-08 23:22:48 +0000679 // Infer as many types as possible. Don't worry about it if we don't infer
680 // all of them, some may depend on the inputs of the pattern.
681 try {
682 ThePat->InferAllTypes();
683 } catch (...) {
684 // If this pattern fragment is not supported by this target (no types can
685 // satisfy its constraints), just ignore it. If the bogus pattern is
686 // actually used by instructions, the type consistency error will be
687 // reported there.
688 }
689
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000690 // If debugging, print out the pattern fragment result.
Chris Lattner32707602005-09-08 23:22:48 +0000691 DEBUG(ThePat->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000692 }
693}
694
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000695/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
Chris Lattnerf1311842005-09-14 23:05:13 +0000696/// instruction input. Return true if this is a real use.
697static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000698 std::map<std::string, TreePatternNode*> &InstInputs) {
699 // No name -> not interesting.
Chris Lattner7da852f2005-09-14 22:06:36 +0000700 if (Pat->getName().empty()) {
701 if (Pat->isLeaf()) {
702 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
703 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
704 I->error("Input " + DI->getDef()->getName() + " must be named!");
705
706 }
Chris Lattnerf1311842005-09-14 23:05:13 +0000707 return false;
Chris Lattner7da852f2005-09-14 22:06:36 +0000708 }
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000709
710 Record *Rec;
711 if (Pat->isLeaf()) {
712 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
713 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
714 Rec = DI->getDef();
715 } else {
716 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
717 Rec = Pat->getOperator();
718 }
719
720 TreePatternNode *&Slot = InstInputs[Pat->getName()];
721 if (!Slot) {
722 Slot = Pat;
723 } else {
724 Record *SlotRec;
725 if (Slot->isLeaf()) {
Chris Lattnerb9f01eb2005-09-16 00:29:46 +0000726 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000727 } else {
728 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
729 SlotRec = Slot->getOperator();
730 }
731
732 // Ensure that the inputs agree if we've already seen this input.
733 if (Rec != SlotRec)
734 I->error("All $" + Pat->getName() + " inputs must agree with each other");
735 if (Slot->getType() != Pat->getType())
736 I->error("All $" + Pat->getName() + " inputs must agree with each other");
737 }
Chris Lattnerf1311842005-09-14 23:05:13 +0000738 return true;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000739}
740
741/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
742/// part of "I", the instruction), computing the set of inputs and outputs of
743/// the pattern. Report errors if we see anything naughty.
744void DAGISelEmitter::
745FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
746 std::map<std::string, TreePatternNode*> &InstInputs,
747 std::map<std::string, Record*> &InstResults) {
748 if (Pat->isLeaf()) {
Chris Lattnerf1311842005-09-14 23:05:13 +0000749 bool isUse = HandleUse(I, Pat, InstInputs);
750 if (!isUse && Pat->getTransformFn())
751 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000752 return;
753 } else if (Pat->getOperator()->getName() != "set") {
754 // If this is not a set, verify that the children nodes are not void typed,
755 // and recurse.
756 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
757 if (Pat->getChild(i)->getType() == MVT::isVoid)
758 I->error("Cannot have void nodes inside of patterns!");
759 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults);
760 }
761
762 // If this is a non-leaf node with no children, treat it basically as if
763 // it were a leaf. This handles nodes like (imm).
Chris Lattnerf1311842005-09-14 23:05:13 +0000764 bool isUse = false;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000765 if (Pat->getNumChildren() == 0)
Chris Lattnerf1311842005-09-14 23:05:13 +0000766 isUse = HandleUse(I, Pat, InstInputs);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000767
Chris Lattnerf1311842005-09-14 23:05:13 +0000768 if (!isUse && Pat->getTransformFn())
769 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000770 return;
771 }
772
773 // Otherwise, this is a set, validate and collect instruction results.
774 if (Pat->getNumChildren() == 0)
775 I->error("set requires operands!");
776 else if (Pat->getNumChildren() & 1)
777 I->error("set requires an even number of operands");
778
Chris Lattnerf1311842005-09-14 23:05:13 +0000779 if (Pat->getTransformFn())
780 I->error("Cannot specify a transform function on a set node!");
781
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000782 // Check the set destinations.
783 unsigned NumValues = Pat->getNumChildren()/2;
784 for (unsigned i = 0; i != NumValues; ++i) {
785 TreePatternNode *Dest = Pat->getChild(i);
786 if (!Dest->isLeaf())
787 I->error("set destination should be a virtual register!");
788
789 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
790 if (!Val)
791 I->error("set destination should be a virtual register!");
792
793 if (!Val->getDef()->isSubClassOf("RegisterClass"))
794 I->error("set destination should be a virtual register!");
795 if (Dest->getName().empty())
796 I->error("set destination must have a name!");
797 if (InstResults.count(Dest->getName()))
798 I->error("cannot set '" + Dest->getName() +"' multiple times");
799 InstResults[Dest->getName()] = Val->getDef();
800
801 // Verify and collect info from the computation.
802 FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
803 InstInputs, InstResults);
804 }
805}
806
807
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000808/// ParseInstructions - Parse all of the instructions, inlining and resolving
809/// any fragments involved. This populates the Instructions list with fully
810/// resolved instructions.
811void DAGISelEmitter::ParseInstructions() {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000812 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
813
814 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
815 if (!dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
816 continue; // no pattern yet, ignore it.
817
818 ListInit *LI = Instrs[i]->getValueAsListInit("Pattern");
819 if (LI->getSize() == 0) continue; // no pattern.
820
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000821 // Parse the instruction.
Chris Lattnera28aec12005-09-15 22:23:50 +0000822 TreePattern *I = new TreePattern(Instrs[i], LI, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000823 // Inline pattern fragments into it.
Chris Lattner32707602005-09-08 23:22:48 +0000824 I->InlinePatternFragments();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000825
Chris Lattner95f6b762005-09-08 23:26:30 +0000826 // Infer as many types as possible. If we cannot infer all of them, we can
827 // never do anything with this instruction pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +0000828 if (!I->InferAllTypes())
Chris Lattner32707602005-09-08 23:22:48 +0000829 I->error("Could not infer all types in pattern!");
Chris Lattnerf2a17a72005-09-09 01:11:44 +0000830
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000831 // InstInputs - Keep track of all of the inputs of the instruction, along
832 // with the record they are declared as.
833 std::map<std::string, TreePatternNode*> InstInputs;
834
835 // InstResults - Keep track of all the virtual registers that are 'set'
Chris Lattner5f8cb2a2005-09-14 02:11:12 +0000836 // in the instruction, including what reg class they are.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000837 std::map<std::string, Record*> InstResults;
838
Chris Lattner1f39e292005-09-14 00:09:24 +0000839 // Verify that the top-level forms in the instruction are of void type, and
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000840 // fill in the InstResults map.
Chris Lattner1f39e292005-09-14 00:09:24 +0000841 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
842 TreePatternNode *Pat = I->getTree(j);
843 if (Pat->getType() != MVT::isVoid) {
Chris Lattnerf2a17a72005-09-09 01:11:44 +0000844 I->dump();
845 I->error("Top-level forms in instruction pattern should have"
846 " void types");
847 }
Chris Lattner5f8cb2a2005-09-14 02:11:12 +0000848
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000849 // Find inputs and outputs, and verify the structure of the uses/defs.
850 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults);
Chris Lattner1f39e292005-09-14 00:09:24 +0000851 }
Chris Lattner5f8cb2a2005-09-14 02:11:12 +0000852
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000853 // Now that we have inputs and outputs of the pattern, inspect the operands
854 // list for the instruction. This determines the order that operands are
855 // added to the machine instruction the node corresponds to.
856 unsigned NumResults = InstResults.size();
Chris Lattner39e8af92005-09-14 18:19:25 +0000857
858 // Parse the operands list from the (ops) list, validating it.
859 std::vector<std::string> &Args = I->getArgList();
860 assert(Args.empty() && "Args list should still be empty here!");
861 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
862
863 // Check that all of the results occur first in the list.
Chris Lattnerae6d8282005-09-15 21:51:12 +0000864 std::vector<MVT::ValueType> ResultTypes;
Chris Lattner39e8af92005-09-14 18:19:25 +0000865 for (unsigned i = 0; i != NumResults; ++i) {
Chris Lattner3a7319d2005-09-14 21:04:12 +0000866 if (i == CGI.OperandList.size())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000867 I->error("'" + InstResults.begin()->first +
868 "' set but does not appear in operand list!");
Chris Lattner39e8af92005-09-14 18:19:25 +0000869 const std::string &OpName = CGI.OperandList[i].Name;
Chris Lattner39e8af92005-09-14 18:19:25 +0000870
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000871 // Check that it exists in InstResults.
872 Record *R = InstResults[OpName];
Chris Lattner39e8af92005-09-14 18:19:25 +0000873 if (R == 0)
874 I->error("Operand $" + OpName + " should be a set destination: all "
875 "outputs must occur before inputs in operand list!");
876
877 if (CGI.OperandList[i].Rec != R)
878 I->error("Operand $" + OpName + " class mismatch!");
879
Chris Lattnerae6d8282005-09-15 21:51:12 +0000880 // Remember the return type.
881 ResultTypes.push_back(CGI.OperandList[i].Ty);
882
Chris Lattner39e8af92005-09-14 18:19:25 +0000883 // Okay, this one checks out.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000884 InstResults.erase(OpName);
885 }
886
Chris Lattner0b592252005-09-14 21:59:34 +0000887 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
888 // the copy while we're checking the inputs.
889 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
Chris Lattnerb0276202005-09-14 22:55:26 +0000890
891 std::vector<TreePatternNode*> ResultNodeOperands;
Chris Lattnerae6d8282005-09-15 21:51:12 +0000892 std::vector<MVT::ValueType> OperandTypes;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000893 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
894 const std::string &OpName = CGI.OperandList[i].Name;
895 if (OpName.empty())
896 I->error("Operand #" + utostr(i) + " in operands list has no name!");
897
Chris Lattner0b592252005-09-14 21:59:34 +0000898 if (!InstInputsCheck.count(OpName))
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000899 I->error("Operand $" + OpName +
900 " does not appear in the instruction pattern");
Chris Lattner0b592252005-09-14 21:59:34 +0000901 TreePatternNode *InVal = InstInputsCheck[OpName];
Chris Lattnerb0276202005-09-14 22:55:26 +0000902 InstInputsCheck.erase(OpName); // It occurred, remove from map.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000903 if (CGI.OperandList[i].Ty != InVal->getType())
904 I->error("Operand $" + OpName +
905 "'s type disagrees between the operand and pattern");
Chris Lattnerae6d8282005-09-15 21:51:12 +0000906 OperandTypes.push_back(InVal->getType());
Chris Lattnerb0276202005-09-14 22:55:26 +0000907
Chris Lattner2175c182005-09-14 23:01:59 +0000908 // Construct the result for the dest-pattern operand list.
909 TreePatternNode *OpNode = InVal->clone();
910
911 // No predicate is useful on the result.
912 OpNode->setPredicateFn("");
913
914 // Promote the xform function to be an explicit node if set.
915 if (Record *Xform = OpNode->getTransformFn()) {
916 OpNode->setTransformFn(0);
917 std::vector<TreePatternNode*> Children;
918 Children.push_back(OpNode);
919 OpNode = new TreePatternNode(Xform, Children);
920 }
921
922 ResultNodeOperands.push_back(OpNode);
Chris Lattner39e8af92005-09-14 18:19:25 +0000923 }
924
Chris Lattner0b592252005-09-14 21:59:34 +0000925 if (!InstInputsCheck.empty())
926 I->error("Input operand $" + InstInputsCheck.begin()->first +
927 " occurs in pattern but not in operands list!");
Chris Lattnerb0276202005-09-14 22:55:26 +0000928
929 TreePatternNode *ResultPattern =
930 new TreePatternNode(I->getRecord(), ResultNodeOperands);
Chris Lattnera28aec12005-09-15 22:23:50 +0000931
932 // Create and insert the instruction.
933 DAGInstruction TheInst(I, ResultTypes, OperandTypes);
934 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
935
936 // Use a temporary tree pattern to infer all types and make sure that the
937 // constructed result is correct. This depends on the instruction already
938 // being inserted into the Instructions map.
939 TreePattern Temp(I->getRecord(), ResultPattern, *this);
940 Temp.InferAllTypes();
941
942 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
943 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
Chris Lattnerb0276202005-09-14 22:55:26 +0000944
Chris Lattner32707602005-09-08 23:22:48 +0000945 DEBUG(I->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000946 }
Chris Lattner1f39e292005-09-14 00:09:24 +0000947
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000948 // If we can, convert the instructions to be patterns that are matched!
Chris Lattnerae5b3502005-09-15 21:57:35 +0000949 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
950 E = Instructions.end(); II != E; ++II) {
951 TreePattern *I = II->second.getPattern();
Chris Lattner1f39e292005-09-14 00:09:24 +0000952
953 if (I->getNumTrees() != 1) {
954 std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
955 continue;
956 }
957 TreePatternNode *Pattern = I->getTree(0);
958 if (Pattern->getOperator()->getName() != "set")
959 continue; // Not a set (store or something?)
960
961 if (Pattern->getNumChildren() != 2)
962 continue; // Not a set of a single value (not handled so far)
963
964 TreePatternNode *SrcPattern = Pattern->getChild(1)->clone();
Chris Lattnerae5b3502005-09-15 21:57:35 +0000965 TreePatternNode *DstPattern = II->second.getResultPattern();
Chris Lattner1f39e292005-09-14 00:09:24 +0000966 PatternsToMatch.push_back(std::make_pair(SrcPattern, DstPattern));
Chris Lattner1f39e292005-09-14 00:09:24 +0000967 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000968}
969
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000970void DAGISelEmitter::ParsePatterns() {
Chris Lattnerabbb6052005-09-15 21:42:00 +0000971 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000972
Chris Lattnerabbb6052005-09-15 21:42:00 +0000973 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +0000974 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
975 TreePattern *Pattern = new TreePattern(Patterns[i], Tree, *this);
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000976
Chris Lattnerabbb6052005-09-15 21:42:00 +0000977 // Inline pattern fragments into it.
978 Pattern->InlinePatternFragments();
979
980 // Infer as many types as possible. If we cannot infer all of them, we can
981 // never do anything with this pattern: report it to the user.
982 if (!Pattern->InferAllTypes())
983 Pattern->error("Could not infer all types in pattern!");
984
985 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
986 if (LI->getSize() == 0) continue; // no pattern.
Chris Lattnerabbb6052005-09-15 21:42:00 +0000987
988 // Parse the instruction.
Chris Lattnera28aec12005-09-15 22:23:50 +0000989 TreePattern *Result = new TreePattern(Patterns[i], LI, *this);
Chris Lattnerabbb6052005-09-15 21:42:00 +0000990
991 // Inline pattern fragments into it.
992 Result->InlinePatternFragments();
993
994 // Infer as many types as possible. If we cannot infer all of them, we can
995 // never do anything with this pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +0000996 if (!Result->InferAllTypes())
Chris Lattnerae5b3502005-09-15 21:57:35 +0000997 Result->error("Could not infer all types in pattern result!");
Chris Lattnerabbb6052005-09-15 21:42:00 +0000998
999 if (Result->getNumTrees() != 1)
1000 Result->error("Cannot handle instructions producing instructions "
1001 "with temporaries yet!");
1002 PatternsToMatch.push_back(std::make_pair(Pattern->getOnlyTree(),
1003 Result->getOnlyTree()));
1004 }
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001005
1006 DEBUG(std::cerr << "\n\nPARSED PATTERNS TO MATCH:\n\n";
1007 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1008 std::cerr << "PATTERN: "; PatternsToMatch[i].first->dump();
1009 std::cerr << "\nRESULT: ";PatternsToMatch[i].second->dump();
1010 std::cerr << "\n";
1011 });
1012}
1013
Chris Lattner05814af2005-09-28 17:57:56 +00001014/// getPatternSize - Return the 'size' of this pattern. We want to match large
1015/// patterns before small ones. This is used to determine the size of a
1016/// pattern.
1017static unsigned getPatternSize(TreePatternNode *P) {
1018 assert(MVT::isInteger(P->getType()) || MVT::isFloatingPoint(P->getType()) &&
1019 "Not a valid pattern node to size!");
1020 unsigned Size = 1; // The node itself.
1021
1022 // Count children in the count if they are also nodes.
1023 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1024 TreePatternNode *Child = P->getChild(i);
1025 if (!Child->isLeaf() && Child->getType() != MVT::Other)
1026 Size += getPatternSize(Child);
1027 }
1028
1029 return Size;
1030}
1031
1032/// getResultPatternCost - Compute the number of instructions for this pattern.
1033/// This is a temporary hack. We should really include the instruction
1034/// latencies in this calculation.
1035static unsigned getResultPatternCost(TreePatternNode *P) {
1036 if (P->isLeaf()) return 0;
1037
1038 unsigned Cost = P->getOperator()->isSubClassOf("Instruction");
1039 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
1040 Cost += getResultPatternCost(P->getChild(i));
1041 return Cost;
1042}
1043
1044// PatternSortingPredicate - return true if we prefer to match LHS before RHS.
1045// In particular, we want to match maximal patterns first and lowest cost within
1046// a particular complexity first.
1047struct PatternSortingPredicate {
1048 bool operator()(DAGISelEmitter::PatternToMatch *LHS,
1049 DAGISelEmitter::PatternToMatch *RHS) {
1050 unsigned LHSSize = getPatternSize(LHS->first);
1051 unsigned RHSSize = getPatternSize(RHS->first);
1052 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
1053 if (LHSSize < RHSSize) return false;
1054
1055 // If the patterns have equal complexity, compare generated instruction cost
1056 return getResultPatternCost(LHS->second) <getResultPatternCost(RHS->second);
1057 }
1058};
1059
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001060/// EmitMatchForPattern - Emit a matcher for N, going to the label for PatternNo
1061/// if the match fails. At this point, we already know that the opcode for N
1062/// matches, and the SDNode for the result has the RootName specified name.
1063void DAGISelEmitter::EmitMatchForPattern(TreePatternNode *N,
Chris Lattner8fc35682005-09-23 23:16:51 +00001064 const std::string &RootName,
1065 std::map<std::string,std::string> &VarMap,
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001066 unsigned PatternNo, std::ostream &OS) {
1067 assert(!N->isLeaf() && "Cannot match against a leaf!");
Chris Lattner72fe91c2005-09-24 00:40:24 +00001068
1069 // If this node has a name associated with it, capture it in VarMap. If
1070 // we already saw this in the pattern, emit code to verify dagness.
1071 if (!N->getName().empty()) {
1072 std::string &VarMapEntry = VarMap[N->getName()];
1073 if (VarMapEntry.empty()) {
1074 VarMapEntry = RootName;
1075 } else {
1076 // If we get here, this is a second reference to a specific name. Since
1077 // we already have checked that the first reference is valid, we don't
1078 // have to recursively match it, just check that it's the same as the
1079 // previously named thing.
1080 OS << " if (" << VarMapEntry << " != " << RootName
1081 << ") goto P" << PatternNo << "Fail;\n";
1082 return;
1083 }
1084 }
1085
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001086 // Emit code to load the child nodes and match their contents recursively.
1087 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
Chris Lattner547394c2005-09-23 21:53:45 +00001088 OS << " SDOperand " << RootName << i <<" = " << RootName
1089 << ".getOperand(" << i << ");\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001090 TreePatternNode *Child = N->getChild(i);
Chris Lattner8fc35682005-09-23 23:16:51 +00001091
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001092 if (!Child->isLeaf()) {
1093 // If it's not a leaf, recursively match.
1094 const SDNodeInfo &CInfo = getSDNodeInfo(Child->getOperator());
Chris Lattner547394c2005-09-23 21:53:45 +00001095 OS << " if (" << RootName << i << ".getOpcode() != "
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001096 << CInfo.getEnumName() << ") goto P" << PatternNo << "Fail;\n";
Chris Lattner8fc35682005-09-23 23:16:51 +00001097 EmitMatchForPattern(Child, RootName + utostr(i), VarMap, PatternNo, OS);
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001098 } else {
Chris Lattner72fe91c2005-09-24 00:40:24 +00001099 // If this child has a name associated with it, capture it in VarMap. If
1100 // we already saw this in the pattern, emit code to verify dagness.
1101 if (!Child->getName().empty()) {
1102 std::string &VarMapEntry = VarMap[Child->getName()];
1103 if (VarMapEntry.empty()) {
1104 VarMapEntry = RootName + utostr(i);
1105 } else {
1106 // If we get here, this is a second reference to a specific name. Since
1107 // we already have checked that the first reference is valid, we don't
1108 // have to recursively match it, just check that it's the same as the
1109 // previously named thing.
1110 OS << " if (" << VarMapEntry << " != " << RootName << i
1111 << ") goto P" << PatternNo << "Fail;\n";
1112 continue;
1113 }
1114 }
1115
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001116 // Handle leaves of various types.
1117 Init *LeafVal = Child->getLeafValue();
1118 Record *LeafRec = dynamic_cast<DefInit*>(LeafVal)->getDef();
1119 if (LeafRec->isSubClassOf("RegisterClass")) {
1120 // Handle register references. Nothing to do here.
1121 } else if (LeafRec->isSubClassOf("ValueType")) {
1122 // Make sure this is the specified value type.
1123 OS << " if (cast<VTSDNode>(" << RootName << i << ")->getVT() != "
1124 << "MVT::" << LeafRec->getName() << ") goto P" << PatternNo
1125 << "Fail;\n";
1126 } else {
1127 Child->dump();
1128 assert(0 && "Unknown leaf type!");
1129 }
1130 }
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001131 }
1132
1133 // If there is a node predicate for this, emit the call.
1134 if (!N->getPredicateFn().empty())
1135 OS << " if (!" << N->getPredicateFn() << "(" << RootName
Chris Lattner547394c2005-09-23 21:53:45 +00001136 << ".Val)) goto P" << PatternNo << "Fail;\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001137}
1138
Chris Lattner6bc7e512005-09-26 21:53:26 +00001139/// CodeGenPatternResult - Emit the action for a pattern. Now that it has
1140/// matched, we actually have to build a DAG!
Chris Lattner72fe91c2005-09-24 00:40:24 +00001141unsigned DAGISelEmitter::
1142CodeGenPatternResult(TreePatternNode *N, unsigned &Ctr,
1143 std::map<std::string,std::string> &VariableMap,
Chris Lattner6bc7e512005-09-26 21:53:26 +00001144 std::ostream &OS) {
Chris Lattner72fe91c2005-09-24 00:40:24 +00001145 // This is something selected from the pattern we matched.
1146 if (!N->getName().empty()) {
Chris Lattner6bc7e512005-09-26 21:53:26 +00001147 std::string &Val = VariableMap[N->getName()];
Chris Lattner72fe91c2005-09-24 00:40:24 +00001148 assert(!Val.empty() &&
1149 "Variable referenced but not defined and not caught earlier!");
1150 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
1151 // Already selected this operand, just return the tmpval.
Chris Lattner6bc7e512005-09-26 21:53:26 +00001152 return atoi(Val.c_str()+3);
Chris Lattner72fe91c2005-09-24 00:40:24 +00001153 }
Chris Lattnerf6f94162005-09-28 16:58:06 +00001154
1155 unsigned ResNo = Ctr++;
1156 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
1157 switch (N->getType()) {
1158 default: assert(0 && "Unknown type for constant node!");
1159 case MVT::i1: OS << " bool Tmp"; break;
1160 case MVT::i8: OS << " unsigned char Tmp"; break;
1161 case MVT::i16: OS << " unsigned short Tmp"; break;
1162 case MVT::i32: OS << " unsigned Tmp"; break;
1163 case MVT::i64: OS << " uint64_t Tmp"; break;
1164 }
1165 OS << ResNo << "C = cast<ConstantSDNode>(" << Val << ")->getValue();\n";
1166 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetConstant(Tmp"
1167 << ResNo << "C, MVT::" << getEnumName(N->getType()) << ");\n";
1168 } else {
1169 OS << " SDOperand Tmp" << ResNo << " = Select(" << Val << ");\n";
1170 }
1171 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
1172 // value if used multiple times by this pattern result.
1173 Val = "Tmp"+utostr(ResNo);
1174 return ResNo;
Chris Lattner72fe91c2005-09-24 00:40:24 +00001175 }
1176
1177 if (N->isLeaf()) {
1178 N->dump();
1179 assert(0 && "Unknown leaf type!");
1180 return ~0U;
1181 }
1182
1183 Record *Op = N->getOperator();
1184 if (Op->isSubClassOf("Instruction")) {
1185 // Emit all of the operands.
1186 std::vector<unsigned> Ops;
1187 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1188 Ops.push_back(CodeGenPatternResult(N->getChild(i), Ctr, VariableMap, OS));
1189
1190 CodeGenInstruction &II = Target.getInstruction(Op->getName());
1191 unsigned ResNo = Ctr++;
1192
1193 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetNode("
1194 << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
1195 << getEnumName(N->getType());
1196 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1197 OS << ", Tmp" << Ops[i];
1198 OS << ");\n";
1199 return ResNo;
1200 } else if (Op->isSubClassOf("SDNodeXForm")) {
1201 assert(N->getNumChildren() == 1 && "node xform should have one child!");
1202 unsigned OpVal = CodeGenPatternResult(N->getChild(0), Ctr, VariableMap, OS);
1203
1204 unsigned ResNo = Ctr++;
1205 OS << " SDOperand Tmp" << ResNo << " = Transform_" << Op->getName()
1206 << "(Tmp" << OpVal << ".Val);\n";
1207 return ResNo;
1208 } else {
1209 N->dump();
1210 assert(0 && "Unknown node in result pattern!");
Jeff Cohena48283b2005-09-25 19:04:43 +00001211 return ~0U;
Chris Lattner72fe91c2005-09-24 00:40:24 +00001212 }
1213}
1214
1215
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001216/// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1217/// stream to match the pattern, and generate the code for the match if it
1218/// succeeds.
Chris Lattner3f7e9142005-09-23 20:52:47 +00001219void DAGISelEmitter::EmitCodeForPattern(PatternToMatch &Pattern,
1220 std::ostream &OS) {
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001221 static unsigned PatternCount = 0;
1222 unsigned PatternNo = PatternCount++;
1223 OS << " { // Pattern #" << PatternNo << ": ";
Chris Lattner3f7e9142005-09-23 20:52:47 +00001224 Pattern.first->print(OS);
Chris Lattner05814af2005-09-28 17:57:56 +00001225 OS << "\n // Emits: ";
1226 Pattern.second->print(OS);
Chris Lattner3f7e9142005-09-23 20:52:47 +00001227 OS << "\n";
Chris Lattner05814af2005-09-28 17:57:56 +00001228 OS << " // Pattern complexity = " << getPatternSize(Pattern.first)
1229 << " cost = " << getResultPatternCost(Pattern.second) << "\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001230
Chris Lattner8fc35682005-09-23 23:16:51 +00001231 // Emit the matcher, capturing named arguments in VariableMap.
1232 std::map<std::string,std::string> VariableMap;
1233 EmitMatchForPattern(Pattern.first, "N", VariableMap, PatternNo, OS);
Chris Lattner3f7e9142005-09-23 20:52:47 +00001234
Chris Lattner72fe91c2005-09-24 00:40:24 +00001235 unsigned TmpNo = 0;
1236 unsigned Res = CodeGenPatternResult(Pattern.second, TmpNo, VariableMap, OS);
Chris Lattner296dfe32005-09-24 00:50:51 +00001237
1238 // Add the result to the map if it has multiple uses.
1239 OS << " if (!N.Val->hasOneUse()) CodeGenMap[N] = Tmp" << Res << ";\n";
Chris Lattner72fe91c2005-09-24 00:40:24 +00001240 OS << " return Tmp" << Res << ";\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001241 OS << " }\n P" << PatternNo << "Fail:\n";
Chris Lattner3f7e9142005-09-23 20:52:47 +00001242}
1243
Chris Lattner37481472005-09-26 21:59:35 +00001244
1245namespace {
1246 /// CompareByRecordName - An ordering predicate that implements less-than by
1247 /// comparing the names records.
1248 struct CompareByRecordName {
1249 bool operator()(const Record *LHS, const Record *RHS) const {
1250 // Sort by name first.
1251 if (LHS->getName() < RHS->getName()) return true;
1252 // If both names are equal, sort by pointer.
1253 return LHS->getName() == RHS->getName() && LHS < RHS;
1254 }
1255 };
1256}
1257
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001258void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
1259 // Emit boilerplate.
1260 OS << "// The main instruction selector code.\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001261 << "SDOperand SelectCode(SDOperand N) {\n"
1262 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
1263 << " N.getOpcode() < PPCISD::FIRST_NUMBER)\n"
1264 << " return N; // Already selected.\n\n"
Chris Lattner296dfe32005-09-24 00:50:51 +00001265 << " if (!N.Val->hasOneUse()) {\n"
1266 << " std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);\n"
1267 << " if (CGMI != CodeGenMap.end()) return CGMI->second;\n"
1268 << " }\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001269 << " switch (N.getOpcode()) {\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001270 << " default: break;\n"
1271 << " case ISD::EntryToken: // These leaves remain the same.\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001272 << " return N;\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001273 << " case ISD::AssertSext:\n"
Chris Lattnerfab37282005-09-26 22:10:24 +00001274 << " case ISD::AssertZext: {\n"
1275 << " SDOperand Tmp0 = Select(N.getOperand(0));\n"
1276 << " if (!N.Val->hasOneUse()) CodeGenMap[N] = Tmp0;\n"
1277 << " return Tmp0;\n"
1278 << " }\n";
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001279
Chris Lattner81303322005-09-23 19:36:15 +00001280 // Group the patterns by their top-level opcodes.
Chris Lattner37481472005-09-26 21:59:35 +00001281 std::map<Record*, std::vector<PatternToMatch*>,
1282 CompareByRecordName> PatternsByOpcode;
Chris Lattner81303322005-09-23 19:36:15 +00001283 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i)
1284 PatternsByOpcode[PatternsToMatch[i].first->getOperator()]
1285 .push_back(&PatternsToMatch[i]);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001286
Chris Lattner3f7e9142005-09-23 20:52:47 +00001287 // Loop over all of the case statements.
Chris Lattner37481472005-09-26 21:59:35 +00001288 for (std::map<Record*, std::vector<PatternToMatch*>,
1289 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
1290 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
Chris Lattner81303322005-09-23 19:36:15 +00001291 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
1292 std::vector<PatternToMatch*> &Patterns = PBOI->second;
1293
1294 OS << " case " << OpcodeInfo.getEnumName() << ":\n";
Chris Lattner3f7e9142005-09-23 20:52:47 +00001295
1296 // We want to emit all of the matching code now. However, we want to emit
1297 // the matches in order of minimal cost. Sort the patterns so the least
1298 // cost one is at the start.
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001299 std::stable_sort(Patterns.begin(), Patterns.end(),
1300 PatternSortingPredicate());
Chris Lattner81303322005-09-23 19:36:15 +00001301
Chris Lattner3f7e9142005-09-23 20:52:47 +00001302 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1303 EmitCodeForPattern(*Patterns[i], OS);
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001304 OS << " break;\n\n";
Chris Lattner81303322005-09-23 19:36:15 +00001305 }
1306
1307
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001308 OS << " } // end of big switch.\n\n"
1309 << " std::cerr << \"Cannot yet select: \";\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001310 << " N.Val->dump();\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001311 << " std::cerr << '\\n';\n"
1312 << " abort();\n"
1313 << "}\n";
1314}
1315
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001316void DAGISelEmitter::run(std::ostream &OS) {
1317 EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
1318 " target", OS);
1319
Chris Lattner1f39e292005-09-14 00:09:24 +00001320 OS << "// *** NOTE: This file is #included into the middle of the target\n"
1321 << "// *** instruction selector class. These functions are really "
1322 << "methods.\n\n";
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00001323
Chris Lattner296dfe32005-09-24 00:50:51 +00001324 OS << "// Instance var to keep track of multiply used nodes that have \n"
1325 << "// already been selected.\n"
1326 << "std::map<SDOperand, SDOperand> CodeGenMap;\n";
1327
Chris Lattnerca559d02005-09-08 21:03:01 +00001328 ParseNodeInfo();
Chris Lattner24eeeb82005-09-13 21:51:00 +00001329 ParseNodeTransforms(OS);
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001330 ParsePatternFragments(OS);
1331 ParseInstructions();
1332 ParsePatterns();
Chris Lattner3f7e9142005-09-23 20:52:47 +00001333
1334 // FIXME: Generate variants. For example, commutative patterns can match
1335 // multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001336
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00001337 // At this point, we have full information about the 'Patterns' we need to
1338 // parse, both implicitly from instructions as well as from explicit pattern
1339 // definitions.
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001340
1341 EmitInstructionSelector(OS);
1342
1343 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1344 E = PatternFragments.end(); I != E; ++I)
1345 delete I->second;
1346 PatternFragments.clear();
1347
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001348 Instructions.clear();
1349}